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