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