acquire-item.cc 105 KB

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