acquire-item.cc 80 KB

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