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