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