mirror.cc 13 KB

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