acquire-item.cc 45 KB

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