mirror.cc 10.0 KB

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