acquire-item.cc 65 KB

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