do not pollute namespace in the headers with using (Closes: #500198)
[ntk/apt.git] / methods / mirror.cc
CommitLineData
5f6b130d
MV
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
3// $Id: mirror.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4/* ######################################################################
5
6 Mirror Aquire Method - This is the Mirror aquire method for APT.
7
8 ##################################################################### */
9 /*}}}*/
10// Include Files /*{{{*/
ea542140
DK
11#include <config.h>
12
ae54c535 13#include <apt-pkg/aptconfiguration.h>
5f6b130d
MV
14#include <apt-pkg/fileutl.h>
15#include <apt-pkg/acquire-method.h>
16#include <apt-pkg/acquire-item.h>
17#include <apt-pkg/acquire.h>
18#include <apt-pkg/error.h>
19#include <apt-pkg/hashes.h>
0c312e0e 20#include <apt-pkg/sourcelist.h>
5f6b130d 21
78c8f3cd 22
01a695e2 23#include <algorithm>
78c8f3cd 24#include <fstream>
5f6b130d 25#include <iostream>
78c8f3cd 26
14e097c1 27#include <stdarg.h>
d731f9c5 28#include <sys/stat.h>
70288656 29#include <sys/types.h>
78c8f3cd 30#include <sys/utsname.h>
70288656 31#include <dirent.h>
14e097c1 32
5f6b130d
MV
33using namespace std;
34
0ded3ad3
MV
35#include<sstream>
36
5f6b130d
MV
37#include "mirror.h"
38#include "http.h"
ea542140 39#include <apti18n.h>
5f6b130d
MV
40 /*}}}*/
41
362d2934 42/* Done:
59271f62 43 * - works with http (only!)
362d2934
MV
44 * - always picks the first mirror from the list
45 * - call out to problem reporting script
46 * - supports "deb mirror://host/path/to/mirror-list/// dist component"
a577a938 47 * - uses pkgAcqMethod::FailReason() to have a string representation
59271f62 48 * of the failure that is also send to LP
362d2934 49 *
86c17f0a 50 * TODO:
d731f9c5
MV
51 * - deal with runing as non-root because we can't write to the lists
52 dir then -> use the cached mirror file
86c17f0a 53 * - better method to download than having a pkgAcquire interface here
3f599bb7 54 * and better error handling there!
066b53e9 55 * - support more than http
86c17f0a 56 * - testing :)
86c17f0a
MV
57 */
58
5f6b130d 59MirrorMethod::MirrorMethod()
f5a34606 60 : HttpMethod(), DownloadedMirrorFile(false), Debug(false)
5f6b130d 61{
5f6b130d
MV
62};
63
14e097c1
MV
64// HttpMethod::Configuration - Handle a configuration message /*{{{*/
65// ---------------------------------------------------------------------
66/* We stash the desired pipeline depth */
67bool MirrorMethod::Configuration(string Message)
68{
69 if (pkgAcqMethod::Configuration(Message) == false)
70 return false;
71 Debug = _config->FindB("Debug::Acquire::mirror",false);
72
73 return true;
74}
75 /*}}}*/
76
d731f9c5 77// clean the mirrors dir based on ttl information
70288656 78bool MirrorMethod::Clean(string Dir)
d731f9c5 79{
0c312e0e
MV
80 vector<metaIndex *>::const_iterator I;
81
82 if(Debug)
83 clog << "MirrorMethod::Clean(): " << Dir << endl;
84
38eedeb7
MV
85 if(Dir == "/")
86 return _error->Error("will not clean: '/'");
87
0c312e0e
MV
88 // read sources.list
89 pkgSourceList list;
90 list.ReadMainList();
70288656
MV
91
92 DIR *D = opendir(Dir.c_str());
93 if (D == 0)
94 return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
95
96 string StartDir = SafeGetCWD();
97 if (chdir(Dir.c_str()) != 0)
98 {
99 closedir(D);
100 return _error->Errno("chdir",_("Unable to change to %s"),Dir.c_str());
101 }
102
103 for (struct dirent *Dir = readdir(D); Dir != 0; Dir = readdir(D))
104 {
105 // Skip some files..
106 if (strcmp(Dir->d_name,"lock") == 0 ||
107 strcmp(Dir->d_name,"partial") == 0 ||
108 strcmp(Dir->d_name,".") == 0 ||
109 strcmp(Dir->d_name,"..") == 0)
110 continue;
0c312e0e
MV
111
112 // see if we have that uri
f7f0d6c7 113 for(I=list.begin(); I != list.end(); ++I)
70288656 114 {
0c312e0e 115 string uri = (*I)->GetURI();
b86f6421 116 if(uri.find("mirror://") != 0)
0c312e0e 117 continue;
066b53e9 118 string BaseUri = uri.substr(0,uri.size()-1);
0c312e0e
MV
119 if (URItoFileName(BaseUri) == Dir->d_name)
120 break;
70288656 121 }
0c312e0e
MV
122 // nothing found, nuke it
123 if (I == list.end())
70288656 124 unlink(Dir->d_name);
70288656 125 };
d731f9c5 126
70288656
MV
127 chdir(StartDir.c_str());
128 closedir(D);
129 return true;
d731f9c5
MV
130}
131
14e097c1 132
38eedeb7
MV
133bool MirrorMethod::DownloadMirrorFile(string mirror_uri_str)
134{
38eedeb7
MV
135 // not that great to use pkgAcquire here, but we do not have
136 // any other way right now
137 string fetch = BaseUri;
138 fetch.replace(0,strlen("mirror://"),"http://");
139
ae54c535
MV
140#if 0 // no need for this, the getArchitectures() will also include the main
141 // arch
142 // append main architecture
143 fetch += "?arch=" + _config->Find("Apt::Architecture");
144#endif
145
146 // append all architectures
147 std::vector<std::string> vec = APT::Configuration::getArchitectures();
148 for (std::vector<std::string>::const_iterator I = vec.begin();
149 I != vec.end(); I++)
150 if (I == vec.begin())
151 fetch += "?arch" + (*I);
152 else
153 fetch += "&arch=" + (*I);
154
6885f3de
MV
155 // append the dist as a query string
156 if (Dist != "")
ae54c535 157 fetch += "&dist=" + Dist;
6885f3de 158
d6cc7079
MV
159 if(Debug)
160 clog << "MirrorMethod::DownloadMirrorFile(): '" << fetch << "'"
161 << " to " << MirrorFile << endl;
162
38eedeb7
MV
163 pkgAcquire Fetcher;
164 new pkgAcqFile(&Fetcher, fetch, "", 0, "", "", "", MirrorFile);
165 bool res = (Fetcher.Run() == pkgAcquire::Continue);
83e6798e 166 if(res) {
38eedeb7 167 DownloadedMirrorFile = true;
83e6798e
MV
168 chmod(MirrorFile.c_str(), 0644);
169 }
38eedeb7 170 Fetcher.Shutdown();
d6cc7079
MV
171
172 if(Debug)
173 clog << "MirrorMethod::DownloadMirrorFile() success: " << res << endl;
174
38eedeb7
MV
175 return res;
176}
177
01a695e2
MV
178// Randomizes the lines in the mirror file, this is used so that
179// we spread the load on the mirrors evenly
180bool MirrorMethod::RandomizeMirrorFile(string mirror_file)
181{
182 vector<string> content;
183 string line;
184
0004842d
MV
185 if (!FileExists(mirror_file))
186 return false;
187
01a695e2
MV
188 // read
189 ifstream in(mirror_file.c_str());
0190e315 190 while ( !in.eof() ) {
01a695e2
MV
191 getline(in, line);
192 content.push_back(line);
193 }
194
78c8f3cd
MV
195 // we want the file to be random for each different machine, but also
196 // "stable" on the same machine. this is to avoid running into out-of-sync
197 // issues (i.e. Release/Release.gpg different on each mirror)
198 struct utsname buf;
199 int seed=1, i;
200 if(uname(&buf) == 0) {
201 for(i=0,seed=1; buf.nodename[i] != 0; i++) {
202 seed = seed * 31 + buf.nodename[i];
203 }
204 }
205 srand( seed );
01a695e2
MV
206 random_shuffle(content.begin(), content.end());
207
208 // write
209 ofstream out(mirror_file.c_str());
210 while ( !content.empty()) {
211 line = content.back();
212 content.pop_back();
213 out << line << "\n";
214 }
215
216 return true;
217}
218
03915427
MV
219/* convert a the Queue->Uri back to the mirror base uri and look
220 * at all mirrors we have for this, this is needed as queue->uri
221 * may point to different mirrors (if TryNextMirror() was run)
222 */
223void MirrorMethod::CurrentQueueUriToMirror()
224{
225 // already in mirror:// style so nothing to do
226 if(Queue->Uri.find("mirror://") == 0)
227 return;
228
229 // find current mirror and select next one
51561c4d
DK
230 for (vector<string>::const_iterator mirror = AllMirrors.begin();
231 mirror != AllMirrors.end(); ++mirror)
03915427 232 {
51561c4d 233 if (Queue->Uri.find(*mirror) == 0)
03915427 234 {
51561c4d 235 Queue->Uri.replace(0, mirror->length(), BaseUri);
03915427
MV
236 return;
237 }
238 }
239 _error->Error("Internal error: Failed to convert %s back to %s",
963b16dc 240 Queue->Uri.c_str(), BaseUri.c_str());
03915427
MV
241}
242
243bool MirrorMethod::TryNextMirror()
96db74ce 244{
03915427 245 // find current mirror and select next one
51561c4d
DK
246 for (vector<string>::const_iterator mirror = AllMirrors.begin();
247 mirror != AllMirrors.end(); ++mirror)
03915427 248 {
51561c4d
DK
249 if (Queue->Uri.find(*mirror) != 0)
250 continue;
251
252 vector<string>::const_iterator nextmirror = mirror + 1;
d6cc7079 253 if (nextmirror == AllMirrors.end())
51561c4d
DK
254 break;
255 Queue->Uri.replace(0, mirror->length(), *nextmirror);
256 if (Debug)
257 clog << "TryNextMirror: " << Queue->Uri << endl;
196fd136
MV
258
259 // inform parent
260 UsedMirror = *nextmirror;
261 Log("Switching mirror");
51561c4d 262 return true;
03915427
MV
263 }
264
963b16dc
MV
265 if (Debug)
266 clog << "TryNextMirror could not find another mirror to try" << endl;
267
0ded3ad3 268 return false;
96db74ce
MV
269}
270
271bool MirrorMethod::InitMirrors()
38eedeb7
MV
272{
273 // if we do not have a MirrorFile, fallback
274 if(!FileExists(MirrorFile))
275 {
276 // FIXME: fallback to a default mirror here instead
277 // and provide a config option to define that default
278 return _error->Error(_("No mirror file '%s' found "), MirrorFile.c_str());
279 }
280
b46fb8ff
MV
281 if (access(MirrorFile.c_str(), R_OK) != 0)
282 {
283 // FIXME: fallback to a default mirror here instead
284 // and provide a config option to define that default
285 return _error->Error(_("Can not read mirror file '%s'"), MirrorFile.c_str());
286 }
287
38eedeb7
MV
288 // FIXME: make the mirror selection more clever, do not
289 // just use the first one!
290 // BUT: we can not make this random, the mirror has to be
291 // stable accross session, because otherwise we can
292 // get into sync issues (got indexfiles from mirror A,
293 // but packages from mirror B - one might be out of date etc)
294 ifstream in(MirrorFile.c_str());
96db74ce
MV
295 string s;
296 while (!in.eof())
297 {
298 getline(in, s);
95f395cc
MV
299
300 // ignore lines that start with #
301 if (s.find("#") == 0)
302 continue;
303 // ignore empty lines
304 if (s.size() == 0)
305 continue;
306 // ignore non http lines
307 if (s.find("http://") != 0)
308 continue;
309
310 AllMirrors.push_back(s);
96db74ce 311 }
03915427
MV
312 Mirror = AllMirrors[0];
313 UsedMirror = Mirror;
38eedeb7
MV
314 return true;
315}
316
317string MirrorMethod::GetMirrorFileName(string mirror_uri_str)
5f6b130d 318{
066b53e9
MV
319 /*
320 - a mirror_uri_str looks like this:
321 mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors/dists/feisty/Release.gpg
322
323 - the matching source.list entry
324 deb mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors feisty main
325
326 - we actually want to go after:
327 http://people.ubuntu.com/~mvo/apt/mirror/mirrors
328
329 And we need to save the BaseUri for later:
330 - mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors
331
332 FIXME: what if we have two similar prefixes?
333 mirror://people.ubuntu.com/~mvo/mirror
334 mirror://people.ubuntu.com/~mvo/mirror2
335 then mirror_uri_str looks like:
336 mirror://people.ubuntu.com/~mvo/apt/mirror/dists/feisty/Release.gpg
337 mirror://people.ubuntu.com/~mvo/apt/mirror2/dists/feisty/Release.gpg
338 we search sources.list and find:
339 mirror://people.ubuntu.com/~mvo/apt/mirror
340 in both cases! So we need to apply some domain knowledge here :( and
341 check for /dists/ or /Release.gpg as suffixes
342 */
38eedeb7 343 string name;
f0b509cd 344 if(Debug)
38eedeb7 345 std::cerr << "GetMirrorFileName: " << mirror_uri_str << std::endl;
066b53e9
MV
346
347 // read sources.list and find match
348 vector<metaIndex *>::const_iterator I;
349 pkgSourceList list;
350 list.ReadMainList();
f7f0d6c7 351 for(I=list.begin(); I != list.end(); ++I)
066b53e9
MV
352 {
353 string uristr = (*I)->GetURI();
f0b509cd
MV
354 if(Debug)
355 std::cerr << "Checking: " << uristr << std::endl;
066b53e9
MV
356 if(uristr.substr(0,strlen("mirror://")) != string("mirror://"))
357 continue;
358 // find matching uri in sources.list
359 if(mirror_uri_str.substr(0,uristr.size()) == uristr)
360 {
f0b509cd
MV
361 if(Debug)
362 std::cerr << "found BaseURI: " << uristr << std::endl;
066b53e9 363 BaseUri = uristr.substr(0,uristr.size()-1);
6885f3de 364 Dist = (*I)->GetDist();
066b53e9
MV
365 }
366 }
70288656 367 // get new file
38eedeb7 368 name = _config->FindDir("Dir::State::mirrors") + URItoFileName(BaseUri);
5f6b130d 369
14e097c1
MV
370 if(Debug)
371 {
372 cerr << "base-uri: " << BaseUri << endl;
38eedeb7 373 cerr << "mirror-file: " << name << endl;
d731f9c5 374 }
38eedeb7 375 return name;
5f6b130d
MV
376}
377
378// MirrorMethod::Fetch - Fetch an item /*{{{*/
379// ---------------------------------------------------------------------
380/* This adds an item to the pipeline. We keep the pipeline at a fixed
381 depth. */
382bool MirrorMethod::Fetch(FetchItem *Itm)
383{
5dad4134
MV
384 if(Debug)
385 clog << "MirrorMethod::Fetch()" << endl;
386
38eedeb7
MV
387 // the http method uses Fetch(0) as a way to update the pipeline,
388 // just let it do its work in this case - Fetch() with a valid
389 // Itm will always run before the first Fetch(0)
390 if(Itm == NULL)
391 return HttpMethod::Fetch(Itm);
392
393 // if we don't have the name of the mirror file on disk yet,
394 // calculate it now (can be derived from the uri)
395 if(MirrorFile.empty())
396 MirrorFile = GetMirrorFileName(Itm->Uri);
397
398 // download mirror file once (if we are after index files)
399 if(Itm->IndexFile && !DownloadedMirrorFile)
5f6b130d 400 {
70288656 401 Clean(_config->FindDir("Dir::State::mirrors"));
0004842d
MV
402 if (DownloadMirrorFile(Itm->Uri))
403 RandomizeMirrorFile(MirrorFile);
5f6b130d
MV
404 }
405
2ac9b90b 406 if(AllMirrors.empty()) {
96db74ce 407 if(!InitMirrors()) {
5dad4134
MV
408 // no valid mirror selected, something went wrong downloading
409 // from the master mirror site most likely and there is
410 // no old mirror file availalbe
411 return false;
412 }
413 }
5dad4134 414
963b16dc
MV
415 if(Itm->Uri.find("mirror://") != string::npos)
416 Itm->Uri.replace(0,BaseUri.size(), Mirror);
38eedeb7 417
963b16dc
MV
418 if(Debug)
419 clog << "Fetch: " << Itm->Uri << endl << endl;
38eedeb7 420
14e097c1
MV
421 // now run the real fetcher
422 return HttpMethod::Fetch(Itm);
5f6b130d
MV
423};
424
14e097c1
MV
425void MirrorMethod::Fail(string Err,bool Transient)
426{
2ac9b90b
MV
427 // FIXME: TryNextMirror is not ideal for indexfile as we may
428 // run into auth issues
429
430 if (Debug)
431 clog << "Failure to get " << Queue->Uri << endl;
432
433 // try the next mirror on fail (if its not a expected failure,
434 // e.g. translations are ok to ignore)
963b16dc 435 if (!Queue->FailIgnore && TryNextMirror())
483dfdd8 436 return;
483dfdd8
MV
437
438 // all mirrors failed, so bail out
0ded3ad3
MV
439 string s;
440 strprintf(s, _("[Mirror: %s]"), Mirror.c_str());
441 SetIP(s);
442
03915427 443 CurrentQueueUriToMirror();
14e097c1
MV
444 pkgAcqMethod::Fail(Err, Transient);
445}
446
447void MirrorMethod::URIStart(FetchResult &Res)
448{
03915427 449 CurrentQueueUriToMirror();
14e097c1
MV
450 pkgAcqMethod::URIStart(Res);
451}
452
453void MirrorMethod::URIDone(FetchResult &Res,FetchResult *Alt)
454{
03915427 455 CurrentQueueUriToMirror();
14e097c1
MV
456 pkgAcqMethod::URIDone(Res, Alt);
457}
458
459
5f6b130d
MV
460int main()
461{
462 setlocale(LC_ALL, "");
463
464 MirrorMethod Mth;
465
14e097c1 466 return Mth.Loop();
5f6b130d
MV
467}
468
469