mirror.cc 13 KB

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