mirror.cc 10 KB

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