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