acquire-item.cc 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
  4. /* ######################################################################
  5. Acquire Item - Item to acquire
  6. Each item can download to exactly one file at a time. This means you
  7. cannot create an item that fetches two uri's to two files at the same
  8. time. The pkgAcqIndex class creates a second class upon instantiation
  9. to fetch the other index files because of this.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <apt-pkg/acquire-item.h>
  14. #include <apt-pkg/configuration.h>
  15. #include <apt-pkg/aptconfiguration.h>
  16. #include <apt-pkg/sourcelist.h>
  17. #include <apt-pkg/vendorlist.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/fileutl.h>
  21. #include <apt-pkg/md5.h>
  22. #include <apt-pkg/sha1.h>
  23. #include <apt-pkg/tagfile.h>
  24. #include <apti18n.h>
  25. #include <sys/stat.h>
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #include <string>
  29. #include <sstream>
  30. #include <stdio.h>
  31. /*}}}*/
  32. using namespace std;
  33. // Acquire::Item::Item - Constructor /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* */
  36. pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
  37. PartialSize(0), Mode(0), ID(0), Complete(false),
  38. Local(false), QueueCounter(0)
  39. {
  40. Owner->Add(this);
  41. Status = StatIdle;
  42. }
  43. /*}}}*/
  44. // Acquire::Item::~Item - Destructor /*{{{*/
  45. // ---------------------------------------------------------------------
  46. /* */
  47. pkgAcquire::Item::~Item()
  48. {
  49. Owner->Remove(this);
  50. }
  51. /*}}}*/
  52. // Acquire::Item::Failed - Item failed to download /*{{{*/
  53. // ---------------------------------------------------------------------
  54. /* We return to an idle state if there are still other queues that could
  55. fetch this object */
  56. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  57. {
  58. Status = StatIdle;
  59. ErrorText = LookupTag(Message,"Message");
  60. UsedMirror = LookupTag(Message,"UsedMirror");
  61. if (QueueCounter <= 1)
  62. {
  63. /* This indicates that the file is not available right now but might
  64. be sometime later. If we do a retry cycle then this should be
  65. retried [CDROMs] */
  66. if (Cnf->LocalOnly == true &&
  67. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  68. {
  69. Status = StatIdle;
  70. Dequeue();
  71. return;
  72. }
  73. Status = StatError;
  74. Dequeue();
  75. }
  76. // report mirror failure back to LP if we actually use a mirror
  77. string FailReason = LookupTag(Message, "FailReason");
  78. if(FailReason.size() != 0)
  79. ReportMirrorFailure(FailReason);
  80. else
  81. ReportMirrorFailure(ErrorText);
  82. }
  83. /*}}}*/
  84. // Acquire::Item::Start - Item has begun to download /*{{{*/
  85. // ---------------------------------------------------------------------
  86. /* Stash status and the file size. Note that setting Complete means
  87. sub-phases of the acquire process such as decompresion are operating */
  88. void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
  89. {
  90. Status = StatFetching;
  91. if (FileSize == 0 && Complete == false)
  92. FileSize = Size;
  93. }
  94. /*}}}*/
  95. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  96. // ---------------------------------------------------------------------
  97. /* */
  98. void pkgAcquire::Item::Done(string Message,unsigned long Size,string Hash,
  99. pkgAcquire::MethodConfig *Cnf)
  100. {
  101. // We just downloaded something..
  102. string FileName = LookupTag(Message,"Filename");
  103. UsedMirror = LookupTag(Message,"UsedMirror");
  104. if (Complete == false && !Local && FileName == DestFile)
  105. {
  106. if (Owner->Log != 0)
  107. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  108. }
  109. if (FileSize == 0)
  110. FileSize= Size;
  111. Status = StatDone;
  112. ErrorText = string();
  113. Owner->Dequeue(this);
  114. }
  115. /*}}}*/
  116. // Acquire::Item::Rename - Rename a file /*{{{*/
  117. // ---------------------------------------------------------------------
  118. /* This helper function is used by alot of item methods as thier final
  119. step */
  120. void pkgAcquire::Item::Rename(string From,string To)
  121. {
  122. if (rename(From.c_str(),To.c_str()) != 0)
  123. {
  124. char S[300];
  125. snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
  126. From.c_str(),To.c_str());
  127. Status = StatError;
  128. ErrorText = S;
  129. }
  130. }
  131. /*}}}*/
  132. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  133. {
  134. // we only act if a mirror was used at all
  135. if(UsedMirror.empty())
  136. return;
  137. #if 0
  138. std::cerr << "\nReportMirrorFailure: "
  139. << UsedMirror
  140. << " Uri: " << DescURI()
  141. << " FailCode: "
  142. << FailCode << std::endl;
  143. #endif
  144. const char *Args[40];
  145. unsigned int i = 0;
  146. string report = _config->Find("Methods::Mirror::ProblemReporting",
  147. "/usr/lib/apt/apt-report-mirror-failure");
  148. if(!FileExists(report))
  149. return;
  150. Args[i++] = report.c_str();
  151. Args[i++] = UsedMirror.c_str();
  152. Args[i++] = DescURI().c_str();
  153. Args[i++] = FailCode.c_str();
  154. Args[i++] = NULL;
  155. pid_t pid = ExecFork();
  156. if(pid < 0)
  157. {
  158. _error->Error("ReportMirrorFailure Fork failed");
  159. return;
  160. }
  161. else if(pid == 0)
  162. {
  163. execvp(Args[0], (char**)Args);
  164. std::cerr << "Could not exec " << Args[0] << std::endl;
  165. _exit(100);
  166. }
  167. if(!ExecWait(pid, "report-mirror-failure"))
  168. {
  169. _error->Warning("Couldn't report problem to '%s'",
  170. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  171. }
  172. }
  173. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  174. // ---------------------------------------------------------------------
  175. /* Get the DiffIndex file first and see if there are patches availabe
  176. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  177. * patches. If anything goes wrong in that process, it will fall back to
  178. * the original packages file
  179. */
  180. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  181. string URI,string URIDesc,string ShortDesc,
  182. HashString ExpectedHash)
  183. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  184. Description(URIDesc)
  185. {
  186. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  187. Desc.Description = URIDesc + "/DiffIndex";
  188. Desc.Owner = this;
  189. Desc.ShortDesc = ShortDesc;
  190. Desc.URI = URI + ".diff/Index";
  191. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  192. DestFile += URItoFileName(URI) + string(".DiffIndex");
  193. if(Debug)
  194. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  195. // look for the current package file
  196. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  197. CurrentPackagesFile += URItoFileName(RealURI);
  198. // FIXME: this file:/ check is a hack to prevent fetching
  199. // from local sources. this is really silly, and
  200. // should be fixed cleanly as soon as possible
  201. if(!FileExists(CurrentPackagesFile) ||
  202. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  203. {
  204. // we don't have a pkg file or we don't want to queue
  205. if(Debug)
  206. std::clog << "No index file, local or canceld by user" << std::endl;
  207. Failed("", NULL);
  208. return;
  209. }
  210. if(Debug)
  211. std::clog << "pkgAcqIndexDiffs::pkgAcqIndexDiffs(): "
  212. << CurrentPackagesFile << std::endl;
  213. QueueURI(Desc);
  214. }
  215. /*}}}*/
  216. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  217. // ---------------------------------------------------------------------
  218. /* The only header we use is the last-modified header. */
  219. string pkgAcqDiffIndex::Custom600Headers()
  220. {
  221. string Final = _config->FindDir("Dir::State::lists");
  222. Final += URItoFileName(RealURI) + string(".IndexDiff");
  223. if(Debug)
  224. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  225. struct stat Buf;
  226. if (stat(Final.c_str(),&Buf) != 0)
  227. return "\nIndex-File: true";
  228. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  229. }
  230. /*}}}*/
  231. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  232. {
  233. if(Debug)
  234. std::clog << "pkgAcqIndexDiffs::ParseIndexDiff() " << IndexDiffFile
  235. << std::endl;
  236. pkgTagSection Tags;
  237. string ServerSha1;
  238. vector<DiffInfo> available_patches;
  239. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  240. pkgTagFile TF(&Fd);
  241. if (_error->PendingError() == true)
  242. return false;
  243. if(TF.Step(Tags) == true)
  244. {
  245. string local_sha1;
  246. bool found = false;
  247. DiffInfo d;
  248. string size;
  249. string tmp = Tags.FindS("SHA1-Current");
  250. std::stringstream ss(tmp);
  251. ss >> ServerSha1;
  252. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  253. SHA1Summation SHA1;
  254. SHA1.AddFD(fd.Fd(), fd.Size());
  255. local_sha1 = string(SHA1.Result());
  256. if(local_sha1 == ServerSha1)
  257. {
  258. // we have the same sha1 as the server
  259. if(Debug)
  260. std::clog << "Package file is up-to-date" << std::endl;
  261. // set found to true, this will queue a pkgAcqIndexDiffs with
  262. // a empty availabe_patches
  263. found = true;
  264. }
  265. else
  266. {
  267. if(Debug)
  268. std::clog << "SHA1-Current: " << ServerSha1 << std::endl;
  269. // check the historie and see what patches we need
  270. string history = Tags.FindS("SHA1-History");
  271. std::stringstream hist(history);
  272. while(hist >> d.sha1 >> size >> d.file)
  273. {
  274. d.size = atoi(size.c_str());
  275. // read until the first match is found
  276. if(d.sha1 == local_sha1)
  277. found=true;
  278. // from that point on, we probably need all diffs
  279. if(found)
  280. {
  281. if(Debug)
  282. std::clog << "Need to get diff: " << d.file << std::endl;
  283. available_patches.push_back(d);
  284. }
  285. }
  286. }
  287. // we have something, queue the next diff
  288. if(found)
  289. {
  290. // queue the diffs
  291. string::size_type last_space = Description.rfind(" ");
  292. if(last_space != string::npos)
  293. Description.erase(last_space, Description.size()-last_space);
  294. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  295. ExpectedHash, available_patches);
  296. Complete = false;
  297. Status = StatDone;
  298. Dequeue();
  299. return true;
  300. }
  301. }
  302. // Nothing found, report and return false
  303. // Failing here is ok, if we return false later, the full
  304. // IndexFile is queued
  305. if(Debug)
  306. std::clog << "Can't find a patch in the index file" << std::endl;
  307. return false;
  308. }
  309. /*}}}*/
  310. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  311. {
  312. if(Debug)
  313. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << std::endl
  314. << "Falling back to normal index file aquire" << std::endl;
  315. new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
  316. ExpectedHash);
  317. Complete = false;
  318. Status = StatDone;
  319. Dequeue();
  320. }
  321. /*}}}*/
  322. void pkgAcqDiffIndex::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  323. pkgAcquire::MethodConfig *Cnf)
  324. {
  325. if(Debug)
  326. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  327. Item::Done(Message,Size,Md5Hash,Cnf);
  328. string FinalFile;
  329. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  330. // sucess in downloading the index
  331. // rename the index
  332. FinalFile += string(".IndexDiff");
  333. if(Debug)
  334. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  335. << std::endl;
  336. Rename(DestFile,FinalFile);
  337. chmod(FinalFile.c_str(),0644);
  338. DestFile = FinalFile;
  339. if(!ParseDiffIndex(DestFile))
  340. return Failed("", NULL);
  341. Complete = true;
  342. Status = StatDone;
  343. Dequeue();
  344. return;
  345. }
  346. /*}}}*/
  347. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  348. // ---------------------------------------------------------------------
  349. /* The package diff is added to the queue. one object is constructed
  350. * for each diff and the index
  351. */
  352. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  353. string URI,string URIDesc,string ShortDesc,
  354. HashString ExpectedHash,
  355. vector<DiffInfo> diffs)
  356. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  357. available_patches(diffs)
  358. {
  359. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  360. DestFile += URItoFileName(URI);
  361. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  362. Description = URIDesc;
  363. Desc.Owner = this;
  364. Desc.ShortDesc = ShortDesc;
  365. if(available_patches.size() == 0)
  366. {
  367. // we are done (yeah!)
  368. Finish(true);
  369. }
  370. else
  371. {
  372. // get the next diff
  373. State = StateFetchDiff;
  374. QueueNextDiff();
  375. }
  376. }
  377. /*}}}*/
  378. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  379. {
  380. if(Debug)
  381. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
  382. << "Falling back to normal index file aquire" << std::endl;
  383. new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
  384. ExpectedHash);
  385. Finish();
  386. }
  387. /*}}}*/
  388. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  389. void pkgAcqIndexDiffs::Finish(bool allDone)
  390. {
  391. // we restore the original name, this is required, otherwise
  392. // the file will be cleaned
  393. if(allDone)
  394. {
  395. DestFile = _config->FindDir("Dir::State::lists");
  396. DestFile += URItoFileName(RealURI);
  397. if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
  398. {
  399. Status = StatAuthError;
  400. ErrorText = _("MD5Sum mismatch");
  401. Rename(DestFile,DestFile + ".FAILED");
  402. Dequeue();
  403. return;
  404. }
  405. // this is for the "real" finish
  406. Complete = true;
  407. Status = StatDone;
  408. Dequeue();
  409. if(Debug)
  410. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  411. return;
  412. }
  413. if(Debug)
  414. std::clog << "Finishing: " << Desc.URI << std::endl;
  415. Complete = false;
  416. Status = StatDone;
  417. Dequeue();
  418. return;
  419. }
  420. /*}}}*/
  421. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  422. {
  423. // calc sha1 of the just patched file
  424. string FinalFile = _config->FindDir("Dir::State::lists");
  425. FinalFile += URItoFileName(RealURI);
  426. FileFd fd(FinalFile, FileFd::ReadOnly);
  427. SHA1Summation SHA1;
  428. SHA1.AddFD(fd.Fd(), fd.Size());
  429. string local_sha1 = string(SHA1.Result());
  430. if(Debug)
  431. std::clog << "QueueNextDiff: "
  432. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  433. // remove all patches until the next matching patch is found
  434. // this requires the Index file to be ordered
  435. for(vector<DiffInfo>::iterator I=available_patches.begin();
  436. available_patches.size() > 0 &&
  437. I != available_patches.end() &&
  438. (*I).sha1 != local_sha1;
  439. I++)
  440. {
  441. available_patches.erase(I);
  442. }
  443. // error checking and falling back if no patch was found
  444. if(available_patches.size() == 0)
  445. {
  446. Failed("", NULL);
  447. return false;
  448. }
  449. // queue the right diff
  450. Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
  451. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  452. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  453. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  454. if(Debug)
  455. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  456. QueueURI(Desc);
  457. return true;
  458. }
  459. /*}}}*/
  460. void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  461. pkgAcquire::MethodConfig *Cnf)
  462. {
  463. if(Debug)
  464. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  465. Item::Done(Message,Size,Md5Hash,Cnf);
  466. string FinalFile;
  467. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  468. // sucess in downloading a diff, enter ApplyDiff state
  469. if(State == StateFetchDiff)
  470. {
  471. if(Debug)
  472. std::clog << "Sending to gzip method: " << FinalFile << std::endl;
  473. string FileName = LookupTag(Message,"Filename");
  474. State = StateUnzipDiff;
  475. Local = true;
  476. Desc.URI = "gzip:" + FileName;
  477. DestFile += ".decomp";
  478. QueueURI(Desc);
  479. Mode = "gzip";
  480. return;
  481. }
  482. // sucess in downloading a diff, enter ApplyDiff state
  483. if(State == StateUnzipDiff)
  484. {
  485. // rred excepts the patch as $FinalFile.ed
  486. Rename(DestFile,FinalFile+".ed");
  487. if(Debug)
  488. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  489. State = StateApplyDiff;
  490. Local = true;
  491. Desc.URI = "rred:" + FinalFile;
  492. QueueURI(Desc);
  493. Mode = "rred";
  494. return;
  495. }
  496. // success in download/apply a diff, queue next (if needed)
  497. if(State == StateApplyDiff)
  498. {
  499. // remove the just applied patch
  500. available_patches.erase(available_patches.begin());
  501. // move into place
  502. if(Debug)
  503. {
  504. std::clog << "Moving patched file in place: " << std::endl
  505. << DestFile << " -> " << FinalFile << std::endl;
  506. }
  507. Rename(DestFile,FinalFile);
  508. chmod(FinalFile.c_str(),0644);
  509. // see if there is more to download
  510. if(available_patches.size() > 0) {
  511. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  512. ExpectedHash, available_patches);
  513. return Finish();
  514. } else
  515. return Finish(true);
  516. }
  517. }
  518. /*}}}*/
  519. // AcqIndex::AcqIndex - Constructor /*{{{*/
  520. // ---------------------------------------------------------------------
  521. /* The package file is added to the queue and a second class is
  522. instantiated to fetch the revision file */
  523. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  524. string URI,string URIDesc,string ShortDesc,
  525. HashString ExpectedHash, string comprExt)
  526. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
  527. {
  528. Decompression = false;
  529. Erase = false;
  530. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  531. DestFile += URItoFileName(URI);
  532. if(comprExt.empty())
  533. {
  534. // autoselect the compression method
  535. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  536. if (types.empty() == true)
  537. comprExt = "plain";
  538. else
  539. comprExt = "." + types[0];
  540. }
  541. CompressionExtension = ((comprExt == "plain" || comprExt == ".") ? "" : comprExt);
  542. Desc.URI = URI + CompressionExtension;
  543. Desc.Description = URIDesc;
  544. Desc.Owner = this;
  545. Desc.ShortDesc = ShortDesc;
  546. QueueURI(Desc);
  547. }
  548. /*}}}*/
  549. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  550. // ---------------------------------------------------------------------
  551. /* The only header we use is the last-modified header. */
  552. string pkgAcqIndex::Custom600Headers()
  553. {
  554. string Final = _config->FindDir("Dir::State::lists");
  555. Final += URItoFileName(RealURI);
  556. struct stat Buf;
  557. if (stat(Final.c_str(),&Buf) != 0)
  558. return "\nIndex-File: true";
  559. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  560. }
  561. /*}}}*/
  562. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  563. {
  564. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  565. for (std::vector<std::string>::const_iterator t = types.begin();
  566. t != types.end(); t++)
  567. {
  568. // jump over all already tried compression types
  569. const unsigned int nameLen = Desc.URI.size() - (*t).size();
  570. if(Desc.URI.substr(nameLen) != *t)
  571. continue;
  572. // we want to try it with the next extension (and make sure to
  573. // not skip over the end)
  574. t++;
  575. if (t == types.end())
  576. break;
  577. // queue new download
  578. Desc.URI = Desc.URI.substr(0, nameLen) + *t;
  579. new pkgAcqIndex(Owner, RealURI, Desc.Description, Desc.ShortDesc,
  580. ExpectedHash, string(".").append(*t));
  581. Status = StatDone;
  582. Complete = false;
  583. Dequeue();
  584. return;
  585. }
  586. // on decompression failure, remove bad versions in partial/
  587. if(Decompression && Erase) {
  588. string s = _config->FindDir("Dir::State::lists") + "partial/";
  589. s += URItoFileName(RealURI);
  590. unlink(s.c_str());
  591. }
  592. Item::Failed(Message,Cnf);
  593. }
  594. /*}}}*/
  595. // AcqIndex::Done - Finished a fetch /*{{{*/
  596. // ---------------------------------------------------------------------
  597. /* This goes through a number of states.. On the initial fetch the
  598. method could possibly return an alternate filename which points
  599. to the uncompressed version of the file. If this is so the file
  600. is copied into the partial directory. In all other cases the file
  601. is decompressed with a gzip uri. */
  602. void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
  603. pkgAcquire::MethodConfig *Cfg)
  604. {
  605. Item::Done(Message,Size,Hash,Cfg);
  606. if (Decompression == true)
  607. {
  608. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  609. {
  610. std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
  611. std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
  612. }
  613. if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
  614. {
  615. Status = StatAuthError;
  616. ErrorText = _("Hash Sum mismatch");
  617. Rename(DestFile,DestFile + ".FAILED");
  618. ReportMirrorFailure("HashChecksumFailure");
  619. return;
  620. }
  621. // Done, move it into position
  622. string FinalFile = _config->FindDir("Dir::State::lists");
  623. FinalFile += URItoFileName(RealURI);
  624. Rename(DestFile,FinalFile);
  625. chmod(FinalFile.c_str(),0644);
  626. /* We restore the original name to DestFile so that the clean operation
  627. will work OK */
  628. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  629. DestFile += URItoFileName(RealURI);
  630. // Remove the compressed version.
  631. if (Erase == true)
  632. unlink(DestFile.c_str());
  633. return;
  634. }
  635. Erase = false;
  636. Complete = true;
  637. // Handle the unzipd case
  638. string FileName = LookupTag(Message,"Alt-Filename");
  639. if (FileName.empty() == false)
  640. {
  641. // The files timestamp matches
  642. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  643. return;
  644. Decompression = true;
  645. Local = true;
  646. DestFile += ".decomp";
  647. Desc.URI = "copy:" + FileName;
  648. QueueURI(Desc);
  649. Mode = "copy";
  650. return;
  651. }
  652. FileName = LookupTag(Message,"Filename");
  653. if (FileName.empty() == true)
  654. {
  655. Status = StatError;
  656. ErrorText = "Method gave a blank filename";
  657. }
  658. // The files timestamp matches
  659. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  660. return;
  661. if (FileName == DestFile)
  662. Erase = true;
  663. else
  664. Local = true;
  665. string compExt = flExtension(flNotDir(URI(Desc.URI).Path));
  666. string decompProg;
  667. // get the binary name for your used compression type
  668. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  669. if(decompProg.empty() == false);
  670. // flExtensions returns the full name if no extension is found
  671. // this is why we have this complicated compare operation here
  672. // FIMXE: add a new flJustExtension() that return "" if no
  673. // extension is found and use that above so that it can
  674. // be tested against ""
  675. else if(compExt == flNotDir(URI(Desc.URI).Path))
  676. decompProg = "copy";
  677. else {
  678. _error->Error("Unsupported extension: %s", compExt.c_str());
  679. return;
  680. }
  681. Decompression = true;
  682. DestFile += ".decomp";
  683. Desc.URI = decompProg + ":" + FileName;
  684. QueueURI(Desc);
  685. Mode = decompProg.c_str();
  686. }
  687. /*}}}*/
  688. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  689. // ---------------------------------------------------------------------
  690. /* The Translation file is added to the queue */
  691. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  692. string URI,string URIDesc,string ShortDesc)
  693. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
  694. {
  695. }
  696. /*}}}*/
  697. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  698. // ---------------------------------------------------------------------
  699. /* */
  700. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  701. {
  702. if (Cnf->LocalOnly == true ||
  703. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  704. {
  705. // Ignore this
  706. Status = StatDone;
  707. Complete = false;
  708. Dequeue();
  709. return;
  710. }
  711. Item::Failed(Message,Cnf);
  712. }
  713. /*}}}*/
  714. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  715. string URI,string URIDesc,string ShortDesc,
  716. string MetaIndexURI, string MetaIndexURIDesc,
  717. string MetaIndexShortDesc,
  718. const vector<IndexTarget*>* IndexTargets,
  719. indexRecords* MetaIndexParser) :
  720. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  721. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  722. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  723. {
  724. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  725. DestFile += URItoFileName(URI);
  726. // remove any partial downloaded sig-file in partial/.
  727. // it may confuse proxies and is too small to warrant a
  728. // partial download anyway
  729. unlink(DestFile.c_str());
  730. // Create the item
  731. Desc.Description = URIDesc;
  732. Desc.Owner = this;
  733. Desc.ShortDesc = ShortDesc;
  734. Desc.URI = URI;
  735. string Final = _config->FindDir("Dir::State::lists");
  736. Final += URItoFileName(RealURI);
  737. struct stat Buf;
  738. if (stat(Final.c_str(),&Buf) == 0)
  739. {
  740. // File was already in place. It needs to be re-downloaded/verified
  741. // because Release might have changed, we do give it a differnt
  742. // name than DestFile because otherwise the http method will
  743. // send If-Range requests and there are too many broken servers
  744. // out there that do not understand them
  745. LastGoodSig = DestFile+".reverify";
  746. Rename(Final,LastGoodSig);
  747. }
  748. QueueURI(Desc);
  749. }
  750. /*}}}*/
  751. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  752. // ---------------------------------------------------------------------
  753. /* The only header we use is the last-modified header. */
  754. string pkgAcqMetaSig::Custom600Headers()
  755. {
  756. struct stat Buf;
  757. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  758. return "\nIndex-File: true";
  759. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  760. }
  761. void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
  762. pkgAcquire::MethodConfig *Cfg)
  763. {
  764. Item::Done(Message,Size,MD5,Cfg);
  765. string FileName = LookupTag(Message,"Filename");
  766. if (FileName.empty() == true)
  767. {
  768. Status = StatError;
  769. ErrorText = "Method gave a blank filename";
  770. return;
  771. }
  772. if (FileName != DestFile)
  773. {
  774. // We have to copy it into place
  775. Local = true;
  776. Desc.URI = "copy:" + FileName;
  777. QueueURI(Desc);
  778. return;
  779. }
  780. Complete = true;
  781. // put the last known good file back on i-m-s hit (it will
  782. // be re-verified again)
  783. // Else do nothing, we have the new file in DestFile then
  784. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  785. Rename(LastGoodSig, DestFile);
  786. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  787. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc,
  788. MetaIndexShortDesc, DestFile, IndexTargets,
  789. MetaIndexParser);
  790. }
  791. /*}}}*/
  792. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  793. {
  794. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  795. // if we get a network error we fail gracefully
  796. if(Status == StatTransientNetworkError)
  797. {
  798. Item::Failed(Message,Cnf);
  799. // move the sigfile back on transient network failures
  800. if(FileExists(LastGoodSig))
  801. Rename(LastGoodSig,Final);
  802. // set the status back to , Item::Failed likes to reset it
  803. Status = pkgAcquire::Item::StatTransientNetworkError;
  804. return;
  805. }
  806. // Delete any existing sigfile when the acquire failed
  807. unlink(Final.c_str());
  808. // queue a pkgAcqMetaIndex with no sigfile
  809. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  810. "", IndexTargets, MetaIndexParser);
  811. if (Cnf->LocalOnly == true ||
  812. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  813. {
  814. // Ignore this
  815. Status = StatDone;
  816. Complete = false;
  817. Dequeue();
  818. return;
  819. }
  820. Item::Failed(Message,Cnf);
  821. }
  822. /*}}}*/
  823. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  824. string URI,string URIDesc,string ShortDesc,
  825. string SigFile,
  826. const vector<struct IndexTarget*>* IndexTargets,
  827. indexRecords* MetaIndexParser) :
  828. Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  829. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  830. {
  831. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  832. DestFile += URItoFileName(URI);
  833. // Create the item
  834. Desc.Description = URIDesc;
  835. Desc.Owner = this;
  836. Desc.ShortDesc = ShortDesc;
  837. Desc.URI = URI;
  838. QueueURI(Desc);
  839. }
  840. /*}}}*/
  841. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  842. // ---------------------------------------------------------------------
  843. /* The only header we use is the last-modified header. */
  844. string pkgAcqMetaIndex::Custom600Headers()
  845. {
  846. string Final = _config->FindDir("Dir::State::lists");
  847. Final += URItoFileName(RealURI);
  848. struct stat Buf;
  849. if (stat(Final.c_str(),&Buf) != 0)
  850. return "\nIndex-File: true";
  851. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  852. }
  853. /*}}}*/
  854. void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash, /*{{{*/
  855. pkgAcquire::MethodConfig *Cfg)
  856. {
  857. Item::Done(Message,Size,Hash,Cfg);
  858. // MetaIndexes are done in two passes: one to download the
  859. // metaindex with an appropriate method, and a second to verify it
  860. // with the gpgv method
  861. if (AuthPass == true)
  862. {
  863. AuthDone(Message);
  864. // all cool, move Release file into place
  865. Complete = true;
  866. string FinalFile = _config->FindDir("Dir::State::lists");
  867. FinalFile += URItoFileName(RealURI);
  868. Rename(DestFile,FinalFile);
  869. chmod(FinalFile.c_str(),0644);
  870. DestFile = FinalFile;
  871. }
  872. else
  873. {
  874. RetrievalDone(Message);
  875. if (!Complete)
  876. // Still more retrieving to do
  877. return;
  878. if (SigFile == "")
  879. {
  880. // There was no signature file, so we are finished. Download
  881. // the indexes without verification.
  882. QueueIndexes(false);
  883. }
  884. else
  885. {
  886. // There was a signature file, so pass it to gpgv for
  887. // verification
  888. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  889. std::cerr << "Metaindex acquired, queueing gpg verification ("
  890. << SigFile << "," << DestFile << ")\n";
  891. AuthPass = true;
  892. Desc.URI = "gpgv:" + SigFile;
  893. QueueURI(Desc);
  894. Mode = "gpgv";
  895. }
  896. }
  897. }
  898. /*}}}*/
  899. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  900. {
  901. // We have just finished downloading a Release file (it is not
  902. // verified yet)
  903. string FileName = LookupTag(Message,"Filename");
  904. if (FileName.empty() == true)
  905. {
  906. Status = StatError;
  907. ErrorText = "Method gave a blank filename";
  908. return;
  909. }
  910. if (FileName != DestFile)
  911. {
  912. Local = true;
  913. Desc.URI = "copy:" + FileName;
  914. QueueURI(Desc);
  915. return;
  916. }
  917. // make sure to verify against the right file on I-M-S hit
  918. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  919. if(IMSHit)
  920. {
  921. string FinalFile = _config->FindDir("Dir::State::lists");
  922. FinalFile += URItoFileName(RealURI);
  923. DestFile = FinalFile;
  924. }
  925. Complete = true;
  926. }
  927. /*}}}*/
  928. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  929. {
  930. // At this point, the gpgv method has succeeded, so there is a
  931. // valid signature from a key in the trusted keyring. We
  932. // perform additional verification of its contents, and use them
  933. // to verify the indexes we are about to download
  934. if (!MetaIndexParser->Load(DestFile))
  935. {
  936. Status = StatAuthError;
  937. ErrorText = MetaIndexParser->ErrorText;
  938. return;
  939. }
  940. if (!VerifyVendor(Message))
  941. {
  942. return;
  943. }
  944. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  945. std::cerr << "Signature verification succeeded: "
  946. << DestFile << std::endl;
  947. // Download further indexes with verification
  948. QueueIndexes(true);
  949. // Done, move signature file into position
  950. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  951. URItoFileName(RealURI) + ".gpg";
  952. Rename(SigFile,VerifiedSigFile);
  953. chmod(VerifiedSigFile.c_str(),0644);
  954. }
  955. /*}}}*/
  956. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  957. {
  958. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  959. Target != IndexTargets->end();
  960. Target++)
  961. {
  962. HashString ExpectedIndexHash;
  963. if (verify)
  964. {
  965. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  966. if (!Record)
  967. {
  968. Status = StatAuthError;
  969. ErrorText = "Unable to find expected entry "
  970. + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
  971. return;
  972. }
  973. ExpectedIndexHash = Record->Hash;
  974. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  975. {
  976. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  977. std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
  978. }
  979. if (ExpectedIndexHash.empty())
  980. {
  981. Status = StatAuthError;
  982. ErrorText = "Unable to find hash sum for "
  983. + (*Target)->MetaKey + " in Meta-index file";
  984. return;
  985. }
  986. }
  987. // Queue Packages file (either diff or full packages files, depending
  988. // on the users option)
  989. if(_config->FindB("Acquire::PDiffs",false) == true)
  990. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  991. (*Target)->ShortDesc, ExpectedIndexHash);
  992. else
  993. new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
  994. (*Target)->ShortDesc, ExpectedIndexHash);
  995. }
  996. }
  997. /*}}}*/
  998. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  999. {
  1000. // // Maybe this should be made available from above so we don't have
  1001. // // to read and parse it every time?
  1002. // pkgVendorList List;
  1003. // List.ReadMainList();
  1004. // const Vendor* Vndr = NULL;
  1005. // for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
  1006. // {
  1007. // string::size_type pos = (*I).find("VALIDSIG ");
  1008. // if (_config->FindB("Debug::Vendor", false))
  1009. // std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
  1010. // << std::endl;
  1011. // if (pos != std::string::npos)
  1012. // {
  1013. // string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
  1014. // if (_config->FindB("Debug::Vendor", false))
  1015. // std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
  1016. // std::endl;
  1017. // Vndr = List.FindVendor(Fingerprint) != "";
  1018. // if (Vndr != NULL);
  1019. // break;
  1020. // }
  1021. // }
  1022. string::size_type pos;
  1023. // check for missing sigs (that where not fatal because otherwise we had
  1024. // bombed earlier)
  1025. string missingkeys;
  1026. string msg = _("There is no public key available for the "
  1027. "following key IDs:\n");
  1028. pos = Message.find("NO_PUBKEY ");
  1029. if (pos != std::string::npos)
  1030. {
  1031. string::size_type start = pos+strlen("NO_PUBKEY ");
  1032. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1033. missingkeys += (Fingerprint);
  1034. }
  1035. if(!missingkeys.empty())
  1036. _error->Warning("%s", string(msg+missingkeys).c_str());
  1037. string Transformed = MetaIndexParser->GetExpectedDist();
  1038. if (Transformed == "../project/experimental")
  1039. {
  1040. Transformed = "experimental";
  1041. }
  1042. pos = Transformed.rfind('/');
  1043. if (pos != string::npos)
  1044. {
  1045. Transformed = Transformed.substr(0, pos);
  1046. }
  1047. if (Transformed == ".")
  1048. {
  1049. Transformed = "";
  1050. }
  1051. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1052. {
  1053. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1054. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1055. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1056. }
  1057. if (MetaIndexParser->CheckDist(Transformed) == false)
  1058. {
  1059. // This might become fatal one day
  1060. // Status = StatAuthError;
  1061. // ErrorText = "Conflicting distribution; expected "
  1062. // + MetaIndexParser->GetExpectedDist() + " but got "
  1063. // + MetaIndexParser->GetDist();
  1064. // return false;
  1065. if (!Transformed.empty())
  1066. {
  1067. _error->Warning("Conflicting distribution: %s (expected %s but got %s)",
  1068. Desc.Description.c_str(),
  1069. Transformed.c_str(),
  1070. MetaIndexParser->GetDist().c_str());
  1071. }
  1072. }
  1073. return true;
  1074. }
  1075. /*}}}*/
  1076. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1077. // ---------------------------------------------------------------------
  1078. /* */
  1079. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1080. {
  1081. if (AuthPass == true)
  1082. {
  1083. // gpgv method failed, if we have a good signature
  1084. string LastGoodSigFile = _config->FindDir("Dir::State::lists") +
  1085. "partial/" + URItoFileName(RealURI) + ".gpg.reverify";
  1086. if(FileExists(LastGoodSigFile))
  1087. {
  1088. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1089. URItoFileName(RealURI) + ".gpg";
  1090. Rename(LastGoodSigFile,VerifiedSigFile);
  1091. Status = StatTransientNetworkError;
  1092. _error->Warning(_("A error occurred during the signature "
  1093. "verification. The repository is not updated "
  1094. "and the previous index files will be used."
  1095. "GPG error: %s: %s\n"),
  1096. Desc.Description.c_str(),
  1097. LookupTag(Message,"Message").c_str());
  1098. RunScripts("APT::Update::Auth-Failure");
  1099. return;
  1100. } else {
  1101. _error->Warning(_("GPG error: %s: %s"),
  1102. Desc.Description.c_str(),
  1103. LookupTag(Message,"Message").c_str());
  1104. }
  1105. // gpgv method failed
  1106. ReportMirrorFailure("GPGFailure");
  1107. }
  1108. // No Release file was present, or verification failed, so fall
  1109. // back to queueing Packages files without verification
  1110. QueueIndexes(false);
  1111. }
  1112. /*}}}*/
  1113. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1114. // ---------------------------------------------------------------------
  1115. /* This just sets up the initial fetch environment and queues the first
  1116. possibilitiy */
  1117. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1118. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1119. string &StoreFilename) :
  1120. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  1121. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1122. Trusted(false)
  1123. {
  1124. Retries = _config->FindI("Acquire::Retries",0);
  1125. if (Version.Arch() == 0)
  1126. {
  1127. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1128. "This might mean you need to manually fix this package. "
  1129. "(due to missing arch)"),
  1130. Version.ParentPkg().Name());
  1131. return;
  1132. }
  1133. /* We need to find a filename to determine the extension. We make the
  1134. assumption here that all the available sources for this version share
  1135. the same extension.. */
  1136. // Skip not source sources, they do not have file fields.
  1137. for (; Vf.end() == false; Vf++)
  1138. {
  1139. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1140. continue;
  1141. break;
  1142. }
  1143. // Does not really matter here.. we are going to fail out below
  1144. if (Vf.end() != true)
  1145. {
  1146. // If this fails to get a file name we will bomb out below.
  1147. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1148. if (_error->PendingError() == true)
  1149. return;
  1150. // Generate the final file name as: package_version_arch.foo
  1151. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1152. QuoteString(Version.VerStr(),"_:") + '_' +
  1153. QuoteString(Version.Arch(),"_:.") +
  1154. "." + flExtension(Parse.FileName());
  1155. }
  1156. // check if we have one trusted source for the package. if so, switch
  1157. // to "TrustedOnly" mode
  1158. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
  1159. {
  1160. pkgIndexFile *Index;
  1161. if (Sources->FindIndex(i.File(),Index) == false)
  1162. continue;
  1163. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1164. {
  1165. std::cerr << "Checking index: " << Index->Describe()
  1166. << "(Trusted=" << Index->IsTrusted() << ")\n";
  1167. }
  1168. if (Index->IsTrusted()) {
  1169. Trusted = true;
  1170. break;
  1171. }
  1172. }
  1173. // "allow-unauthenticated" restores apts old fetching behaviour
  1174. // that means that e.g. unauthenticated file:// uris are higher
  1175. // priority than authenticated http:// uris
  1176. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  1177. Trusted = false;
  1178. // Select a source
  1179. if (QueueNext() == false && _error->PendingError() == false)
  1180. _error->Error(_("I wasn't able to locate file for the %s package. "
  1181. "This might mean you need to manually fix this package."),
  1182. Version.ParentPkg().Name());
  1183. }
  1184. /*}}}*/
  1185. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1186. // ---------------------------------------------------------------------
  1187. /* This queues the next available file version for download. It checks if
  1188. the archive is already available in the cache and stashs the MD5 for
  1189. checking later. */
  1190. bool pkgAcqArchive::QueueNext()
  1191. {
  1192. for (; Vf.end() == false; Vf++)
  1193. {
  1194. // Ignore not source sources
  1195. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1196. continue;
  1197. // Try to cross match against the source list
  1198. pkgIndexFile *Index;
  1199. if (Sources->FindIndex(Vf.File(),Index) == false)
  1200. continue;
  1201. // only try to get a trusted package from another source if that source
  1202. // is also trusted
  1203. if(Trusted && !Index->IsTrusted())
  1204. continue;
  1205. // Grab the text package record
  1206. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1207. if (_error->PendingError() == true)
  1208. return false;
  1209. string PkgFile = Parse.FileName();
  1210. if(Parse.SHA256Hash() != "")
  1211. ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
  1212. else if (Parse.SHA1Hash() != "")
  1213. ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
  1214. else
  1215. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1216. if (PkgFile.empty() == true)
  1217. return _error->Error(_("The package index files are corrupted. No Filename: "
  1218. "field for package %s."),
  1219. Version.ParentPkg().Name());
  1220. Desc.URI = Index->ArchiveURI(PkgFile);
  1221. Desc.Description = Index->ArchiveInfo(Version);
  1222. Desc.Owner = this;
  1223. Desc.ShortDesc = Version.ParentPkg().Name();
  1224. // See if we already have the file. (Legacy filenames)
  1225. FileSize = Version->Size;
  1226. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1227. struct stat Buf;
  1228. if (stat(FinalFile.c_str(),&Buf) == 0)
  1229. {
  1230. // Make sure the size matches
  1231. if ((unsigned)Buf.st_size == Version->Size)
  1232. {
  1233. Complete = true;
  1234. Local = true;
  1235. Status = StatDone;
  1236. StoreFilename = DestFile = FinalFile;
  1237. return true;
  1238. }
  1239. /* Hmm, we have a file and its size does not match, this means it is
  1240. an old style mismatched arch */
  1241. unlink(FinalFile.c_str());
  1242. }
  1243. // Check it again using the new style output filenames
  1244. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1245. if (stat(FinalFile.c_str(),&Buf) == 0)
  1246. {
  1247. // Make sure the size matches
  1248. if ((unsigned)Buf.st_size == Version->Size)
  1249. {
  1250. Complete = true;
  1251. Local = true;
  1252. Status = StatDone;
  1253. StoreFilename = DestFile = FinalFile;
  1254. return true;
  1255. }
  1256. /* Hmm, we have a file and its size does not match, this shouldnt
  1257. happen.. */
  1258. unlink(FinalFile.c_str());
  1259. }
  1260. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1261. // Check the destination file
  1262. if (stat(DestFile.c_str(),&Buf) == 0)
  1263. {
  1264. // Hmm, the partial file is too big, erase it
  1265. if ((unsigned)Buf.st_size > Version->Size)
  1266. unlink(DestFile.c_str());
  1267. else
  1268. PartialSize = Buf.st_size;
  1269. }
  1270. // Create the item
  1271. Local = false;
  1272. Desc.URI = Index->ArchiveURI(PkgFile);
  1273. Desc.Description = Index->ArchiveInfo(Version);
  1274. Desc.Owner = this;
  1275. Desc.ShortDesc = Version.ParentPkg().Name();
  1276. QueueURI(Desc);
  1277. Vf++;
  1278. return true;
  1279. }
  1280. return false;
  1281. }
  1282. /*}}}*/
  1283. // AcqArchive::Done - Finished fetching /*{{{*/
  1284. // ---------------------------------------------------------------------
  1285. /* */
  1286. void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
  1287. pkgAcquire::MethodConfig *Cfg)
  1288. {
  1289. Item::Done(Message,Size,CalcHash,Cfg);
  1290. // Check the size
  1291. if (Size != Version->Size)
  1292. {
  1293. Status = StatError;
  1294. ErrorText = _("Size mismatch");
  1295. return;
  1296. }
  1297. // Check the hash
  1298. if(ExpectedHash.toStr() != CalcHash)
  1299. {
  1300. Status = StatError;
  1301. ErrorText = _("Hash Sum mismatch");
  1302. if(FileExists(DestFile))
  1303. Rename(DestFile,DestFile + ".FAILED");
  1304. return;
  1305. }
  1306. // Grab the output filename
  1307. string FileName = LookupTag(Message,"Filename");
  1308. if (FileName.empty() == true)
  1309. {
  1310. Status = StatError;
  1311. ErrorText = "Method gave a blank filename";
  1312. return;
  1313. }
  1314. Complete = true;
  1315. // Reference filename
  1316. if (FileName != DestFile)
  1317. {
  1318. StoreFilename = DestFile = FileName;
  1319. Local = true;
  1320. return;
  1321. }
  1322. // Done, move it into position
  1323. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  1324. FinalFile += flNotDir(StoreFilename);
  1325. Rename(DestFile,FinalFile);
  1326. StoreFilename = DestFile = FinalFile;
  1327. Complete = true;
  1328. }
  1329. /*}}}*/
  1330. // AcqArchive::Failed - Failure handler /*{{{*/
  1331. // ---------------------------------------------------------------------
  1332. /* Here we try other sources */
  1333. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1334. {
  1335. ErrorText = LookupTag(Message,"Message");
  1336. /* We don't really want to retry on failed media swaps, this prevents
  1337. that. An interesting observation is that permanent failures are not
  1338. recorded. */
  1339. if (Cnf->Removable == true &&
  1340. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1341. {
  1342. // Vf = Version.FileList();
  1343. while (Vf.end() == false) Vf++;
  1344. StoreFilename = string();
  1345. Item::Failed(Message,Cnf);
  1346. return;
  1347. }
  1348. if (QueueNext() == false)
  1349. {
  1350. // This is the retry counter
  1351. if (Retries != 0 &&
  1352. Cnf->LocalOnly == false &&
  1353. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1354. {
  1355. Retries--;
  1356. Vf = Version.FileList();
  1357. if (QueueNext() == true)
  1358. return;
  1359. }
  1360. StoreFilename = string();
  1361. Item::Failed(Message,Cnf);
  1362. }
  1363. }
  1364. /*}}}*/
  1365. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  1366. // ---------------------------------------------------------------------
  1367. bool pkgAcqArchive::IsTrusted()
  1368. {
  1369. return Trusted;
  1370. }
  1371. /*}}}*/
  1372. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  1373. // ---------------------------------------------------------------------
  1374. /* */
  1375. void pkgAcqArchive::Finished()
  1376. {
  1377. if (Status == pkgAcquire::Item::StatDone &&
  1378. Complete == true)
  1379. return;
  1380. StoreFilename = string();
  1381. }
  1382. /*}}}*/
  1383. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  1384. // ---------------------------------------------------------------------
  1385. /* The file is added to the queue */
  1386. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
  1387. unsigned long Size,string Dsc,string ShortDesc,
  1388. const string &DestDir, const string &DestFilename) :
  1389. Item(Owner), ExpectedHash(Hash)
  1390. {
  1391. Retries = _config->FindI("Acquire::Retries",0);
  1392. if(!DestFilename.empty())
  1393. DestFile = DestFilename;
  1394. else if(!DestDir.empty())
  1395. DestFile = DestDir + "/" + flNotDir(URI);
  1396. else
  1397. DestFile = flNotDir(URI);
  1398. // Create the item
  1399. Desc.URI = URI;
  1400. Desc.Description = Dsc;
  1401. Desc.Owner = this;
  1402. // Set the short description to the archive component
  1403. Desc.ShortDesc = ShortDesc;
  1404. // Get the transfer sizes
  1405. FileSize = Size;
  1406. struct stat Buf;
  1407. if (stat(DestFile.c_str(),&Buf) == 0)
  1408. {
  1409. // Hmm, the partial file is too big, erase it
  1410. if ((unsigned)Buf.st_size > Size)
  1411. unlink(DestFile.c_str());
  1412. else
  1413. PartialSize = Buf.st_size;
  1414. }
  1415. QueueURI(Desc);
  1416. }
  1417. /*}}}*/
  1418. // AcqFile::Done - Item downloaded OK /*{{{*/
  1419. // ---------------------------------------------------------------------
  1420. /* */
  1421. void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
  1422. pkgAcquire::MethodConfig *Cnf)
  1423. {
  1424. Item::Done(Message,Size,CalcHash,Cnf);
  1425. // Check the hash
  1426. if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
  1427. {
  1428. Status = StatError;
  1429. ErrorText = "Hash Sum mismatch";
  1430. Rename(DestFile,DestFile + ".FAILED");
  1431. return;
  1432. }
  1433. string FileName = LookupTag(Message,"Filename");
  1434. if (FileName.empty() == true)
  1435. {
  1436. Status = StatError;
  1437. ErrorText = "Method gave a blank filename";
  1438. return;
  1439. }
  1440. Complete = true;
  1441. // The files timestamp matches
  1442. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1443. return;
  1444. // We have to copy it into place
  1445. if (FileName != DestFile)
  1446. {
  1447. Local = true;
  1448. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1449. Cnf->Removable == true)
  1450. {
  1451. Desc.URI = "copy:" + FileName;
  1452. QueueURI(Desc);
  1453. return;
  1454. }
  1455. // Erase the file if it is a symlink so we can overwrite it
  1456. struct stat St;
  1457. if (lstat(DestFile.c_str(),&St) == 0)
  1458. {
  1459. if (S_ISLNK(St.st_mode) != 0)
  1460. unlink(DestFile.c_str());
  1461. }
  1462. // Symlink the file
  1463. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  1464. {
  1465. ErrorText = "Link to " + DestFile + " failure ";
  1466. Status = StatError;
  1467. Complete = false;
  1468. }
  1469. }
  1470. }
  1471. /*}}}*/
  1472. // AcqFile::Failed - Failure handler /*{{{*/
  1473. // ---------------------------------------------------------------------
  1474. /* Here we try other sources */
  1475. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1476. {
  1477. ErrorText = LookupTag(Message,"Message");
  1478. // This is the retry counter
  1479. if (Retries != 0 &&
  1480. Cnf->LocalOnly == false &&
  1481. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1482. {
  1483. Retries--;
  1484. QueueURI(Desc);
  1485. return;
  1486. }
  1487. Item::Failed(Message,Cnf);
  1488. }
  1489. /*}}}*/