acquire-item.cc 63 KB

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