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