acquire-item.cc 49 KB

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