mirror.cc 12 KB

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