mirror.cc 10 KB

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