You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1680 lines
50 KiB

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