acquire-item.cc 105 KB

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