acquire-item.cc 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437
  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 <config.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/aptconfiguration.h>
  17. #include <apt-pkg/sourcelist.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/fileutl.h>
  21. #include <apt-pkg/sha1.h>
  22. #include <apt-pkg/tagfile.h>
  23. #include <apt-pkg/indexrecords.h>
  24. #include <apt-pkg/acquire.h>
  25. #include <apt-pkg/hashes.h>
  26. #include <apt-pkg/indexfile.h>
  27. #include <apt-pkg/pkgcache.h>
  28. #include <apt-pkg/cacheiterators.h>
  29. #include <apt-pkg/pkgrecords.h>
  30. #include <stddef.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <iostream>
  34. #include <vector>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <errno.h>
  38. #include <string>
  39. #include <sstream>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <apti18n.h>
  43. /*}}}*/
  44. using namespace std;
  45. static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  46. {
  47. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  48. return;
  49. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  50. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  51. std::cerr << "\t- " << hs->toStr() << std::endl;
  52. std::cerr << " Actual Hash: " << std::endl;
  53. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  54. std::cerr << "\t- " << hs->toStr() << std::endl;
  55. }
  56. /*}}}*/
  57. // Acquire::Item::Item - Constructor /*{{{*/
  58. pkgAcquire::Item::Item(pkgAcquire *Owner, HashStringList const &ExpectedHashes) :
  59. Owner(Owner), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
  60. Local(false), QueueCounter(0), ExpectedAdditionalItems(0),
  61. ExpectedHashes(ExpectedHashes)
  62. {
  63. Owner->Add(this);
  64. Status = StatIdle;
  65. }
  66. /*}}}*/
  67. // Acquire::Item::~Item - Destructor /*{{{*/
  68. // ---------------------------------------------------------------------
  69. /* */
  70. pkgAcquire::Item::~Item()
  71. {
  72. Owner->Remove(this);
  73. }
  74. /*}}}*/
  75. // Acquire::Item::Failed - Item failed to download /*{{{*/
  76. // ---------------------------------------------------------------------
  77. /* We return to an idle state if there are still other queues that could
  78. fetch this object */
  79. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  80. {
  81. Status = StatIdle;
  82. ErrorText = LookupTag(Message,"Message");
  83. UsedMirror = LookupTag(Message,"UsedMirror");
  84. if (QueueCounter <= 1)
  85. {
  86. /* This indicates that the file is not available right now but might
  87. be sometime later. If we do a retry cycle then this should be
  88. retried [CDROMs] */
  89. if (Cnf->LocalOnly == true &&
  90. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  91. {
  92. Status = StatIdle;
  93. Dequeue();
  94. return;
  95. }
  96. Status = StatError;
  97. Dequeue();
  98. }
  99. // report mirror failure back to LP if we actually use a mirror
  100. string FailReason = LookupTag(Message, "FailReason");
  101. if(FailReason.size() != 0)
  102. ReportMirrorFailure(FailReason);
  103. else
  104. ReportMirrorFailure(ErrorText);
  105. }
  106. /*}}}*/
  107. // Acquire::Item::Start - Item has begun to download /*{{{*/
  108. // ---------------------------------------------------------------------
  109. /* Stash status and the file size. Note that setting Complete means
  110. sub-phases of the acquire process such as decompresion are operating */
  111. void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
  112. {
  113. Status = StatFetching;
  114. if (FileSize == 0 && Complete == false)
  115. FileSize = Size;
  116. }
  117. /*}}}*/
  118. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  119. // ---------------------------------------------------------------------
  120. /* */
  121. void pkgAcquire::Item::Done(string Message,unsigned long long Size,HashStringList const &/*Hash*/,
  122. pkgAcquire::MethodConfig * /*Cnf*/)
  123. {
  124. // We just downloaded something..
  125. string FileName = LookupTag(Message,"Filename");
  126. UsedMirror = LookupTag(Message,"UsedMirror");
  127. if (Complete == false && !Local && FileName == DestFile)
  128. {
  129. if (Owner->Log != 0)
  130. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  131. }
  132. if (FileSize == 0)
  133. FileSize= Size;
  134. Status = StatDone;
  135. ErrorText = string();
  136. Owner->Dequeue(this);
  137. }
  138. /*}}}*/
  139. // Acquire::Item::Rename - Rename a file /*{{{*/
  140. // ---------------------------------------------------------------------
  141. /* This helper function is used by a lot of item methods as their final
  142. step */
  143. void pkgAcquire::Item::Rename(string From,string To)
  144. {
  145. if (rename(From.c_str(),To.c_str()) != 0)
  146. {
  147. char S[300];
  148. snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
  149. From.c_str(),To.c_str());
  150. Status = StatError;
  151. ErrorText = S;
  152. }
  153. }
  154. /*}}}*/
  155. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  156. {
  157. if(FileExists(DestFile))
  158. Rename(DestFile, DestFile + ".FAILED");
  159. switch (error)
  160. {
  161. case HashSumMismatch:
  162. ErrorText = _("Hash Sum mismatch");
  163. Status = StatAuthError;
  164. ReportMirrorFailure("HashChecksumFailure");
  165. break;
  166. case SizeMismatch:
  167. ErrorText = _("Size mismatch");
  168. Status = StatAuthError;
  169. ReportMirrorFailure("SizeFailure");
  170. break;
  171. case InvalidFormat:
  172. ErrorText = _("Invalid file format");
  173. Status = StatError;
  174. // do not report as usually its not the mirrors fault, but Portal/Proxy
  175. break;
  176. }
  177. return false;
  178. }
  179. /*}}}*/
  180. // Acquire::Item::ReportMirrorFailure /*{{{*/
  181. // ---------------------------------------------------------------------
  182. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  183. {
  184. // we only act if a mirror was used at all
  185. if(UsedMirror.empty())
  186. return;
  187. #if 0
  188. std::cerr << "\nReportMirrorFailure: "
  189. << UsedMirror
  190. << " Uri: " << DescURI()
  191. << " FailCode: "
  192. << FailCode << std::endl;
  193. #endif
  194. const char *Args[40];
  195. unsigned int i = 0;
  196. string report = _config->Find("Methods::Mirror::ProblemReporting",
  197. "/usr/lib/apt/apt-report-mirror-failure");
  198. if(!FileExists(report))
  199. return;
  200. Args[i++] = report.c_str();
  201. Args[i++] = UsedMirror.c_str();
  202. Args[i++] = DescURI().c_str();
  203. Args[i++] = FailCode.c_str();
  204. Args[i++] = NULL;
  205. pid_t pid = ExecFork();
  206. if(pid < 0)
  207. {
  208. _error->Error("ReportMirrorFailure Fork failed");
  209. return;
  210. }
  211. else if(pid == 0)
  212. {
  213. execvp(Args[0], (char**)Args);
  214. std::cerr << "Could not exec " << Args[0] << std::endl;
  215. _exit(100);
  216. }
  217. if(!ExecWait(pid, "report-mirror-failure"))
  218. {
  219. _error->Warning("Couldn't report problem to '%s'",
  220. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  221. }
  222. }
  223. /*}}}*/
  224. // AcqSubIndex::AcqSubIndex - Constructor /*{{{*/
  225. // ---------------------------------------------------------------------
  226. /* Get a sub-index file based on checksums from a 'master' file and
  227. possibly query additional files */
  228. pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI,
  229. string const &URIDesc, string const &ShortDesc,
  230. HashStringList const &ExpectedHashes)
  231. : Item(Owner, ExpectedHashes)
  232. {
  233. /* XXX: Beware: Currently this class does nothing (of value) anymore ! */
  234. Debug = _config->FindB("Debug::pkgAcquire::SubIndex",false);
  235. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  236. DestFile += URItoFileName(URI);
  237. Desc.URI = URI;
  238. Desc.Description = URIDesc;
  239. Desc.Owner = this;
  240. Desc.ShortDesc = ShortDesc;
  241. QueueURI(Desc);
  242. if(Debug)
  243. std::clog << "pkgAcqSubIndex: " << Desc.URI << std::endl;
  244. }
  245. /*}}}*/
  246. // AcqSubIndex::Custom600Headers - Insert custom request headers /*{{{*/
  247. // ---------------------------------------------------------------------
  248. /* The only header we use is the last-modified header. */
  249. string pkgAcqSubIndex::Custom600Headers() const
  250. {
  251. string Final = _config->FindDir("Dir::State::lists");
  252. Final += URItoFileName(Desc.URI);
  253. struct stat Buf;
  254. if (stat(Final.c_str(),&Buf) != 0)
  255. return "\nIndex-File: true\nFail-Ignore: true\n";
  256. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  257. }
  258. /*}}}*/
  259. void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  260. {
  261. if(Debug)
  262. std::clog << "pkgAcqSubIndex failed: " << Desc.URI << " with " << Message << std::endl;
  263. Complete = false;
  264. Status = StatDone;
  265. Dequeue();
  266. // No good Index is provided
  267. }
  268. /*}}}*/
  269. void pkgAcqSubIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  270. pkgAcquire::MethodConfig *Cnf)
  271. {
  272. if(Debug)
  273. std::clog << "pkgAcqSubIndex::Done(): " << Desc.URI << std::endl;
  274. string FileName = LookupTag(Message,"Filename");
  275. if (FileName.empty() == true)
  276. {
  277. Status = StatError;
  278. ErrorText = "Method gave a blank filename";
  279. return;
  280. }
  281. if (FileName != DestFile)
  282. {
  283. Local = true;
  284. Desc.URI = "copy:" + FileName;
  285. QueueURI(Desc);
  286. return;
  287. }
  288. Item::Done(Message, Size, Hashes, Cnf);
  289. string FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(Desc.URI);
  290. /* Downloaded invalid transindex => Error (LP: #346386) (Closes: #627642) */
  291. indexRecords SubIndexParser;
  292. if (FileExists(DestFile) == true && !SubIndexParser.Load(DestFile)) {
  293. Status = StatError;
  294. ErrorText = SubIndexParser.ErrorText;
  295. return;
  296. }
  297. // success in downloading the index
  298. // rename the index
  299. if(Debug)
  300. std::clog << "Renaming: " << DestFile << " -> " << FinalFile << std::endl;
  301. Rename(DestFile,FinalFile);
  302. chmod(FinalFile.c_str(),0644);
  303. DestFile = FinalFile;
  304. if(ParseIndex(DestFile) == false)
  305. return Failed("", NULL);
  306. Complete = true;
  307. Status = StatDone;
  308. Dequeue();
  309. return;
  310. }
  311. /*}}}*/
  312. bool pkgAcqSubIndex::ParseIndex(string const &IndexFile) /*{{{*/
  313. {
  314. indexRecords SubIndexParser;
  315. if (FileExists(IndexFile) == false || SubIndexParser.Load(IndexFile) == false)
  316. return false;
  317. // so something with the downloaded index
  318. return true;
  319. }
  320. /*}}}*/
  321. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  322. // ---------------------------------------------------------------------
  323. /* Get the DiffIndex file first and see if there are patches available
  324. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  325. * patches. If anything goes wrong in that process, it will fall back to
  326. * the original packages file
  327. */
  328. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  329. IndexTarget const * const Target,
  330. HashStringList const &ExpectedHashes,
  331. indexRecords *MetaIndexParser)
  332. : pkgAcqBaseIndex(Owner, Target, ExpectedHashes, MetaIndexParser)
  333. {
  334. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  335. RealURI = Target->URI;
  336. Desc.Owner = this;
  337. Desc.Description = Target->Description + "/DiffIndex";
  338. Desc.ShortDesc = Target->ShortDesc;
  339. Desc.URI = Target->URI + ".diff/Index";
  340. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  341. DestFile += URItoFileName(Desc.URI);
  342. if(Debug)
  343. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  344. // look for the current package file
  345. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  346. CurrentPackagesFile += URItoFileName(RealURI);
  347. // FIXME: this file:/ check is a hack to prevent fetching
  348. // from local sources. this is really silly, and
  349. // should be fixed cleanly as soon as possible
  350. if(!FileExists(CurrentPackagesFile) ||
  351. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  352. {
  353. // we don't have a pkg file or we don't want to queue
  354. if(Debug)
  355. std::clog << "No index file, local or canceld by user" << std::endl;
  356. Failed("", NULL);
  357. return;
  358. }
  359. if(Debug)
  360. std::clog << "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
  361. << CurrentPackagesFile << std::endl;
  362. QueueURI(Desc);
  363. }
  364. /*}}}*/
  365. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  366. // ---------------------------------------------------------------------
  367. /* The only header we use is the last-modified header. */
  368. string pkgAcqDiffIndex::Custom600Headers() const
  369. {
  370. string Final = _config->FindDir("Dir::State::lists");
  371. Final += URItoFileName(Desc.URI);
  372. if(Debug)
  373. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  374. struct stat Buf;
  375. if (stat(Final.c_str(),&Buf) != 0)
  376. return "\nIndex-File: true";
  377. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  378. }
  379. /*}}}*/
  380. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  381. {
  382. if(Debug)
  383. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  384. << std::endl;
  385. pkgTagSection Tags;
  386. string ServerSha1;
  387. vector<DiffInfo> available_patches;
  388. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  389. pkgTagFile TF(&Fd);
  390. if (_error->PendingError() == true)
  391. return false;
  392. if(TF.Step(Tags) == true)
  393. {
  394. bool found = false;
  395. DiffInfo d;
  396. string size;
  397. string const tmp = Tags.FindS("SHA1-Current");
  398. std::stringstream ss(tmp);
  399. ss >> ServerSha1 >> size;
  400. unsigned long const ServerSize = atol(size.c_str());
  401. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  402. SHA1Summation SHA1;
  403. SHA1.AddFD(fd);
  404. string const local_sha1 = SHA1.Result();
  405. if(local_sha1 == ServerSha1)
  406. {
  407. // we have the same sha1 as the server so we are done here
  408. if(Debug)
  409. std::clog << "Package file is up-to-date" << std::endl;
  410. // list cleanup needs to know that this file as well as the already
  411. // present index is ours, so we create an empty diff to save it for us
  412. new pkgAcqIndexDiffs(Owner, Target, ExpectedHashes, MetaIndexParser,
  413. ServerSha1, available_patches);
  414. return true;
  415. }
  416. else
  417. {
  418. if(Debug)
  419. std::clog << "SHA1-Current: " << ServerSha1 << " and we start at "<< fd.Name() << " " << fd.Size() << " " << local_sha1 << std::endl;
  420. // check the historie and see what patches we need
  421. string const history = Tags.FindS("SHA1-History");
  422. std::stringstream hist(history);
  423. while(hist >> d.sha1 >> size >> d.file)
  424. {
  425. // read until the first match is found
  426. // from that point on, we probably need all diffs
  427. if(d.sha1 == local_sha1)
  428. found=true;
  429. else if (found == false)
  430. continue;
  431. if(Debug)
  432. std::clog << "Need to get diff: " << d.file << std::endl;
  433. available_patches.push_back(d);
  434. }
  435. if (available_patches.empty() == false)
  436. {
  437. // patching with too many files is rather slow compared to a fast download
  438. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  439. if (fileLimit != 0 && fileLimit < available_patches.size())
  440. {
  441. if (Debug)
  442. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  443. << ") so fallback to complete download" << std::endl;
  444. return false;
  445. }
  446. // see if the patches are too big
  447. found = false; // it was true and it will be true again at the end
  448. d = *available_patches.begin();
  449. string const firstPatch = d.file;
  450. unsigned long patchesSize = 0;
  451. std::stringstream patches(Tags.FindS("SHA1-Patches"));
  452. while(patches >> d.sha1 >> size >> d.file)
  453. {
  454. if (firstPatch == d.file)
  455. found = true;
  456. else if (found == false)
  457. continue;
  458. patchesSize += atol(size.c_str());
  459. }
  460. unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  461. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  462. {
  463. if (Debug)
  464. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  465. << ") so fallback to complete download" << std::endl;
  466. return false;
  467. }
  468. }
  469. }
  470. // we have something, queue the next diff
  471. if(found)
  472. {
  473. // queue the diffs
  474. string::size_type const last_space = Description.rfind(" ");
  475. if(last_space != string::npos)
  476. Description.erase(last_space, Description.size()-last_space);
  477. /* decide if we should download patches one by one or in one go:
  478. The first is good if the server merges patches, but many don't so client
  479. based merging can be attempt in which case the second is better.
  480. "bad things" will happen if patches are merged on the server,
  481. but client side merging is attempt as well */
  482. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  483. if (pdiff_merge == true)
  484. {
  485. // reprepro adds this flag if it has merged patches on the server
  486. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  487. pdiff_merge = (precedence != "merged");
  488. }
  489. if (pdiff_merge == false)
  490. {
  491. new pkgAcqIndexDiffs(Owner, Target, ExpectedHashes, MetaIndexParser,
  492. ServerSha1, available_patches);
  493. }
  494. else
  495. {
  496. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  497. for(size_t i = 0; i < available_patches.size(); ++i)
  498. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, Target,
  499. ExpectedHashes,
  500. MetaIndexParser,
  501. available_patches[i],
  502. diffs);
  503. }
  504. Complete = false;
  505. Status = StatDone;
  506. Dequeue();
  507. return true;
  508. }
  509. }
  510. // Nothing found, report and return false
  511. // Failing here is ok, if we return false later, the full
  512. // IndexFile is queued
  513. if(Debug)
  514. std::clog << "Can't find a patch in the index file" << std::endl;
  515. return false;
  516. }
  517. /*}}}*/
  518. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  519. {
  520. if(Debug)
  521. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  522. << "Falling back to normal index file acquire" << std::endl;
  523. new pkgAcqIndex(Owner, Target, ExpectedHashes, MetaIndexParser);
  524. Complete = false;
  525. Status = StatDone;
  526. Dequeue();
  527. }
  528. /*}}}*/
  529. void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  530. pkgAcquire::MethodConfig *Cnf)
  531. {
  532. if(Debug)
  533. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  534. Item::Done(Message, Size, Hashes, Cnf);
  535. string FinalFile;
  536. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  537. // success in downloading the index
  538. // rename the index
  539. FinalFile += string(".IndexDiff");
  540. if(Debug)
  541. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  542. << std::endl;
  543. Rename(DestFile,FinalFile);
  544. chmod(FinalFile.c_str(),0644);
  545. DestFile = FinalFile;
  546. if(!ParseDiffIndex(DestFile))
  547. return Failed("", NULL);
  548. Complete = true;
  549. Status = StatDone;
  550. Dequeue();
  551. return;
  552. }
  553. /*}}}*/
  554. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  555. // ---------------------------------------------------------------------
  556. /* The package diff is added to the queue. one object is constructed
  557. * for each diff and the index
  558. */
  559. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  560. struct IndexTarget const * const Target,
  561. HashStringList const &ExpectedHashes,
  562. indexRecords *MetaIndexParser,
  563. string ServerSha1,
  564. vector<DiffInfo> diffs)
  565. : pkgAcqBaseIndex(Owner, Target, ExpectedHashes, MetaIndexParser),
  566. available_patches(diffs), ServerSha1(ServerSha1)
  567. {
  568. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  569. DestFile += URItoFileName(Target->URI);
  570. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  571. RealURI = Target->URI;
  572. Desc.Owner = this;
  573. Description = Target->Description;
  574. Desc.ShortDesc = Target->ShortDesc;
  575. if(available_patches.empty() == true)
  576. {
  577. // we are done (yeah!)
  578. Finish(true);
  579. }
  580. else
  581. {
  582. // get the next diff
  583. State = StateFetchDiff;
  584. QueueNextDiff();
  585. }
  586. }
  587. /*}}}*/
  588. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  589. {
  590. if(Debug)
  591. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  592. << "Falling back to normal index file acquire" << std::endl;
  593. new pkgAcqIndex(Owner, Target, ExpectedHashes, MetaIndexParser);
  594. Finish();
  595. }
  596. /*}}}*/
  597. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  598. void pkgAcqIndexDiffs::Finish(bool allDone)
  599. {
  600. // we restore the original name, this is required, otherwise
  601. // the file will be cleaned
  602. if(allDone)
  603. {
  604. DestFile = _config->FindDir("Dir::State::lists");
  605. DestFile += URItoFileName(RealURI);
  606. if(HashSums().usable() && !HashSums().VerifyFile(DestFile))
  607. {
  608. RenameOnError(HashSumMismatch);
  609. Dequeue();
  610. return;
  611. }
  612. // this is for the "real" finish
  613. Complete = true;
  614. Status = StatDone;
  615. Dequeue();
  616. if(Debug)
  617. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  618. return;
  619. }
  620. if(Debug)
  621. std::clog << "Finishing: " << Desc.URI << std::endl;
  622. Complete = false;
  623. Status = StatDone;
  624. Dequeue();
  625. return;
  626. }
  627. /*}}}*/
  628. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  629. {
  630. // calc sha1 of the just patched file
  631. string FinalFile = _config->FindDir("Dir::State::lists");
  632. FinalFile += URItoFileName(RealURI);
  633. FileFd fd(FinalFile, FileFd::ReadOnly);
  634. SHA1Summation SHA1;
  635. SHA1.AddFD(fd);
  636. string local_sha1 = string(SHA1.Result());
  637. if(Debug)
  638. std::clog << "QueueNextDiff: "
  639. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  640. // final file reached before all patches are applied
  641. if(local_sha1 == ServerSha1)
  642. {
  643. Finish(true);
  644. return true;
  645. }
  646. // remove all patches until the next matching patch is found
  647. // this requires the Index file to be ordered
  648. for(vector<DiffInfo>::iterator I=available_patches.begin();
  649. available_patches.empty() == false &&
  650. I != available_patches.end() &&
  651. I->sha1 != local_sha1;
  652. ++I)
  653. {
  654. available_patches.erase(I);
  655. }
  656. // error checking and falling back if no patch was found
  657. if(available_patches.empty() == true)
  658. {
  659. Failed("", NULL);
  660. return false;
  661. }
  662. // queue the right diff
  663. Desc.URI = RealURI + ".diff/" + available_patches[0].file + ".gz";
  664. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  665. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  666. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  667. if(Debug)
  668. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  669. QueueURI(Desc);
  670. return true;
  671. }
  672. /*}}}*/
  673. void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size, HashStringList const &Hashes, /*{{{*/
  674. pkgAcquire::MethodConfig *Cnf)
  675. {
  676. if(Debug)
  677. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  678. Item::Done(Message, Size, Hashes, Cnf);
  679. string FinalFile;
  680. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  681. // success in downloading a diff, enter ApplyDiff state
  682. if(State == StateFetchDiff)
  683. {
  684. // rred excepts the patch as $FinalFile.ed
  685. Rename(DestFile,FinalFile+".ed");
  686. if(Debug)
  687. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  688. State = StateApplyDiff;
  689. Local = true;
  690. Desc.URI = "rred:" + FinalFile;
  691. QueueURI(Desc);
  692. Mode = "rred";
  693. return;
  694. }
  695. // success in download/apply a diff, queue next (if needed)
  696. if(State == StateApplyDiff)
  697. {
  698. // remove the just applied patch
  699. available_patches.erase(available_patches.begin());
  700. unlink((FinalFile + ".ed").c_str());
  701. // move into place
  702. if(Debug)
  703. {
  704. std::clog << "Moving patched file in place: " << std::endl
  705. << DestFile << " -> " << FinalFile << std::endl;
  706. }
  707. Rename(DestFile,FinalFile);
  708. chmod(FinalFile.c_str(),0644);
  709. // see if there is more to download
  710. if(available_patches.empty() == false) {
  711. new pkgAcqIndexDiffs(Owner, Target,
  712. ExpectedHashes, MetaIndexParser,
  713. ServerSha1, available_patches);
  714. return Finish();
  715. } else
  716. return Finish(true);
  717. }
  718. }
  719. /*}}}*/
  720. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  721. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
  722. struct IndexTarget const * const Target,
  723. HashStringList const &ExpectedHashes,
  724. indexRecords *MetaIndexParser,
  725. DiffInfo const &patch,
  726. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  727. : pkgAcqBaseIndex(Owner, Target, ExpectedHashes, MetaIndexParser),
  728. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  729. {
  730. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  731. DestFile += URItoFileName(Target->URI);
  732. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  733. RealURI = Target->URI;
  734. Desc.Owner = this;
  735. Description = Target->Description;
  736. Desc.ShortDesc = Target->ShortDesc;
  737. Desc.URI = RealURI + ".diff/" + patch.file + ".gz";
  738. Desc.Description = Description + " " + patch.file + string(".pdiff");
  739. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  740. DestFile += URItoFileName(RealURI + ".diff/" + patch.file);
  741. if(Debug)
  742. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  743. QueueURI(Desc);
  744. }
  745. /*}}}*/
  746. void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  747. {
  748. if(Debug)
  749. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  750. Complete = false;
  751. Status = StatDone;
  752. Dequeue();
  753. // check if we are the first to fail, otherwise we are done here
  754. State = StateDoneDiff;
  755. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  756. I != allPatches->end(); ++I)
  757. if ((*I)->State == StateErrorDiff)
  758. return;
  759. // first failure means we should fallback
  760. State = StateErrorDiff;
  761. std::clog << "Falling back to normal index file acquire" << std::endl;
  762. new pkgAcqIndex(Owner, Target, ExpectedHashes, MetaIndexParser);
  763. }
  764. /*}}}*/
  765. void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  766. pkgAcquire::MethodConfig *Cnf)
  767. {
  768. if(Debug)
  769. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  770. Item::Done(Message,Size,Hashes,Cnf);
  771. string const FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  772. if (State == StateFetchDiff)
  773. {
  774. // rred expects the patch as $FinalFile.ed.$patchname.gz
  775. Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
  776. // check if this is the last completed diff
  777. State = StateDoneDiff;
  778. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  779. I != allPatches->end(); ++I)
  780. if ((*I)->State != StateDoneDiff)
  781. {
  782. if(Debug)
  783. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  784. return;
  785. }
  786. // this is the last completed diff, so we are ready to apply now
  787. State = StateApplyDiff;
  788. if(Debug)
  789. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  790. Local = true;
  791. Desc.URI = "rred:" + FinalFile;
  792. QueueURI(Desc);
  793. Mode = "rred";
  794. return;
  795. }
  796. // success in download/apply all diffs, clean up
  797. else if (State == StateApplyDiff)
  798. {
  799. // see if we really got the expected file
  800. if(ExpectedHashes.usable() && !ExpectedHashes.VerifyFile(DestFile))
  801. {
  802. RenameOnError(HashSumMismatch);
  803. return;
  804. }
  805. // move the result into place
  806. if(Debug)
  807. std::clog << "Moving patched file in place: " << std::endl
  808. << DestFile << " -> " << FinalFile << std::endl;
  809. Rename(DestFile, FinalFile);
  810. chmod(FinalFile.c_str(), 0644);
  811. // otherwise lists cleanup will eat the file
  812. DestFile = FinalFile;
  813. // ensure the ed's are gone regardless of list-cleanup
  814. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  815. I != allPatches->end(); ++I)
  816. {
  817. std::string patch = FinalFile + ".ed." + (*I)->patch.file + ".gz";
  818. unlink(patch.c_str());
  819. }
  820. // all set and done
  821. Complete = true;
  822. if(Debug)
  823. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  824. }
  825. }
  826. /*}}}*/
  827. // AcqIndex::AcqIndex - Constructor /*{{{*/
  828. // ---------------------------------------------------------------------
  829. /* The package file is added to the queue and a second class is
  830. instantiated to fetch the revision file */
  831. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  832. string URI,string URIDesc,string ShortDesc,
  833. HashStringList const &ExpectedHash, string comprExt)
  834. : pkgAcqBaseIndex(Owner, NULL, ExpectedHash, NULL), RealURI(URI)
  835. {
  836. if(comprExt.empty() == true)
  837. {
  838. // autoselect the compression method
  839. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  840. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  841. comprExt.append(*t).append(" ");
  842. if (comprExt.empty() == false)
  843. comprExt.erase(comprExt.end()-1);
  844. }
  845. CompressionExtension = comprExt;
  846. Init(URI, URIDesc, ShortDesc);
  847. }
  848. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target,
  849. HashStringList const &ExpectedHash,
  850. indexRecords *MetaIndexParser)
  851. : pkgAcqBaseIndex(Owner, Target, ExpectedHash, MetaIndexParser),
  852. RealURI(Target->URI)
  853. {
  854. // autoselect the compression method
  855. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  856. CompressionExtension = "";
  857. if (ExpectedHashes.usable())
  858. {
  859. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  860. if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
  861. CompressionExtension.append(*t).append(" ");
  862. }
  863. else
  864. {
  865. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  866. CompressionExtension.append(*t).append(" ");
  867. }
  868. if (CompressionExtension.empty() == false)
  869. CompressionExtension.erase(CompressionExtension.end()-1);
  870. Init(Target->URI, Target->Description, Target->ShortDesc);
  871. }
  872. /*}}}*/
  873. // AcqIndex::Init - defered Constructor /*{{{*/
  874. void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &ShortDesc) {
  875. Decompression = false;
  876. Erase = false;
  877. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  878. DestFile += URItoFileName(URI);
  879. std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  880. std::string MetaKey;
  881. if (comprExt == "uncompressed")
  882. {
  883. Desc.URI = URI;
  884. if(Target)
  885. MetaKey = string(Target->MetaKey);
  886. }
  887. else
  888. {
  889. Desc.URI = URI + '.' + comprExt;
  890. if(Target)
  891. MetaKey = string(Target->MetaKey) + '.' + comprExt;
  892. }
  893. // load the filesize
  894. if(MetaIndexParser)
  895. {
  896. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  897. if(Record)
  898. FileSize = Record->Size;
  899. InitByHashIfNeeded(MetaKey);
  900. }
  901. Desc.Description = URIDesc;
  902. Desc.Owner = this;
  903. Desc.ShortDesc = ShortDesc;
  904. QueueURI(Desc);
  905. }
  906. /*}}}*/
  907. // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
  908. // ---------------------------------------------------------------------
  909. /* */
  910. void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
  911. {
  912. // TODO:
  913. // - (maybe?) add support for by-hash into the sources.list as flag
  914. // - make apt-ftparchive generate the hashes (and expire?)
  915. std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
  916. if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
  917. _config->FindB(HostKnob, false) == true ||
  918. MetaIndexParser->GetSupportsAcquireByHash())
  919. {
  920. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  921. if(Record)
  922. {
  923. // FIXME: should we really use the best hash here? or a fixed one?
  924. const HashString *TargetHash = Record->Hashes.find("");
  925. std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  926. size_t trailing_slash = Desc.URI.find_last_of("/");
  927. Desc.URI = Desc.URI.replace(
  928. trailing_slash,
  929. Desc.URI.substr(trailing_slash+1).size()+1,
  930. ByHash);
  931. } else {
  932. _error->Warning(
  933. "Fetching ByHash requested but can not find record for %s",
  934. MetaKey.c_str());
  935. }
  936. }
  937. }
  938. /*}}}*/
  939. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  940. // ---------------------------------------------------------------------
  941. /* The only header we use is the last-modified header. */
  942. string pkgAcqIndex::Custom600Headers() const
  943. {
  944. string Final = _config->FindDir("Dir::State::lists");
  945. Final += URItoFileName(RealURI);
  946. if (_config->FindB("Acquire::GzipIndexes",false))
  947. Final += ".gz";
  948. string msg = "\nIndex-File: true";
  949. struct stat Buf;
  950. if (stat(Final.c_str(),&Buf) == 0)
  951. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  952. return msg;
  953. }
  954. /*}}}*/
  955. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  956. {
  957. size_t const nextExt = CompressionExtension.find(' ');
  958. if (nextExt != std::string::npos)
  959. {
  960. CompressionExtension = CompressionExtension.substr(nextExt+1);
  961. Init(RealURI, Desc.Description, Desc.ShortDesc);
  962. return;
  963. }
  964. // on decompression failure, remove bad versions in partial/
  965. if (Decompression && Erase) {
  966. string s = _config->FindDir("Dir::State::lists") + "partial/";
  967. s.append(URItoFileName(RealURI));
  968. unlink(s.c_str());
  969. }
  970. Item::Failed(Message,Cnf);
  971. }
  972. /*}}}*/
  973. // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
  974. std::string pkgAcqIndex::GetFinalFilename(std::string const &URI,
  975. std::string const &compExt)
  976. {
  977. std::string FinalFile = _config->FindDir("Dir::State::lists");
  978. FinalFile += URItoFileName(URI);
  979. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  980. FinalFile += ".gz";
  981. return FinalFile;
  982. }
  983. /*}}}*/
  984. // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
  985. void pkgAcqIndex::ReverifyAfterIMS(std::string const &FileName)
  986. {
  987. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  988. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  989. DestFile += ".gz";
  990. string FinalFile = GetFinalFilename(RealURI, compExt);
  991. Rename(FinalFile, FileName);
  992. Decompression = true;
  993. Desc.URI = "copy:" + FileName;
  994. QueueURI(Desc);
  995. }
  996. /*}}}*/
  997. // AcqIndex::Done - Finished a fetch /*{{{*/
  998. // ---------------------------------------------------------------------
  999. /* This goes through a number of states.. On the initial fetch the
  1000. method could possibly return an alternate filename which points
  1001. to the uncompressed version of the file. If this is so the file
  1002. is copied into the partial directory. In all other cases the file
  1003. is decompressed with a gzip uri. */
  1004. void pkgAcqIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes,
  1005. pkgAcquire::MethodConfig *Cfg)
  1006. {
  1007. Item::Done(Message,Size,Hashes,Cfg);
  1008. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  1009. if (Decompression == true)
  1010. {
  1011. if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
  1012. {
  1013. Desc.URI = RealURI;
  1014. RenameOnError(HashSumMismatch);
  1015. printHashSumComparision(RealURI, ExpectedHashes, Hashes);
  1016. return;
  1017. }
  1018. // FIXME: this can go away once we only ever download stuff that
  1019. // has a valid hash and we never do GET based probing
  1020. //
  1021. /* Always verify the index file for correctness (all indexes must
  1022. * have a Package field) (LP: #346386) (Closes: #627642)
  1023. */
  1024. FileFd fd(DestFile, FileFd::ReadOnlyGzip);
  1025. // Only test for correctness if the file is not empty (empty is ok)
  1026. if (fd.Size() > 0)
  1027. {
  1028. pkgTagSection sec;
  1029. pkgTagFile tag(&fd);
  1030. // all our current indexes have a field 'Package' in each section
  1031. if (_error->PendingError() == true || tag.Step(sec) == false || sec.Exists("Package") == false)
  1032. {
  1033. RenameOnError(InvalidFormat);
  1034. return;
  1035. }
  1036. }
  1037. // Done, move it into position
  1038. string FinalFile = GetFinalFilename(RealURI, compExt);
  1039. Rename(DestFile,FinalFile);
  1040. chmod(FinalFile.c_str(),0644);
  1041. /* We restore the original name to DestFile so that the clean operation
  1042. will work OK */
  1043. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1044. DestFile += URItoFileName(RealURI);
  1045. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  1046. DestFile += ".gz";
  1047. // Remove the compressed version.
  1048. if (Erase == true)
  1049. unlink(DestFile.c_str());
  1050. return;
  1051. }
  1052. Erase = false;
  1053. Complete = true;
  1054. // Handle the unzipd case
  1055. string FileName = LookupTag(Message,"Alt-Filename");
  1056. if (FileName.empty() == false)
  1057. {
  1058. Decompression = true;
  1059. Local = true;
  1060. DestFile += ".decomp";
  1061. Desc.URI = "copy:" + FileName;
  1062. QueueURI(Desc);
  1063. Mode = "copy";
  1064. return;
  1065. }
  1066. FileName = LookupTag(Message,"Filename");
  1067. if (FileName.empty() == true)
  1068. {
  1069. Status = StatError;
  1070. ErrorText = "Method gave a blank filename";
  1071. }
  1072. if (FileName == DestFile)
  1073. Erase = true;
  1074. else
  1075. Local = true;
  1076. // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
  1077. // file when its doing the indexcopy
  1078. if (RealURI.substr(0,6) == "cdrom:" &&
  1079. StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1080. return;
  1081. // The files timestamp matches, for non-local URLs reverify the local
  1082. // file, for local file, uncompress again to ensure the hashsum is still
  1083. // matching the Release file
  1084. if (!Local && StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1085. {
  1086. ReverifyAfterIMS(FileName);
  1087. return;
  1088. }
  1089. string decompProg;
  1090. // If we enable compressed indexes, queue for hash verification
  1091. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz" && !Local)
  1092. {
  1093. DestFile = _config->FindDir("Dir::State::lists");
  1094. DestFile += URItoFileName(RealURI) + ".gz";
  1095. Decompression = true;
  1096. Desc.URI = "copy:" + FileName;
  1097. QueueURI(Desc);
  1098. return;
  1099. }
  1100. // get the binary name for your used compression type
  1101. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  1102. if(decompProg.empty() == false);
  1103. else if(compExt == "uncompressed")
  1104. decompProg = "copy";
  1105. else {
  1106. _error->Error("Unsupported extension: %s", compExt.c_str());
  1107. return;
  1108. }
  1109. Decompression = true;
  1110. DestFile += ".decomp";
  1111. Desc.URI = decompProg + ":" + FileName;
  1112. QueueURI(Desc);
  1113. // FIXME: this points to a c++ string that goes out of scope
  1114. Mode = decompProg.c_str();
  1115. }
  1116. /*}}}*/
  1117. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  1118. // ---------------------------------------------------------------------
  1119. /* The Translation file is added to the queue */
  1120. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  1121. string URI,string URIDesc,string ShortDesc)
  1122. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashStringList(), "")
  1123. {
  1124. }
  1125. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner, IndexTarget const * const Target,
  1126. HashStringList const &ExpectedHashes, indexRecords *MetaIndexParser)
  1127. : pkgAcqIndex(Owner, Target, ExpectedHashes, MetaIndexParser)
  1128. {
  1129. // load the filesize
  1130. indexRecords::checkSum *Record = MetaIndexParser->Lookup(string(Target->MetaKey));
  1131. if(Record)
  1132. FileSize = Record->Size;
  1133. }
  1134. /*}}}*/
  1135. // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
  1136. // ---------------------------------------------------------------------
  1137. string pkgAcqIndexTrans::Custom600Headers() const
  1138. {
  1139. string Final = _config->FindDir("Dir::State::lists");
  1140. Final += URItoFileName(RealURI);
  1141. if (_config->FindB("Acquire::GzipIndexes",false))
  1142. Final += ".gz";
  1143. struct stat Buf;
  1144. if (stat(Final.c_str(),&Buf) != 0)
  1145. return "\nFail-Ignore: true\nIndex-File: true";
  1146. return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1147. }
  1148. /*}}}*/
  1149. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  1150. // ---------------------------------------------------------------------
  1151. /* */
  1152. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1153. {
  1154. size_t const nextExt = CompressionExtension.find(' ');
  1155. if (nextExt != std::string::npos)
  1156. {
  1157. CompressionExtension = CompressionExtension.substr(nextExt+1);
  1158. Init(RealURI, Desc.Description, Desc.ShortDesc);
  1159. Status = StatIdle;
  1160. return;
  1161. }
  1162. if (Cnf->LocalOnly == true ||
  1163. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1164. {
  1165. // Ignore this
  1166. Status = StatDone;
  1167. Complete = false;
  1168. Dequeue();
  1169. return;
  1170. }
  1171. Item::Failed(Message,Cnf);
  1172. }
  1173. /*}}}*/
  1174. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  1175. string URI,string URIDesc,string ShortDesc,
  1176. string MetaIndexURI, string MetaIndexURIDesc,
  1177. string MetaIndexShortDesc,
  1178. const vector<IndexTarget*>* IndexTargets,
  1179. indexRecords* MetaIndexParser) :
  1180. Item(Owner, HashStringList()), RealURI(URI), MetaIndexURI(MetaIndexURI),
  1181. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1182. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  1183. {
  1184. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1185. DestFile += URItoFileName(URI);
  1186. // remove any partial downloaded sig-file in partial/.
  1187. // it may confuse proxies and is too small to warrant a
  1188. // partial download anyway
  1189. unlink(DestFile.c_str());
  1190. // Create the item
  1191. Desc.Description = URIDesc;
  1192. Desc.Owner = this;
  1193. Desc.ShortDesc = ShortDesc;
  1194. Desc.URI = URI;
  1195. string Final = _config->FindDir("Dir::State::lists");
  1196. Final += URItoFileName(RealURI);
  1197. if (RealFileExists(Final) == true)
  1198. {
  1199. // File was already in place. It needs to be re-downloaded/verified
  1200. // because Release might have changed, we do give it a different
  1201. // name than DestFile because otherwise the http method will
  1202. // send If-Range requests and there are too many broken servers
  1203. // out there that do not understand them
  1204. LastGoodSig = DestFile+".reverify";
  1205. Rename(Final,LastGoodSig);
  1206. }
  1207. // we expect the indextargets + one additional Release file
  1208. ExpectedAdditionalItems = IndexTargets->size() + 1;
  1209. QueueURI(Desc);
  1210. }
  1211. /*}}}*/
  1212. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1213. {
  1214. // if the file was never queued undo file-changes done in the constructor
  1215. if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false &&
  1216. LastGoodSig.empty() == false)
  1217. {
  1218. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1219. if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
  1220. Rename(LastGoodSig, Final);
  1221. }
  1222. }
  1223. /*}}}*/
  1224. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1225. // ---------------------------------------------------------------------
  1226. /* The only header we use is the last-modified header. */
  1227. string pkgAcqMetaSig::Custom600Headers() const
  1228. {
  1229. struct stat Buf;
  1230. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  1231. return "\nIndex-File: true";
  1232. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1233. }
  1234. void pkgAcqMetaSig::Done(string Message,unsigned long long Size, HashStringList const &Hashes,
  1235. pkgAcquire::MethodConfig *Cfg)
  1236. {
  1237. Item::Done(Message, Size, Hashes, Cfg);
  1238. string FileName = LookupTag(Message,"Filename");
  1239. if (FileName.empty() == true)
  1240. {
  1241. Status = StatError;
  1242. ErrorText = "Method gave a blank filename";
  1243. return;
  1244. }
  1245. if (FileName != DestFile)
  1246. {
  1247. // We have to copy it into place
  1248. Local = true;
  1249. Desc.URI = "copy:" + FileName;
  1250. QueueURI(Desc);
  1251. return;
  1252. }
  1253. Complete = true;
  1254. // at this point pkgAcqMetaIndex takes over
  1255. ExpectedAdditionalItems = 0;
  1256. // put the last known good file back on i-m-s hit (it will
  1257. // be re-verified again)
  1258. // Else do nothing, we have the new file in DestFile then
  1259. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1260. Rename(LastGoodSig, DestFile);
  1261. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  1262. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc,
  1263. MetaIndexShortDesc, DestFile, IndexTargets,
  1264. MetaIndexParser);
  1265. }
  1266. /*}}}*/
  1267. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1268. {
  1269. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1270. // at this point pkgAcqMetaIndex takes over
  1271. ExpectedAdditionalItems = 0;
  1272. // if we get a network error we fail gracefully
  1273. if(Status == StatTransientNetworkError)
  1274. {
  1275. Item::Failed(Message,Cnf);
  1276. // move the sigfile back on transient network failures
  1277. if(FileExists(LastGoodSig))
  1278. Rename(LastGoodSig,Final);
  1279. // set the status back to , Item::Failed likes to reset it
  1280. Status = pkgAcquire::Item::StatTransientNetworkError;
  1281. return;
  1282. }
  1283. // Delete any existing sigfile when the acquire failed
  1284. unlink(Final.c_str());
  1285. // queue a pkgAcqMetaIndex with no sigfile
  1286. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1287. "", IndexTargets, MetaIndexParser);
  1288. if (Cnf->LocalOnly == true ||
  1289. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1290. {
  1291. // Ignore this
  1292. Status = StatDone;
  1293. Complete = false;
  1294. Dequeue();
  1295. return;
  1296. }
  1297. Item::Failed(Message,Cnf);
  1298. }
  1299. /*}}}*/
  1300. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1301. string URI,string URIDesc,string ShortDesc,
  1302. string SigFile,
  1303. const vector<IndexTarget*>* IndexTargets,
  1304. indexRecords* MetaIndexParser) :
  1305. Item(Owner, HashStringList()), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  1306. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  1307. {
  1308. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1309. DestFile += URItoFileName(URI);
  1310. // Create the item
  1311. Desc.Description = URIDesc;
  1312. Desc.Owner = this;
  1313. Desc.ShortDesc = ShortDesc;
  1314. Desc.URI = URI;
  1315. // we expect more item
  1316. ExpectedAdditionalItems = IndexTargets->size();
  1317. QueueURI(Desc);
  1318. }
  1319. /*}}}*/
  1320. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1321. // ---------------------------------------------------------------------
  1322. /* The only header we use is the last-modified header. */
  1323. string pkgAcqMetaIndex::Custom600Headers() const
  1324. {
  1325. string Final = _config->FindDir("Dir::State::lists");
  1326. Final += URItoFileName(RealURI);
  1327. struct stat Buf;
  1328. if (stat(Final.c_str(),&Buf) != 0)
  1329. return "\nIndex-File: true";
  1330. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1331. }
  1332. /*}}}*/
  1333. void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  1334. pkgAcquire::MethodConfig *Cfg)
  1335. {
  1336. Item::Done(Message,Size,Hashes,Cfg);
  1337. // MetaIndexes are done in two passes: one to download the
  1338. // metaindex with an appropriate method, and a second to verify it
  1339. // with the gpgv method
  1340. if (AuthPass == true)
  1341. {
  1342. AuthDone(Message);
  1343. // all cool, move Release file into place
  1344. Complete = true;
  1345. }
  1346. else
  1347. {
  1348. RetrievalDone(Message);
  1349. if (!Complete)
  1350. // Still more retrieving to do
  1351. return;
  1352. if (SigFile == "")
  1353. {
  1354. // There was no signature file, so we are finished. Download
  1355. // the indexes and do only hashsum verification if possible
  1356. MetaIndexParser->Load(DestFile);
  1357. QueueIndexes(false);
  1358. }
  1359. else
  1360. {
  1361. // FIXME: move this into pkgAcqMetaClearSig::Done on the next
  1362. // ABI break
  1363. // if we expect a ClearTextSignature (InRelase), ensure that
  1364. // this is what we get and if not fail to queue a
  1365. // Release/Release.gpg, see #346386
  1366. if (SigFile == DestFile && !StartsWithGPGClearTextSignature(DestFile))
  1367. {
  1368. Failed(Message, Cfg);
  1369. return;
  1370. }
  1371. // There was a signature file, so pass it to gpgv for
  1372. // verification
  1373. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1374. std::cerr << "Metaindex acquired, queueing gpg verification ("
  1375. << SigFile << "," << DestFile << ")\n";
  1376. AuthPass = true;
  1377. Desc.URI = "gpgv:" + SigFile;
  1378. QueueURI(Desc);
  1379. Mode = "gpgv";
  1380. return;
  1381. }
  1382. }
  1383. if (Complete == true)
  1384. {
  1385. string FinalFile = _config->FindDir("Dir::State::lists");
  1386. FinalFile += URItoFileName(RealURI);
  1387. if (SigFile == DestFile)
  1388. SigFile = FinalFile;
  1389. Rename(DestFile,FinalFile);
  1390. chmod(FinalFile.c_str(),0644);
  1391. DestFile = FinalFile;
  1392. }
  1393. }
  1394. /*}}}*/
  1395. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  1396. {
  1397. // We have just finished downloading a Release file (it is not
  1398. // verified yet)
  1399. string FileName = LookupTag(Message,"Filename");
  1400. if (FileName.empty() == true)
  1401. {
  1402. Status = StatError;
  1403. ErrorText = "Method gave a blank filename";
  1404. return;
  1405. }
  1406. if (FileName != DestFile)
  1407. {
  1408. Local = true;
  1409. Desc.URI = "copy:" + FileName;
  1410. QueueURI(Desc);
  1411. return;
  1412. }
  1413. // make sure to verify against the right file on I-M-S hit
  1414. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1415. if(IMSHit)
  1416. {
  1417. string FinalFile = _config->FindDir("Dir::State::lists");
  1418. FinalFile += URItoFileName(RealURI);
  1419. if (SigFile == DestFile)
  1420. {
  1421. SigFile = FinalFile;
  1422. // constructor of pkgAcqMetaClearSig moved it out of the way,
  1423. // now move it back in on IMS hit for the 'old' file
  1424. string const OldClearSig = DestFile + ".reverify";
  1425. if (RealFileExists(OldClearSig) == true)
  1426. Rename(OldClearSig, FinalFile);
  1427. }
  1428. DestFile = FinalFile;
  1429. }
  1430. Complete = true;
  1431. }
  1432. /*}}}*/
  1433. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  1434. {
  1435. // At this point, the gpgv method has succeeded, so there is a
  1436. // valid signature from a key in the trusted keyring. We
  1437. // perform additional verification of its contents, and use them
  1438. // to verify the indexes we are about to download
  1439. if (!MetaIndexParser->Load(DestFile))
  1440. {
  1441. Status = StatAuthError;
  1442. ErrorText = MetaIndexParser->ErrorText;
  1443. return;
  1444. }
  1445. if (!VerifyVendor(Message))
  1446. {
  1447. return;
  1448. }
  1449. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1450. std::cerr << "Signature verification succeeded: "
  1451. << DestFile << std::endl;
  1452. // do not trust any previously unverified content that we may have
  1453. string LastGoodSigFile = _config->FindDir("Dir::State::lists").append("partial/").append(URItoFileName(RealURI));
  1454. if (DestFile != SigFile)
  1455. LastGoodSigFile.append(".gpg");
  1456. LastGoodSigFile.append(".reverify");
  1457. if(IMSHit == false && RealFileExists(LastGoodSigFile) == false)
  1458. {
  1459. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1460. Target != IndexTargets->end();
  1461. ++Target)
  1462. {
  1463. // remove old indexes
  1464. std::string index = _config->FindDir("Dir::State::lists") +
  1465. URItoFileName((*Target)->URI);
  1466. unlink(index.c_str());
  1467. // and also old gzipindexes
  1468. index += ".gz";
  1469. unlink(index.c_str());
  1470. }
  1471. }
  1472. // Download further indexes with verification
  1473. QueueIndexes(true);
  1474. // is it a clearsigned MetaIndex file?
  1475. if (DestFile == SigFile)
  1476. return;
  1477. // Done, move signature file into position
  1478. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1479. URItoFileName(RealURI) + ".gpg";
  1480. Rename(SigFile,VerifiedSigFile);
  1481. chmod(VerifiedSigFile.c_str(),0644);
  1482. }
  1483. /*}}}*/
  1484. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  1485. {
  1486. #if 0
  1487. /* Reject invalid, existing Release files (LP: #346386) (Closes: #627642)
  1488. * FIXME: Disabled; it breaks unsigned repositories without hashes */
  1489. if (!verify && FileExists(DestFile) && !MetaIndexParser->Load(DestFile))
  1490. {
  1491. Status = StatError;
  1492. ErrorText = MetaIndexParser->ErrorText;
  1493. return;
  1494. }
  1495. #endif
  1496. bool transInRelease = false;
  1497. {
  1498. std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
  1499. for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
  1500. // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
  1501. if (k->find("Translation-") != std::string::npos)
  1502. {
  1503. transInRelease = true;
  1504. break;
  1505. }
  1506. }
  1507. // at this point the real Items are loaded in the fetcher
  1508. ExpectedAdditionalItems = 0;
  1509. for (vector <IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1510. Target != IndexTargets->end();
  1511. ++Target)
  1512. {
  1513. HashStringList ExpectedIndexHashes;
  1514. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1515. bool compressedAvailable = false;
  1516. if (Record == NULL)
  1517. {
  1518. if ((*Target)->IsOptional() == true)
  1519. {
  1520. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  1521. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  1522. if (MetaIndexParser->Exists((*Target)->MetaKey + "." + *t) == true)
  1523. {
  1524. compressedAvailable = true;
  1525. break;
  1526. }
  1527. }
  1528. else if (verify == true)
  1529. {
  1530. Status = StatAuthError;
  1531. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1532. return;
  1533. }
  1534. }
  1535. else
  1536. {
  1537. ExpectedIndexHashes = Record->Hashes;
  1538. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1539. {
  1540. std::cerr << "Queueing: " << (*Target)->URI << std::endl
  1541. << "Expected Hash:" << std::endl;
  1542. for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
  1543. std::cerr << "\t- " << hs->toStr() << std::endl;
  1544. std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
  1545. }
  1546. if (verify == true && ExpectedIndexHashes.empty() == true && (*Target)->IsOptional() == false)
  1547. {
  1548. Status = StatAuthError;
  1549. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1550. return;
  1551. }
  1552. }
  1553. if ((*Target)->IsOptional() == true)
  1554. {
  1555. if ((*Target)->IsSubIndex() == true)
  1556. new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description,
  1557. (*Target)->ShortDesc, ExpectedIndexHashes);
  1558. else if (transInRelease == false || Record != NULL || compressedAvailable == true)
  1559. {
  1560. if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
  1561. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true)
  1562. new pkgAcqDiffIndex(Owner, *Target, ExpectedIndexHashes, MetaIndexParser);
  1563. else
  1564. new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHashes, MetaIndexParser);
  1565. }
  1566. continue;
  1567. }
  1568. /* Queue Packages file (either diff or full packages files, depending
  1569. on the users option) - we also check if the PDiff Index file is listed
  1570. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1571. instead, but passing the required info to it is to much hassle */
  1572. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1573. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
  1574. new pkgAcqDiffIndex(Owner, *Target, ExpectedIndexHashes, MetaIndexParser);
  1575. else
  1576. new pkgAcqIndex(Owner, *Target, ExpectedIndexHashes, MetaIndexParser);
  1577. }
  1578. }
  1579. /*}}}*/
  1580. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  1581. {
  1582. string::size_type pos;
  1583. // check for missing sigs (that where not fatal because otherwise we had
  1584. // bombed earlier)
  1585. string missingkeys;
  1586. string msg = _("There is no public key available for the "
  1587. "following key IDs:\n");
  1588. pos = Message.find("NO_PUBKEY ");
  1589. if (pos != std::string::npos)
  1590. {
  1591. string::size_type start = pos+strlen("NO_PUBKEY ");
  1592. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1593. missingkeys += (Fingerprint);
  1594. }
  1595. if(!missingkeys.empty())
  1596. _error->Warning("%s", (msg + missingkeys).c_str());
  1597. string Transformed = MetaIndexParser->GetExpectedDist();
  1598. if (Transformed == "../project/experimental")
  1599. {
  1600. Transformed = "experimental";
  1601. }
  1602. pos = Transformed.rfind('/');
  1603. if (pos != string::npos)
  1604. {
  1605. Transformed = Transformed.substr(0, pos);
  1606. }
  1607. if (Transformed == ".")
  1608. {
  1609. Transformed = "";
  1610. }
  1611. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1612. MetaIndexParser->GetValidUntil() > 0) {
  1613. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1614. if (invalid_since > 0)
  1615. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1616. // the time since then the file is invalid - formated in the same way as in
  1617. // the download progress display (e.g. 7d 3h 42min 1s)
  1618. return _error->Error(
  1619. _("Release file for %s is expired (invalid since %s). "
  1620. "Updates for this repository will not be applied."),
  1621. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1622. }
  1623. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1624. {
  1625. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1626. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1627. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1628. }
  1629. if (MetaIndexParser->CheckDist(Transformed) == false)
  1630. {
  1631. // This might become fatal one day
  1632. // Status = StatAuthError;
  1633. // ErrorText = "Conflicting distribution; expected "
  1634. // + MetaIndexParser->GetExpectedDist() + " but got "
  1635. // + MetaIndexParser->GetDist();
  1636. // return false;
  1637. if (!Transformed.empty())
  1638. {
  1639. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1640. Desc.Description.c_str(),
  1641. Transformed.c_str(),
  1642. MetaIndexParser->GetDist().c_str());
  1643. }
  1644. }
  1645. return true;
  1646. }
  1647. /*}}}*/
  1648. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1649. // ---------------------------------------------------------------------
  1650. /* */
  1651. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)
  1652. {
  1653. if (AuthPass == true)
  1654. {
  1655. // gpgv method failed, if we have a good signature
  1656. string LastGoodSigFile = _config->FindDir("Dir::State::lists").append("partial/").append(URItoFileName(RealURI));
  1657. if (DestFile != SigFile)
  1658. LastGoodSigFile.append(".gpg");
  1659. LastGoodSigFile.append(".reverify");
  1660. if(FileExists(LastGoodSigFile))
  1661. {
  1662. string VerifiedSigFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1663. if (DestFile != SigFile)
  1664. VerifiedSigFile.append(".gpg");
  1665. Rename(LastGoodSigFile, VerifiedSigFile);
  1666. Status = StatTransientNetworkError;
  1667. _error->Warning(_("An error occurred during the signature "
  1668. "verification. The repository is not updated "
  1669. "and the previous index files will be used. "
  1670. "GPG error: %s: %s\n"),
  1671. Desc.Description.c_str(),
  1672. LookupTag(Message,"Message").c_str());
  1673. RunScripts("APT::Update::Auth-Failure");
  1674. return;
  1675. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1676. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1677. _error->Error(_("GPG error: %s: %s"),
  1678. Desc.Description.c_str(),
  1679. LookupTag(Message,"Message").c_str());
  1680. return;
  1681. } else {
  1682. _error->Warning(_("GPG error: %s: %s"),
  1683. Desc.Description.c_str(),
  1684. LookupTag(Message,"Message").c_str());
  1685. }
  1686. // gpgv method failed
  1687. ReportMirrorFailure("GPGFailure");
  1688. }
  1689. /* Always move the meta index, even if gpgv failed. This ensures
  1690. * that PackageFile objects are correctly filled in */
  1691. if (FileExists(DestFile)) {
  1692. string FinalFile = _config->FindDir("Dir::State::lists");
  1693. FinalFile += URItoFileName(RealURI);
  1694. /* InRelease files become Release files, otherwise
  1695. * they would be considered as trusted later on */
  1696. if (SigFile == DestFile) {
  1697. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  1698. "Release");
  1699. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  1700. "Release");
  1701. SigFile = FinalFile;
  1702. }
  1703. Rename(DestFile,FinalFile);
  1704. chmod(FinalFile.c_str(),0644);
  1705. DestFile = FinalFile;
  1706. }
  1707. // No Release file was present, or verification failed, so fall
  1708. // back to queueing Packages files without verification
  1709. QueueIndexes(false);
  1710. }
  1711. /*}}}*/
  1712. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1713. string const &URI, string const &URIDesc, string const &ShortDesc,
  1714. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1715. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1716. const vector<IndexTarget*>* IndexTargets,
  1717. indexRecords* MetaIndexParser) :
  1718. pkgAcqMetaIndex(Owner, URI, URIDesc, ShortDesc, "", IndexTargets, MetaIndexParser),
  1719. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1720. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1721. {
  1722. SigFile = DestFile;
  1723. // index targets + (worst case:) Release/Release.gpg
  1724. ExpectedAdditionalItems = IndexTargets->size() + 2;
  1725. // keep the old InRelease around in case of transistent network errors
  1726. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1727. if (RealFileExists(Final) == true)
  1728. {
  1729. string const LastGoodSig = DestFile + ".reverify";
  1730. Rename(Final,LastGoodSig);
  1731. }
  1732. }
  1733. /*}}}*/
  1734. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1735. {
  1736. // if the file was never queued undo file-changes done in the constructor
  1737. if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false)
  1738. {
  1739. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1740. string const LastGoodSig = DestFile + ".reverify";
  1741. if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
  1742. Rename(LastGoodSig, Final);
  1743. }
  1744. }
  1745. /*}}}*/
  1746. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1747. // ---------------------------------------------------------------------
  1748. // FIXME: this can go away once the InRelease file is used widely
  1749. string pkgAcqMetaClearSig::Custom600Headers() const
  1750. {
  1751. string Final = _config->FindDir("Dir::State::lists");
  1752. Final += URItoFileName(RealURI);
  1753. struct stat Buf;
  1754. if (stat(Final.c_str(),&Buf) != 0)
  1755. {
  1756. Final = DestFile + ".reverify";
  1757. if (stat(Final.c_str(),&Buf) != 0)
  1758. return "\nIndex-File: true\nFail-Ignore: true\n";
  1759. }
  1760. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1761. }
  1762. /*}}}*/
  1763. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  1764. {
  1765. // we failed, we will not get additional items from this method
  1766. ExpectedAdditionalItems = 0;
  1767. if (AuthPass == false)
  1768. {
  1769. // Remove the 'old' InRelease file if we try Release.gpg now as otherwise
  1770. // the file will stay around and gives a false-auth impression (CVE-2012-0214)
  1771. string FinalFile = _config->FindDir("Dir::State::lists");
  1772. FinalFile.append(URItoFileName(RealURI));
  1773. if (FileExists(FinalFile))
  1774. unlink(FinalFile.c_str());
  1775. new pkgAcqMetaSig(Owner,
  1776. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  1777. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1778. IndexTargets, MetaIndexParser);
  1779. if (Cnf->LocalOnly == true ||
  1780. StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
  1781. Dequeue();
  1782. }
  1783. else
  1784. pkgAcqMetaIndex::Failed(Message, Cnf);
  1785. }
  1786. /*}}}*/
  1787. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1788. // ---------------------------------------------------------------------
  1789. /* This just sets up the initial fetch environment and queues the first
  1790. possibilitiy */
  1791. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1792. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1793. string &StoreFilename) :
  1794. Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
  1795. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1796. Trusted(false)
  1797. {
  1798. Retries = _config->FindI("Acquire::Retries",0);
  1799. if (Version.Arch() == 0)
  1800. {
  1801. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1802. "This might mean you need to manually fix this package. "
  1803. "(due to missing arch)"),
  1804. Version.ParentPkg().FullName().c_str());
  1805. return;
  1806. }
  1807. /* We need to find a filename to determine the extension. We make the
  1808. assumption here that all the available sources for this version share
  1809. the same extension.. */
  1810. // Skip not source sources, they do not have file fields.
  1811. for (; Vf.end() == false; ++Vf)
  1812. {
  1813. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1814. continue;
  1815. break;
  1816. }
  1817. // Does not really matter here.. we are going to fail out below
  1818. if (Vf.end() != true)
  1819. {
  1820. // If this fails to get a file name we will bomb out below.
  1821. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1822. if (_error->PendingError() == true)
  1823. return;
  1824. // Generate the final file name as: package_version_arch.foo
  1825. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1826. QuoteString(Version.VerStr(),"_:") + '_' +
  1827. QuoteString(Version.Arch(),"_:.") +
  1828. "." + flExtension(Parse.FileName());
  1829. }
  1830. // check if we have one trusted source for the package. if so, switch
  1831. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  1832. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  1833. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  1834. bool seenUntrusted = false;
  1835. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  1836. {
  1837. pkgIndexFile *Index;
  1838. if (Sources->FindIndex(i.File(),Index) == false)
  1839. continue;
  1840. if (debugAuth == true)
  1841. std::cerr << "Checking index: " << Index->Describe()
  1842. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  1843. if (Index->IsTrusted() == true)
  1844. {
  1845. Trusted = true;
  1846. if (allowUnauth == false)
  1847. break;
  1848. }
  1849. else
  1850. seenUntrusted = true;
  1851. }
  1852. // "allow-unauthenticated" restores apts old fetching behaviour
  1853. // that means that e.g. unauthenticated file:// uris are higher
  1854. // priority than authenticated http:// uris
  1855. if (allowUnauth == true && seenUntrusted == true)
  1856. Trusted = false;
  1857. // Select a source
  1858. if (QueueNext() == false && _error->PendingError() == false)
  1859. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  1860. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  1861. }
  1862. /*}}}*/
  1863. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1864. // ---------------------------------------------------------------------
  1865. /* This queues the next available file version for download. It checks if
  1866. the archive is already available in the cache and stashs the MD5 for
  1867. checking later. */
  1868. bool pkgAcqArchive::QueueNext()
  1869. {
  1870. for (; Vf.end() == false; ++Vf)
  1871. {
  1872. // Ignore not source sources
  1873. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1874. continue;
  1875. // Try to cross match against the source list
  1876. pkgIndexFile *Index;
  1877. if (Sources->FindIndex(Vf.File(),Index) == false)
  1878. continue;
  1879. // only try to get a trusted package from another source if that source
  1880. // is also trusted
  1881. if(Trusted && !Index->IsTrusted())
  1882. continue;
  1883. // Grab the text package record
  1884. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1885. if (_error->PendingError() == true)
  1886. return false;
  1887. string PkgFile = Parse.FileName();
  1888. ExpectedHashes = Parse.Hashes();
  1889. if (PkgFile.empty() == true)
  1890. return _error->Error(_("The package index files are corrupted. No Filename: "
  1891. "field for package %s."),
  1892. Version.ParentPkg().Name());
  1893. Desc.URI = Index->ArchiveURI(PkgFile);
  1894. Desc.Description = Index->ArchiveInfo(Version);
  1895. Desc.Owner = this;
  1896. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  1897. // See if we already have the file. (Legacy filenames)
  1898. FileSize = Version->Size;
  1899. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1900. struct stat Buf;
  1901. if (stat(FinalFile.c_str(),&Buf) == 0)
  1902. {
  1903. // Make sure the size matches
  1904. if ((unsigned long long)Buf.st_size == Version->Size)
  1905. {
  1906. Complete = true;
  1907. Local = true;
  1908. Status = StatDone;
  1909. StoreFilename = DestFile = FinalFile;
  1910. return true;
  1911. }
  1912. /* Hmm, we have a file and its size does not match, this means it is
  1913. an old style mismatched arch */
  1914. unlink(FinalFile.c_str());
  1915. }
  1916. // Check it again using the new style output filenames
  1917. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1918. if (stat(FinalFile.c_str(),&Buf) == 0)
  1919. {
  1920. // Make sure the size matches
  1921. if ((unsigned long long)Buf.st_size == Version->Size)
  1922. {
  1923. Complete = true;
  1924. Local = true;
  1925. Status = StatDone;
  1926. StoreFilename = DestFile = FinalFile;
  1927. return true;
  1928. }
  1929. /* Hmm, we have a file and its size does not match, this shouldn't
  1930. happen.. */
  1931. unlink(FinalFile.c_str());
  1932. }
  1933. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1934. // Check the destination file
  1935. if (stat(DestFile.c_str(),&Buf) == 0)
  1936. {
  1937. // Hmm, the partial file is too big, erase it
  1938. if ((unsigned long long)Buf.st_size > Version->Size)
  1939. unlink(DestFile.c_str());
  1940. else
  1941. PartialSize = Buf.st_size;
  1942. }
  1943. // Disables download of archives - useful if no real installation follows,
  1944. // e.g. if we are just interested in proposed installation order
  1945. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  1946. {
  1947. Complete = true;
  1948. Local = true;
  1949. Status = StatDone;
  1950. StoreFilename = DestFile = FinalFile;
  1951. return true;
  1952. }
  1953. // Create the item
  1954. Local = false;
  1955. QueueURI(Desc);
  1956. ++Vf;
  1957. return true;
  1958. }
  1959. return false;
  1960. }
  1961. /*}}}*/
  1962. // AcqArchive::Done - Finished fetching /*{{{*/
  1963. // ---------------------------------------------------------------------
  1964. /* */
  1965. void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
  1966. pkgAcquire::MethodConfig *Cfg)
  1967. {
  1968. Item::Done(Message, Size, CalcHashes, Cfg);
  1969. // Check the size
  1970. if (Size != Version->Size)
  1971. {
  1972. RenameOnError(SizeMismatch);
  1973. return;
  1974. }
  1975. // FIXME: could this empty() check impose *any* sort of security issue?
  1976. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  1977. {
  1978. RenameOnError(HashSumMismatch);
  1979. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  1980. return;
  1981. }
  1982. // Grab the output filename
  1983. string FileName = LookupTag(Message,"Filename");
  1984. if (FileName.empty() == true)
  1985. {
  1986. Status = StatError;
  1987. ErrorText = "Method gave a blank filename";
  1988. return;
  1989. }
  1990. Complete = true;
  1991. // Reference filename
  1992. if (FileName != DestFile)
  1993. {
  1994. StoreFilename = DestFile = FileName;
  1995. Local = true;
  1996. return;
  1997. }
  1998. // Done, move it into position
  1999. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  2000. FinalFile += flNotDir(StoreFilename);
  2001. Rename(DestFile,FinalFile);
  2002. StoreFilename = DestFile = FinalFile;
  2003. Complete = true;
  2004. }
  2005. /*}}}*/
  2006. // AcqArchive::Failed - Failure handler /*{{{*/
  2007. // ---------------------------------------------------------------------
  2008. /* Here we try other sources */
  2009. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2010. {
  2011. ErrorText = LookupTag(Message,"Message");
  2012. /* We don't really want to retry on failed media swaps, this prevents
  2013. that. An interesting observation is that permanent failures are not
  2014. recorded. */
  2015. if (Cnf->Removable == true &&
  2016. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2017. {
  2018. // Vf = Version.FileList();
  2019. while (Vf.end() == false) ++Vf;
  2020. StoreFilename = string();
  2021. Item::Failed(Message,Cnf);
  2022. return;
  2023. }
  2024. if (QueueNext() == false)
  2025. {
  2026. // This is the retry counter
  2027. if (Retries != 0 &&
  2028. Cnf->LocalOnly == false &&
  2029. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2030. {
  2031. Retries--;
  2032. Vf = Version.FileList();
  2033. if (QueueNext() == true)
  2034. return;
  2035. }
  2036. StoreFilename = string();
  2037. Item::Failed(Message,Cnf);
  2038. }
  2039. }
  2040. /*}}}*/
  2041. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  2042. // ---------------------------------------------------------------------
  2043. APT_PURE bool pkgAcqArchive::IsTrusted() const
  2044. {
  2045. return Trusted;
  2046. }
  2047. /*}}}*/
  2048. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  2049. // ---------------------------------------------------------------------
  2050. /* */
  2051. void pkgAcqArchive::Finished()
  2052. {
  2053. if (Status == pkgAcquire::Item::StatDone &&
  2054. Complete == true)
  2055. return;
  2056. StoreFilename = string();
  2057. }
  2058. /*}}}*/
  2059. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  2060. // ---------------------------------------------------------------------
  2061. /* The file is added to the queue */
  2062. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
  2063. unsigned long long Size,string Dsc,string ShortDesc,
  2064. const string &DestDir, const string &DestFilename,
  2065. bool IsIndexFile) :
  2066. Item(Owner, Hashes), IsIndexFile(IsIndexFile)
  2067. {
  2068. Retries = _config->FindI("Acquire::Retries",0);
  2069. if(!DestFilename.empty())
  2070. DestFile = DestFilename;
  2071. else if(!DestDir.empty())
  2072. DestFile = DestDir + "/" + flNotDir(URI);
  2073. else
  2074. DestFile = flNotDir(URI);
  2075. // Create the item
  2076. Desc.URI = URI;
  2077. Desc.Description = Dsc;
  2078. Desc.Owner = this;
  2079. // Set the short description to the archive component
  2080. Desc.ShortDesc = ShortDesc;
  2081. // Get the transfer sizes
  2082. FileSize = Size;
  2083. struct stat Buf;
  2084. if (stat(DestFile.c_str(),&Buf) == 0)
  2085. {
  2086. // Hmm, the partial file is too big, erase it
  2087. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  2088. unlink(DestFile.c_str());
  2089. else
  2090. PartialSize = Buf.st_size;
  2091. }
  2092. QueueURI(Desc);
  2093. }
  2094. /*}}}*/
  2095. // AcqFile::Done - Item downloaded OK /*{{{*/
  2096. // ---------------------------------------------------------------------
  2097. /* */
  2098. void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
  2099. pkgAcquire::MethodConfig *Cnf)
  2100. {
  2101. Item::Done(Message,Size,CalcHashes,Cnf);
  2102. // Check the hash
  2103. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2104. {
  2105. RenameOnError(HashSumMismatch);
  2106. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2107. return;
  2108. }
  2109. string FileName = LookupTag(Message,"Filename");
  2110. if (FileName.empty() == true)
  2111. {
  2112. Status = StatError;
  2113. ErrorText = "Method gave a blank filename";
  2114. return;
  2115. }
  2116. Complete = true;
  2117. // The files timestamp matches
  2118. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2119. return;
  2120. // We have to copy it into place
  2121. if (FileName != DestFile)
  2122. {
  2123. Local = true;
  2124. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  2125. Cnf->Removable == true)
  2126. {
  2127. Desc.URI = "copy:" + FileName;
  2128. QueueURI(Desc);
  2129. return;
  2130. }
  2131. // Erase the file if it is a symlink so we can overwrite it
  2132. struct stat St;
  2133. if (lstat(DestFile.c_str(),&St) == 0)
  2134. {
  2135. if (S_ISLNK(St.st_mode) != 0)
  2136. unlink(DestFile.c_str());
  2137. }
  2138. // Symlink the file
  2139. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2140. {
  2141. ErrorText = "Link to " + DestFile + " failure ";
  2142. Status = StatError;
  2143. Complete = false;
  2144. }
  2145. }
  2146. }
  2147. /*}}}*/
  2148. // AcqFile::Failed - Failure handler /*{{{*/
  2149. // ---------------------------------------------------------------------
  2150. /* Here we try other sources */
  2151. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2152. {
  2153. ErrorText = LookupTag(Message,"Message");
  2154. // This is the retry counter
  2155. if (Retries != 0 &&
  2156. Cnf->LocalOnly == false &&
  2157. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2158. {
  2159. Retries--;
  2160. QueueURI(Desc);
  2161. return;
  2162. }
  2163. Item::Failed(Message,Cnf);
  2164. }
  2165. /*}}}*/
  2166. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2167. // ---------------------------------------------------------------------
  2168. /* The only header we use is the last-modified header. */
  2169. string pkgAcqFile::Custom600Headers() const
  2170. {
  2171. if (IsIndexFile)
  2172. return "\nIndex-File: true";
  2173. return "";
  2174. }
  2175. /*}}}*/