acquire-item.cc 47 KB

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