mirror.cc 11 KB

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