mirror.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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/aptconfiguration.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), Debug(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. #if 0 // no need for this, the getArchitectures() will also include the main
  115. // arch
  116. // append main architecture
  117. fetch += "?arch=" + _config->Find("Apt::Architecture");
  118. #endif
  119. // append all architectures
  120. std::vector<std::string> vec = APT::Configuration::getArchitectures();
  121. for (std::vector<std::string>::const_iterator I = vec.begin();
  122. I != vec.end(); I++)
  123. if (I == vec.begin())
  124. fetch += "?arch" + (*I);
  125. else
  126. fetch += "&arch=" + (*I);
  127. // append the dist as a query string
  128. if (Dist != "")
  129. fetch += "&dist=" + Dist;
  130. if(Debug)
  131. clog << "MirrorMethod::DownloadMirrorFile(): '" << fetch << "'"
  132. << " to " << MirrorFile << endl;
  133. pkgAcquire Fetcher;
  134. new pkgAcqFile(&Fetcher, fetch, "", 0, "", "", "", MirrorFile);
  135. bool res = (Fetcher.Run() == pkgAcquire::Continue);
  136. if(res) {
  137. DownloadedMirrorFile = true;
  138. chmod(MirrorFile.c_str(), 0644);
  139. }
  140. Fetcher.Shutdown();
  141. if(Debug)
  142. clog << "MirrorMethod::DownloadMirrorFile() success: " << res << endl;
  143. return res;
  144. }
  145. // Randomizes the lines in the mirror file, this is used so that
  146. // we spread the load on the mirrors evenly
  147. bool MirrorMethod::RandomizeMirrorFile(string mirror_file)
  148. {
  149. vector<string> content;
  150. string line;
  151. if (!FileExists(mirror_file))
  152. return false;
  153. // read
  154. ifstream in(mirror_file.c_str());
  155. while ( !in.eof() ) {
  156. getline(in, line);
  157. content.push_back(line);
  158. }
  159. // we want the file to be random for each different machine, but also
  160. // "stable" on the same machine. this is to avoid running into out-of-sync
  161. // issues (i.e. Release/Release.gpg different on each mirror)
  162. struct utsname buf;
  163. int seed=1, i;
  164. if(uname(&buf) == 0) {
  165. for(i=0,seed=1; buf.nodename[i] != 0; i++) {
  166. seed = seed * 31 + buf.nodename[i];
  167. }
  168. }
  169. srand( seed );
  170. random_shuffle(content.begin(), content.end());
  171. // write
  172. ofstream out(mirror_file.c_str());
  173. while ( !content.empty()) {
  174. line = content.back();
  175. content.pop_back();
  176. out << line << "\n";
  177. }
  178. return true;
  179. }
  180. /* convert a the Queue->Uri back to the mirror base uri and look
  181. * at all mirrors we have for this, this is needed as queue->uri
  182. * may point to different mirrors (if TryNextMirror() was run)
  183. */
  184. void MirrorMethod::CurrentQueueUriToMirror()
  185. {
  186. // already in mirror:// style so nothing to do
  187. if(Queue->Uri.find("mirror://") == 0)
  188. return;
  189. // find current mirror and select next one
  190. for (vector<string>::const_iterator mirror = AllMirrors.begin();
  191. mirror != AllMirrors.end(); ++mirror)
  192. {
  193. if (Queue->Uri.find(*mirror) == 0)
  194. {
  195. Queue->Uri.replace(0, mirror->length(), BaseUri);
  196. return;
  197. }
  198. }
  199. _error->Error("Internal error: Failed to convert %s back to %s",
  200. Queue->Uri.c_str(), BaseUri.c_str());
  201. }
  202. bool MirrorMethod::TryNextMirror()
  203. {
  204. // find current mirror and select next one
  205. for (vector<string>::const_iterator mirror = AllMirrors.begin();
  206. mirror != AllMirrors.end(); ++mirror)
  207. {
  208. if (Queue->Uri.find(*mirror) != 0)
  209. continue;
  210. vector<string>::const_iterator nextmirror = mirror + 1;
  211. if (nextmirror == AllMirrors.end())
  212. break;
  213. Queue->Uri.replace(0, mirror->length(), *nextmirror);
  214. if (Debug)
  215. clog << "TryNextMirror: " << Queue->Uri << endl;
  216. // inform parent
  217. UsedMirror = *nextmirror;
  218. Log("Switching mirror");
  219. return true;
  220. }
  221. if (Debug)
  222. clog << "TryNextMirror could not find another mirror to try" << endl;
  223. return false;
  224. }
  225. bool MirrorMethod::InitMirrors()
  226. {
  227. // if we do not have a MirrorFile, fallback
  228. if(!FileExists(MirrorFile))
  229. {
  230. // FIXME: fallback to a default mirror here instead
  231. // and provide a config option to define that default
  232. return _error->Error(_("No mirror file '%s' found "), MirrorFile.c_str());
  233. }
  234. if (access(MirrorFile.c_str(), R_OK) != 0)
  235. {
  236. // FIXME: fallback to a default mirror here instead
  237. // and provide a config option to define that default
  238. return _error->Error(_("Can not read mirror file '%s'"), MirrorFile.c_str());
  239. }
  240. // FIXME: make the mirror selection more clever, do not
  241. // just use the first one!
  242. // BUT: we can not make this random, the mirror has to be
  243. // stable accross session, because otherwise we can
  244. // get into sync issues (got indexfiles from mirror A,
  245. // but packages from mirror B - one might be out of date etc)
  246. ifstream in(MirrorFile.c_str());
  247. string s;
  248. while (!in.eof())
  249. {
  250. getline(in, s);
  251. // ignore lines that start with #
  252. if (s.find("#") == 0)
  253. continue;
  254. // ignore empty lines
  255. if (s.size() == 0)
  256. continue;
  257. // ignore non http lines
  258. if (s.find("http://") != 0)
  259. continue;
  260. AllMirrors.push_back(s);
  261. }
  262. Mirror = AllMirrors[0];
  263. UsedMirror = Mirror;
  264. return true;
  265. }
  266. string MirrorMethod::GetMirrorFileName(string mirror_uri_str)
  267. {
  268. /*
  269. - a mirror_uri_str looks like this:
  270. mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors/dists/feisty/Release.gpg
  271. - the matching source.list entry
  272. deb mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors feisty main
  273. - we actually want to go after:
  274. http://people.ubuntu.com/~mvo/apt/mirror/mirrors
  275. And we need to save the BaseUri for later:
  276. - mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors
  277. FIXME: what if we have two similar prefixes?
  278. mirror://people.ubuntu.com/~mvo/mirror
  279. mirror://people.ubuntu.com/~mvo/mirror2
  280. then mirror_uri_str looks like:
  281. mirror://people.ubuntu.com/~mvo/apt/mirror/dists/feisty/Release.gpg
  282. mirror://people.ubuntu.com/~mvo/apt/mirror2/dists/feisty/Release.gpg
  283. we search sources.list and find:
  284. mirror://people.ubuntu.com/~mvo/apt/mirror
  285. in both cases! So we need to apply some domain knowledge here :( and
  286. check for /dists/ or /Release.gpg as suffixes
  287. */
  288. string name;
  289. if(Debug)
  290. std::cerr << "GetMirrorFileName: " << mirror_uri_str << std::endl;
  291. // read sources.list and find match
  292. vector<metaIndex *>::const_iterator I;
  293. pkgSourceList list;
  294. list.ReadMainList();
  295. for(I=list.begin(); I != list.end(); ++I)
  296. {
  297. string uristr = (*I)->GetURI();
  298. if(Debug)
  299. std::cerr << "Checking: " << uristr << std::endl;
  300. if(uristr.substr(0,strlen("mirror://")) != string("mirror://"))
  301. continue;
  302. // find matching uri in sources.list
  303. if(mirror_uri_str.substr(0,uristr.size()) == uristr)
  304. {
  305. if(Debug)
  306. std::cerr << "found BaseURI: " << uristr << std::endl;
  307. BaseUri = uristr.substr(0,uristr.size()-1);
  308. Dist = (*I)->GetDist();
  309. }
  310. }
  311. // get new file
  312. name = _config->FindDir("Dir::State::mirrors") + URItoFileName(BaseUri);
  313. if(Debug)
  314. {
  315. cerr << "base-uri: " << BaseUri << endl;
  316. cerr << "mirror-file: " << name << endl;
  317. }
  318. return name;
  319. }
  320. // MirrorMethod::Fetch - Fetch an item /*{{{*/
  321. // ---------------------------------------------------------------------
  322. /* This adds an item to the pipeline. We keep the pipeline at a fixed
  323. depth. */
  324. bool MirrorMethod::Fetch(FetchItem *Itm)
  325. {
  326. if(Debug)
  327. clog << "MirrorMethod::Fetch()" << endl;
  328. // the http method uses Fetch(0) as a way to update the pipeline,
  329. // just let it do its work in this case - Fetch() with a valid
  330. // Itm will always run before the first Fetch(0)
  331. if(Itm == NULL)
  332. return HttpMethod::Fetch(Itm);
  333. // if we don't have the name of the mirror file on disk yet,
  334. // calculate it now (can be derived from the uri)
  335. if(MirrorFile.empty())
  336. MirrorFile = GetMirrorFileName(Itm->Uri);
  337. // download mirror file once (if we are after index files)
  338. if(Itm->IndexFile && !DownloadedMirrorFile)
  339. {
  340. Clean(_config->FindDir("Dir::State::mirrors"));
  341. if (DownloadMirrorFile(Itm->Uri))
  342. RandomizeMirrorFile(MirrorFile);
  343. }
  344. if(AllMirrors.empty()) {
  345. if(!InitMirrors()) {
  346. // no valid mirror selected, something went wrong downloading
  347. // from the master mirror site most likely and there is
  348. // no old mirror file availalbe
  349. return false;
  350. }
  351. }
  352. if(Itm->Uri.find("mirror://") != string::npos)
  353. Itm->Uri.replace(0,BaseUri.size(), Mirror);
  354. if(Debug)
  355. clog << "Fetch: " << Itm->Uri << endl << endl;
  356. // now run the real fetcher
  357. return HttpMethod::Fetch(Itm);
  358. };
  359. void MirrorMethod::Fail(string Err,bool Transient)
  360. {
  361. // FIXME: TryNextMirror is not ideal for indexfile as we may
  362. // run into auth issues
  363. if (Debug)
  364. clog << "Failure to get " << Queue->Uri << endl;
  365. // try the next mirror on fail (if its not a expected failure,
  366. // e.g. translations are ok to ignore)
  367. if (!Queue->FailIgnore && TryNextMirror())
  368. return;
  369. // all mirrors failed, so bail out
  370. string s;
  371. strprintf(s, _("[Mirror: %s]"), Mirror.c_str());
  372. SetIP(s);
  373. CurrentQueueUriToMirror();
  374. pkgAcqMethod::Fail(Err, Transient);
  375. }
  376. void MirrorMethod::URIStart(FetchResult &Res)
  377. {
  378. CurrentQueueUriToMirror();
  379. pkgAcqMethod::URIStart(Res);
  380. }
  381. void MirrorMethod::URIDone(FetchResult &Res,FetchResult *Alt)
  382. {
  383. CurrentQueueUriToMirror();
  384. pkgAcqMethod::URIDone(Res, Alt);
  385. }
  386. int main()
  387. {
  388. setlocale(LC_ALL, "");
  389. MirrorMethod Mth;
  390. return Mth.Loop();
  391. }