mirror.cc 12 KB

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