mirror.cc 10 KB

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