acquire-item.cc 49 KB

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