acquire-item.cc 105 KB

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