acquire-item.cc 48 KB

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