acquire-item.cc 51 KB

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