mirror.cc 13 KB

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