acquire-item.cc 86 KB

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