acquire-item.cc 126 KB

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