acquire-item.cc 109 KB

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