acquire-item.cc 119 KB

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