acquire-item.cc 87 KB

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