mirror.cc 11 KB

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