acquire-item.cc 90 KB

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