acquire-item.cc 89 KB

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