acquire-item.cc 84 KB

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