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.
 
 
 
 
 
 

1700 lines
51 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::ReadOnlyGzip);
  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::ReadOnlyGzip);
  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. if (_config->FindB("Acquire::GzipIndexes",false))
  548. Final += ".gz";
  549. struct stat Buf;
  550. if (stat(Final.c_str(),&Buf) != 0)
  551. return "\nIndex-File: true";
  552. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  553. }
  554. /*}}}*/
  555. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  556. {
  557. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  558. for (std::vector<std::string>::const_iterator t = types.begin();
  559. t != types.end(); t++)
  560. {
  561. // jump over all already tried compression types
  562. const unsigned int nameLen = Desc.URI.size() - (*t).size();
  563. if(Desc.URI.substr(nameLen) != *t)
  564. continue;
  565. // we want to try it with the next extension (and make sure to
  566. // not skip over the end)
  567. t++;
  568. if (t == types.end())
  569. break;
  570. // queue new download
  571. Desc.URI = Desc.URI.substr(0, nameLen) + *t;
  572. new pkgAcqIndex(Owner, RealURI, Desc.Description, Desc.ShortDesc,
  573. ExpectedHash, string(".").append(*t));
  574. Status = StatDone;
  575. Complete = false;
  576. Dequeue();
  577. return;
  578. }
  579. // on decompression failure, remove bad versions in partial/
  580. if(Decompression && Erase) {
  581. string s = _config->FindDir("Dir::State::lists") + "partial/";
  582. s += URItoFileName(RealURI);
  583. unlink(s.c_str());
  584. }
  585. Item::Failed(Message,Cnf);
  586. }
  587. /*}}}*/
  588. // AcqIndex::Done - Finished a fetch /*{{{*/
  589. // ---------------------------------------------------------------------
  590. /* This goes through a number of states.. On the initial fetch the
  591. method could possibly return an alternate filename which points
  592. to the uncompressed version of the file. If this is so the file
  593. is copied into the partial directory. In all other cases the file
  594. is decompressed with a gzip uri. */
  595. void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
  596. pkgAcquire::MethodConfig *Cfg)
  597. {
  598. Item::Done(Message,Size,Hash,Cfg);
  599. if (Decompression == true)
  600. {
  601. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  602. {
  603. std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
  604. std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
  605. }
  606. if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
  607. {
  608. Status = StatAuthError;
  609. ErrorText = _("Hash Sum mismatch");
  610. Rename(DestFile,DestFile + ".FAILED");
  611. return;
  612. }
  613. // Done, move it into position
  614. string FinalFile = _config->FindDir("Dir::State::lists");
  615. FinalFile += URItoFileName(RealURI);
  616. Rename(DestFile,FinalFile);
  617. chmod(FinalFile.c_str(),0644);
  618. /* We restore the original name to DestFile so that the clean operation
  619. will work OK */
  620. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  621. DestFile += URItoFileName(RealURI);
  622. // Remove the compressed version.
  623. if (Erase == true)
  624. unlink(DestFile.c_str());
  625. return;
  626. }
  627. Erase = false;
  628. Complete = true;
  629. // Handle the unzipd case
  630. string FileName = LookupTag(Message,"Alt-Filename");
  631. if (FileName.empty() == false)
  632. {
  633. // The files timestamp matches
  634. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  635. return;
  636. Decompression = true;
  637. Local = true;
  638. DestFile += ".decomp";
  639. Desc.URI = "copy:" + FileName;
  640. QueueURI(Desc);
  641. Mode = "copy";
  642. return;
  643. }
  644. FileName = LookupTag(Message,"Filename");
  645. if (FileName.empty() == true)
  646. {
  647. Status = StatError;
  648. ErrorText = "Method gave a blank filename";
  649. }
  650. string compExt = flExtension(flNotDir(URI(Desc.URI).Path));
  651. // The files timestamp matches
  652. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true) {
  653. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  654. // Update DestFile for .gz suffix so that the clean operation keeps it
  655. DestFile += ".gz";
  656. return;
  657. }
  658. if (FileName == DestFile)
  659. Erase = true;
  660. else
  661. Local = true;
  662. string decompProg;
  663. // If we enable compressed indexes and already have gzip, keep it
  664. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz") {
  665. string FinalFile = _config->FindDir("Dir::State::lists");
  666. FinalFile += URItoFileName(RealURI) + ".gz";
  667. //if(Debug)
  668. // std::clog << "pkgAcqIndex: keeping gzipped " << FinalFile << endl;
  669. Rename(DestFile,FinalFile);
  670. chmod(FinalFile.c_str(),0644);
  671. // Update DestFile for .gz suffix so that the clean operation keeps it
  672. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  673. DestFile += URItoFileName(RealURI) + ".gz";
  674. return;
  675. }
  676. // get the binary name for your used compression type
  677. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  678. if(decompProg.empty() == false);
  679. // flExtensions returns the full name if no extension is found
  680. // this is why we have this complicated compare operation here
  681. // FIMXE: add a new flJustExtension() that return "" if no
  682. // extension is found and use that above so that it can
  683. // be tested against ""
  684. else if(compExt == flNotDir(URI(Desc.URI).Path))
  685. decompProg = "copy";
  686. else {
  687. _error->Error("Unsupported extension: %s", compExt.c_str());
  688. return;
  689. }
  690. Decompression = true;
  691. DestFile += ".decomp";
  692. Desc.URI = decompProg + ":" + FileName;
  693. QueueURI(Desc);
  694. Mode = decompProg.c_str();
  695. }
  696. /*}}}*/
  697. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  698. // ---------------------------------------------------------------------
  699. /* The Translation file is added to the queue */
  700. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  701. string URI,string URIDesc,string ShortDesc)
  702. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
  703. {
  704. }
  705. /*}}}*/
  706. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  707. // ---------------------------------------------------------------------
  708. /* */
  709. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  710. {
  711. if (Cnf->LocalOnly == true ||
  712. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  713. {
  714. // Ignore this
  715. Status = StatDone;
  716. Complete = false;
  717. Dequeue();
  718. return;
  719. }
  720. Item::Failed(Message,Cnf);
  721. }
  722. /*}}}*/
  723. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  724. string URI,string URIDesc,string ShortDesc,
  725. string MetaIndexURI, string MetaIndexURIDesc,
  726. string MetaIndexShortDesc,
  727. const vector<IndexTarget*>* IndexTargets,
  728. indexRecords* MetaIndexParser) :
  729. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  730. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  731. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  732. {
  733. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  734. DestFile += URItoFileName(URI);
  735. // remove any partial downloaded sig-file in partial/.
  736. // it may confuse proxies and is too small to warrant a
  737. // partial download anyway
  738. unlink(DestFile.c_str());
  739. // Create the item
  740. Desc.Description = URIDesc;
  741. Desc.Owner = this;
  742. Desc.ShortDesc = ShortDesc;
  743. Desc.URI = URI;
  744. string Final = _config->FindDir("Dir::State::lists");
  745. Final += URItoFileName(RealURI);
  746. struct stat Buf;
  747. if (stat(Final.c_str(),&Buf) == 0)
  748. {
  749. // File was already in place. It needs to be re-downloaded/verified
  750. // because Release might have changed, we do give it a differnt
  751. // name than DestFile because otherwise the http method will
  752. // send If-Range requests and there are too many broken servers
  753. // out there that do not understand them
  754. LastGoodSig = DestFile+".reverify";
  755. Rename(Final,LastGoodSig);
  756. }
  757. QueueURI(Desc);
  758. }
  759. /*}}}*/
  760. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  761. // ---------------------------------------------------------------------
  762. /* The only header we use is the last-modified header. */
  763. string pkgAcqMetaSig::Custom600Headers()
  764. {
  765. struct stat Buf;
  766. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  767. return "\nIndex-File: true";
  768. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  769. }
  770. void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
  771. pkgAcquire::MethodConfig *Cfg)
  772. {
  773. Item::Done(Message,Size,MD5,Cfg);
  774. string FileName = LookupTag(Message,"Filename");
  775. if (FileName.empty() == true)
  776. {
  777. Status = StatError;
  778. ErrorText = "Method gave a blank filename";
  779. return;
  780. }
  781. if (FileName != DestFile)
  782. {
  783. // We have to copy it into place
  784. Local = true;
  785. Desc.URI = "copy:" + FileName;
  786. QueueURI(Desc);
  787. return;
  788. }
  789. Complete = true;
  790. // put the last known good file back on i-m-s hit (it will
  791. // be re-verified again)
  792. // Else do nothing, we have the new file in DestFile then
  793. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  794. Rename(LastGoodSig, DestFile);
  795. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  796. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  797. DestFile, IndexTargets, MetaIndexParser);
  798. }
  799. /*}}}*/
  800. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  801. {
  802. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  803. // if we get a network error we fail gracefully
  804. if(Status == StatTransientNetworkError)
  805. {
  806. Item::Failed(Message,Cnf);
  807. // move the sigfile back on transient network failures
  808. if(FileExists(DestFile))
  809. Rename(LastGoodSig,Final);
  810. // set the status back to , Item::Failed likes to reset it
  811. Status = pkgAcquire::Item::StatTransientNetworkError;
  812. return;
  813. }
  814. // Delete any existing sigfile when the acquire failed
  815. unlink(Final.c_str());
  816. // queue a pkgAcqMetaIndex with no sigfile
  817. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  818. "", IndexTargets, MetaIndexParser);
  819. if (Cnf->LocalOnly == true ||
  820. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  821. {
  822. // Ignore this
  823. Status = StatDone;
  824. Complete = false;
  825. Dequeue();
  826. return;
  827. }
  828. Item::Failed(Message,Cnf);
  829. }
  830. /*}}}*/
  831. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  832. string URI,string URIDesc,string ShortDesc,
  833. string SigFile,
  834. const vector<struct IndexTarget*>* IndexTargets,
  835. indexRecords* MetaIndexParser) :
  836. Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  837. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  838. {
  839. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  840. DestFile += URItoFileName(URI);
  841. // Create the item
  842. Desc.Description = URIDesc;
  843. Desc.Owner = this;
  844. Desc.ShortDesc = ShortDesc;
  845. Desc.URI = URI;
  846. QueueURI(Desc);
  847. }
  848. /*}}}*/
  849. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  850. // ---------------------------------------------------------------------
  851. /* The only header we use is the last-modified header. */
  852. string pkgAcqMetaIndex::Custom600Headers()
  853. {
  854. string Final = _config->FindDir("Dir::State::lists");
  855. Final += URItoFileName(RealURI);
  856. struct stat Buf;
  857. if (stat(Final.c_str(),&Buf) != 0)
  858. return "\nIndex-File: true";
  859. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  860. }
  861. /*}}}*/
  862. void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash, /*{{{*/
  863. pkgAcquire::MethodConfig *Cfg)
  864. {
  865. Item::Done(Message,Size,Hash,Cfg);
  866. // MetaIndexes are done in two passes: one to download the
  867. // metaindex with an appropriate method, and a second to verify it
  868. // with the gpgv method
  869. if (AuthPass == true)
  870. {
  871. AuthDone(Message);
  872. }
  873. else
  874. {
  875. RetrievalDone(Message);
  876. if (!Complete)
  877. // Still more retrieving to do
  878. return;
  879. if (SigFile == "")
  880. {
  881. // There was no signature file, so we are finished. Download
  882. // the indexes without verification.
  883. QueueIndexes(false);
  884. }
  885. else
  886. {
  887. // There was a signature file, so pass it to gpgv for
  888. // verification
  889. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  890. std::cerr << "Metaindex acquired, queueing gpg verification ("
  891. << SigFile << "," << DestFile << ")\n";
  892. AuthPass = true;
  893. Desc.URI = "gpgv:" + SigFile;
  894. QueueURI(Desc);
  895. Mode = "gpgv";
  896. }
  897. }
  898. }
  899. /*}}}*/
  900. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  901. {
  902. // We have just finished downloading a Release file (it is not
  903. // verified yet)
  904. string FileName = LookupTag(Message,"Filename");
  905. if (FileName.empty() == true)
  906. {
  907. Status = StatError;
  908. ErrorText = "Method gave a blank filename";
  909. return;
  910. }
  911. if (FileName != DestFile)
  912. {
  913. Local = true;
  914. Desc.URI = "copy:" + FileName;
  915. QueueURI(Desc);
  916. return;
  917. }
  918. // see if the download was a IMSHit
  919. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  920. Complete = true;
  921. string FinalFile = _config->FindDir("Dir::State::lists");
  922. FinalFile += URItoFileName(RealURI);
  923. // If we get a IMS hit we can remove the empty file in partial
  924. // othersie we move the file in place
  925. if (IMSHit)
  926. unlink(DestFile.c_str());
  927. else
  928. Rename(DestFile,FinalFile);
  929. chmod(FinalFile.c_str(),0644);
  930. DestFile = FinalFile;
  931. }
  932. /*}}}*/
  933. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  934. {
  935. // At this point, the gpgv method has succeeded, so there is a
  936. // valid signature from a key in the trusted keyring. We
  937. // perform additional verification of its contents, and use them
  938. // to verify the indexes we are about to download
  939. if (!MetaIndexParser->Load(DestFile))
  940. {
  941. Status = StatAuthError;
  942. ErrorText = MetaIndexParser->ErrorText;
  943. return;
  944. }
  945. if (!VerifyVendor(Message))
  946. {
  947. return;
  948. }
  949. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  950. std::cerr << "Signature verification succeeded: "
  951. << DestFile << std::endl;
  952. // Download further indexes with verification
  953. QueueIndexes(true);
  954. // Done, move signature file into position
  955. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  956. URItoFileName(RealURI) + ".gpg";
  957. Rename(SigFile,VerifiedSigFile);
  958. chmod(VerifiedSigFile.c_str(),0644);
  959. }
  960. /*}}}*/
  961. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  962. {
  963. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  964. Target != IndexTargets->end();
  965. Target++)
  966. {
  967. HashString ExpectedIndexHash;
  968. if (verify)
  969. {
  970. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  971. if (!Record)
  972. {
  973. Status = StatAuthError;
  974. ErrorText = "Unable to find expected entry "
  975. + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
  976. return;
  977. }
  978. ExpectedIndexHash = Record->Hash;
  979. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  980. {
  981. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  982. std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
  983. }
  984. if (ExpectedIndexHash.empty())
  985. {
  986. Status = StatAuthError;
  987. ErrorText = "Unable to find hash sum for "
  988. + (*Target)->MetaKey + " in Meta-index file";
  989. return;
  990. }
  991. }
  992. // Queue Packages file (either diff or full packages files, depending
  993. // on the users option)
  994. if(_config->FindB("Acquire::PDiffs",true) == true)
  995. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  996. (*Target)->ShortDesc, ExpectedIndexHash);
  997. else
  998. new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
  999. (*Target)->ShortDesc, ExpectedIndexHash);
  1000. }
  1001. }
  1002. /*}}}*/
  1003. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  1004. {
  1005. // // Maybe this should be made available from above so we don't have
  1006. // // to read and parse it every time?
  1007. // pkgVendorList List;
  1008. // List.ReadMainList();
  1009. // const Vendor* Vndr = NULL;
  1010. // for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
  1011. // {
  1012. // string::size_type pos = (*I).find("VALIDSIG ");
  1013. // if (_config->FindB("Debug::Vendor", false))
  1014. // std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
  1015. // << std::endl;
  1016. // if (pos != std::string::npos)
  1017. // {
  1018. // string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
  1019. // if (_config->FindB("Debug::Vendor", false))
  1020. // std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
  1021. // std::endl;
  1022. // Vndr = List.FindVendor(Fingerprint) != "";
  1023. // if (Vndr != NULL);
  1024. // break;
  1025. // }
  1026. // }
  1027. string::size_type pos;
  1028. // check for missing sigs (that where not fatal because otherwise we had
  1029. // bombed earlier)
  1030. string missingkeys;
  1031. string msg = _("There is no public key available for the "
  1032. "following key IDs:\n");
  1033. pos = Message.find("NO_PUBKEY ");
  1034. if (pos != std::string::npos)
  1035. {
  1036. string::size_type start = pos+strlen("NO_PUBKEY ");
  1037. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1038. missingkeys += (Fingerprint);
  1039. }
  1040. if(!missingkeys.empty())
  1041. _error->Warning("%s", string(msg+missingkeys).c_str());
  1042. string Transformed = MetaIndexParser->GetExpectedDist();
  1043. if (Transformed == "../project/experimental")
  1044. {
  1045. Transformed = "experimental";
  1046. }
  1047. pos = Transformed.rfind('/');
  1048. if (pos != string::npos)
  1049. {
  1050. Transformed = Transformed.substr(0, pos);
  1051. }
  1052. if (Transformed == ".")
  1053. {
  1054. Transformed = "";
  1055. }
  1056. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1057. {
  1058. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1059. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1060. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1061. }
  1062. if (MetaIndexParser->CheckDist(Transformed) == false)
  1063. {
  1064. // This might become fatal one day
  1065. // Status = StatAuthError;
  1066. // ErrorText = "Conflicting distribution; expected "
  1067. // + MetaIndexParser->GetExpectedDist() + " but got "
  1068. // + MetaIndexParser->GetDist();
  1069. // return false;
  1070. if (!Transformed.empty())
  1071. {
  1072. _error->Warning("Conflicting distribution: %s (expected %s but got %s)",
  1073. Desc.Description.c_str(),
  1074. Transformed.c_str(),
  1075. MetaIndexParser->GetDist().c_str());
  1076. }
  1077. }
  1078. return true;
  1079. }
  1080. /*}}}*/
  1081. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1082. // ---------------------------------------------------------------------
  1083. /* */
  1084. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1085. {
  1086. if (AuthPass == true)
  1087. {
  1088. // if we fail the authentication but got the file via a IMS-Hit
  1089. // this means that the file wasn't downloaded and that it might be
  1090. // just stale (server problem, proxy etc). we delete what we have
  1091. // queue it again without i-m-s
  1092. // alternatively we could just unlink the file and let the user try again
  1093. if (IMSHit)
  1094. {
  1095. Complete = false;
  1096. Local = false;
  1097. AuthPass = false;
  1098. unlink(DestFile.c_str());
  1099. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1100. DestFile += URItoFileName(RealURI);
  1101. Desc.URI = RealURI;
  1102. QueueURI(Desc);
  1103. return;
  1104. }
  1105. // gpgv method failed
  1106. _error->Warning("GPG error: %s: %s",
  1107. Desc.Description.c_str(),
  1108. LookupTag(Message,"Message").c_str());
  1109. }
  1110. // No Release file was present, or verification failed, so fall
  1111. // back to queueing Packages files without verification
  1112. QueueIndexes(false);
  1113. }
  1114. /*}}}*/
  1115. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1116. // ---------------------------------------------------------------------
  1117. /* This just sets up the initial fetch environment and queues the first
  1118. possibilitiy */
  1119. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1120. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1121. string &StoreFilename) :
  1122. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  1123. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1124. Trusted(false)
  1125. {
  1126. Retries = _config->FindI("Acquire::Retries",0);
  1127. if (Version.Arch() == 0)
  1128. {
  1129. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1130. "This might mean you need to manually fix this package. "
  1131. "(due to missing arch)"),
  1132. Version.ParentPkg().Name());
  1133. return;
  1134. }
  1135. /* We need to find a filename to determine the extension. We make the
  1136. assumption here that all the available sources for this version share
  1137. the same extension.. */
  1138. // Skip not source sources, they do not have file fields.
  1139. for (; Vf.end() == false; Vf++)
  1140. {
  1141. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1142. continue;
  1143. break;
  1144. }
  1145. // Does not really matter here.. we are going to fail out below
  1146. if (Vf.end() != true)
  1147. {
  1148. // If this fails to get a file name we will bomb out below.
  1149. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1150. if (_error->PendingError() == true)
  1151. return;
  1152. // Generate the final file name as: package_version_arch.foo
  1153. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1154. QuoteString(Version.VerStr(),"_:") + '_' +
  1155. QuoteString(Version.Arch(),"_:.") +
  1156. "." + flExtension(Parse.FileName());
  1157. }
  1158. // check if we have one trusted source for the package. if so, switch
  1159. // to "TrustedOnly" mode
  1160. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
  1161. {
  1162. pkgIndexFile *Index;
  1163. if (Sources->FindIndex(i.File(),Index) == false)
  1164. continue;
  1165. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1166. {
  1167. std::cerr << "Checking index: " << Index->Describe()
  1168. << "(Trusted=" << Index->IsTrusted() << ")\n";
  1169. }
  1170. if (Index->IsTrusted()) {
  1171. Trusted = true;
  1172. break;
  1173. }
  1174. }
  1175. // "allow-unauthenticated" restores apts old fetching behaviour
  1176. // that means that e.g. unauthenticated file:// uris are higher
  1177. // priority than authenticated http:// uris
  1178. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  1179. Trusted = false;
  1180. // Select a source
  1181. if (QueueNext() == false && _error->PendingError() == false)
  1182. _error->Error(_("I wasn't able to locate file for the %s package. "
  1183. "This might mean you need to manually fix this package."),
  1184. Version.ParentPkg().Name());
  1185. }
  1186. /*}}}*/
  1187. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1188. // ---------------------------------------------------------------------
  1189. /* This queues the next available file version for download. It checks if
  1190. the archive is already available in the cache and stashs the MD5 for
  1191. checking later. */
  1192. bool pkgAcqArchive::QueueNext()
  1193. {
  1194. for (; Vf.end() == false; Vf++)
  1195. {
  1196. // Ignore not source sources
  1197. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1198. continue;
  1199. // Try to cross match against the source list
  1200. pkgIndexFile *Index;
  1201. if (Sources->FindIndex(Vf.File(),Index) == false)
  1202. continue;
  1203. // only try to get a trusted package from another source if that source
  1204. // is also trusted
  1205. if(Trusted && !Index->IsTrusted())
  1206. continue;
  1207. // Grab the text package record
  1208. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1209. if (_error->PendingError() == true)
  1210. return false;
  1211. string PkgFile = Parse.FileName();
  1212. if(Parse.SHA256Hash() != "")
  1213. ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
  1214. else if (Parse.SHA1Hash() != "")
  1215. ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
  1216. else
  1217. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1218. if (PkgFile.empty() == true)
  1219. return _error->Error(_("The package index files are corrupted. No Filename: "
  1220. "field for package %s."),
  1221. Version.ParentPkg().Name());
  1222. Desc.URI = Index->ArchiveURI(PkgFile);
  1223. Desc.Description = Index->ArchiveInfo(Version);
  1224. Desc.Owner = this;
  1225. Desc.ShortDesc = Version.ParentPkg().Name();
  1226. // See if we already have the file. (Legacy filenames)
  1227. FileSize = Version->Size;
  1228. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1229. struct stat Buf;
  1230. if (stat(FinalFile.c_str(),&Buf) == 0)
  1231. {
  1232. // Make sure the size matches
  1233. if ((unsigned)Buf.st_size == Version->Size)
  1234. {
  1235. Complete = true;
  1236. Local = true;
  1237. Status = StatDone;
  1238. StoreFilename = DestFile = FinalFile;
  1239. return true;
  1240. }
  1241. /* Hmm, we have a file and its size does not match, this means it is
  1242. an old style mismatched arch */
  1243. unlink(FinalFile.c_str());
  1244. }
  1245. // Check it again using the new style output filenames
  1246. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1247. if (stat(FinalFile.c_str(),&Buf) == 0)
  1248. {
  1249. // Make sure the size matches
  1250. if ((unsigned)Buf.st_size == Version->Size)
  1251. {
  1252. Complete = true;
  1253. Local = true;
  1254. Status = StatDone;
  1255. StoreFilename = DestFile = FinalFile;
  1256. return true;
  1257. }
  1258. /* Hmm, we have a file and its size does not match, this shouldnt
  1259. happen.. */
  1260. unlink(FinalFile.c_str());
  1261. }
  1262. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1263. // Check the destination file
  1264. if (stat(DestFile.c_str(),&Buf) == 0)
  1265. {
  1266. // Hmm, the partial file is too big, erase it
  1267. if ((unsigned)Buf.st_size > Version->Size)
  1268. unlink(DestFile.c_str());
  1269. else
  1270. PartialSize = Buf.st_size;
  1271. }
  1272. // Create the item
  1273. Local = false;
  1274. Desc.URI = Index->ArchiveURI(PkgFile);
  1275. Desc.Description = Index->ArchiveInfo(Version);
  1276. Desc.Owner = this;
  1277. Desc.ShortDesc = Version.ParentPkg().Name();
  1278. QueueURI(Desc);
  1279. Vf++;
  1280. return true;
  1281. }
  1282. return false;
  1283. }
  1284. /*}}}*/
  1285. // AcqArchive::Done - Finished fetching /*{{{*/
  1286. // ---------------------------------------------------------------------
  1287. /* */
  1288. void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
  1289. pkgAcquire::MethodConfig *Cfg)
  1290. {
  1291. Item::Done(Message,Size,CalcHash,Cfg);
  1292. // Check the size
  1293. if (Size != Version->Size)
  1294. {
  1295. Status = StatError;
  1296. ErrorText = _("Size mismatch");
  1297. return;
  1298. }
  1299. // Check the hash
  1300. if(ExpectedHash.toStr() != CalcHash)
  1301. {
  1302. Status = StatError;
  1303. ErrorText = _("Hash Sum mismatch");
  1304. if(FileExists(DestFile))
  1305. Rename(DestFile,DestFile + ".FAILED");
  1306. return;
  1307. }
  1308. // Grab the output filename
  1309. string FileName = LookupTag(Message,"Filename");
  1310. if (FileName.empty() == true)
  1311. {
  1312. Status = StatError;
  1313. ErrorText = "Method gave a blank filename";
  1314. return;
  1315. }
  1316. Complete = true;
  1317. // Reference filename
  1318. if (FileName != DestFile)
  1319. {
  1320. StoreFilename = DestFile = FileName;
  1321. Local = true;
  1322. return;
  1323. }
  1324. // Done, move it into position
  1325. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  1326. FinalFile += flNotDir(StoreFilename);
  1327. Rename(DestFile,FinalFile);
  1328. StoreFilename = DestFile = FinalFile;
  1329. Complete = true;
  1330. }
  1331. /*}}}*/
  1332. // AcqArchive::Failed - Failure handler /*{{{*/
  1333. // ---------------------------------------------------------------------
  1334. /* Here we try other sources */
  1335. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1336. {
  1337. ErrorText = LookupTag(Message,"Message");
  1338. /* We don't really want to retry on failed media swaps, this prevents
  1339. that. An interesting observation is that permanent failures are not
  1340. recorded. */
  1341. if (Cnf->Removable == true &&
  1342. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1343. {
  1344. // Vf = Version.FileList();
  1345. while (Vf.end() == false) Vf++;
  1346. StoreFilename = string();
  1347. Item::Failed(Message,Cnf);
  1348. return;
  1349. }
  1350. if (QueueNext() == false)
  1351. {
  1352. // This is the retry counter
  1353. if (Retries != 0 &&
  1354. Cnf->LocalOnly == false &&
  1355. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1356. {
  1357. Retries--;
  1358. Vf = Version.FileList();
  1359. if (QueueNext() == true)
  1360. return;
  1361. }
  1362. StoreFilename = string();
  1363. Item::Failed(Message,Cnf);
  1364. }
  1365. }
  1366. /*}}}*/
  1367. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  1368. // ---------------------------------------------------------------------
  1369. bool pkgAcqArchive::IsTrusted()
  1370. {
  1371. return Trusted;
  1372. }
  1373. /*}}}*/
  1374. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  1375. // ---------------------------------------------------------------------
  1376. /* */
  1377. void pkgAcqArchive::Finished()
  1378. {
  1379. if (Status == pkgAcquire::Item::StatDone &&
  1380. Complete == true)
  1381. return;
  1382. StoreFilename = string();
  1383. }
  1384. /*}}}*/
  1385. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  1386. // ---------------------------------------------------------------------
  1387. /* The file is added to the queue */
  1388. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
  1389. unsigned long Size,string Dsc,string ShortDesc,
  1390. const string &DestDir, const string &DestFilename,
  1391. bool IsIndexFile) :
  1392. Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
  1393. {
  1394. Retries = _config->FindI("Acquire::Retries",0);
  1395. if(!DestFilename.empty())
  1396. DestFile = DestFilename;
  1397. else if(!DestDir.empty())
  1398. DestFile = DestDir + "/" + flNotDir(URI);
  1399. else
  1400. DestFile = flNotDir(URI);
  1401. // Create the item
  1402. Desc.URI = URI;
  1403. Desc.Description = Dsc;
  1404. Desc.Owner = this;
  1405. // Set the short description to the archive component
  1406. Desc.ShortDesc = ShortDesc;
  1407. // Get the transfer sizes
  1408. FileSize = Size;
  1409. struct stat Buf;
  1410. if (stat(DestFile.c_str(),&Buf) == 0)
  1411. {
  1412. // Hmm, the partial file is too big, erase it
  1413. if ((unsigned)Buf.st_size > Size)
  1414. unlink(DestFile.c_str());
  1415. else
  1416. PartialSize = Buf.st_size;
  1417. }
  1418. QueueURI(Desc);
  1419. }
  1420. /*}}}*/
  1421. // AcqFile::Done - Item downloaded OK /*{{{*/
  1422. // ---------------------------------------------------------------------
  1423. /* */
  1424. void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
  1425. pkgAcquire::MethodConfig *Cnf)
  1426. {
  1427. Item::Done(Message,Size,CalcHash,Cnf);
  1428. // Check the hash
  1429. if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
  1430. {
  1431. Status = StatError;
  1432. ErrorText = "Hash Sum mismatch";
  1433. Rename(DestFile,DestFile + ".FAILED");
  1434. return;
  1435. }
  1436. string FileName = LookupTag(Message,"Filename");
  1437. if (FileName.empty() == true)
  1438. {
  1439. Status = StatError;
  1440. ErrorText = "Method gave a blank filename";
  1441. return;
  1442. }
  1443. Complete = true;
  1444. // The files timestamp matches
  1445. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1446. return;
  1447. // We have to copy it into place
  1448. if (FileName != DestFile)
  1449. {
  1450. Local = true;
  1451. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1452. Cnf->Removable == true)
  1453. {
  1454. Desc.URI = "copy:" + FileName;
  1455. QueueURI(Desc);
  1456. return;
  1457. }
  1458. // Erase the file if it is a symlink so we can overwrite it
  1459. struct stat St;
  1460. if (lstat(DestFile.c_str(),&St) == 0)
  1461. {
  1462. if (S_ISLNK(St.st_mode) != 0)
  1463. unlink(DestFile.c_str());
  1464. }
  1465. // Symlink the file
  1466. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  1467. {
  1468. ErrorText = "Link to " + DestFile + " failure ";
  1469. Status = StatError;
  1470. Complete = false;
  1471. }
  1472. }
  1473. }
  1474. /*}}}*/
  1475. // AcqFile::Failed - Failure handler /*{{{*/
  1476. // ---------------------------------------------------------------------
  1477. /* Here we try other sources */
  1478. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1479. {
  1480. ErrorText = LookupTag(Message,"Message");
  1481. // This is the retry counter
  1482. if (Retries != 0 &&
  1483. Cnf->LocalOnly == false &&
  1484. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1485. {
  1486. Retries--;
  1487. QueueURI(Desc);
  1488. return;
  1489. }
  1490. Item::Failed(Message,Cnf);
  1491. }
  1492. /*}}}*/
  1493. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1494. // ---------------------------------------------------------------------
  1495. /* The only header we use is the last-modified header. */
  1496. string pkgAcqFile::Custom600Headers()
  1497. {
  1498. if (IsIndexFile)
  1499. return "\nIndex-File: true";
  1500. else
  1501. return "";
  1502. }
  1503. /*}}}*/