acquire-item.cc 132 KB

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