acquire-item.cc 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968
  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. static std::string GetPartialFileName(std::string const &file) /*{{{*/
  58. {
  59. std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  60. DestFile += file;
  61. return DestFile;
  62. }
  63. /*}}}*/
  64. static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
  65. {
  66. return GetPartialFileName(URItoFileName(uri));
  67. }
  68. /*}}}*/
  69. static std::string GetFinalFileNameFromURI(std::string const &uri) /*{{{*/
  70. {
  71. return _config->FindDir("Dir::State::lists") + URItoFileName(uri);
  72. }
  73. /*}}}*/
  74. static std::string GetCompressedFileName(std::string const &URI, std::string const &Name, std::string const &Ext) /*{{{*/
  75. {
  76. if (Ext.empty() || Ext == "uncompressed")
  77. return Name;
  78. // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
  79. // file when its doing the indexcopy
  80. if (URI.substr(0,6) == "cdrom:")
  81. return Name;
  82. // adjust DestFile if its compressed on disk
  83. if (_config->FindB("Acquire::GzipIndexes",false) == true)
  84. return Name + '.' + Ext;
  85. return Name;
  86. }
  87. /*}}}*/
  88. static std::string GetMergeDiffsPatchFileName(std::string const &Final, std::string const &Patch)/*{{{*/
  89. {
  90. // rred expects the patch as $FinalFile.ed.$patchname.gz
  91. return Final + ".ed." + Patch + ".gz";
  92. }
  93. /*}}}*/
  94. static std::string GetDiffsPatchFileName(std::string const &Final) /*{{{*/
  95. {
  96. // rred expects the patch as $FinalFile.ed
  97. return Final + ".ed";
  98. }
  99. /*}}}*/
  100. static bool AllowInsecureRepositories(indexRecords const * const MetaIndexParser, pkgAcqMetaBase * const TransactionManager, pkgAcquire::Item * const I) /*{{{*/
  101. {
  102. if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
  103. return true;
  104. _error->Error(_("Use --allow-insecure-repositories to force the update"));
  105. TransactionManager->AbortTransaction();
  106. I->Status = pkgAcquire::Item::StatError;
  107. return false;
  108. }
  109. /*}}}*/
  110. // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
  111. /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
  112. It is best to implement it as broadly as possible, while ::HashesRequired defaults
  113. to true and should be as restrictive as possible for false cases. Note that if
  114. a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
  115. ::HashesRequired is called to evaluate if its okay to have no hashes. */
  116. APT_CONST bool pkgAcqTransactionItem::HashesRequired() const
  117. {
  118. /* signed repositories obviously have a parser and good hashes.
  119. unsigned repositories, too, as even if we can't trust them for security,
  120. we can at least trust them for integrity of the download itself.
  121. Only repositories without a Release file can (obviously) not have
  122. hashes – and they are very uncommon and strongly discouraged */
  123. return TransactionManager->MetaIndexParser != NULL;
  124. }
  125. HashStringList pkgAcqTransactionItem::GetExpectedHashes() const
  126. {
  127. return GetExpectedHashesFor(GetMetaKey());
  128. }
  129. APT_CONST bool pkgAcqMetaBase::HashesRequired() const
  130. {
  131. // Release and co have no hashes 'by design'.
  132. return false;
  133. }
  134. HashStringList pkgAcqMetaBase::GetExpectedHashes() const
  135. {
  136. return HashStringList();
  137. }
  138. APT_CONST bool pkgAcqIndexDiffs::HashesRequired() const
  139. {
  140. /* We don't always have the diff of the downloaded pdiff file.
  141. What we have for sure is hashes for the uncompressed file,
  142. but rred uncompresses them on the fly while parsing, so not handled here.
  143. Hashes are (also) checked while searching for (next) patch to apply. */
  144. if (State == StateFetchDiff)
  145. return available_patches[0].download_hashes.empty() == false;
  146. return false;
  147. }
  148. HashStringList pkgAcqIndexDiffs::GetExpectedHashes() const
  149. {
  150. if (State == StateFetchDiff)
  151. return available_patches[0].download_hashes;
  152. return HashStringList();
  153. }
  154. APT_CONST bool pkgAcqIndexMergeDiffs::HashesRequired() const
  155. {
  156. /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
  157. we can check the rred result after all patches are applied as
  158. we know the expected result rather than potentially apply more patches */
  159. if (State == StateFetchDiff)
  160. return patch.download_hashes.empty() == false;
  161. return State == StateApplyDiff;
  162. }
  163. HashStringList pkgAcqIndexMergeDiffs::GetExpectedHashes() const
  164. {
  165. if (State == StateFetchDiff)
  166. return patch.download_hashes;
  167. else if (State == StateApplyDiff)
  168. return GetExpectedHashesFor(Target->MetaKey);
  169. return HashStringList();
  170. }
  171. APT_CONST bool pkgAcqArchive::HashesRequired() const
  172. {
  173. return LocalSource == false;
  174. }
  175. HashStringList pkgAcqArchive::GetExpectedHashes() const
  176. {
  177. // figured out while parsing the records
  178. return ExpectedHashes;
  179. }
  180. APT_CONST bool pkgAcqFile::HashesRequired() const
  181. {
  182. // supplied as parameter at creation time, so the caller decides
  183. return ExpectedHashes.usable();
  184. }
  185. HashStringList pkgAcqFile::GetExpectedHashes() const
  186. {
  187. return ExpectedHashes;
  188. }
  189. /*}}}*/
  190. // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
  191. bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc &Item)
  192. {
  193. Owner->Enqueue(Item);
  194. return true;
  195. }
  196. /* The idea here is that an item isn't queued if it exists on disk and the
  197. transition manager was a hit as this means that the files it contains
  198. the checksums for can't be updated either (or they are and we are asking
  199. for a hashsum mismatch to happen which helps nobody) */
  200. bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc &Item)
  201. {
  202. std::string const FinalFile = GetFinalFilename();
  203. if (TransactionManager != NULL && TransactionManager->IMSHit == true &&
  204. FileExists(FinalFile) == true)
  205. {
  206. PartialFile = DestFile = FinalFile;
  207. Status = StatDone;
  208. return false;
  209. }
  210. return pkgAcquire::Item::QueueURI(Item);
  211. }
  212. /* The transition manager InRelease itself (or its older sisters-in-law
  213. Release & Release.gpg) is always queued as this allows us to rerun gpgv
  214. on it to verify that we aren't stalled with old files */
  215. bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc &Item)
  216. {
  217. return pkgAcquire::Item::QueueURI(Item);
  218. }
  219. /* the Diff/Index needs to queue also the up-to-date complete index file
  220. to ensure that the list cleaner isn't eating it */
  221. bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc &Item)
  222. {
  223. if (pkgAcqTransactionItem::QueueURI(Item) == true)
  224. return true;
  225. QueueOnIMSHit();
  226. return false;
  227. }
  228. /*}}}*/
  229. // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
  230. std::string pkgAcquire::Item::GetFinalFilename() const
  231. {
  232. return GetFinalFileNameFromURI(Desc.URI);
  233. }
  234. std::string pkgAcqDiffIndex::GetFinalFilename() const
  235. {
  236. // the logic we inherent from pkgAcqBaseIndex isn't what we need here
  237. return pkgAcquire::Item::GetFinalFilename();
  238. }
  239. std::string pkgAcqIndex::GetFinalFilename() const
  240. {
  241. std::string const FinalFile = GetFinalFileNameFromURI(Target->URI);
  242. return GetCompressedFileName(Target->URI, FinalFile, CurrentCompressionExtension);
  243. }
  244. std::string pkgAcqMetaSig::GetFinalFilename() const
  245. {
  246. return GetFinalFileNameFromURI(Target->URI);
  247. }
  248. std::string pkgAcqBaseIndex::GetFinalFilename() const
  249. {
  250. return GetFinalFileNameFromURI(Target->URI);
  251. }
  252. std::string pkgAcqMetaBase::GetFinalFilename() const
  253. {
  254. return GetFinalFileNameFromURI(DataTarget.URI);
  255. }
  256. std::string pkgAcqArchive::GetFinalFilename() const
  257. {
  258. return _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  259. }
  260. /*}}}*/
  261. // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
  262. std::string pkgAcqTransactionItem::GetMetaKey() const
  263. {
  264. return Target->MetaKey;
  265. }
  266. std::string pkgAcqIndex::GetMetaKey() const
  267. {
  268. if (Stage == STAGE_DECOMPRESS_AND_VERIFY || CurrentCompressionExtension == "uncompressed")
  269. return Target->MetaKey;
  270. return Target->MetaKey + "." + CurrentCompressionExtension;
  271. }
  272. std::string pkgAcqDiffIndex::GetMetaKey() const
  273. {
  274. return Target->MetaKey + ".diff/Index";
  275. }
  276. /*}}}*/
  277. //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
  278. bool pkgAcqTransactionItem::TransactionState(TransactionStates const state)
  279. {
  280. bool const Debug = _config->FindB("Debug::Acquire::Transaction", false);
  281. switch(state)
  282. {
  283. case TransactionAbort:
  284. if(Debug == true)
  285. std::clog << " Cancel: " << DestFile << std::endl;
  286. if (Status == pkgAcquire::Item::StatIdle)
  287. {
  288. Status = pkgAcquire::Item::StatDone;
  289. Dequeue();
  290. }
  291. break;
  292. case TransactionCommit:
  293. if(PartialFile != "")
  294. {
  295. if(Debug == true)
  296. std::clog << "mv " << PartialFile << " -> "<< DestFile << " # " << DescURI() << std::endl;
  297. Rename(PartialFile, DestFile);
  298. } else {
  299. if(Debug == true)
  300. std::clog << "rm " << DestFile << " # " << DescURI() << std::endl;
  301. unlink(DestFile.c_str());
  302. }
  303. break;
  304. }
  305. return true;
  306. }
  307. bool pkgAcqMetaBase::TransactionState(TransactionStates const state)
  308. {
  309. // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
  310. if (TransactionManager->IMSHit == false)
  311. return pkgAcqTransactionItem::TransactionState(state);
  312. return true;
  313. }
  314. bool pkgAcqIndex::TransactionState(TransactionStates const state)
  315. {
  316. if (pkgAcqTransactionItem::TransactionState(state) == false)
  317. return false;
  318. switch (state)
  319. {
  320. case TransactionAbort:
  321. if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
  322. {
  323. // keep the compressed file, but drop the decompressed
  324. EraseFileName.clear();
  325. if (PartialFile.empty() == false && flExtension(PartialFile) == "decomp")
  326. unlink(PartialFile.c_str());
  327. }
  328. break;
  329. case TransactionCommit:
  330. if (EraseFileName.empty() == false)
  331. unlink(EraseFileName.c_str());
  332. break;
  333. }
  334. return true;
  335. }
  336. bool pkgAcqDiffIndex::TransactionState(TransactionStates const state)
  337. {
  338. if (pkgAcqTransactionItem::TransactionState(state) == false)
  339. return false;
  340. switch (state)
  341. {
  342. case TransactionCommit:
  343. break;
  344. case TransactionAbort:
  345. std::string const Partial = GetPartialFileNameFromURI(Target->URI);
  346. unlink(Partial.c_str());
  347. break;
  348. }
  349. return true;
  350. }
  351. /*}}}*/
  352. // Acquire::Item::Item - Constructor /*{{{*/
  353. APT_IGNORE_DEPRECATED_PUSH
  354. pkgAcquire::Item::Item(pkgAcquire * const Owner) :
  355. FileSize(0), PartialSize(0), Mode(0), Complete(false), Local(false),
  356. QueueCounter(0), ExpectedAdditionalItems(0), Owner(Owner)
  357. {
  358. Owner->Add(this);
  359. Status = StatIdle;
  360. }
  361. APT_IGNORE_DEPRECATED_POP
  362. /*}}}*/
  363. // Acquire::Item::~Item - Destructor /*{{{*/
  364. pkgAcquire::Item::~Item()
  365. {
  366. Owner->Remove(this);
  367. }
  368. /*}}}*/
  369. std::string pkgAcquire::Item::Custom600Headers() const /*{{{*/
  370. {
  371. return std::string();
  372. }
  373. /*}}}*/
  374. std::string pkgAcquire::Item::ShortDesc() const /*{{{*/
  375. {
  376. return DescURI();
  377. }
  378. /*}}}*/
  379. APT_CONST void pkgAcquire::Item::Finished() /*{{{*/
  380. {
  381. }
  382. /*}}}*/
  383. APT_PURE pkgAcquire * pkgAcquire::Item::GetOwner() const /*{{{*/
  384. {
  385. return Owner;
  386. }
  387. /*}}}*/
  388. APT_CONST bool pkgAcquire::Item::IsTrusted() const /*{{{*/
  389. {
  390. return false;
  391. }
  392. /*}}}*/
  393. // Acquire::Item::Failed - Item failed to download /*{{{*/
  394. // ---------------------------------------------------------------------
  395. /* We return to an idle state if there are still other queues that could
  396. fetch this object */
  397. void pkgAcquire::Item::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  398. {
  399. if(ErrorText.empty())
  400. ErrorText = LookupTag(Message,"Message");
  401. UsedMirror = LookupTag(Message,"UsedMirror");
  402. if (QueueCounter <= 1)
  403. {
  404. /* This indicates that the file is not available right now but might
  405. be sometime later. If we do a retry cycle then this should be
  406. retried [CDROMs] */
  407. if (Cnf != NULL && Cnf->LocalOnly == true &&
  408. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  409. {
  410. Status = StatIdle;
  411. Dequeue();
  412. return;
  413. }
  414. switch (Status)
  415. {
  416. case StatIdle:
  417. case StatFetching:
  418. case StatDone:
  419. Status = StatError;
  420. break;
  421. case StatAuthError:
  422. case StatError:
  423. case StatTransientNetworkError:
  424. break;
  425. }
  426. Complete = false;
  427. Dequeue();
  428. }
  429. string const FailReason = LookupTag(Message, "FailReason");
  430. if (FailReason == "MaximumSizeExceeded")
  431. RenameOnError(MaximumSizeExceeded);
  432. else if (Status == StatAuthError)
  433. RenameOnError(HashSumMismatch);
  434. // report mirror failure back to LP if we actually use a mirror
  435. if (FailReason.empty() == false)
  436. ReportMirrorFailure(FailReason);
  437. else
  438. ReportMirrorFailure(ErrorText);
  439. if (QueueCounter > 1)
  440. Status = StatIdle;
  441. }
  442. /*}}}*/
  443. // Acquire::Item::Start - Item has begun to download /*{{{*/
  444. // ---------------------------------------------------------------------
  445. /* Stash status and the file size. Note that setting Complete means
  446. sub-phases of the acquire process such as decompresion are operating */
  447. void pkgAcquire::Item::Start(string const &/*Message*/, unsigned long long const Size)
  448. {
  449. Status = StatFetching;
  450. ErrorText.clear();
  451. if (FileSize == 0 && Complete == false)
  452. FileSize = Size;
  453. }
  454. /*}}}*/
  455. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  456. void pkgAcquire::Item::Done(string const &Message, HashStringList const &Hashes,
  457. pkgAcquire::MethodConfig const * const /*Cnf*/)
  458. {
  459. // We just downloaded something..
  460. string FileName = LookupTag(Message,"Filename");
  461. UsedMirror = LookupTag(Message,"UsedMirror");
  462. unsigned long long const downloadedSize = Hashes.FileSize();
  463. if (downloadedSize != 0)
  464. {
  465. if (Complete == false && !Local && FileName == DestFile)
  466. {
  467. if (Owner->Log != 0)
  468. Owner->Log->Fetched(Hashes.FileSize(),atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  469. }
  470. if (FileSize == 0)
  471. FileSize= downloadedSize;
  472. }
  473. Status = StatDone;
  474. ErrorText = string();
  475. Owner->Dequeue(this);
  476. }
  477. /*}}}*/
  478. // Acquire::Item::Rename - Rename a file /*{{{*/
  479. // ---------------------------------------------------------------------
  480. /* This helper function is used by a lot of item methods as their final
  481. step */
  482. bool pkgAcquire::Item::Rename(string const &From,string const &To)
  483. {
  484. if (From == To || rename(From.c_str(),To.c_str()) == 0)
  485. return true;
  486. std::string S;
  487. strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
  488. From.c_str(),To.c_str());
  489. Status = StatError;
  490. if (ErrorText.empty())
  491. ErrorText = S;
  492. else
  493. ErrorText = ErrorText + ": " + S;
  494. return false;
  495. }
  496. /*}}}*/
  497. void pkgAcquire::Item::Dequeue() /*{{{*/
  498. {
  499. Owner->Dequeue(this);
  500. }
  501. /*}}}*/
  502. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  503. {
  504. if (RealFileExists(DestFile))
  505. Rename(DestFile, DestFile + ".FAILED");
  506. std::string errtext;
  507. switch (error)
  508. {
  509. case HashSumMismatch:
  510. errtext = _("Hash Sum mismatch");
  511. Status = StatAuthError;
  512. ReportMirrorFailure("HashChecksumFailure");
  513. break;
  514. case SizeMismatch:
  515. errtext = _("Size mismatch");
  516. Status = StatAuthError;
  517. ReportMirrorFailure("SizeFailure");
  518. break;
  519. case InvalidFormat:
  520. errtext = _("Invalid file format");
  521. Status = StatError;
  522. // do not report as usually its not the mirrors fault, but Portal/Proxy
  523. break;
  524. case SignatureError:
  525. errtext = _("Signature error");
  526. Status = StatError;
  527. break;
  528. case NotClearsigned:
  529. errtext = _("Does not start with a cleartext signature");
  530. Status = StatError;
  531. break;
  532. case MaximumSizeExceeded:
  533. // the method is expected to report a good error for this
  534. Status = StatError;
  535. break;
  536. case PDiffError:
  537. // no handling here, done by callers
  538. break;
  539. }
  540. if (ErrorText.empty())
  541. ErrorText = errtext;
  542. return false;
  543. }
  544. /*}}}*/
  545. void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
  546. {
  547. ActiveSubprocess = subprocess;
  548. APT_IGNORE_DEPRECATED(Mode = ActiveSubprocess.c_str();)
  549. }
  550. /*}}}*/
  551. // Acquire::Item::ReportMirrorFailure /*{{{*/
  552. void pkgAcquire::Item::ReportMirrorFailure(string const &FailCode)
  553. {
  554. // we only act if a mirror was used at all
  555. if(UsedMirror.empty())
  556. return;
  557. #if 0
  558. std::cerr << "\nReportMirrorFailure: "
  559. << UsedMirror
  560. << " Uri: " << DescURI()
  561. << " FailCode: "
  562. << FailCode << std::endl;
  563. #endif
  564. string report = _config->Find("Methods::Mirror::ProblemReporting",
  565. "/usr/lib/apt/apt-report-mirror-failure");
  566. if(!FileExists(report))
  567. return;
  568. std::vector<char const*> Args;
  569. Args.push_back(report.c_str());
  570. Args.push_back(UsedMirror.c_str());
  571. Args.push_back(DescURI().c_str());
  572. Args.push_back(FailCode.c_str());
  573. Args.push_back(NULL);
  574. pid_t pid = ExecFork();
  575. if(pid < 0)
  576. {
  577. _error->Error("ReportMirrorFailure Fork failed");
  578. return;
  579. }
  580. else if(pid == 0)
  581. {
  582. execvp(Args[0], (char**)Args.data());
  583. std::cerr << "Could not exec " << Args[0] << std::endl;
  584. _exit(100);
  585. }
  586. if(!ExecWait(pid, "report-mirror-failure"))
  587. {
  588. _error->Warning("Couldn't report problem to '%s'",
  589. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  590. }
  591. }
  592. /*}}}*/
  593. std::string pkgAcquire::Item::HashSum() const /*{{{*/
  594. {
  595. HashStringList const hashes = GetExpectedHashes();
  596. HashString const * const hs = hashes.find(NULL);
  597. return hs != NULL ? hs->toStr() : "";
  598. }
  599. /*}}}*/
  600. pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire * const Owner, /*{{{*/
  601. pkgAcqMetaBase * const TransactionManager, IndexTarget const * const Target) :
  602. pkgAcquire::Item(Owner), Target(Target), TransactionManager(TransactionManager)
  603. {
  604. if (TransactionManager != this)
  605. TransactionManager->Add(this);
  606. }
  607. /*}}}*/
  608. pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
  609. {
  610. }
  611. /*}}}*/
  612. HashStringList pkgAcqTransactionItem::GetExpectedHashesFor(std::string const MetaKey) const /*{{{*/
  613. {
  614. if (TransactionManager->MetaIndexParser == NULL)
  615. return HashStringList();
  616. indexRecords::checkSum * const R = TransactionManager->MetaIndexParser->Lookup(MetaKey);
  617. if (R == NULL)
  618. return HashStringList();
  619. return R->Hashes;
  620. }
  621. /*}}}*/
  622. // AcqMetaBase - Constructor /*{{{*/
  623. pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire * const Owner,
  624. pkgAcqMetaBase * const TransactionManager,
  625. std::vector<IndexTarget*> const * const IndexTargets,
  626. IndexTarget const &DataTarget,
  627. indexRecords * const MetaIndexParser)
  628. : pkgAcqTransactionItem(Owner, TransactionManager, NULL), DataTarget(DataTarget),
  629. MetaIndexParser(MetaIndexParser), LastMetaIndexParser(NULL), IndexTargets(IndexTargets),
  630. AuthPass(false), IMSHit(false)
  631. {
  632. }
  633. /*}}}*/
  634. // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
  635. void pkgAcqMetaBase::Add(pkgAcqTransactionItem * const I)
  636. {
  637. Transaction.push_back(I);
  638. }
  639. /*}}}*/
  640. // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
  641. void pkgAcqMetaBase::AbortTransaction()
  642. {
  643. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  644. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  645. // ensure the toplevel is in error state too
  646. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  647. I != Transaction.end(); ++I)
  648. {
  649. (*I)->TransactionState(TransactionAbort);
  650. }
  651. Transaction.clear();
  652. }
  653. /*}}}*/
  654. // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
  655. APT_PURE bool pkgAcqMetaBase::TransactionHasError() const
  656. {
  657. for (std::vector<pkgAcqTransactionItem*>::const_iterator I = Transaction.begin();
  658. I != Transaction.end(); ++I)
  659. {
  660. switch((*I)->Status) {
  661. case StatDone: break;
  662. case StatIdle: break;
  663. case StatAuthError: return true;
  664. case StatError: return true;
  665. case StatTransientNetworkError: return true;
  666. case StatFetching: break;
  667. }
  668. }
  669. return false;
  670. }
  671. /*}}}*/
  672. // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
  673. void pkgAcqMetaBase::CommitTransaction()
  674. {
  675. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  676. std::clog << "CommitTransaction: " << this << std::endl;
  677. // move new files into place *and* remove files that are not
  678. // part of the transaction but are still on disk
  679. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  680. I != Transaction.end(); ++I)
  681. {
  682. (*I)->TransactionState(TransactionCommit);
  683. }
  684. Transaction.clear();
  685. }
  686. /*}}}*/
  687. // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
  688. void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem * const I,
  689. const std::string &From,
  690. const std::string &To)
  691. {
  692. I->PartialFile = From;
  693. I->DestFile = To;
  694. }
  695. /*}}}*/
  696. // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
  697. void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem * const I,
  698. const std::string &FinalFile)
  699. {
  700. I->PartialFile = "";
  701. I->DestFile = FinalFile;
  702. }
  703. /*}}}*/
  704. // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
  705. bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item * const I, const std::string &Message)
  706. {
  707. // FIXME: this entire function can do now that we disallow going to
  708. // a unauthenticated state and can cleanly rollback
  709. string const Final = I->GetFinalFilename();
  710. if(FileExists(Final))
  711. {
  712. I->Status = StatTransientNetworkError;
  713. _error->Warning(_("An error occurred during the signature "
  714. "verification. The repository is not updated "
  715. "and the previous index files will be used. "
  716. "GPG error: %s: %s\n"),
  717. Desc.Description.c_str(),
  718. LookupTag(Message,"Message").c_str());
  719. RunScripts("APT::Update::Auth-Failure");
  720. return true;
  721. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  722. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  723. _error->Error(_("GPG error: %s: %s"),
  724. Desc.Description.c_str(),
  725. LookupTag(Message,"Message").c_str());
  726. I->Status = StatError;
  727. return true;
  728. } else {
  729. _error->Warning(_("GPG error: %s: %s"),
  730. Desc.Description.c_str(),
  731. LookupTag(Message,"Message").c_str());
  732. }
  733. // gpgv method failed
  734. ReportMirrorFailure("GPGFailure");
  735. return false;
  736. }
  737. /*}}}*/
  738. // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
  739. // ---------------------------------------------------------------------
  740. string pkgAcqMetaBase::Custom600Headers() const
  741. {
  742. std::string Header = "\nIndex-File: true";
  743. std::string MaximumSize;
  744. strprintf(MaximumSize, "\nMaximum-Size: %i",
  745. _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
  746. Header += MaximumSize;
  747. string const FinalFile = GetFinalFilename();
  748. struct stat Buf;
  749. if (stat(FinalFile.c_str(),&Buf) == 0)
  750. Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  751. return Header;
  752. }
  753. /*}}}*/
  754. // AcqMetaBase::QueueForSignatureVerify /*{{{*/
  755. void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem * const I, std::string const &File, std::string const &Signature)
  756. {
  757. AuthPass = true;
  758. I->Desc.URI = "gpgv:" + Signature;
  759. I->DestFile = File;
  760. QueueURI(I->Desc);
  761. I->SetActiveSubprocess("gpgv");
  762. }
  763. /*}}}*/
  764. // AcqMetaBase::CheckDownloadDone /*{{{*/
  765. bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem * const I, const std::string &Message, HashStringList const &Hashes) const
  766. {
  767. // We have just finished downloading a Release file (it is not
  768. // verified yet)
  769. string const FileName = LookupTag(Message,"Filename");
  770. if (FileName.empty() == true)
  771. {
  772. I->Status = StatError;
  773. I->ErrorText = "Method gave a blank filename";
  774. return false;
  775. }
  776. if (FileName != I->DestFile)
  777. {
  778. I->Local = true;
  779. I->Desc.URI = "copy:" + FileName;
  780. I->QueueURI(I->Desc);
  781. return false;
  782. }
  783. // make sure to verify against the right file on I-M-S hit
  784. bool IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"), false);
  785. if (IMSHit == false && Hashes.usable())
  786. {
  787. // detect IMS-Hits servers haven't detected by Hash comparison
  788. std::string const FinalFile = I->GetFinalFilename();
  789. if (RealFileExists(FinalFile) && Hashes.VerifyFile(FinalFile) == true)
  790. {
  791. IMSHit = true;
  792. unlink(I->DestFile.c_str());
  793. }
  794. }
  795. if(IMSHit == true)
  796. {
  797. // for simplicity, the transaction manager is always InRelease
  798. // even if it doesn't exist.
  799. if (TransactionManager != NULL)
  800. TransactionManager->IMSHit = true;
  801. I->PartialFile = I->DestFile = I->GetFinalFilename();
  802. }
  803. // set Item to complete as the remaining work is all local (verify etc)
  804. I->Complete = true;
  805. return true;
  806. }
  807. /*}}}*/
  808. bool pkgAcqMetaBase::CheckAuthDone(string const &Message) /*{{{*/
  809. {
  810. // At this point, the gpgv method has succeeded, so there is a
  811. // valid signature from a key in the trusted keyring. We
  812. // perform additional verification of its contents, and use them
  813. // to verify the indexes we are about to download
  814. if (TransactionManager->IMSHit == false)
  815. {
  816. // open the last (In)Release if we have it
  817. std::string const FinalFile = GetFinalFilename();
  818. std::string FinalRelease;
  819. std::string FinalInRelease;
  820. if (APT::String::Endswith(FinalFile, "InRelease"))
  821. {
  822. FinalInRelease = FinalFile;
  823. FinalRelease = FinalFile.substr(0, FinalFile.length() - strlen("InRelease")) + "Release";
  824. }
  825. else
  826. {
  827. FinalInRelease = FinalFile.substr(0, FinalFile.length() - strlen("Release")) + "InRelease";
  828. FinalRelease = FinalFile;
  829. }
  830. if (RealFileExists(FinalInRelease) || RealFileExists(FinalRelease))
  831. {
  832. TransactionManager->LastMetaIndexParser = new indexRecords;
  833. _error->PushToStack();
  834. if (RealFileExists(FinalInRelease))
  835. TransactionManager->LastMetaIndexParser->Load(FinalInRelease);
  836. else
  837. TransactionManager->LastMetaIndexParser->Load(FinalRelease);
  838. // its unlikely to happen, but if what we have is bad ignore it
  839. if (_error->PendingError())
  840. {
  841. delete TransactionManager->LastMetaIndexParser;
  842. TransactionManager->LastMetaIndexParser = NULL;
  843. }
  844. _error->RevertToStack();
  845. }
  846. }
  847. if (TransactionManager->MetaIndexParser->Load(DestFile) == false)
  848. {
  849. Status = StatAuthError;
  850. ErrorText = TransactionManager->MetaIndexParser->ErrorText;
  851. return false;
  852. }
  853. if (!VerifyVendor(Message))
  854. {
  855. Status = StatAuthError;
  856. return false;
  857. }
  858. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  859. std::cerr << "Signature verification succeeded: "
  860. << DestFile << std::endl;
  861. // Download further indexes with verification
  862. QueueIndexes(true);
  863. return true;
  864. }
  865. /*}}}*/
  866. void pkgAcqMetaBase::QueueIndexes(bool const verify) /*{{{*/
  867. {
  868. // at this point the real Items are loaded in the fetcher
  869. ExpectedAdditionalItems = 0;
  870. vector <IndexTarget*>::const_iterator Target;
  871. for (Target = IndexTargets->begin();
  872. Target != IndexTargets->end();
  873. ++Target)
  874. {
  875. if (verify == true && TransactionManager->MetaIndexParser->Exists((*Target)->MetaKey) == false)
  876. {
  877. // optional target that we do not have in the Release file are skipped
  878. if ((*Target)->IsOptional())
  879. continue;
  880. Status = StatAuthError;
  881. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  882. return;
  883. }
  884. /* Queue the Index file (Packages, Sources, Translation-$foo
  885. (either diff or full packages files, depending
  886. on the users option) - we also check if the PDiff Index file is listed
  887. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  888. instead, but passing the required info to it is to much hassle */
  889. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  890. TransactionManager->MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
  891. new pkgAcqDiffIndex(Owner, TransactionManager, *Target);
  892. else
  893. new pkgAcqIndex(Owner, TransactionManager, *Target);
  894. }
  895. }
  896. /*}}}*/
  897. bool pkgAcqMetaBase::VerifyVendor(string const &Message) /*{{{*/
  898. {
  899. string::size_type pos;
  900. // check for missing sigs (that where not fatal because otherwise we had
  901. // bombed earlier)
  902. string missingkeys;
  903. string msg = _("There is no public key available for the "
  904. "following key IDs:\n");
  905. pos = Message.find("NO_PUBKEY ");
  906. if (pos != std::string::npos)
  907. {
  908. string::size_type start = pos+strlen("NO_PUBKEY ");
  909. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  910. missingkeys += (Fingerprint);
  911. }
  912. if(!missingkeys.empty())
  913. _error->Warning("%s", (msg + missingkeys).c_str());
  914. string Transformed = TransactionManager->MetaIndexParser->GetExpectedDist();
  915. if (Transformed == "../project/experimental")
  916. {
  917. Transformed = "experimental";
  918. }
  919. pos = Transformed.rfind('/');
  920. if (pos != string::npos)
  921. {
  922. Transformed = Transformed.substr(0, pos);
  923. }
  924. if (Transformed == ".")
  925. {
  926. Transformed = "";
  927. }
  928. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  929. TransactionManager->MetaIndexParser->GetValidUntil() > 0) {
  930. time_t const invalid_since = time(NULL) - TransactionManager->MetaIndexParser->GetValidUntil();
  931. if (invalid_since > 0)
  932. {
  933. std::string errmsg;
  934. strprintf(errmsg,
  935. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  936. // the time since then the file is invalid - formated in the same way as in
  937. // the download progress display (e.g. 7d 3h 42min 1s)
  938. _("Release file for %s is expired (invalid since %s). "
  939. "Updates for this repository will not be applied."),
  940. DataTarget.URI.c_str(), TimeToStr(invalid_since).c_str());
  941. if (ErrorText.empty())
  942. ErrorText = errmsg;
  943. return _error->Error("%s", errmsg.c_str());
  944. }
  945. }
  946. /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
  947. as a prevention of downgrading us to older (still valid) files */
  948. if (TransactionManager->IMSHit == false && TransactionManager->LastMetaIndexParser != NULL &&
  949. TransactionManager->LastMetaIndexParser->GetDate() > TransactionManager->MetaIndexParser->GetDate())
  950. {
  951. TransactionManager->IMSHit = true;
  952. unlink(DestFile.c_str());
  953. PartialFile = DestFile = GetFinalFilename();
  954. delete TransactionManager->MetaIndexParser;
  955. TransactionManager->MetaIndexParser = TransactionManager->LastMetaIndexParser;
  956. TransactionManager->LastMetaIndexParser = NULL;
  957. }
  958. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  959. {
  960. std::cerr << "Got Codename: " << TransactionManager->MetaIndexParser->GetDist() << std::endl;
  961. std::cerr << "Expecting Dist: " << TransactionManager->MetaIndexParser->GetExpectedDist() << std::endl;
  962. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  963. }
  964. if (TransactionManager->MetaIndexParser->CheckDist(Transformed) == false)
  965. {
  966. // This might become fatal one day
  967. // Status = StatAuthError;
  968. // ErrorText = "Conflicting distribution; expected "
  969. // + MetaIndexParser->GetExpectedDist() + " but got "
  970. // + MetaIndexParser->GetDist();
  971. // return false;
  972. if (!Transformed.empty())
  973. {
  974. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  975. Desc.Description.c_str(),
  976. Transformed.c_str(),
  977. TransactionManager->MetaIndexParser->GetDist().c_str());
  978. }
  979. }
  980. return true;
  981. }
  982. /*}}}*/
  983. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire * const Owner, /*{{{*/
  984. IndexTarget const &ClearsignedTarget,
  985. IndexTarget const &DetachedDataTarget, IndexTarget const &DetachedSigTarget,
  986. const vector<IndexTarget*>* const IndexTargets,
  987. indexRecords * const MetaIndexParser) :
  988. pkgAcqMetaIndex(Owner, this, ClearsignedTarget, DetachedSigTarget, IndexTargets, MetaIndexParser),
  989. ClearsignedTarget(ClearsignedTarget),
  990. DetachedDataTarget(DetachedDataTarget), DetachedSigTarget(DetachedSigTarget)
  991. {
  992. // index targets + (worst case:) Release/Release.gpg
  993. ExpectedAdditionalItems = IndexTargets->size() + 2;
  994. TransactionManager->Add(this);
  995. }
  996. /*}}}*/
  997. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  998. {
  999. }
  1000. /*}}}*/
  1001. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1002. string pkgAcqMetaClearSig::Custom600Headers() const
  1003. {
  1004. string Header = pkgAcqMetaBase::Custom600Headers();
  1005. Header += "\nFail-Ignore: true";
  1006. return Header;
  1007. }
  1008. /*}}}*/
  1009. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  1010. class APT_HIDDEN DummyItem : public pkgAcquire::Item
  1011. {
  1012. IndexTarget const * const Target;
  1013. public:
  1014. virtual std::string DescURI() const {return Target->URI;};
  1015. virtual HashStringList GetExpectedHashes() const {return HashStringList();};
  1016. DummyItem(pkgAcquire * const Owner, IndexTarget const * const Target) :
  1017. pkgAcquire::Item(Owner), Target(Target)
  1018. {
  1019. Status = StatDone;
  1020. DestFile = GetFinalFileNameFromURI(Target->URI);
  1021. }
  1022. };
  1023. void pkgAcqMetaClearSig::Done(std::string const &Message,
  1024. HashStringList const &Hashes,
  1025. pkgAcquire::MethodConfig const * const Cnf)
  1026. {
  1027. Item::Done(Message, Hashes, Cnf);
  1028. // if we expect a ClearTextSignature (InRelease), ensure that
  1029. // this is what we get and if not fail to queue a
  1030. // Release/Release.gpg, see #346386
  1031. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  1032. {
  1033. pkgAcquire::Item::Failed(Message, Cnf);
  1034. RenameOnError(NotClearsigned);
  1035. TransactionManager->AbortTransaction();
  1036. return;
  1037. }
  1038. if(AuthPass == false)
  1039. {
  1040. if(CheckDownloadDone(this, Message, Hashes) == true)
  1041. QueueForSignatureVerify(this, DestFile, DestFile);
  1042. return;
  1043. }
  1044. else if(CheckAuthDone(Message) == true)
  1045. {
  1046. if (TransactionManager->IMSHit == false)
  1047. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1048. else if (RealFileExists(GetFinalFilename()) == false)
  1049. {
  1050. // We got an InRelease file IMSHit, but we haven't one, which means
  1051. // we had a valid Release/Release.gpg combo stepping in, which we have
  1052. // to 'acquire' now to ensure list cleanup isn't removing them
  1053. new DummyItem(Owner, &DetachedDataTarget);
  1054. new DummyItem(Owner, &DetachedSigTarget);
  1055. }
  1056. }
  1057. }
  1058. /*}}}*/
  1059. void pkgAcqMetaClearSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf) /*{{{*/
  1060. {
  1061. Item::Failed(Message, Cnf);
  1062. // we failed, we will not get additional items from this method
  1063. ExpectedAdditionalItems = 0;
  1064. if (AuthPass == false)
  1065. {
  1066. // Queue the 'old' InRelease file for removal if we try Release.gpg
  1067. // as otherwise the file will stay around and gives a false-auth
  1068. // impression (CVE-2012-0214)
  1069. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1070. Status = StatDone;
  1071. new pkgAcqMetaIndex(Owner, TransactionManager, DetachedDataTarget, DetachedSigTarget, IndexTargets, TransactionManager->MetaIndexParser);
  1072. }
  1073. else
  1074. {
  1075. if(CheckStopAuthentication(this, Message))
  1076. return;
  1077. _error->Warning(_("The data from '%s' is not signed. Packages "
  1078. "from that repository can not be authenticated."),
  1079. ClearsignedTarget.Description.c_str());
  1080. // No Release file was present, or verification failed, so fall
  1081. // back to queueing Packages files without verification
  1082. // only allow going further if the users explicitely wants it
  1083. if(AllowInsecureRepositories(TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1084. {
  1085. Status = StatDone;
  1086. /* InRelease files become Release files, otherwise
  1087. * they would be considered as trusted later on */
  1088. string const FinalRelease = GetFinalFileNameFromURI(DetachedDataTarget.URI);
  1089. string const PartialRelease = GetPartialFileNameFromURI(DetachedDataTarget.URI);
  1090. string const FinalReleasegpg = GetFinalFileNameFromURI(DetachedSigTarget.URI);
  1091. string const FinalInRelease = GetFinalFilename();
  1092. Rename(DestFile, PartialRelease);
  1093. TransactionManager->TransactionStageCopy(this, PartialRelease, FinalRelease);
  1094. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1095. {
  1096. // open the last Release if we have it
  1097. if (TransactionManager->IMSHit == false)
  1098. {
  1099. TransactionManager->LastMetaIndexParser = new indexRecords;
  1100. _error->PushToStack();
  1101. if (RealFileExists(FinalInRelease))
  1102. TransactionManager->LastMetaIndexParser->Load(FinalInRelease);
  1103. else
  1104. TransactionManager->LastMetaIndexParser->Load(FinalRelease);
  1105. // its unlikely to happen, but if what we have is bad ignore it
  1106. if (_error->PendingError())
  1107. {
  1108. delete TransactionManager->LastMetaIndexParser;
  1109. TransactionManager->LastMetaIndexParser = NULL;
  1110. }
  1111. _error->RevertToStack();
  1112. }
  1113. }
  1114. // we parse the indexes here because at this point the user wanted
  1115. // a repository that may potentially harm him
  1116. if (TransactionManager->MetaIndexParser->Load(PartialRelease) == false || VerifyVendor(Message) == false)
  1117. /* expired Release files are still a problem you need extra force for */;
  1118. else
  1119. QueueIndexes(true);
  1120. }
  1121. }
  1122. }
  1123. /*}}}*/
  1124. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire * const Owner, /*{{{*/
  1125. pkgAcqMetaBase * const TransactionManager,
  1126. IndexTarget const &DataTarget,
  1127. IndexTarget const &DetachedSigTarget,
  1128. vector<IndexTarget*> const * const IndexTargets,
  1129. indexRecords * const MetaIndexParser) :
  1130. pkgAcqMetaBase(Owner, TransactionManager, IndexTargets, DataTarget, MetaIndexParser),
  1131. DetachedSigTarget(DetachedSigTarget)
  1132. {
  1133. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1134. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1135. << this->TransactionManager << std::endl;
  1136. DestFile = GetPartialFileNameFromURI(DataTarget.URI);
  1137. // Create the item
  1138. Desc.Description = DataTarget.Description;
  1139. Desc.Owner = this;
  1140. Desc.ShortDesc = DataTarget.ShortDesc;
  1141. Desc.URI = DataTarget.URI;
  1142. // we expect more item
  1143. ExpectedAdditionalItems = IndexTargets->size();
  1144. QueueURI(Desc);
  1145. }
  1146. /*}}}*/
  1147. void pkgAcqMetaIndex::Done(string const &Message, /*{{{*/
  1148. HashStringList const &Hashes,
  1149. pkgAcquire::MethodConfig const * const Cfg)
  1150. {
  1151. Item::Done(Message,Hashes,Cfg);
  1152. if(CheckDownloadDone(this, Message, Hashes))
  1153. {
  1154. // we have a Release file, now download the Signature, all further
  1155. // verify/queue for additional downloads will be done in the
  1156. // pkgAcqMetaSig::Done() code
  1157. new pkgAcqMetaSig(Owner, TransactionManager, &DetachedSigTarget, this);
  1158. }
  1159. }
  1160. /*}}}*/
  1161. // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
  1162. void pkgAcqMetaIndex::Failed(string const &Message,
  1163. pkgAcquire::MethodConfig const * const Cnf)
  1164. {
  1165. pkgAcquire::Item::Failed(Message, Cnf);
  1166. Status = StatDone;
  1167. _error->Warning(_("The repository '%s' does not have a Release file. "
  1168. "This is deprecated, please contact the owner of the "
  1169. "repository."), DataTarget.Description.c_str());
  1170. // No Release file was present so fall
  1171. // back to queueing Packages files without verification
  1172. // only allow going further if the users explicitely wants it
  1173. if(AllowInsecureRepositories(TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1174. {
  1175. // ensure old Release files are removed
  1176. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1177. delete TransactionManager->MetaIndexParser;
  1178. TransactionManager->MetaIndexParser = NULL;
  1179. // queue without any kind of hashsum support
  1180. QueueIndexes(false);
  1181. }
  1182. }
  1183. /*}}}*/
  1184. void pkgAcqMetaIndex::Finished() /*{{{*/
  1185. {
  1186. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1187. std::clog << "Finished: " << DestFile <<std::endl;
  1188. if(TransactionManager != NULL &&
  1189. TransactionManager->TransactionHasError() == false)
  1190. TransactionManager->CommitTransaction();
  1191. }
  1192. /*}}}*/
  1193. std::string pkgAcqMetaIndex::DescURI() const /*{{{*/
  1194. {
  1195. return DataTarget.URI;
  1196. }
  1197. /*}}}*/
  1198. // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
  1199. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire * const Owner,
  1200. pkgAcqMetaBase * const TransactionManager,
  1201. IndexTarget const * const Target,
  1202. pkgAcqMetaIndex * const MetaIndex) :
  1203. pkgAcqTransactionItem(Owner, TransactionManager, Target), MetaIndex(MetaIndex)
  1204. {
  1205. DestFile = GetPartialFileNameFromURI(Target->URI);
  1206. // remove any partial downloaded sig-file in partial/.
  1207. // it may confuse proxies and is too small to warrant a
  1208. // partial download anyway
  1209. unlink(DestFile.c_str());
  1210. // set the TransactionManager
  1211. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1212. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1213. << TransactionManager << std::endl;
  1214. // Create the item
  1215. Desc.Description = Target->Description;
  1216. Desc.Owner = this;
  1217. Desc.ShortDesc = Target->ShortDesc;
  1218. Desc.URI = Target->URI;
  1219. // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
  1220. // so we skip the download step and go instantly to verification
  1221. if (TransactionManager->IMSHit == true && RealFileExists(GetFinalFilename()))
  1222. {
  1223. Complete = true;
  1224. Status = StatDone;
  1225. PartialFile = DestFile = GetFinalFilename();
  1226. MetaIndexFileSignature = DestFile;
  1227. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1228. }
  1229. else
  1230. QueueURI(Desc);
  1231. }
  1232. /*}}}*/
  1233. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1234. {
  1235. }
  1236. /*}}}*/
  1237. // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
  1238. void pkgAcqMetaSig::Done(string const &Message, HashStringList const &Hashes,
  1239. pkgAcquire::MethodConfig const * const Cfg)
  1240. {
  1241. if (MetaIndexFileSignature.empty() == false)
  1242. {
  1243. DestFile = MetaIndexFileSignature;
  1244. MetaIndexFileSignature.clear();
  1245. }
  1246. Item::Done(Message, Hashes, Cfg);
  1247. if(MetaIndex->AuthPass == false)
  1248. {
  1249. if(MetaIndex->CheckDownloadDone(this, Message, Hashes) == true)
  1250. {
  1251. // destfile will be modified to point to MetaIndexFile for the
  1252. // gpgv method, so we need to save it here
  1253. MetaIndexFileSignature = DestFile;
  1254. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1255. }
  1256. return;
  1257. }
  1258. else if(MetaIndex->CheckAuthDone(Message) == true)
  1259. {
  1260. if (TransactionManager->IMSHit == false)
  1261. {
  1262. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1263. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1264. }
  1265. }
  1266. }
  1267. /*}}}*/
  1268. void pkgAcqMetaSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1269. {
  1270. Item::Failed(Message,Cnf);
  1271. // check if we need to fail at this point
  1272. if (MetaIndex->AuthPass == true && MetaIndex->CheckStopAuthentication(this, Message))
  1273. return;
  1274. string const FinalRelease = MetaIndex->GetFinalFilename();
  1275. string const FinalReleasegpg = GetFinalFilename();
  1276. string const FinalInRelease = TransactionManager->GetFinalFilename();
  1277. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1278. {
  1279. std::string downgrade_msg;
  1280. strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
  1281. MetaIndex->DataTarget.Description.c_str());
  1282. if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
  1283. {
  1284. // meh, the users wants to take risks (we still mark the packages
  1285. // from this repository as unauthenticated)
  1286. _error->Warning("%s", downgrade_msg.c_str());
  1287. _error->Warning(_("This is normally not allowed, but the option "
  1288. "Acquire::AllowDowngradeToInsecureRepositories was "
  1289. "given to override it."));
  1290. Status = StatDone;
  1291. } else {
  1292. _error->Error("%s", downgrade_msg.c_str());
  1293. if (TransactionManager->IMSHit == false)
  1294. Rename(MetaIndex->DestFile, MetaIndex->DestFile + ".FAILED");
  1295. Item::Failed("Message: " + downgrade_msg, Cnf);
  1296. TransactionManager->AbortTransaction();
  1297. return;
  1298. }
  1299. }
  1300. else
  1301. _error->Warning(_("The data from '%s' is not signed. Packages "
  1302. "from that repository can not be authenticated."),
  1303. MetaIndex->DataTarget.Description.c_str());
  1304. // ensures that a Release.gpg file in the lists/ is removed by the transaction
  1305. TransactionManager->TransactionStageRemoval(this, DestFile);
  1306. // only allow going further if the users explicitely wants it
  1307. if(AllowInsecureRepositories(TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1308. {
  1309. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1310. {
  1311. // open the last Release if we have it
  1312. if (TransactionManager->IMSHit == false)
  1313. {
  1314. TransactionManager->LastMetaIndexParser = new indexRecords;
  1315. _error->PushToStack();
  1316. if (RealFileExists(FinalInRelease))
  1317. TransactionManager->LastMetaIndexParser->Load(FinalInRelease);
  1318. else
  1319. TransactionManager->LastMetaIndexParser->Load(FinalRelease);
  1320. // its unlikely to happen, but if what we have is bad ignore it
  1321. if (_error->PendingError())
  1322. {
  1323. delete TransactionManager->LastMetaIndexParser;
  1324. TransactionManager->LastMetaIndexParser = NULL;
  1325. }
  1326. _error->RevertToStack();
  1327. }
  1328. }
  1329. // we parse the indexes here because at this point the user wanted
  1330. // a repository that may potentially harm him
  1331. if (TransactionManager->MetaIndexParser->Load(MetaIndex->DestFile) == false || MetaIndex->VerifyVendor(Message) == false)
  1332. /* expired Release files are still a problem you need extra force for */;
  1333. else
  1334. MetaIndex->QueueIndexes(true);
  1335. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1336. }
  1337. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1338. if (Cnf->LocalOnly == true ||
  1339. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1340. {
  1341. // Ignore this
  1342. Status = StatDone;
  1343. }
  1344. }
  1345. /*}}}*/
  1346. // AcqBaseIndex - Constructor /*{{{*/
  1347. pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire * const Owner,
  1348. pkgAcqMetaBase * const TransactionManager,
  1349. IndexTarget const * const Target)
  1350. : pkgAcqTransactionItem(Owner, TransactionManager, Target)
  1351. {
  1352. }
  1353. /*}}}*/
  1354. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  1355. // ---------------------------------------------------------------------
  1356. /* Get the DiffIndex file first and see if there are patches available
  1357. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  1358. * patches. If anything goes wrong in that process, it will fall back to
  1359. * the original packages file
  1360. */
  1361. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire * const Owner,
  1362. pkgAcqMetaBase * const TransactionManager,
  1363. IndexTarget const * const Target)
  1364. : pkgAcqBaseIndex(Owner, TransactionManager, Target)
  1365. {
  1366. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1367. Desc.Owner = this;
  1368. Desc.Description = Target->Description + ".diff/Index";
  1369. Desc.ShortDesc = Target->ShortDesc;
  1370. Desc.URI = Target->URI + ".diff/Index";
  1371. DestFile = GetPartialFileNameFromURI(Desc.URI);
  1372. if(Debug)
  1373. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  1374. // look for the current package file
  1375. CurrentPackagesFile = GetFinalFileNameFromURI(Target->URI);
  1376. // FIXME: this file:/ check is a hack to prevent fetching
  1377. // from local sources. this is really silly, and
  1378. // should be fixed cleanly as soon as possible
  1379. if(!FileExists(CurrentPackagesFile) ||
  1380. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  1381. {
  1382. // we don't have a pkg file or we don't want to queue
  1383. Failed("No index file, local or canceld by user", NULL);
  1384. return;
  1385. }
  1386. if(Debug)
  1387. std::clog << "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
  1388. << CurrentPackagesFile << std::endl;
  1389. QueueURI(Desc);
  1390. }
  1391. /*}}}*/
  1392. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1393. // ---------------------------------------------------------------------
  1394. /* The only header we use is the last-modified header. */
  1395. string pkgAcqDiffIndex::Custom600Headers() const
  1396. {
  1397. string const Final = GetFinalFilename();
  1398. if(Debug)
  1399. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  1400. struct stat Buf;
  1401. if (stat(Final.c_str(),&Buf) != 0)
  1402. return "\nIndex-File: true";
  1403. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1404. }
  1405. /*}}}*/
  1406. void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
  1407. {
  1408. // list cleanup needs to know that this file as well as the already
  1409. // present index is ours, so we create an empty diff to save it for us
  1410. new pkgAcqIndexDiffs(Owner, TransactionManager, Target);
  1411. }
  1412. /*}}}*/
  1413. bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/
  1414. {
  1415. // failing here is fine: our caller will take care of trying to
  1416. // get the complete file if patching fails
  1417. if(Debug)
  1418. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  1419. << std::endl;
  1420. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  1421. pkgTagFile TF(&Fd);
  1422. if (_error->PendingError() == true)
  1423. return false;
  1424. pkgTagSection Tags;
  1425. if(unlikely(TF.Step(Tags) == false))
  1426. return false;
  1427. HashStringList ServerHashes;
  1428. unsigned long long ServerSize = 0;
  1429. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1430. {
  1431. std::string tagname = *type;
  1432. tagname.append("-Current");
  1433. std::string const tmp = Tags.FindS(tagname.c_str());
  1434. if (tmp.empty() == true)
  1435. continue;
  1436. string hash;
  1437. unsigned long long size;
  1438. std::stringstream ss(tmp);
  1439. ss >> hash >> size;
  1440. if (unlikely(hash.empty() == true))
  1441. continue;
  1442. if (unlikely(ServerSize != 0 && ServerSize != size))
  1443. continue;
  1444. ServerHashes.push_back(HashString(*type, hash));
  1445. ServerSize = size;
  1446. }
  1447. if (ServerHashes.usable() == false)
  1448. {
  1449. if (Debug == true)
  1450. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
  1451. return false;
  1452. }
  1453. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target->MetaKey);
  1454. if (TargetFileHashes.usable() == false || ServerHashes != TargetFileHashes)
  1455. {
  1456. if (Debug == true)
  1457. {
  1458. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
  1459. printHashSumComparision(CurrentPackagesFile, ServerHashes, TargetFileHashes);
  1460. }
  1461. return false;
  1462. }
  1463. if (ServerHashes.VerifyFile(CurrentPackagesFile) == true)
  1464. {
  1465. // we have the same sha1 as the server so we are done here
  1466. if(Debug)
  1467. std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
  1468. QueueOnIMSHit();
  1469. return true;
  1470. }
  1471. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  1472. Hashes LocalHashesCalc;
  1473. LocalHashesCalc.AddFD(fd);
  1474. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  1475. if(Debug)
  1476. std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
  1477. << fd.Name() << " " << fd.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
  1478. // parse all of (provided) history
  1479. vector<DiffInfo> available_patches;
  1480. bool firstAcceptedHashes = true;
  1481. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1482. {
  1483. if (LocalHashes.find(*type) == NULL)
  1484. continue;
  1485. std::string tagname = *type;
  1486. tagname.append("-History");
  1487. std::string const tmp = Tags.FindS(tagname.c_str());
  1488. if (tmp.empty() == true)
  1489. continue;
  1490. string hash, filename;
  1491. unsigned long long size;
  1492. std::stringstream ss(tmp);
  1493. while (ss >> hash >> size >> filename)
  1494. {
  1495. if (unlikely(hash.empty() == true || filename.empty() == true))
  1496. continue;
  1497. // see if we have a record for this file already
  1498. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1499. for (; cur != available_patches.end(); ++cur)
  1500. {
  1501. if (cur->file != filename)
  1502. continue;
  1503. cur->result_hashes.push_back(HashString(*type, hash));
  1504. break;
  1505. }
  1506. if (cur != available_patches.end())
  1507. continue;
  1508. if (firstAcceptedHashes == true)
  1509. {
  1510. DiffInfo next;
  1511. next.file = filename;
  1512. next.result_hashes.push_back(HashString(*type, hash));
  1513. next.result_hashes.FileSize(size);
  1514. available_patches.push_back(next);
  1515. }
  1516. else
  1517. {
  1518. if (Debug == true)
  1519. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1520. << " wasn't in the list for the first parsed hash! (history)" << std::endl;
  1521. break;
  1522. }
  1523. }
  1524. firstAcceptedHashes = false;
  1525. }
  1526. if (unlikely(available_patches.empty() == true))
  1527. {
  1528. if (Debug)
  1529. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  1530. << "Couldn't find any patches for the patch series." << std::endl;
  1531. return false;
  1532. }
  1533. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1534. {
  1535. if (LocalHashes.find(*type) == NULL)
  1536. continue;
  1537. std::string tagname = *type;
  1538. tagname.append("-Patches");
  1539. std::string const tmp = Tags.FindS(tagname.c_str());
  1540. if (tmp.empty() == true)
  1541. continue;
  1542. string hash, filename;
  1543. unsigned long long size;
  1544. std::stringstream ss(tmp);
  1545. while (ss >> hash >> size >> filename)
  1546. {
  1547. if (unlikely(hash.empty() == true || filename.empty() == true))
  1548. continue;
  1549. // see if we have a record for this file already
  1550. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1551. for (; cur != available_patches.end(); ++cur)
  1552. {
  1553. if (cur->file != filename)
  1554. continue;
  1555. if (cur->patch_hashes.empty())
  1556. cur->patch_hashes.FileSize(size);
  1557. cur->patch_hashes.push_back(HashString(*type, hash));
  1558. break;
  1559. }
  1560. if (cur != available_patches.end())
  1561. continue;
  1562. if (Debug == true)
  1563. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1564. << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
  1565. break;
  1566. }
  1567. }
  1568. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1569. {
  1570. std::string tagname = *type;
  1571. tagname.append("-Download");
  1572. std::string const tmp = Tags.FindS(tagname.c_str());
  1573. if (tmp.empty() == true)
  1574. continue;
  1575. string hash, filename;
  1576. unsigned long long size;
  1577. std::stringstream ss(tmp);
  1578. // FIXME: all of pdiff supports only .gz compressed patches
  1579. while (ss >> hash >> size >> filename)
  1580. {
  1581. if (unlikely(hash.empty() == true || filename.empty() == true))
  1582. continue;
  1583. if (unlikely(APT::String::Endswith(filename, ".gz") == false))
  1584. continue;
  1585. filename.erase(filename.length() - 3);
  1586. // see if we have a record for this file already
  1587. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1588. for (; cur != available_patches.end(); ++cur)
  1589. {
  1590. if (cur->file != filename)
  1591. continue;
  1592. if (cur->download_hashes.empty())
  1593. cur->download_hashes.FileSize(size);
  1594. cur->download_hashes.push_back(HashString(*type, hash));
  1595. break;
  1596. }
  1597. if (cur != available_patches.end())
  1598. continue;
  1599. if (Debug == true)
  1600. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1601. << " wasn't in the list for the first parsed hash! (download)" << std::endl;
  1602. break;
  1603. }
  1604. }
  1605. bool foundStart = false;
  1606. for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1607. cur != available_patches.end(); ++cur)
  1608. {
  1609. if (LocalHashes != cur->result_hashes)
  1610. continue;
  1611. available_patches.erase(available_patches.begin(), cur);
  1612. foundStart = true;
  1613. break;
  1614. }
  1615. if (foundStart == false || unlikely(available_patches.empty() == true))
  1616. {
  1617. if (Debug)
  1618. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  1619. << "Couldn't find the start of the patch series." << std::endl;
  1620. return false;
  1621. }
  1622. // patching with too many files is rather slow compared to a fast download
  1623. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  1624. if (fileLimit != 0 && fileLimit < available_patches.size())
  1625. {
  1626. if (Debug)
  1627. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  1628. << ") so fallback to complete download" << std::endl;
  1629. return false;
  1630. }
  1631. // calculate the size of all patches we have to get
  1632. // note that all sizes are uncompressed, while we download compressed files
  1633. unsigned long long patchesSize = 0;
  1634. for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
  1635. cur != available_patches.end(); ++cur)
  1636. patchesSize += cur->patch_hashes.FileSize();
  1637. unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  1638. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  1639. {
  1640. if (Debug)
  1641. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  1642. << ") so fallback to complete download" << std::endl;
  1643. return false;
  1644. }
  1645. // we have something, queue the diffs
  1646. string::size_type const last_space = Description.rfind(" ");
  1647. if(last_space != string::npos)
  1648. Description.erase(last_space, Description.size()-last_space);
  1649. /* decide if we should download patches one by one or in one go:
  1650. The first is good if the server merges patches, but many don't so client
  1651. based merging can be attempt in which case the second is better.
  1652. "bad things" will happen if patches are merged on the server,
  1653. but client side merging is attempt as well */
  1654. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  1655. if (pdiff_merge == true)
  1656. {
  1657. // reprepro adds this flag if it has merged patches on the server
  1658. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  1659. pdiff_merge = (precedence != "merged");
  1660. }
  1661. if (pdiff_merge == false)
  1662. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
  1663. else
  1664. {
  1665. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  1666. for(size_t i = 0; i < available_patches.size(); ++i)
  1667. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
  1668. Target,
  1669. available_patches[i],
  1670. diffs);
  1671. }
  1672. Complete = false;
  1673. Status = StatDone;
  1674. Dequeue();
  1675. return true;
  1676. }
  1677. /*}}}*/
  1678. void pkgAcqDiffIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1679. {
  1680. Item::Failed(Message,Cnf);
  1681. Status = StatDone;
  1682. if(Debug)
  1683. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  1684. << "Falling back to normal index file acquire" << std::endl;
  1685. new pkgAcqIndex(Owner, TransactionManager, Target);
  1686. }
  1687. /*}}}*/
  1688. void pkgAcqDiffIndex::Done(string const &Message,HashStringList const &Hashes, /*{{{*/
  1689. pkgAcquire::MethodConfig const * const Cnf)
  1690. {
  1691. if(Debug)
  1692. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  1693. Item::Done(Message, Hashes, Cnf);
  1694. string const FinalFile = GetFinalFilename();
  1695. if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
  1696. DestFile = FinalFile;
  1697. if(ParseDiffIndex(DestFile) == false)
  1698. {
  1699. Failed("Message: Couldn't parse pdiff index", Cnf);
  1700. // queue for final move - this should happen even if we fail
  1701. // while parsing (e.g. on sizelimit) and download the complete file.
  1702. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1703. return;
  1704. }
  1705. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1706. Complete = true;
  1707. Status = StatDone;
  1708. Dequeue();
  1709. return;
  1710. }
  1711. /*}}}*/
  1712. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  1713. // ---------------------------------------------------------------------
  1714. /* The package diff is added to the queue. one object is constructed
  1715. * for each diff and the index
  1716. */
  1717. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire * const Owner,
  1718. pkgAcqMetaBase * const TransactionManager,
  1719. IndexTarget const * const Target,
  1720. vector<DiffInfo> const &diffs)
  1721. : pkgAcqBaseIndex(Owner, TransactionManager, Target),
  1722. available_patches(diffs)
  1723. {
  1724. DestFile = GetPartialFileNameFromURI(Target->URI);
  1725. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1726. Desc.Owner = this;
  1727. Description = Target->Description;
  1728. Desc.ShortDesc = Target->ShortDesc;
  1729. if(available_patches.empty() == true)
  1730. {
  1731. // we are done (yeah!), check hashes against the final file
  1732. DestFile = GetFinalFileNameFromURI(Target->URI);
  1733. Finish(true);
  1734. }
  1735. else
  1736. {
  1737. // patching needs to be bootstrapped with the 'old' version
  1738. std::string const PartialFile = GetPartialFileNameFromURI(Target->URI);
  1739. if (RealFileExists(PartialFile) == false)
  1740. {
  1741. if (symlink(GetFinalFilename().c_str(), PartialFile.c_str()) != 0)
  1742. {
  1743. Failed("Link creation of " + PartialFile + " to " + GetFinalFilename() + " failed", NULL);
  1744. return;
  1745. }
  1746. }
  1747. // get the next diff
  1748. State = StateFetchDiff;
  1749. QueueNextDiff();
  1750. }
  1751. }
  1752. /*}}}*/
  1753. void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1754. {
  1755. Item::Failed(Message,Cnf);
  1756. Status = StatDone;
  1757. if(Debug)
  1758. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  1759. << "Falling back to normal index file acquire" << std::endl;
  1760. DestFile = GetPartialFileNameFromURI(Target->URI);
  1761. RenameOnError(PDiffError);
  1762. std::string const patchname = GetDiffsPatchFileName(DestFile);
  1763. if (RealFileExists(patchname))
  1764. rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
  1765. new pkgAcqIndex(Owner, TransactionManager, Target);
  1766. Finish();
  1767. }
  1768. /*}}}*/
  1769. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  1770. void pkgAcqIndexDiffs::Finish(bool allDone)
  1771. {
  1772. if(Debug)
  1773. std::clog << "pkgAcqIndexDiffs::Finish(): "
  1774. << allDone << " "
  1775. << Desc.URI << std::endl;
  1776. // we restore the original name, this is required, otherwise
  1777. // the file will be cleaned
  1778. if(allDone)
  1779. {
  1780. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1781. // this is for the "real" finish
  1782. Complete = true;
  1783. Status = StatDone;
  1784. Dequeue();
  1785. if(Debug)
  1786. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  1787. return;
  1788. }
  1789. if(Debug)
  1790. std::clog << "Finishing: " << Desc.URI << std::endl;
  1791. Complete = false;
  1792. Status = StatDone;
  1793. Dequeue();
  1794. return;
  1795. }
  1796. /*}}}*/
  1797. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  1798. {
  1799. // calc sha1 of the just patched file
  1800. std::string const FinalFile = GetPartialFileNameFromURI(Target->URI);
  1801. if(!FileExists(FinalFile))
  1802. {
  1803. Failed("Message: No FinalFile " + FinalFile + " available", NULL);
  1804. return false;
  1805. }
  1806. FileFd fd(FinalFile, FileFd::ReadOnly);
  1807. Hashes LocalHashesCalc;
  1808. LocalHashesCalc.AddFD(fd);
  1809. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  1810. if(Debug)
  1811. std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
  1812. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target->MetaKey);
  1813. if (unlikely(LocalHashes.usable() == false || TargetFileHashes.usable() == false))
  1814. {
  1815. Failed("Local/Expected hashes are not usable", NULL);
  1816. return false;
  1817. }
  1818. // final file reached before all patches are applied
  1819. if(LocalHashes == TargetFileHashes)
  1820. {
  1821. Finish(true);
  1822. return true;
  1823. }
  1824. // remove all patches until the next matching patch is found
  1825. // this requires the Index file to be ordered
  1826. for(vector<DiffInfo>::iterator I = available_patches.begin();
  1827. available_patches.empty() == false &&
  1828. I != available_patches.end() &&
  1829. I->result_hashes != LocalHashes;
  1830. ++I)
  1831. {
  1832. available_patches.erase(I);
  1833. }
  1834. // error checking and falling back if no patch was found
  1835. if(available_patches.empty() == true)
  1836. {
  1837. Failed("No patches left to reach target", NULL);
  1838. return false;
  1839. }
  1840. // queue the right diff
  1841. Desc.URI = Target->URI + ".diff/" + available_patches[0].file + ".gz";
  1842. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  1843. DestFile = GetPartialFileNameFromURI(Target->URI + ".diff/" + available_patches[0].file);
  1844. if(Debug)
  1845. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  1846. QueueURI(Desc);
  1847. return true;
  1848. }
  1849. /*}}}*/
  1850. void pkgAcqIndexDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  1851. pkgAcquire::MethodConfig const * const Cnf)
  1852. {
  1853. if(Debug)
  1854. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  1855. Item::Done(Message, Hashes, Cnf);
  1856. std::string const FinalFile = GetPartialFileNameFromURI(Target->URI);
  1857. std::string const PatchFile = GetDiffsPatchFileName(FinalFile);
  1858. // success in downloading a diff, enter ApplyDiff state
  1859. if(State == StateFetchDiff)
  1860. {
  1861. Rename(DestFile, PatchFile);
  1862. if(Debug)
  1863. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  1864. State = StateApplyDiff;
  1865. Local = true;
  1866. Desc.URI = "rred:" + FinalFile;
  1867. QueueURI(Desc);
  1868. SetActiveSubprocess("rred");
  1869. return;
  1870. }
  1871. // success in download/apply a diff, queue next (if needed)
  1872. if(State == StateApplyDiff)
  1873. {
  1874. // remove the just applied patch
  1875. available_patches.erase(available_patches.begin());
  1876. unlink(PatchFile.c_str());
  1877. // move into place
  1878. if(Debug)
  1879. {
  1880. std::clog << "Moving patched file in place: " << std::endl
  1881. << DestFile << " -> " << FinalFile << std::endl;
  1882. }
  1883. Rename(DestFile,FinalFile);
  1884. chmod(FinalFile.c_str(),0644);
  1885. // see if there is more to download
  1886. if(available_patches.empty() == false) {
  1887. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  1888. available_patches);
  1889. return Finish();
  1890. } else
  1891. // update
  1892. DestFile = FinalFile;
  1893. return Finish(true);
  1894. }
  1895. }
  1896. /*}}}*/
  1897. std::string pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
  1898. {
  1899. if(State != StateApplyDiff)
  1900. return pkgAcqBaseIndex::Custom600Headers();
  1901. std::ostringstream patchhashes;
  1902. HashStringList const ExpectedHashes = available_patches[0].patch_hashes;
  1903. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  1904. patchhashes << "\nPatch-0-" << hs->HashType() << "-Hash: " << hs->HashValue();
  1905. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  1906. return patchhashes.str();
  1907. }
  1908. /*}}}*/
  1909. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  1910. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire * const Owner,
  1911. pkgAcqMetaBase * const TransactionManager,
  1912. IndexTarget const * const Target,
  1913. DiffInfo const &patch,
  1914. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  1915. : pkgAcqBaseIndex(Owner, TransactionManager, Target),
  1916. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  1917. {
  1918. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1919. Desc.Owner = this;
  1920. Description = Target->Description;
  1921. Desc.ShortDesc = Target->ShortDesc;
  1922. Desc.URI = Target->URI + ".diff/" + patch.file + ".gz";
  1923. Desc.Description = Description + " " + patch.file + string(".pdiff");
  1924. DestFile = GetPartialFileNameFromURI(Target->URI + ".diff/" + patch.file);
  1925. if(Debug)
  1926. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  1927. QueueURI(Desc);
  1928. }
  1929. /*}}}*/
  1930. void pkgAcqIndexMergeDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1931. {
  1932. if(Debug)
  1933. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  1934. Item::Failed(Message,Cnf);
  1935. Status = StatDone;
  1936. // check if we are the first to fail, otherwise we are done here
  1937. State = StateDoneDiff;
  1938. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  1939. I != allPatches->end(); ++I)
  1940. if ((*I)->State == StateErrorDiff)
  1941. return;
  1942. // first failure means we should fallback
  1943. State = StateErrorDiff;
  1944. if (Debug)
  1945. std::clog << "Falling back to normal index file acquire" << std::endl;
  1946. DestFile = GetPartialFileNameFromURI(Target->URI);
  1947. RenameOnError(PDiffError);
  1948. std::string const patchname = GetMergeDiffsPatchFileName(DestFile, patch.file);
  1949. if (RealFileExists(patchname))
  1950. rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
  1951. new pkgAcqIndex(Owner, TransactionManager, Target);
  1952. }
  1953. /*}}}*/
  1954. void pkgAcqIndexMergeDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  1955. pkgAcquire::MethodConfig const * const Cnf)
  1956. {
  1957. if(Debug)
  1958. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  1959. Item::Done(Message, Hashes, Cnf);
  1960. string const FinalFile = GetPartialFileNameFromURI(Target->URI);
  1961. if (State == StateFetchDiff)
  1962. {
  1963. Rename(DestFile, GetMergeDiffsPatchFileName(FinalFile, patch.file));
  1964. // check if this is the last completed diff
  1965. State = StateDoneDiff;
  1966. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  1967. I != allPatches->end(); ++I)
  1968. if ((*I)->State != StateDoneDiff)
  1969. {
  1970. if(Debug)
  1971. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  1972. return;
  1973. }
  1974. // this is the last completed diff, so we are ready to apply now
  1975. State = StateApplyDiff;
  1976. // patching needs to be bootstrapped with the 'old' version
  1977. if (symlink(GetFinalFilename().c_str(), FinalFile.c_str()) != 0)
  1978. {
  1979. Failed("Link creation of " + FinalFile + " to " + GetFinalFilename() + " failed", NULL);
  1980. return;
  1981. }
  1982. if(Debug)
  1983. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  1984. Local = true;
  1985. Desc.URI = "rred:" + FinalFile;
  1986. QueueURI(Desc);
  1987. SetActiveSubprocess("rred");
  1988. return;
  1989. }
  1990. // success in download/apply all diffs, clean up
  1991. else if (State == StateApplyDiff)
  1992. {
  1993. // move the result into place
  1994. std::string const Final = GetFinalFilename();
  1995. if(Debug)
  1996. std::clog << "Queue patched file in place: " << std::endl
  1997. << DestFile << " -> " << Final << std::endl;
  1998. // queue for copy by the transaction manager
  1999. TransactionManager->TransactionStageCopy(this, DestFile, Final);
  2000. // ensure the ed's are gone regardless of list-cleanup
  2001. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2002. I != allPatches->end(); ++I)
  2003. {
  2004. std::string const PartialFile = GetPartialFileNameFromURI(Target->URI);
  2005. std::string const patch = GetMergeDiffsPatchFileName(PartialFile, (*I)->patch.file);
  2006. unlink(patch.c_str());
  2007. }
  2008. unlink(FinalFile.c_str());
  2009. // all set and done
  2010. Complete = true;
  2011. if(Debug)
  2012. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  2013. }
  2014. }
  2015. /*}}}*/
  2016. std::string pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
  2017. {
  2018. if(State != StateApplyDiff)
  2019. return pkgAcqBaseIndex::Custom600Headers();
  2020. std::ostringstream patchhashes;
  2021. unsigned int seen_patches = 0;
  2022. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2023. I != allPatches->end(); ++I)
  2024. {
  2025. HashStringList const ExpectedHashes = (*I)->patch.patch_hashes;
  2026. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  2027. patchhashes << "\nPatch-" << seen_patches << "-" << hs->HashType() << "-Hash: " << hs->HashValue();
  2028. ++seen_patches;
  2029. }
  2030. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  2031. return patchhashes.str();
  2032. }
  2033. /*}}}*/
  2034. // AcqIndex::AcqIndex - Constructor /*{{{*/
  2035. pkgAcqIndex::pkgAcqIndex(pkgAcquire * const Owner,
  2036. pkgAcqMetaBase * const TransactionManager,
  2037. IndexTarget const * const Target)
  2038. : pkgAcqBaseIndex(Owner, TransactionManager, Target)
  2039. {
  2040. // autoselect the compression method
  2041. AutoSelectCompression();
  2042. Init(Target->URI, Target->Description, Target->ShortDesc);
  2043. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  2044. std::clog << "New pkgIndex with TransactionManager "
  2045. << TransactionManager << std::endl;
  2046. }
  2047. /*}}}*/
  2048. // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
  2049. void pkgAcqIndex::AutoSelectCompression()
  2050. {
  2051. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  2052. CompressionExtensions = "";
  2053. if (TransactionManager->MetaIndexParser != NULL && TransactionManager->MetaIndexParser->Exists(Target->MetaKey))
  2054. {
  2055. for (std::vector<std::string>::const_iterator t = types.begin();
  2056. t != types.end(); ++t)
  2057. {
  2058. std::string CompressedMetaKey = string(Target->MetaKey).append(".").append(*t);
  2059. if (*t == "uncompressed" ||
  2060. TransactionManager->MetaIndexParser->Exists(CompressedMetaKey) == true)
  2061. CompressionExtensions.append(*t).append(" ");
  2062. }
  2063. }
  2064. else
  2065. {
  2066. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  2067. CompressionExtensions.append(*t).append(" ");
  2068. }
  2069. if (CompressionExtensions.empty() == false)
  2070. CompressionExtensions.erase(CompressionExtensions.end()-1);
  2071. }
  2072. /*}}}*/
  2073. // AcqIndex::Init - defered Constructor /*{{{*/
  2074. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  2075. string const &ShortDesc)
  2076. {
  2077. Stage = STAGE_DOWNLOAD;
  2078. DestFile = GetPartialFileNameFromURI(URI);
  2079. size_t const nextExt = CompressionExtensions.find(' ');
  2080. if (nextExt == std::string::npos)
  2081. {
  2082. CurrentCompressionExtension = CompressionExtensions;
  2083. CompressionExtensions.clear();
  2084. }
  2085. else
  2086. {
  2087. CurrentCompressionExtension = CompressionExtensions.substr(0, nextExt);
  2088. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  2089. }
  2090. if (CurrentCompressionExtension == "uncompressed")
  2091. {
  2092. Desc.URI = URI;
  2093. }
  2094. else if (unlikely(CurrentCompressionExtension.empty()))
  2095. return;
  2096. else
  2097. {
  2098. Desc.URI = URI + '.' + CurrentCompressionExtension;
  2099. DestFile = DestFile + '.' + CurrentCompressionExtension;
  2100. }
  2101. if(TransactionManager->MetaIndexParser != NULL)
  2102. InitByHashIfNeeded();
  2103. Desc.Description = URIDesc;
  2104. Desc.Owner = this;
  2105. Desc.ShortDesc = ShortDesc;
  2106. QueueURI(Desc);
  2107. }
  2108. /*}}}*/
  2109. // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
  2110. void pkgAcqIndex::InitByHashIfNeeded()
  2111. {
  2112. // TODO:
  2113. // - (maybe?) add support for by-hash into the sources.list as flag
  2114. // - make apt-ftparchive generate the hashes (and expire?)
  2115. std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
  2116. if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
  2117. _config->FindB(HostKnob, false) == true ||
  2118. TransactionManager->MetaIndexParser->GetSupportsAcquireByHash())
  2119. {
  2120. HashStringList const Hashes = GetExpectedHashes();
  2121. if(Hashes.usable())
  2122. {
  2123. // FIXME: should we really use the best hash here? or a fixed one?
  2124. HashString const * const TargetHash = Hashes.find("");
  2125. std::string const ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  2126. size_t const trailing_slash = Desc.URI.find_last_of("/");
  2127. Desc.URI = Desc.URI.replace(
  2128. trailing_slash,
  2129. Desc.URI.substr(trailing_slash+1).size()+1,
  2130. ByHash);
  2131. } else {
  2132. _error->Warning(
  2133. "Fetching ByHash requested but can not find record for %s",
  2134. GetMetaKey().c_str());
  2135. }
  2136. }
  2137. }
  2138. /*}}}*/
  2139. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2140. // ---------------------------------------------------------------------
  2141. /* The only header we use is the last-modified header. */
  2142. string pkgAcqIndex::Custom600Headers() const
  2143. {
  2144. string Final = GetFinalFilename();
  2145. string msg = "\nIndex-File: true";
  2146. struct stat Buf;
  2147. if (stat(Final.c_str(),&Buf) == 0)
  2148. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  2149. if(Target->IsOptional())
  2150. msg += "\nFail-Ignore: true";
  2151. return msg;
  2152. }
  2153. /*}}}*/
  2154. // AcqIndex::Failed - getting the indexfile failed /*{{{*/
  2155. void pkgAcqIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2156. {
  2157. Item::Failed(Message,Cnf);
  2158. // authorisation matches will not be fixed by other compression types
  2159. if (Status != StatAuthError)
  2160. {
  2161. if (CompressionExtensions.empty() == false)
  2162. {
  2163. Init(Target->URI, Desc.Description, Desc.ShortDesc);
  2164. Status = StatIdle;
  2165. return;
  2166. }
  2167. }
  2168. if(Target->IsOptional() && GetExpectedHashes().empty() && Stage == STAGE_DOWNLOAD)
  2169. Status = StatDone;
  2170. else
  2171. TransactionManager->AbortTransaction();
  2172. }
  2173. /*}}}*/
  2174. // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
  2175. void pkgAcqIndex::ReverifyAfterIMS()
  2176. {
  2177. // update destfile to *not* include the compression extension when doing
  2178. // a reverify (as its uncompressed on disk already)
  2179. DestFile = GetCompressedFileName(Target->URI, GetPartialFileNameFromURI(Target->URI), CurrentCompressionExtension);
  2180. // copy FinalFile into partial/ so that we check the hash again
  2181. string FinalFile = GetFinalFilename();
  2182. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2183. Desc.URI = "copy:" + FinalFile;
  2184. QueueURI(Desc);
  2185. }
  2186. /*}}}*/
  2187. // AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
  2188. bool pkgAcqIndex::ValidateFile(const std::string &FileName)
  2189. {
  2190. // FIXME: this can go away once we only ever download stuff that
  2191. // has a valid hash and we never do GET based probing
  2192. // FIXME2: this also leaks debian-isms into the code and should go therefore
  2193. /* Always validate the index file for correctness (all indexes must
  2194. * have a Package field) (LP: #346386) (Closes: #627642)
  2195. */
  2196. FileFd fd(FileName, FileFd::ReadOnly, FileFd::Extension);
  2197. // Only test for correctness if the content of the file is not empty
  2198. // (empty is ok)
  2199. if (fd.Size() > 0)
  2200. {
  2201. pkgTagSection sec;
  2202. pkgTagFile tag(&fd);
  2203. // all our current indexes have a field 'Package' in each section
  2204. if (_error->PendingError() == true ||
  2205. tag.Step(sec) == false ||
  2206. sec.Exists("Package") == false)
  2207. return false;
  2208. }
  2209. return true;
  2210. }
  2211. /*}}}*/
  2212. // AcqIndex::Done - Finished a fetch /*{{{*/
  2213. // ---------------------------------------------------------------------
  2214. /* This goes through a number of states.. On the initial fetch the
  2215. method could possibly return an alternate filename which points
  2216. to the uncompressed version of the file. If this is so the file
  2217. is copied into the partial directory. In all other cases the file
  2218. is decompressed with a compressed uri. */
  2219. void pkgAcqIndex::Done(string const &Message,
  2220. HashStringList const &Hashes,
  2221. pkgAcquire::MethodConfig const * const Cfg)
  2222. {
  2223. Item::Done(Message,Hashes,Cfg);
  2224. switch(Stage)
  2225. {
  2226. case STAGE_DOWNLOAD:
  2227. StageDownloadDone(Message, Hashes, Cfg);
  2228. break;
  2229. case STAGE_DECOMPRESS_AND_VERIFY:
  2230. StageDecompressDone(Message, Hashes, Cfg);
  2231. break;
  2232. }
  2233. }
  2234. /*}}}*/
  2235. // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
  2236. void pkgAcqIndex::StageDownloadDone(string const &Message, HashStringList const &,
  2237. pkgAcquire::MethodConfig const * const)
  2238. {
  2239. Complete = true;
  2240. // Handle the unzipd case
  2241. string FileName = LookupTag(Message,"Alt-Filename");
  2242. if (FileName.empty() == false)
  2243. {
  2244. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2245. Local = true;
  2246. DestFile += ".decomp";
  2247. Desc.URI = "copy:" + FileName;
  2248. QueueURI(Desc);
  2249. SetActiveSubprocess("copy");
  2250. return;
  2251. }
  2252. FileName = LookupTag(Message,"Filename");
  2253. if (FileName.empty() == true)
  2254. {
  2255. Status = StatError;
  2256. ErrorText = "Method gave a blank filename";
  2257. }
  2258. // Methods like e.g. "file:" will give us a (compressed) FileName that is
  2259. // not the "DestFile" we set, in this case we uncompress from the local file
  2260. if (FileName != DestFile)
  2261. Local = true;
  2262. else
  2263. EraseFileName = FileName;
  2264. // we need to verify the file against the current Release file again
  2265. // on if-modfied-since hit to avoid a stale attack against us
  2266. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2267. {
  2268. // The files timestamp matches, reverify by copy into partial/
  2269. EraseFileName = "";
  2270. ReverifyAfterIMS();
  2271. return;
  2272. }
  2273. // If we have compressed indexes enabled, queue for hash verification
  2274. if (_config->FindB("Acquire::GzipIndexes",false))
  2275. {
  2276. DestFile = GetPartialFileNameFromURI(Target->URI + '.' + CurrentCompressionExtension);
  2277. EraseFileName = "";
  2278. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2279. Desc.URI = "copy:" + FileName;
  2280. QueueURI(Desc);
  2281. SetActiveSubprocess("copy");
  2282. return;
  2283. }
  2284. // get the binary name for your used compression type
  2285. string decompProg;
  2286. if(CurrentCompressionExtension == "uncompressed")
  2287. decompProg = "copy";
  2288. else
  2289. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
  2290. if(decompProg.empty() == true)
  2291. {
  2292. _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
  2293. return;
  2294. }
  2295. // queue uri for the next stage
  2296. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2297. DestFile += ".decomp";
  2298. Desc.URI = decompProg + ":" + FileName;
  2299. QueueURI(Desc);
  2300. SetActiveSubprocess(decompProg);
  2301. }
  2302. /*}}}*/
  2303. // AcqIndex::StageDecompressDone - Final verification /*{{{*/
  2304. void pkgAcqIndex::StageDecompressDone(string const &Message,
  2305. HashStringList const &,
  2306. pkgAcquire::MethodConfig const * const Cfg)
  2307. {
  2308. if(!ValidateFile(DestFile))
  2309. {
  2310. RenameOnError(InvalidFormat);
  2311. Failed(Message, Cfg);
  2312. return;
  2313. }
  2314. // Done, queue for rename on transaction finished
  2315. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  2316. return;
  2317. }
  2318. /*}}}*/
  2319. // AcqArchive::AcqArchive - Constructor /*{{{*/
  2320. // ---------------------------------------------------------------------
  2321. /* This just sets up the initial fetch environment and queues the first
  2322. possibilitiy */
  2323. pkgAcqArchive::pkgAcqArchive(pkgAcquire * const Owner,pkgSourceList * const Sources,
  2324. pkgRecords * const Recs,pkgCache::VerIterator const &Version,
  2325. string &StoreFilename) :
  2326. Item(Owner), LocalSource(false), Version(Version), Sources(Sources), Recs(Recs),
  2327. StoreFilename(StoreFilename), Vf(Version.FileList()),
  2328. Trusted(false)
  2329. {
  2330. Retries = _config->FindI("Acquire::Retries",0);
  2331. if (Version.Arch() == 0)
  2332. {
  2333. _error->Error(_("I wasn't able to locate a file for the %s package. "
  2334. "This might mean you need to manually fix this package. "
  2335. "(due to missing arch)"),
  2336. Version.ParentPkg().FullName().c_str());
  2337. return;
  2338. }
  2339. /* We need to find a filename to determine the extension. We make the
  2340. assumption here that all the available sources for this version share
  2341. the same extension.. */
  2342. // Skip not source sources, they do not have file fields.
  2343. for (; Vf.end() == false; ++Vf)
  2344. {
  2345. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  2346. continue;
  2347. break;
  2348. }
  2349. // Does not really matter here.. we are going to fail out below
  2350. if (Vf.end() != true)
  2351. {
  2352. // If this fails to get a file name we will bomb out below.
  2353. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2354. if (_error->PendingError() == true)
  2355. return;
  2356. // Generate the final file name as: package_version_arch.foo
  2357. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  2358. QuoteString(Version.VerStr(),"_:") + '_' +
  2359. QuoteString(Version.Arch(),"_:.") +
  2360. "." + flExtension(Parse.FileName());
  2361. }
  2362. // check if we have one trusted source for the package. if so, switch
  2363. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  2364. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  2365. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  2366. bool seenUntrusted = false;
  2367. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  2368. {
  2369. pkgIndexFile *Index;
  2370. if (Sources->FindIndex(i.File(),Index) == false)
  2371. continue;
  2372. if (debugAuth == true)
  2373. std::cerr << "Checking index: " << Index->Describe()
  2374. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  2375. if (Index->IsTrusted() == true)
  2376. {
  2377. Trusted = true;
  2378. if (allowUnauth == false)
  2379. break;
  2380. }
  2381. else
  2382. seenUntrusted = true;
  2383. }
  2384. // "allow-unauthenticated" restores apts old fetching behaviour
  2385. // that means that e.g. unauthenticated file:// uris are higher
  2386. // priority than authenticated http:// uris
  2387. if (allowUnauth == true && seenUntrusted == true)
  2388. Trusted = false;
  2389. // Select a source
  2390. if (QueueNext() == false && _error->PendingError() == false)
  2391. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  2392. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  2393. }
  2394. /*}}}*/
  2395. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  2396. // ---------------------------------------------------------------------
  2397. /* This queues the next available file version for download. It checks if
  2398. the archive is already available in the cache and stashs the MD5 for
  2399. checking later. */
  2400. bool pkgAcqArchive::QueueNext()
  2401. {
  2402. for (; Vf.end() == false; ++Vf)
  2403. {
  2404. pkgCache::PkgFileIterator const PkgF = Vf.File();
  2405. // Ignore not source sources
  2406. if ((PkgF->Flags & pkgCache::Flag::NotSource) != 0)
  2407. continue;
  2408. // Try to cross match against the source list
  2409. pkgIndexFile *Index;
  2410. if (Sources->FindIndex(PkgF, Index) == false)
  2411. continue;
  2412. LocalSource = (PkgF->Flags & pkgCache::Flag::LocalSource) == pkgCache::Flag::LocalSource;
  2413. // only try to get a trusted package from another source if that source
  2414. // is also trusted
  2415. if(Trusted && !Index->IsTrusted())
  2416. continue;
  2417. // Grab the text package record
  2418. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2419. if (_error->PendingError() == true)
  2420. return false;
  2421. string PkgFile = Parse.FileName();
  2422. ExpectedHashes = Parse.Hashes();
  2423. if (PkgFile.empty() == true)
  2424. return _error->Error(_("The package index files are corrupted. No Filename: "
  2425. "field for package %s."),
  2426. Version.ParentPkg().Name());
  2427. Desc.URI = Index->ArchiveURI(PkgFile);
  2428. Desc.Description = Index->ArchiveInfo(Version);
  2429. Desc.Owner = this;
  2430. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  2431. // See if we already have the file. (Legacy filenames)
  2432. FileSize = Version->Size;
  2433. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  2434. struct stat Buf;
  2435. if (stat(FinalFile.c_str(),&Buf) == 0)
  2436. {
  2437. // Make sure the size matches
  2438. if ((unsigned long long)Buf.st_size == Version->Size)
  2439. {
  2440. Complete = true;
  2441. Local = true;
  2442. Status = StatDone;
  2443. StoreFilename = DestFile = FinalFile;
  2444. return true;
  2445. }
  2446. /* Hmm, we have a file and its size does not match, this means it is
  2447. an old style mismatched arch */
  2448. unlink(FinalFile.c_str());
  2449. }
  2450. // Check it again using the new style output filenames
  2451. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2452. if (stat(FinalFile.c_str(),&Buf) == 0)
  2453. {
  2454. // Make sure the size matches
  2455. if ((unsigned long long)Buf.st_size == Version->Size)
  2456. {
  2457. Complete = true;
  2458. Local = true;
  2459. Status = StatDone;
  2460. StoreFilename = DestFile = FinalFile;
  2461. return true;
  2462. }
  2463. /* Hmm, we have a file and its size does not match, this shouldn't
  2464. happen.. */
  2465. unlink(FinalFile.c_str());
  2466. }
  2467. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2468. // Check the destination file
  2469. if (stat(DestFile.c_str(),&Buf) == 0)
  2470. {
  2471. // Hmm, the partial file is too big, erase it
  2472. if ((unsigned long long)Buf.st_size > Version->Size)
  2473. unlink(DestFile.c_str());
  2474. else
  2475. PartialSize = Buf.st_size;
  2476. }
  2477. // Disables download of archives - useful if no real installation follows,
  2478. // e.g. if we are just interested in proposed installation order
  2479. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2480. {
  2481. Complete = true;
  2482. Local = true;
  2483. Status = StatDone;
  2484. StoreFilename = DestFile = FinalFile;
  2485. return true;
  2486. }
  2487. // Create the item
  2488. Local = false;
  2489. QueueURI(Desc);
  2490. ++Vf;
  2491. return true;
  2492. }
  2493. return false;
  2494. }
  2495. /*}}}*/
  2496. // AcqArchive::Done - Finished fetching /*{{{*/
  2497. // ---------------------------------------------------------------------
  2498. /* */
  2499. void pkgAcqArchive::Done(string const &Message, HashStringList const &Hashes,
  2500. pkgAcquire::MethodConfig const * const Cfg)
  2501. {
  2502. Item::Done(Message, Hashes, Cfg);
  2503. // Grab the output filename
  2504. string FileName = LookupTag(Message,"Filename");
  2505. if (FileName.empty() == true)
  2506. {
  2507. Status = StatError;
  2508. ErrorText = "Method gave a blank filename";
  2509. return;
  2510. }
  2511. // Reference filename
  2512. if (FileName != DestFile)
  2513. {
  2514. StoreFilename = DestFile = FileName;
  2515. Local = true;
  2516. Complete = true;
  2517. return;
  2518. }
  2519. // Done, move it into position
  2520. string const FinalFile = GetFinalFilename();
  2521. Rename(DestFile,FinalFile);
  2522. StoreFilename = DestFile = FinalFile;
  2523. Complete = true;
  2524. }
  2525. /*}}}*/
  2526. // AcqArchive::Failed - Failure handler /*{{{*/
  2527. // ---------------------------------------------------------------------
  2528. /* Here we try other sources */
  2529. void pkgAcqArchive::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2530. {
  2531. Item::Failed(Message,Cnf);
  2532. /* We don't really want to retry on failed media swaps, this prevents
  2533. that. An interesting observation is that permanent failures are not
  2534. recorded. */
  2535. if (Cnf->Removable == true &&
  2536. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2537. {
  2538. // Vf = Version.FileList();
  2539. while (Vf.end() == false) ++Vf;
  2540. StoreFilename = string();
  2541. return;
  2542. }
  2543. Status = StatIdle;
  2544. if (QueueNext() == false)
  2545. {
  2546. // This is the retry counter
  2547. if (Retries != 0 &&
  2548. Cnf->LocalOnly == false &&
  2549. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2550. {
  2551. Retries--;
  2552. Vf = Version.FileList();
  2553. if (QueueNext() == true)
  2554. return;
  2555. }
  2556. StoreFilename = string();
  2557. Status = StatError;
  2558. }
  2559. }
  2560. /*}}}*/
  2561. APT_PURE bool pkgAcqArchive::IsTrusted() const /*{{{*/
  2562. {
  2563. return Trusted;
  2564. }
  2565. /*}}}*/
  2566. void pkgAcqArchive::Finished() /*{{{*/
  2567. {
  2568. if (Status == pkgAcquire::Item::StatDone &&
  2569. Complete == true)
  2570. return;
  2571. StoreFilename = string();
  2572. }
  2573. /*}}}*/
  2574. std::string pkgAcqArchive::DescURI() const /*{{{*/
  2575. {
  2576. return Desc.URI;
  2577. }
  2578. /*}}}*/
  2579. std::string pkgAcqArchive::ShortDesc() const /*{{{*/
  2580. {
  2581. return Desc.ShortDesc;
  2582. }
  2583. /*}}}*/
  2584. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  2585. pkgAcqFile::pkgAcqFile(pkgAcquire * const Owner,string const &URI, HashStringList const &Hashes,
  2586. unsigned long long const Size,string const &Dsc,string const &ShortDesc,
  2587. const string &DestDir, const string &DestFilename,
  2588. bool const IsIndexFile) :
  2589. Item(Owner), IsIndexFile(IsIndexFile), ExpectedHashes(Hashes)
  2590. {
  2591. Retries = _config->FindI("Acquire::Retries",0);
  2592. if(!DestFilename.empty())
  2593. DestFile = DestFilename;
  2594. else if(!DestDir.empty())
  2595. DestFile = DestDir + "/" + flNotDir(URI);
  2596. else
  2597. DestFile = flNotDir(URI);
  2598. // Create the item
  2599. Desc.URI = URI;
  2600. Desc.Description = Dsc;
  2601. Desc.Owner = this;
  2602. // Set the short description to the archive component
  2603. Desc.ShortDesc = ShortDesc;
  2604. // Get the transfer sizes
  2605. FileSize = Size;
  2606. struct stat Buf;
  2607. if (stat(DestFile.c_str(),&Buf) == 0)
  2608. {
  2609. // Hmm, the partial file is too big, erase it
  2610. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  2611. unlink(DestFile.c_str());
  2612. else
  2613. PartialSize = Buf.st_size;
  2614. }
  2615. QueueURI(Desc);
  2616. }
  2617. /*}}}*/
  2618. // AcqFile::Done - Item downloaded OK /*{{{*/
  2619. void pkgAcqFile::Done(string const &Message,HashStringList const &CalcHashes,
  2620. pkgAcquire::MethodConfig const * const Cnf)
  2621. {
  2622. Item::Done(Message,CalcHashes,Cnf);
  2623. string FileName = LookupTag(Message,"Filename");
  2624. if (FileName.empty() == true)
  2625. {
  2626. Status = StatError;
  2627. ErrorText = "Method gave a blank filename";
  2628. return;
  2629. }
  2630. Complete = true;
  2631. // The files timestamp matches
  2632. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2633. return;
  2634. // We have to copy it into place
  2635. if (FileName != DestFile)
  2636. {
  2637. Local = true;
  2638. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  2639. Cnf->Removable == true)
  2640. {
  2641. Desc.URI = "copy:" + FileName;
  2642. QueueURI(Desc);
  2643. return;
  2644. }
  2645. // Erase the file if it is a symlink so we can overwrite it
  2646. struct stat St;
  2647. if (lstat(DestFile.c_str(),&St) == 0)
  2648. {
  2649. if (S_ISLNK(St.st_mode) != 0)
  2650. unlink(DestFile.c_str());
  2651. }
  2652. // Symlink the file
  2653. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2654. {
  2655. _error->PushToStack();
  2656. _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
  2657. std::stringstream msg;
  2658. _error->DumpErrors(msg);
  2659. _error->RevertToStack();
  2660. ErrorText = msg.str();
  2661. Status = StatError;
  2662. Complete = false;
  2663. }
  2664. }
  2665. }
  2666. /*}}}*/
  2667. // AcqFile::Failed - Failure handler /*{{{*/
  2668. // ---------------------------------------------------------------------
  2669. /* Here we try other sources */
  2670. void pkgAcqFile::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
  2671. {
  2672. Item::Failed(Message,Cnf);
  2673. // This is the retry counter
  2674. if (Retries != 0 &&
  2675. Cnf->LocalOnly == false &&
  2676. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2677. {
  2678. --Retries;
  2679. QueueURI(Desc);
  2680. Status = StatIdle;
  2681. return;
  2682. }
  2683. }
  2684. /*}}}*/
  2685. string pkgAcqFile::Custom600Headers() const /*{{{*/
  2686. {
  2687. if (IsIndexFile)
  2688. return "\nIndex-File: true";
  2689. return "";
  2690. }
  2691. /*}}}*/