acquire-item.cc 112 KB

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