acquire-item.cc 113 KB

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