acquire-item.cc 108 KB

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