enable APT in unpack/configure ordering to handle loops as well
[ntk/apt.git] / methods / mirror.cc
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 /*{{{*/
11 #include <config.h>
12
13 #include <apt-pkg/aptconfiguration.h>
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>
20 #include <apt-pkg/sourcelist.h>
21
22
23 #include <algorithm>
24 #include <fstream>
25 #include <iostream>
26
27 #include <stdarg.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <sys/utsname.h>
31 #include <dirent.h>
32
33 using namespace std;
34
35 #include<sstream>
36
37 #include "mirror.h"
38 #include "http.h"
39 #include <apti18n.h>
40 /*}}}*/
41
42 /* Done:
43 * - works with http (only!)
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"
47 * - uses pkgAcqMethod::FailReason() to have a string representation
48 * of the failure that is also send to LP
49 *
50 * TODO:
51 * - deal with runing as non-root because we can't write to the lists
52 dir then -> use the cached mirror file
53 * - better method to download than having a pkgAcquire interface here
54 * and better error handling there!
55 * - support more than http
56 * - testing :)
57 */
58
59 MirrorMethod::MirrorMethod()
60 : HttpMethod(), DownloadedMirrorFile(false), Debug(false)
61 {
62 };
63
64 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
65 // ---------------------------------------------------------------------
66 /* We stash the desired pipeline depth */
67 bool 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
77 // clean the mirrors dir based on ttl information
78 bool MirrorMethod::Clean(string Dir)
79 {
80 vector<metaIndex *>::const_iterator I;
81
82 if(Debug)
83 clog << "MirrorMethod::Clean(): " << Dir << endl;
84
85 if(Dir == "/")
86 return _error->Error("will not clean: '/'");
87
88 // read sources.list
89 pkgSourceList list;
90 list.ReadMainList();
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;
111
112 // see if we have that uri
113 for(I=list.begin(); I != list.end(); ++I)
114 {
115 string uri = (*I)->GetURI();
116 if(uri.find("mirror://") != 0)
117 continue;
118 string BaseUri = uri.substr(0,uri.size()-1);
119 if (URItoFileName(BaseUri) == Dir->d_name)
120 break;
121 }
122 // nothing found, nuke it
123 if (I == list.end())
124 unlink(Dir->d_name);
125 };
126
127 chdir(StartDir.c_str());
128 closedir(D);
129 return true;
130 }
131
132
133 bool MirrorMethod::DownloadMirrorFile(string mirror_uri_str)
134 {
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
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
155 // append the dist as a query string
156 if (Dist != "")
157 fetch += "&dist=" + Dist;
158
159 if(Debug)
160 clog << "MirrorMethod::DownloadMirrorFile(): '" << fetch << "'"
161 << " to " << MirrorFile << endl;
162
163 pkgAcquire Fetcher;
164 new pkgAcqFile(&Fetcher, fetch, "", 0, "", "", "", MirrorFile);
165 bool res = (Fetcher.Run() == pkgAcquire::Continue);
166 if(res) {
167 DownloadedMirrorFile = true;
168 chmod(MirrorFile.c_str(), 0644);
169 }
170 Fetcher.Shutdown();
171
172 if(Debug)
173 clog << "MirrorMethod::DownloadMirrorFile() success: " << res << endl;
174
175 return res;
176 }
177
178 // Randomizes the lines in the mirror file, this is used so that
179 // we spread the load on the mirrors evenly
180 bool MirrorMethod::RandomizeMirrorFile(string mirror_file)
181 {
182 vector<string> content;
183 string line;
184
185 if (!FileExists(mirror_file))
186 return false;
187
188 // read
189 ifstream in(mirror_file.c_str());
190 while ( !in.eof() ) {
191 getline(in, line);
192 content.push_back(line);
193 }
194
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 );
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
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 */
223 void 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
230 for (vector<string>::const_iterator mirror = AllMirrors.begin();
231 mirror != AllMirrors.end(); ++mirror)
232 {
233 if (Queue->Uri.find(*mirror) == 0)
234 {
235 Queue->Uri.replace(0, mirror->length(), BaseUri);
236 return;
237 }
238 }
239 _error->Error("Internal error: Failed to convert %s back to %s",
240 Queue->Uri.c_str(), BaseUri.c_str());
241 }
242
243 bool MirrorMethod::TryNextMirror()
244 {
245 // find current mirror and select next one
246 for (vector<string>::const_iterator mirror = AllMirrors.begin();
247 mirror != AllMirrors.end(); ++mirror)
248 {
249 if (Queue->Uri.find(*mirror) != 0)
250 continue;
251
252 vector<string>::const_iterator nextmirror = mirror + 1;
253 if (nextmirror == AllMirrors.end())
254 break;
255 Queue->Uri.replace(0, mirror->length(), *nextmirror);
256 if (Debug)
257 clog << "TryNextMirror: " << Queue->Uri << endl;
258
259 // inform parent
260 UsedMirror = *nextmirror;
261 Log("Switching mirror");
262 return true;
263 }
264
265 if (Debug)
266 clog << "TryNextMirror could not find another mirror to try" << endl;
267
268 return false;
269 }
270
271 bool MirrorMethod::InitMirrors()
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
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
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());
295 string s;
296 while (!in.eof())
297 {
298 getline(in, s);
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);
311 }
312 Mirror = AllMirrors[0];
313 UsedMirror = Mirror;
314 return true;
315 }
316
317 string MirrorMethod::GetMirrorFileName(string mirror_uri_str)
318 {
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 */
343 string name;
344 if(Debug)
345 std::cerr << "GetMirrorFileName: " << mirror_uri_str << std::endl;
346
347 // read sources.list and find match
348 vector<metaIndex *>::const_iterator I;
349 pkgSourceList list;
350 list.ReadMainList();
351 for(I=list.begin(); I != list.end(); ++I)
352 {
353 string uristr = (*I)->GetURI();
354 if(Debug)
355 std::cerr << "Checking: " << uristr << std::endl;
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 {
361 if(Debug)
362 std::cerr << "found BaseURI: " << uristr << std::endl;
363 BaseUri = uristr.substr(0,uristr.size()-1);
364 Dist = (*I)->GetDist();
365 }
366 }
367 // get new file
368 name = _config->FindDir("Dir::State::mirrors") + URItoFileName(BaseUri);
369
370 if(Debug)
371 {
372 cerr << "base-uri: " << BaseUri << endl;
373 cerr << "mirror-file: " << name << endl;
374 }
375 return name;
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. */
382 bool MirrorMethod::Fetch(FetchItem *Itm)
383 {
384 if(Debug)
385 clog << "MirrorMethod::Fetch()" << endl;
386
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)
400 {
401 Clean(_config->FindDir("Dir::State::mirrors"));
402 if (DownloadMirrorFile(Itm->Uri))
403 RandomizeMirrorFile(MirrorFile);
404 }
405
406 if(AllMirrors.empty()) {
407 if(!InitMirrors()) {
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 }
414
415 if(Itm->Uri.find("mirror://") != string::npos)
416 Itm->Uri.replace(0,BaseUri.size(), Mirror);
417
418 if(Debug)
419 clog << "Fetch: " << Itm->Uri << endl << endl;
420
421 // now run the real fetcher
422 return HttpMethod::Fetch(Itm);
423 };
424
425 void MirrorMethod::Fail(string Err,bool Transient)
426 {
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)
435 if (!Queue->FailIgnore && TryNextMirror())
436 return;
437
438 // all mirrors failed, so bail out
439 string s;
440 strprintf(s, _("[Mirror: %s]"), Mirror.c_str());
441 SetIP(s);
442
443 CurrentQueueUriToMirror();
444 pkgAcqMethod::Fail(Err, Transient);
445 }
446
447 void MirrorMethod::URIStart(FetchResult &Res)
448 {
449 CurrentQueueUriToMirror();
450 pkgAcqMethod::URIStart(Res);
451 }
452
453 void MirrorMethod::URIDone(FetchResult &Res,FetchResult *Alt)
454 {
455 CurrentQueueUriToMirror();
456 pkgAcqMethod::URIDone(Res, Alt);
457 }
458
459
460 int main()
461 {
462 setlocale(LC_ALL, "");
463
464 MirrorMethod Mth;
465
466 return Mth.Loop();
467 }
468
469