acquire-item.cc 51 KB

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