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