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.
 
 
 
 
 
 

3690 lines
126 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 <config.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/aptconfiguration.h>
  17. #include <apt-pkg/sourcelist.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/fileutl.h>
  21. #include <apt-pkg/tagfile.h>
  22. #include <apt-pkg/metaindex.h>
  23. #include <apt-pkg/acquire.h>
  24. #include <apt-pkg/hashes.h>
  25. #include <apt-pkg/indexfile.h>
  26. #include <apt-pkg/pkgcache.h>
  27. #include <apt-pkg/cacheiterators.h>
  28. #include <apt-pkg/pkgrecords.h>
  29. #include <apt-pkg/gpgv.h>
  30. #include <algorithm>
  31. #include <stddef.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <iostream>
  35. #include <vector>
  36. #include <sys/stat.h>
  37. #include <unistd.h>
  38. #include <errno.h>
  39. #include <string>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <sstream>
  43. #include <numeric>
  44. #include <apti18n.h>
  45. /*}}}*/
  46. using namespace std;
  47. static void printHashSumComparison(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  48. {
  49. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  50. return;
  51. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  52. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  53. std::cerr << "\t- " << hs->toStr() << std::endl;
  54. std::cerr << " Actual Hash: " << std::endl;
  55. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  56. std::cerr << "\t- " << hs->toStr() << std::endl;
  57. }
  58. /*}}}*/
  59. static std::string GetPartialFileName(std::string const &file) /*{{{*/
  60. {
  61. std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  62. DestFile += file;
  63. return DestFile;
  64. }
  65. /*}}}*/
  66. static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
  67. {
  68. return GetPartialFileName(URItoFileName(uri));
  69. }
  70. /*}}}*/
  71. static std::string GetFinalFileNameFromURI(std::string const &uri) /*{{{*/
  72. {
  73. return _config->FindDir("Dir::State::lists") + URItoFileName(uri);
  74. }
  75. /*}}}*/
  76. static std::string GetKeepCompressedFileName(std::string file, IndexTarget const &Target)/*{{{*/
  77. {
  78. if (Target.KeepCompressed == false)
  79. return file;
  80. std::string const KeepCompressedAs = Target.Option(IndexTarget::KEEPCOMPRESSEDAS);
  81. if (KeepCompressedAs.empty() == false)
  82. {
  83. std::string const ext = KeepCompressedAs.substr(0, KeepCompressedAs.find(' '));
  84. if (ext != "uncompressed")
  85. file.append(".").append(ext);
  86. }
  87. return file;
  88. }
  89. /*}}}*/
  90. static std::string GetMergeDiffsPatchFileName(std::string const &Final, std::string const &Patch)/*{{{*/
  91. {
  92. // rred expects the patch as $FinalFile.ed.$patchname.gz
  93. return Final + ".ed." + Patch + ".gz";
  94. }
  95. /*}}}*/
  96. static std::string GetDiffsPatchFileName(std::string const &Final) /*{{{*/
  97. {
  98. // rred expects the patch as $FinalFile.ed
  99. return Final + ".ed";
  100. }
  101. /*}}}*/
  102. static std::string GetExistingFilename(std::string const &File) /*{{{*/
  103. {
  104. if (RealFileExists(File))
  105. return File;
  106. for (auto const &type : APT::Configuration::getCompressorExtensions())
  107. {
  108. std::string const Final = File + type;
  109. if (RealFileExists(Final))
  110. return Final;
  111. }
  112. return "";
  113. }
  114. /*}}}*/
  115. static std::string GetDiffIndexFileName(std::string const &Name) /*{{{*/
  116. {
  117. return Name + ".diff/Index";
  118. }
  119. /*}}}*/
  120. static std::string GetDiffIndexURI(IndexTarget const &Target) /*{{{*/
  121. {
  122. return Target.URI + ".diff/Index";
  123. }
  124. /*}}}*/
  125. static void ReportMirrorFailureToCentral(pkgAcquire::Item const &I, std::string const &FailCode, std::string const &Details)/*{{{*/
  126. {
  127. // we only act if a mirror was used at all
  128. if(I.UsedMirror.empty())
  129. return;
  130. #if 0
  131. std::cerr << "\nReportMirrorFailure: "
  132. << UsedMirror
  133. << " Uri: " << DescURI()
  134. << " FailCode: "
  135. << FailCode << std::endl;
  136. #endif
  137. string const report = _config->Find("Methods::Mirror::ProblemReporting",
  138. "/usr/lib/apt/apt-report-mirror-failure");
  139. if(!FileExists(report))
  140. return;
  141. std::vector<char const*> const Args = {
  142. report.c_str(),
  143. I.UsedMirror.c_str(),
  144. I.DescURI().c_str(),
  145. FailCode.c_str(),
  146. Details.c_str(),
  147. NULL
  148. };
  149. pid_t pid = ExecFork();
  150. if(pid < 0)
  151. {
  152. _error->Error("ReportMirrorFailure Fork failed");
  153. return;
  154. }
  155. else if(pid == 0)
  156. {
  157. execvp(Args[0], (char**)Args.data());
  158. std::cerr << "Could not exec " << Args[0] << std::endl;
  159. _exit(100);
  160. }
  161. if(!ExecWait(pid, "report-mirror-failure"))
  162. _error->Warning("Couldn't report problem to '%s'", report.c_str());
  163. }
  164. /*}}}*/
  165. static APT_NONNULL(2) bool MessageInsecureRepository(bool const isError, char const * const msg, std::string const &repo)/*{{{*/
  166. {
  167. std::string m;
  168. strprintf(m, msg, repo.c_str());
  169. if (isError)
  170. {
  171. _error->Error("%s", m.c_str());
  172. _error->Notice("%s", _("Updating from such a repository can't be done securely, and is therefore disabled by default."));
  173. }
  174. else
  175. {
  176. _error->Warning("%s", m.c_str());
  177. _error->Notice("%s", _("Data from such a repository can't be authenticated and is therefore potentially dangerous to use."));
  178. }
  179. _error->Notice("%s", _("See apt-secure(8) manpage for repository creation and user configuration details."));
  180. return false;
  181. }
  182. /*}}}*/
  183. // AllowInsecureRepositories /*{{{*/
  184. enum class InsecureType { UNSIGNED, WEAK, NORELEASE };
  185. static bool TargetIsAllowedToBe(IndexTarget const &Target, InsecureType const type)
  186. {
  187. if (_config->FindB("Acquire::AllowInsecureRepositories"))
  188. return true;
  189. if (Target.OptionBool(IndexTarget::ALLOW_INSECURE))
  190. return true;
  191. switch (type)
  192. {
  193. case InsecureType::UNSIGNED: break;
  194. case InsecureType::NORELEASE: break;
  195. case InsecureType::WEAK:
  196. if (_config->FindB("Acquire::AllowWeakRepositories"))
  197. return true;
  198. if (Target.OptionBool(IndexTarget::ALLOW_WEAK))
  199. return true;
  200. break;
  201. }
  202. return false;
  203. }
  204. static bool APT_NONNULL(3, 4, 5) AllowInsecureRepositories(InsecureType const msg, std::string const &repo,
  205. metaIndex const * const MetaIndexParser, pkgAcqMetaClearSig * const TransactionManager, pkgAcquire::Item * const I)
  206. {
  207. // we skip weak downgrades as its unlikely that a repository gets really weaker –
  208. // its more realistic that apt got pickier in a newer version
  209. if (msg != InsecureType::WEAK)
  210. {
  211. std::string const FinalInRelease = TransactionManager->GetFinalFilename();
  212. std::string const FinalReleasegpg = FinalInRelease.substr(0, FinalInRelease.length() - strlen("InRelease")) + "Release.gpg";
  213. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  214. {
  215. char const * msgstr = nullptr;
  216. switch (msg)
  217. {
  218. case InsecureType::UNSIGNED: msgstr = _("The repository '%s' is no longer signed."); break;
  219. case InsecureType::NORELEASE: msgstr = _("The repository '%s' does no longer have a Release file."); break;
  220. case InsecureType::WEAK: /* unreachable */ break;
  221. }
  222. if (_config->FindB("Acquire::AllowDowngradeToInsecureRepositories") ||
  223. TransactionManager->Target.OptionBool(IndexTarget::ALLOW_DOWNGRADE_TO_INSECURE))
  224. {
  225. // meh, the users wants to take risks (we still mark the packages
  226. // from this repository as unauthenticated)
  227. _error->Warning(msgstr, repo.c_str());
  228. _error->Warning(_("This is normally not allowed, but the option "
  229. "Acquire::AllowDowngradeToInsecureRepositories was "
  230. "given to override it."));
  231. } else {
  232. MessageInsecureRepository(true, msgstr, repo);
  233. TransactionManager->AbortTransaction();
  234. I->Status = pkgAcquire::Item::StatError;
  235. return false;
  236. }
  237. }
  238. }
  239. if(MetaIndexParser->GetTrusted() == metaIndex::TRI_YES)
  240. return true;
  241. char const * msgstr = nullptr;
  242. switch (msg)
  243. {
  244. case InsecureType::UNSIGNED: msgstr = _("The repository '%s' is not signed."); break;
  245. case InsecureType::NORELEASE: msgstr = _("The repository '%s' does not have a Release file."); break;
  246. case InsecureType::WEAK: msgstr = _("The repository '%s' provides only weak security information."); break;
  247. }
  248. if (TargetIsAllowedToBe(TransactionManager->Target, msg) == true)
  249. {
  250. MessageInsecureRepository(false, msgstr, repo);
  251. return true;
  252. }
  253. MessageInsecureRepository(true, msgstr, repo);
  254. TransactionManager->AbortTransaction();
  255. I->Status = pkgAcquire::Item::StatError;
  256. return false;
  257. }
  258. /*}}}*/
  259. static HashStringList GetExpectedHashesFromFor(metaIndex * const Parser, std::string const &MetaKey)/*{{{*/
  260. {
  261. if (Parser == NULL)
  262. return HashStringList();
  263. metaIndex::checkSum * const R = Parser->Lookup(MetaKey);
  264. if (R == NULL)
  265. return HashStringList();
  266. return R->Hashes;
  267. }
  268. /*}}}*/
  269. // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
  270. /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
  271. It is best to implement it as broadly as possible, while ::HashesRequired defaults
  272. to true and should be as restrictive as possible for false cases. Note that if
  273. a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
  274. ::HashesRequired is called to evaluate if its okay to have no hashes. */
  275. APT_CONST bool pkgAcqTransactionItem::HashesRequired() const
  276. {
  277. /* signed repositories obviously have a parser and good hashes.
  278. unsigned repositories, too, as even if we can't trust them for security,
  279. we can at least trust them for integrity of the download itself.
  280. Only repositories without a Release file can (obviously) not have
  281. hashes – and they are very uncommon and strongly discouraged */
  282. if (TransactionManager->MetaIndexParser->GetLoadedSuccessfully() != metaIndex::TRI_YES)
  283. return false;
  284. if (TargetIsAllowedToBe(Target, InsecureType::WEAK))
  285. {
  286. /* If we allow weak hashes, we check that we have some (weak) and then
  287. declare hashes not needed. That will tip us in the right direction
  288. as if hashes exist, they will be used, even if not required */
  289. auto const hsl = GetExpectedHashes();
  290. if (hsl.usable())
  291. return true;
  292. if (hsl.empty() == false)
  293. return false;
  294. }
  295. return true;
  296. }
  297. HashStringList pkgAcqTransactionItem::GetExpectedHashes() const
  298. {
  299. return GetExpectedHashesFor(GetMetaKey());
  300. }
  301. APT_CONST bool pkgAcqMetaBase::HashesRequired() const
  302. {
  303. // Release and co have no hashes 'by design'.
  304. return false;
  305. }
  306. HashStringList pkgAcqMetaBase::GetExpectedHashes() const
  307. {
  308. return HashStringList();
  309. }
  310. APT_CONST bool pkgAcqIndexDiffs::HashesRequired() const
  311. {
  312. /* We can't check hashes of rred result as we don't know what the
  313. hash of the file will be. We just know the hash of the patch(es),
  314. the hash of the file they will apply on and the hash of the resulting
  315. file. */
  316. if (State == StateFetchDiff)
  317. return true;
  318. return false;
  319. }
  320. HashStringList pkgAcqIndexDiffs::GetExpectedHashes() const
  321. {
  322. if (State == StateFetchDiff)
  323. return available_patches[0].download_hashes;
  324. return HashStringList();
  325. }
  326. APT_CONST bool pkgAcqIndexMergeDiffs::HashesRequired() const
  327. {
  328. /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
  329. we can check the rred result after all patches are applied as
  330. we know the expected result rather than potentially apply more patches */
  331. if (State == StateFetchDiff)
  332. return true;
  333. return State == StateApplyDiff;
  334. }
  335. HashStringList pkgAcqIndexMergeDiffs::GetExpectedHashes() const
  336. {
  337. if (State == StateFetchDiff)
  338. return patch.download_hashes;
  339. else if (State == StateApplyDiff)
  340. return GetExpectedHashesFor(Target.MetaKey);
  341. return HashStringList();
  342. }
  343. APT_CONST bool pkgAcqArchive::HashesRequired() const
  344. {
  345. return LocalSource == false;
  346. }
  347. HashStringList pkgAcqArchive::GetExpectedHashes() const
  348. {
  349. // figured out while parsing the records
  350. return ExpectedHashes;
  351. }
  352. APT_CONST bool pkgAcqFile::HashesRequired() const
  353. {
  354. // supplied as parameter at creation time, so the caller decides
  355. return ExpectedHashes.usable();
  356. }
  357. HashStringList pkgAcqFile::GetExpectedHashes() const
  358. {
  359. return ExpectedHashes;
  360. }
  361. /*}}}*/
  362. // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
  363. bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc &Item)
  364. {
  365. Owner->Enqueue(Item);
  366. return true;
  367. }
  368. /* The idea here is that an item isn't queued if it exists on disk and the
  369. transition manager was a hit as this means that the files it contains
  370. the checksums for can't be updated either (or they are and we are asking
  371. for a hashsum mismatch to happen which helps nobody) */
  372. bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc &Item)
  373. {
  374. if (TransactionManager->State != TransactionStarted)
  375. {
  376. if (_config->FindB("Debug::Acquire::Transaction", false))
  377. std::clog << "Skip " << Target.URI << " as transaction was already dealt with!" << std::endl;
  378. return false;
  379. }
  380. std::string const FinalFile = GetFinalFilename();
  381. if (TransactionManager->IMSHit == true && FileExists(FinalFile) == true)
  382. {
  383. PartialFile = DestFile = FinalFile;
  384. Status = StatDone;
  385. return false;
  386. }
  387. // If we got the InRelease file via a mirror, pick all indexes directly from this mirror, too
  388. if (TransactionManager->BaseURI.empty() == false &&
  389. URI::SiteOnly(Item.URI) != URI::SiteOnly(TransactionManager->BaseURI))
  390. {
  391. // this ensures we rewrite only once and only the first step
  392. auto const OldBaseURI = Target.Option(IndexTarget::BASE_URI);
  393. if (OldBaseURI.empty() == false && APT::String::Startswith(Item.URI, OldBaseURI))
  394. {
  395. auto const ExtraPath = Item.URI.substr(OldBaseURI.length());
  396. Item.URI = flCombine(TransactionManager->BaseURI, ExtraPath);
  397. UsedMirror = TransactionManager->UsedMirror;
  398. if (Item.Description.find(" ") != string::npos)
  399. Item.Description.replace(0, Item.Description.find(" "), UsedMirror);
  400. }
  401. }
  402. return pkgAcquire::Item::QueueURI(Item);
  403. }
  404. /* The transition manager InRelease itself (or its older sisters-in-law
  405. Release & Release.gpg) is always queued as this allows us to rerun gpgv
  406. on it to verify that we aren't stalled with old files */
  407. bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc &Item)
  408. {
  409. return pkgAcquire::Item::QueueURI(Item);
  410. }
  411. /* the Diff/Index needs to queue also the up-to-date complete index file
  412. to ensure that the list cleaner isn't eating it */
  413. bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc &Item)
  414. {
  415. if (pkgAcqTransactionItem::QueueURI(Item) == true)
  416. return true;
  417. QueueOnIMSHit();
  418. return false;
  419. }
  420. /*}}}*/
  421. // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
  422. std::string pkgAcquire::Item::GetFinalFilename() const
  423. {
  424. // Beware: Desc.URI is modified by redirections
  425. return GetFinalFileNameFromURI(Desc.URI);
  426. }
  427. std::string pkgAcqDiffIndex::GetFinalFilename() const
  428. {
  429. return GetFinalFileNameFromURI(GetDiffIndexURI(Target));
  430. }
  431. std::string pkgAcqIndex::GetFinalFilename() const
  432. {
  433. std::string const FinalFile = GetFinalFileNameFromURI(Target.URI);
  434. return GetKeepCompressedFileName(FinalFile, Target);
  435. }
  436. std::string pkgAcqMetaSig::GetFinalFilename() const
  437. {
  438. return GetFinalFileNameFromURI(Target.URI);
  439. }
  440. std::string pkgAcqBaseIndex::GetFinalFilename() const
  441. {
  442. return GetFinalFileNameFromURI(Target.URI);
  443. }
  444. std::string pkgAcqMetaBase::GetFinalFilename() const
  445. {
  446. return GetFinalFileNameFromURI(Target.URI);
  447. }
  448. std::string pkgAcqArchive::GetFinalFilename() const
  449. {
  450. return _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  451. }
  452. /*}}}*/
  453. // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
  454. std::string pkgAcqTransactionItem::GetMetaKey() const
  455. {
  456. return Target.MetaKey;
  457. }
  458. std::string pkgAcqIndex::GetMetaKey() const
  459. {
  460. if (Stage == STAGE_DECOMPRESS_AND_VERIFY || CurrentCompressionExtension == "uncompressed")
  461. return Target.MetaKey;
  462. return Target.MetaKey + "." + CurrentCompressionExtension;
  463. }
  464. std::string pkgAcqDiffIndex::GetMetaKey() const
  465. {
  466. return GetDiffIndexFileName(Target.MetaKey);
  467. }
  468. /*}}}*/
  469. //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
  470. bool pkgAcqTransactionItem::TransactionState(TransactionStates const state)
  471. {
  472. bool const Debug = _config->FindB("Debug::Acquire::Transaction", false);
  473. switch(state)
  474. {
  475. case TransactionStarted: _error->Fatal("Item %s changed to invalid transaction start state!", Target.URI.c_str()); break;
  476. case TransactionAbort:
  477. if(Debug == true)
  478. std::clog << " Cancel: " << DestFile << std::endl;
  479. if (Status == pkgAcquire::Item::StatIdle)
  480. {
  481. Status = pkgAcquire::Item::StatDone;
  482. Dequeue();
  483. }
  484. break;
  485. case TransactionCommit:
  486. if(PartialFile.empty() == false)
  487. {
  488. bool sameFile = (PartialFile == DestFile);
  489. // we use symlinks on IMS-Hit to avoid copies
  490. if (RealFileExists(DestFile))
  491. {
  492. struct stat Buf;
  493. if (lstat(PartialFile.c_str(), &Buf) != -1)
  494. {
  495. if (S_ISLNK(Buf.st_mode) && Buf.st_size > 0)
  496. {
  497. char partial[Buf.st_size + 1];
  498. ssize_t const sp = readlink(PartialFile.c_str(), partial, Buf.st_size);
  499. if (sp == -1)
  500. _error->Errno("pkgAcqTransactionItem::TransactionState-sp", _("Failed to readlink %s"), PartialFile.c_str());
  501. else
  502. {
  503. partial[sp] = '\0';
  504. sameFile = (DestFile == partial);
  505. }
  506. }
  507. }
  508. else
  509. _error->Errno("pkgAcqTransactionItem::TransactionState-stat", _("Failed to stat %s"), PartialFile.c_str());
  510. }
  511. if (sameFile == false)
  512. {
  513. // ensure that even without lists-cleanup all compressions are nuked
  514. std::string FinalFile = GetFinalFileNameFromURI(Target.URI);
  515. if (FileExists(FinalFile))
  516. {
  517. if(Debug == true)
  518. std::clog << "rm " << FinalFile << " # " << DescURI() << std::endl;
  519. if (RemoveFile("TransactionStates-Cleanup", FinalFile) == false)
  520. return false;
  521. }
  522. for (auto const &ext: APT::Configuration::getCompressorExtensions())
  523. {
  524. auto const Final = FinalFile + ext;
  525. if (FileExists(Final))
  526. {
  527. if(Debug == true)
  528. std::clog << "rm " << Final << " # " << DescURI() << std::endl;
  529. if (RemoveFile("TransactionStates-Cleanup", Final) == false)
  530. return false;
  531. }
  532. }
  533. if(Debug == true)
  534. std::clog << "mv " << PartialFile << " -> "<< DestFile << " # " << DescURI() << std::endl;
  535. if (Rename(PartialFile, DestFile) == false)
  536. return false;
  537. }
  538. else if(Debug == true)
  539. std::clog << "keep " << PartialFile << " # " << DescURI() << std::endl;
  540. } else {
  541. if(Debug == true)
  542. std::clog << "rm " << DestFile << " # " << DescURI() << std::endl;
  543. if (RemoveFile("TransItem::TransactionCommit", DestFile) == false)
  544. return false;
  545. }
  546. break;
  547. }
  548. return true;
  549. }
  550. bool pkgAcqMetaBase::TransactionState(TransactionStates const state)
  551. {
  552. // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
  553. if (TransactionManager->IMSHit == false)
  554. return pkgAcqTransactionItem::TransactionState(state);
  555. return true;
  556. }
  557. bool pkgAcqIndex::TransactionState(TransactionStates const state)
  558. {
  559. if (pkgAcqTransactionItem::TransactionState(state) == false)
  560. return false;
  561. switch (state)
  562. {
  563. case TransactionStarted: _error->Fatal("AcqIndex %s changed to invalid transaction start state!", Target.URI.c_str()); break;
  564. case TransactionAbort:
  565. if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
  566. {
  567. // keep the compressed file, but drop the decompressed
  568. EraseFileName.clear();
  569. if (PartialFile.empty() == false && flExtension(PartialFile) != CurrentCompressionExtension)
  570. RemoveFile("TransactionAbort", PartialFile);
  571. }
  572. break;
  573. case TransactionCommit:
  574. if (EraseFileName.empty() == false)
  575. RemoveFile("AcqIndex::TransactionCommit", EraseFileName);
  576. break;
  577. }
  578. return true;
  579. }
  580. bool pkgAcqDiffIndex::TransactionState(TransactionStates const state)
  581. {
  582. if (pkgAcqTransactionItem::TransactionState(state) == false)
  583. return false;
  584. switch (state)
  585. {
  586. case TransactionStarted: _error->Fatal("Item %s changed to invalid transaction start state!", Target.URI.c_str()); break;
  587. case TransactionCommit:
  588. break;
  589. case TransactionAbort:
  590. std::string const Partial = GetPartialFileNameFromURI(Target.URI);
  591. RemoveFile("TransactionAbort", Partial);
  592. break;
  593. }
  594. return true;
  595. }
  596. /*}}}*/
  597. class APT_HIDDEN NoActionItem : public pkgAcquire::Item /*{{{*/
  598. /* The sole purpose of this class is having an item which does nothing to
  599. reach its done state to prevent cleanup deleting the mentioned file.
  600. Handy in cases in which we know we have the file already, like IMS-Hits. */
  601. {
  602. IndexTarget const Target;
  603. public:
  604. virtual std::string DescURI() const APT_OVERRIDE {return Target.URI;};
  605. virtual HashStringList GetExpectedHashes() const APT_OVERRIDE {return HashStringList();};
  606. NoActionItem(pkgAcquire * const Owner, IndexTarget const &Target) :
  607. pkgAcquire::Item(Owner), Target(Target)
  608. {
  609. Status = StatDone;
  610. DestFile = GetFinalFileNameFromURI(Target.URI);
  611. }
  612. NoActionItem(pkgAcquire * const Owner, IndexTarget const &Target, std::string const &FinalFile) :
  613. pkgAcquire::Item(Owner), Target(Target)
  614. {
  615. Status = StatDone;
  616. DestFile = FinalFile;
  617. }
  618. };
  619. /*}}}*/
  620. class APT_HIDDEN CleanupItem : public pkgAcqTransactionItem /*{{{*/
  621. /* This class ensures that a file which was configured but isn't downloaded
  622. for various reasons isn't kept in an old version in the lists directory.
  623. In a way its the reverse of NoActionItem as it helps with removing files
  624. even if the lists-cleanup is deactivated. */
  625. {
  626. public:
  627. virtual std::string DescURI() const APT_OVERRIDE {return Target.URI;};
  628. virtual HashStringList GetExpectedHashes() const APT_OVERRIDE {return HashStringList();};
  629. CleanupItem(pkgAcquire * const Owner, pkgAcqMetaClearSig * const TransactionManager, IndexTarget const &Target) :
  630. pkgAcqTransactionItem(Owner, TransactionManager, Target)
  631. {
  632. Status = StatDone;
  633. DestFile = GetFinalFileNameFromURI(Target.URI);
  634. }
  635. bool TransactionState(TransactionStates const state) APT_OVERRIDE
  636. {
  637. switch (state)
  638. {
  639. case TransactionStarted:
  640. break;
  641. case TransactionAbort:
  642. break;
  643. case TransactionCommit:
  644. if (_config->FindB("Debug::Acquire::Transaction", false) == true)
  645. std::clog << "rm " << DestFile << " # " << DescURI() << std::endl;
  646. if (RemoveFile("TransItem::TransactionCommit", DestFile) == false)
  647. return false;
  648. break;
  649. }
  650. return true;
  651. }
  652. };
  653. /*}}}*/
  654. // Acquire::Item::Item - Constructor /*{{{*/
  655. APT_IGNORE_DEPRECATED_PUSH
  656. pkgAcquire::Item::Item(pkgAcquire * const owner) :
  657. FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
  658. QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner), d(NULL)
  659. {
  660. Owner->Add(this);
  661. Status = StatIdle;
  662. }
  663. APT_IGNORE_DEPRECATED_POP
  664. /*}}}*/
  665. // Acquire::Item::~Item - Destructor /*{{{*/
  666. pkgAcquire::Item::~Item()
  667. {
  668. Owner->Remove(this);
  669. }
  670. /*}}}*/
  671. std::string pkgAcquire::Item::Custom600Headers() const /*{{{*/
  672. {
  673. return std::string();
  674. }
  675. /*}}}*/
  676. std::string pkgAcquire::Item::ShortDesc() const /*{{{*/
  677. {
  678. return DescURI();
  679. }
  680. /*}}}*/
  681. APT_CONST void pkgAcquire::Item::Finished() /*{{{*/
  682. {
  683. }
  684. /*}}}*/
  685. APT_PURE pkgAcquire * pkgAcquire::Item::GetOwner() const /*{{{*/
  686. {
  687. return Owner;
  688. }
  689. /*}}}*/
  690. APT_CONST pkgAcquire::ItemDesc &pkgAcquire::Item::GetItemDesc() /*{{{*/
  691. {
  692. return Desc;
  693. }
  694. /*}}}*/
  695. APT_CONST bool pkgAcquire::Item::IsTrusted() const /*{{{*/
  696. {
  697. return false;
  698. }
  699. /*}}}*/
  700. // Acquire::Item::Failed - Item failed to download /*{{{*/
  701. // ---------------------------------------------------------------------
  702. /* We return to an idle state if there are still other queues that could
  703. fetch this object */
  704. void pkgAcquire::Item::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  705. {
  706. if (QueueCounter <= 1)
  707. {
  708. /* This indicates that the file is not available right now but might
  709. be sometime later. If we do a retry cycle then this should be
  710. retried [CDROMs] */
  711. if (Cnf != NULL && Cnf->LocalOnly == true &&
  712. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  713. {
  714. Status = StatIdle;
  715. Dequeue();
  716. return;
  717. }
  718. switch (Status)
  719. {
  720. case StatIdle:
  721. case StatFetching:
  722. case StatDone:
  723. Status = StatError;
  724. break;
  725. case StatAuthError:
  726. case StatError:
  727. case StatTransientNetworkError:
  728. break;
  729. }
  730. Complete = false;
  731. Dequeue();
  732. }
  733. string const FailReason = LookupTag(Message, "FailReason");
  734. enum { MAXIMUM_SIZE_EXCEEDED, HASHSUM_MISMATCH, WEAK_HASHSUMS, OTHER } failreason = OTHER;
  735. if ( FailReason == "MaximumSizeExceeded")
  736. failreason = MAXIMUM_SIZE_EXCEEDED;
  737. else if ( FailReason == "WeakHashSums")
  738. failreason = WEAK_HASHSUMS;
  739. else if (Status == StatAuthError)
  740. failreason = HASHSUM_MISMATCH;
  741. if(ErrorText.empty())
  742. {
  743. if (Status == StatAuthError)
  744. {
  745. std::ostringstream out;
  746. switch (failreason)
  747. {
  748. case HASHSUM_MISMATCH:
  749. out << _("Hash Sum mismatch") << std::endl;
  750. break;
  751. case WEAK_HASHSUMS:
  752. out << _("Insufficient information available to perform this download securely") << std::endl;
  753. break;
  754. case MAXIMUM_SIZE_EXCEEDED:
  755. case OTHER:
  756. out << LookupTag(Message, "Message") << std::endl;
  757. break;
  758. }
  759. auto const ExpectedHashes = GetExpectedHashes();
  760. if (ExpectedHashes.empty() == false)
  761. {
  762. out << "Hashes of expected file:" << std::endl;
  763. for (auto const &hs: ExpectedHashes)
  764. {
  765. out << " - " << hs.toStr();
  766. if (hs.usable() == false)
  767. out << " [weak]";
  768. out << std::endl;
  769. }
  770. }
  771. if (failreason == HASHSUM_MISMATCH)
  772. {
  773. out << "Hashes of received file:" << std::endl;
  774. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  775. {
  776. std::string const tagname = std::string(*type) + "-Hash";
  777. std::string const hashsum = LookupTag(Message, tagname.c_str());
  778. if (hashsum.empty() == false)
  779. {
  780. auto const hs = HashString(*type, hashsum);
  781. out << " - " << hs.toStr();
  782. if (hs.usable() == false)
  783. out << " [weak]";
  784. out << std::endl;
  785. }
  786. }
  787. out << "Last modification reported: " << LookupTag(Message, "Last-Modified", "<none>") << std::endl;
  788. }
  789. ErrorText = out.str();
  790. }
  791. else
  792. ErrorText = LookupTag(Message,"Message");
  793. }
  794. switch (failreason)
  795. {
  796. case MAXIMUM_SIZE_EXCEEDED: RenameOnError(MaximumSizeExceeded); break;
  797. case HASHSUM_MISMATCH: RenameOnError(HashSumMismatch); break;
  798. case WEAK_HASHSUMS: break;
  799. case OTHER: break;
  800. }
  801. if (FailReason.empty() == false)
  802. ReportMirrorFailureToCentral(*this, FailReason, ErrorText);
  803. else
  804. ReportMirrorFailureToCentral(*this, ErrorText, ErrorText);
  805. if (QueueCounter > 1)
  806. Status = StatIdle;
  807. }
  808. /*}}}*/
  809. // Acquire::Item::Start - Item has begun to download /*{{{*/
  810. // ---------------------------------------------------------------------
  811. /* Stash status and the file size. Note that setting Complete means
  812. sub-phases of the acquire process such as decompresion are operating */
  813. void pkgAcquire::Item::Start(string const &/*Message*/, unsigned long long const Size)
  814. {
  815. Status = StatFetching;
  816. ErrorText.clear();
  817. if (FileSize == 0 && Complete == false)
  818. FileSize = Size;
  819. }
  820. /*}}}*/
  821. // Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
  822. /* Note that hash-verification is 'hardcoded' in acquire-worker and has
  823. * already passed if this method is called. */
  824. bool pkgAcquire::Item::VerifyDone(std::string const &Message,
  825. pkgAcquire::MethodConfig const * const /*Cnf*/)
  826. {
  827. std::string const FileName = LookupTag(Message,"Filename");
  828. if (FileName.empty() == true)
  829. {
  830. Status = StatError;
  831. ErrorText = "Method gave a blank filename";
  832. return false;
  833. }
  834. return true;
  835. }
  836. /*}}}*/
  837. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  838. void pkgAcquire::Item::Done(string const &/*Message*/, HashStringList const &Hashes,
  839. pkgAcquire::MethodConfig const * const /*Cnf*/)
  840. {
  841. // We just downloaded something..
  842. if (FileSize == 0)
  843. {
  844. unsigned long long const downloadedSize = Hashes.FileSize();
  845. if (downloadedSize != 0)
  846. {
  847. FileSize = downloadedSize;
  848. }
  849. }
  850. Status = StatDone;
  851. ErrorText = string();
  852. Owner->Dequeue(this);
  853. }
  854. /*}}}*/
  855. // Acquire::Item::Rename - Rename a file /*{{{*/
  856. // ---------------------------------------------------------------------
  857. /* This helper function is used by a lot of item methods as their final
  858. step */
  859. bool pkgAcquire::Item::Rename(string const &From,string const &To)
  860. {
  861. if (From == To || rename(From.c_str(),To.c_str()) == 0)
  862. return true;
  863. std::string S;
  864. strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
  865. From.c_str(),To.c_str());
  866. Status = StatError;
  867. if (ErrorText.empty())
  868. ErrorText = S;
  869. else
  870. ErrorText = ErrorText + ": " + S;
  871. return false;
  872. }
  873. /*}}}*/
  874. void pkgAcquire::Item::Dequeue() /*{{{*/
  875. {
  876. Owner->Dequeue(this);
  877. }
  878. /*}}}*/
  879. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  880. {
  881. if (RealFileExists(DestFile))
  882. Rename(DestFile, DestFile + ".FAILED");
  883. std::string errtext;
  884. switch (error)
  885. {
  886. case HashSumMismatch:
  887. errtext = _("Hash Sum mismatch");
  888. break;
  889. case SizeMismatch:
  890. errtext = _("Size mismatch");
  891. Status = StatAuthError;
  892. break;
  893. case InvalidFormat:
  894. errtext = _("Invalid file format");
  895. Status = StatError;
  896. // do not report as usually its not the mirrors fault, but Portal/Proxy
  897. break;
  898. case SignatureError:
  899. errtext = _("Signature error");
  900. Status = StatError;
  901. break;
  902. case NotClearsigned:
  903. strprintf(errtext, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
  904. Status = StatAuthError;
  905. break;
  906. case MaximumSizeExceeded:
  907. // the method is expected to report a good error for this
  908. break;
  909. case PDiffError:
  910. // no handling here, done by callers
  911. break;
  912. }
  913. if (ErrorText.empty())
  914. ErrorText = errtext;
  915. return false;
  916. }
  917. /*}}}*/
  918. void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
  919. {
  920. ActiveSubprocess = subprocess;
  921. APT_IGNORE_DEPRECATED(Mode = ActiveSubprocess.c_str();)
  922. }
  923. /*}}}*/
  924. // Acquire::Item::ReportMirrorFailure /*{{{*/
  925. void pkgAcquire::Item::ReportMirrorFailure(std::string const &FailCode)
  926. {
  927. ReportMirrorFailureToCentral(*this, FailCode, FailCode);
  928. }
  929. /*}}}*/
  930. std::string pkgAcquire::Item::HashSum() const /*{{{*/
  931. {
  932. HashStringList const hashes = GetExpectedHashes();
  933. HashString const * const hs = hashes.find(NULL);
  934. return hs != NULL ? hs->toStr() : "";
  935. }
  936. /*}}}*/
  937. pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire * const Owner, /*{{{*/
  938. pkgAcqMetaClearSig * const transactionManager, IndexTarget const &target) :
  939. pkgAcquire::Item(Owner), d(NULL), Target(target), TransactionManager(transactionManager)
  940. {
  941. if (TransactionManager != this)
  942. TransactionManager->Add(this);
  943. }
  944. /*}}}*/
  945. pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
  946. {
  947. }
  948. /*}}}*/
  949. HashStringList pkgAcqTransactionItem::GetExpectedHashesFor(std::string const &MetaKey) const /*{{{*/
  950. {
  951. return GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, MetaKey);
  952. }
  953. /*}}}*/
  954. static void LoadLastMetaIndexParser(pkgAcqMetaClearSig * const TransactionManager, std::string const &FinalRelease, std::string const &FinalInRelease)/*{{{*/
  955. {
  956. if (TransactionManager->IMSHit == true)
  957. return;
  958. if (RealFileExists(FinalInRelease) || RealFileExists(FinalRelease))
  959. {
  960. TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
  961. if (TransactionManager->LastMetaIndexParser != NULL)
  962. {
  963. _error->PushToStack();
  964. if (RealFileExists(FinalInRelease))
  965. TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
  966. else
  967. TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
  968. // its unlikely to happen, but if what we have is bad ignore it
  969. if (_error->PendingError())
  970. {
  971. delete TransactionManager->LastMetaIndexParser;
  972. TransactionManager->LastMetaIndexParser = NULL;
  973. }
  974. _error->RevertToStack();
  975. }
  976. }
  977. }
  978. /*}}}*/
  979. // AcqMetaBase - Constructor /*{{{*/
  980. pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire * const Owner,
  981. pkgAcqMetaClearSig * const TransactionManager,
  982. IndexTarget const &DataTarget)
  983. : pkgAcqTransactionItem(Owner, TransactionManager, DataTarget), d(NULL),
  984. AuthPass(false), IMSHit(false), State(TransactionStarted)
  985. {
  986. }
  987. /*}}}*/
  988. // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
  989. void pkgAcqMetaBase::Add(pkgAcqTransactionItem * const I)
  990. {
  991. Transaction.push_back(I);
  992. }
  993. /*}}}*/
  994. // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
  995. void pkgAcqMetaBase::AbortTransaction()
  996. {
  997. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  998. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  999. switch (TransactionManager->State)
  1000. {
  1001. case TransactionStarted: break;
  1002. case TransactionAbort: _error->Fatal("Transaction %s was already aborted and is aborted again", TransactionManager->Target.URI.c_str()); return;
  1003. case TransactionCommit: _error->Fatal("Transaction %s was already aborted and is now committed", TransactionManager->Target.URI.c_str()); return;
  1004. }
  1005. TransactionManager->State = TransactionAbort;
  1006. // ensure the toplevel is in error state too
  1007. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  1008. I != Transaction.end(); ++I)
  1009. {
  1010. if ((*I)->Status != pkgAcquire::Item::StatFetching)
  1011. Owner->Dequeue(*I);
  1012. (*I)->TransactionState(TransactionAbort);
  1013. }
  1014. Transaction.clear();
  1015. }
  1016. /*}}}*/
  1017. // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
  1018. APT_PURE bool pkgAcqMetaBase::TransactionHasError() const
  1019. {
  1020. for (std::vector<pkgAcqTransactionItem*>::const_iterator I = Transaction.begin();
  1021. I != Transaction.end(); ++I)
  1022. {
  1023. switch((*I)->Status) {
  1024. case StatDone: break;
  1025. case StatIdle: break;
  1026. case StatAuthError: return true;
  1027. case StatError: return true;
  1028. case StatTransientNetworkError: return true;
  1029. case StatFetching: break;
  1030. }
  1031. }
  1032. return false;
  1033. }
  1034. /*}}}*/
  1035. // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
  1036. void pkgAcqMetaBase::CommitTransaction()
  1037. {
  1038. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1039. std::clog << "CommitTransaction: " << this << std::endl;
  1040. switch (TransactionManager->State)
  1041. {
  1042. case TransactionStarted: break;
  1043. case TransactionAbort: _error->Fatal("Transaction %s was already committed and is now aborted", TransactionManager->Target.URI.c_str()); return;
  1044. case TransactionCommit: _error->Fatal("Transaction %s was already committed and is again committed", TransactionManager->Target.URI.c_str()); return;
  1045. }
  1046. TransactionManager->State = TransactionCommit;
  1047. // move new files into place *and* remove files that are not
  1048. // part of the transaction but are still on disk
  1049. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  1050. I != Transaction.end(); ++I)
  1051. {
  1052. (*I)->TransactionState(TransactionCommit);
  1053. }
  1054. Transaction.clear();
  1055. }
  1056. /*}}}*/
  1057. // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
  1058. void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem * const I,
  1059. const std::string &From,
  1060. const std::string &To)
  1061. {
  1062. I->PartialFile = From;
  1063. I->DestFile = To;
  1064. }
  1065. /*}}}*/
  1066. // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
  1067. void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem * const I,
  1068. const std::string &FinalFile)
  1069. {
  1070. I->PartialFile = "";
  1071. I->DestFile = FinalFile;
  1072. }
  1073. /*}}}*/
  1074. // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
  1075. /* This method is called from ::Failed handlers. If it returns true,
  1076. no fallback to other files or modi is performed */
  1077. bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item * const I, const std::string &Message)
  1078. {
  1079. string const Final = I->GetFinalFilename();
  1080. std::string const GPGError = LookupTag(Message, "Message");
  1081. if (FileExists(Final))
  1082. {
  1083. I->Status = StatTransientNetworkError;
  1084. _error->Warning(_("An error occurred during the signature verification. "
  1085. "The repository is not updated and the previous index files will be used. "
  1086. "GPG error: %s: %s"),
  1087. Desc.Description.c_str(),
  1088. GPGError.c_str());
  1089. RunScripts("APT::Update::Auth-Failure");
  1090. return true;
  1091. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1092. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1093. _error->Error(_("GPG error: %s: %s"),
  1094. Desc.Description.c_str(),
  1095. GPGError.c_str());
  1096. I->Status = StatAuthError;
  1097. return true;
  1098. } else {
  1099. _error->Warning(_("GPG error: %s: %s"),
  1100. Desc.Description.c_str(),
  1101. GPGError.c_str());
  1102. }
  1103. // gpgv method failed
  1104. ReportMirrorFailureToCentral(*this, "GPGFailure", GPGError);
  1105. return false;
  1106. }
  1107. /*}}}*/
  1108. // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
  1109. // ---------------------------------------------------------------------
  1110. string pkgAcqMetaBase::Custom600Headers() const
  1111. {
  1112. std::string Header = "\nIndex-File: true";
  1113. std::string MaximumSize;
  1114. strprintf(MaximumSize, "\nMaximum-Size: %i",
  1115. _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
  1116. Header += MaximumSize;
  1117. string const FinalFile = GetFinalFilename();
  1118. struct stat Buf;
  1119. if (stat(FinalFile.c_str(),&Buf) == 0)
  1120. Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime, false);
  1121. return Header;
  1122. }
  1123. /*}}}*/
  1124. // AcqMetaBase::QueueForSignatureVerify /*{{{*/
  1125. void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem * const I, std::string const &File, std::string const &Signature)
  1126. {
  1127. AuthPass = true;
  1128. I->Desc.URI = "gpgv:" + Signature;
  1129. I->DestFile = File;
  1130. QueueURI(I->Desc);
  1131. I->SetActiveSubprocess("gpgv");
  1132. }
  1133. /*}}}*/
  1134. // AcqMetaBase::CheckDownloadDone /*{{{*/
  1135. bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem * const I, const std::string &Message, HashStringList const &Hashes) const
  1136. {
  1137. // We have just finished downloading a Release file (it is not
  1138. // verified yet)
  1139. // Save the final base URI we got this Release file from
  1140. if (I->UsedMirror.empty() == false && _config->FindB("Acquire::SameMirrorForAllIndexes", true))
  1141. {
  1142. if (APT::String::Endswith(I->Desc.URI, "InRelease"))
  1143. TransactionManager->BaseURI = I->Desc.URI.substr(0, I->Desc.URI.length() - strlen("InRelease"));
  1144. else if (APT::String::Endswith(I->Desc.URI, "Release"))
  1145. TransactionManager->BaseURI = I->Desc.URI.substr(0, I->Desc.URI.length() - strlen("Release"));
  1146. }
  1147. std::string const FileName = LookupTag(Message,"Filename");
  1148. if (FileName != I->DestFile && RealFileExists(I->DestFile) == false)
  1149. {
  1150. I->Local = true;
  1151. I->Desc.URI = "copy:" + FileName;
  1152. I->QueueURI(I->Desc);
  1153. return false;
  1154. }
  1155. // make sure to verify against the right file on I-M-S hit
  1156. bool IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"), false);
  1157. if (IMSHit == false && Hashes.usable())
  1158. {
  1159. // detect IMS-Hits servers haven't detected by Hash comparison
  1160. std::string const FinalFile = I->GetFinalFilename();
  1161. if (RealFileExists(FinalFile) && Hashes.VerifyFile(FinalFile) == true)
  1162. {
  1163. IMSHit = true;
  1164. RemoveFile("CheckDownloadDone", I->DestFile);
  1165. }
  1166. }
  1167. if(IMSHit == true)
  1168. {
  1169. // for simplicity, the transaction manager is always InRelease
  1170. // even if it doesn't exist.
  1171. TransactionManager->IMSHit = true;
  1172. I->PartialFile = I->DestFile = I->GetFinalFilename();
  1173. }
  1174. // set Item to complete as the remaining work is all local (verify etc)
  1175. I->Complete = true;
  1176. return true;
  1177. }
  1178. /*}}}*/
  1179. bool pkgAcqMetaBase::CheckAuthDone(string const &Message) /*{{{*/
  1180. {
  1181. // At this point, the gpgv method has succeeded, so there is a
  1182. // valid signature from a key in the trusted keyring. We
  1183. // perform additional verification of its contents, and use them
  1184. // to verify the indexes we are about to download
  1185. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1186. std::cerr << "Signature verification succeeded: " << DestFile << std::endl;
  1187. if (TransactionManager->IMSHit == false)
  1188. {
  1189. // open the last (In)Release if we have it
  1190. std::string const FinalFile = GetFinalFilename();
  1191. std::string FinalRelease;
  1192. std::string FinalInRelease;
  1193. if (APT::String::Endswith(FinalFile, "InRelease"))
  1194. {
  1195. FinalInRelease = FinalFile;
  1196. FinalRelease = FinalFile.substr(0, FinalFile.length() - strlen("InRelease")) + "Release";
  1197. }
  1198. else
  1199. {
  1200. FinalInRelease = FinalFile.substr(0, FinalFile.length() - strlen("Release")) + "InRelease";
  1201. FinalRelease = FinalFile;
  1202. }
  1203. LoadLastMetaIndexParser(TransactionManager, FinalRelease, FinalInRelease);
  1204. }
  1205. bool const GoodAuth = TransactionManager->MetaIndexParser->Load(DestFile, &ErrorText);
  1206. if (GoodAuth == false && AllowInsecureRepositories(InsecureType::WEAK, Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == false)
  1207. {
  1208. Status = StatAuthError;
  1209. return false;
  1210. }
  1211. if (!VerifyVendor(Message))
  1212. {
  1213. Status = StatAuthError;
  1214. return false;
  1215. }
  1216. // Download further indexes with verification
  1217. TransactionManager->QueueIndexes(GoodAuth);
  1218. return GoodAuth;
  1219. }
  1220. /*}}}*/
  1221. void pkgAcqMetaClearSig::QueueIndexes(bool const verify) /*{{{*/
  1222. {
  1223. // at this point the real Items are loaded in the fetcher
  1224. ExpectedAdditionalItems = 0;
  1225. std::set<std::string> targetsSeen;
  1226. bool const hasReleaseFile = TransactionManager->MetaIndexParser != NULL;
  1227. bool const metaBaseSupportsByHash = hasReleaseFile && TransactionManager->MetaIndexParser->GetSupportsAcquireByHash();
  1228. bool hasHashes = true;
  1229. auto IndexTargets = TransactionManager->MetaIndexParser->GetIndexTargets();
  1230. if (hasReleaseFile && verify == false)
  1231. hasHashes = std::any_of(IndexTargets.begin(), IndexTargets.end(),
  1232. [&](IndexTarget const &Target) { return TransactionManager->MetaIndexParser->Exists(Target.MetaKey); });
  1233. for (auto&& Target: IndexTargets)
  1234. {
  1235. // if we have seen a target which is created-by a target this one here is declared a
  1236. // fallback to, we skip acquiring the fallback (but we make sure we clean up)
  1237. if (targetsSeen.find(Target.Option(IndexTarget::FALLBACK_OF)) != targetsSeen.end())
  1238. {
  1239. targetsSeen.emplace(Target.Option(IndexTarget::CREATED_BY));
  1240. new CleanupItem(Owner, TransactionManager, Target);
  1241. continue;
  1242. }
  1243. // all is an implementation detail. Users shouldn't use this as arch
  1244. // We need this support trickery here as e.g. Debian has binary-all files already,
  1245. // but arch:all packages are still in the arch:any files, so we would waste precious
  1246. // download time, bandwidth and diskspace for nothing, BUT Debian doesn't feature all
  1247. // in the set of supported architectures, so we can filter based on this property rather
  1248. // than invent an entirely new flag we would need to carry for all of eternity.
  1249. if (hasReleaseFile && Target.Option(IndexTarget::ARCHITECTURE) == "all")
  1250. {
  1251. if (TransactionManager->MetaIndexParser->IsArchitectureAllSupportedFor(Target) == false)
  1252. {
  1253. new CleanupItem(Owner, TransactionManager, Target);
  1254. continue;
  1255. }
  1256. }
  1257. bool trypdiff = Target.OptionBool(IndexTarget::PDIFFS);
  1258. if (hasReleaseFile == true)
  1259. {
  1260. if (TransactionManager->MetaIndexParser->Exists(Target.MetaKey) == false)
  1261. {
  1262. // optional targets that we do not have in the Release file are skipped
  1263. if (hasHashes == true && Target.IsOptional)
  1264. {
  1265. new CleanupItem(Owner, TransactionManager, Target);
  1266. continue;
  1267. }
  1268. std::string const &arch = Target.Option(IndexTarget::ARCHITECTURE);
  1269. if (arch.empty() == false)
  1270. {
  1271. if (TransactionManager->MetaIndexParser->IsArchitectureSupported(arch) == false)
  1272. {
  1273. new CleanupItem(Owner, TransactionManager, Target);
  1274. _error->Notice(_("Skipping acquire of configured file '%s' as repository '%s' doesn't support architecture '%s'"),
  1275. Target.MetaKey.c_str(), TransactionManager->Target.Description.c_str(), arch.c_str());
  1276. continue;
  1277. }
  1278. // if the architecture is officially supported but currently no packages for it available,
  1279. // ignore silently as this is pretty much the same as just shipping an empty file.
  1280. // if we don't know which architectures are supported, we do NOT ignore it to notify user about this
  1281. if (hasHashes == true && TransactionManager->MetaIndexParser->IsArchitectureSupported("*undefined*") == false)
  1282. {
  1283. new CleanupItem(Owner, TransactionManager, Target);
  1284. continue;
  1285. }
  1286. }
  1287. if (hasHashes == true)
  1288. {
  1289. Status = StatAuthError;
  1290. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target.MetaKey.c_str());
  1291. return;
  1292. }
  1293. else
  1294. {
  1295. new pkgAcqIndex(Owner, TransactionManager, Target);
  1296. continue;
  1297. }
  1298. }
  1299. else if (verify)
  1300. {
  1301. auto const hashes = GetExpectedHashesFor(Target.MetaKey);
  1302. if (hashes.empty() == false)
  1303. {
  1304. if (hashes.usable() == false && TargetIsAllowedToBe(TransactionManager->Target, InsecureType::WEAK) == false)
  1305. {
  1306. new CleanupItem(Owner, TransactionManager, Target);
  1307. _error->Warning(_("Skipping acquire of configured file '%s' as repository '%s' provides only weak security information for it"),
  1308. Target.MetaKey.c_str(), TransactionManager->Target.Description.c_str());
  1309. continue;
  1310. }
  1311. // empty files are skipped as acquiring the very small compressed files is a waste of time
  1312. else if (hashes.FileSize() == 0)
  1313. {
  1314. new CleanupItem(Owner, TransactionManager, Target);
  1315. targetsSeen.emplace(Target.Option(IndexTarget::CREATED_BY));
  1316. continue;
  1317. }
  1318. }
  1319. }
  1320. // autoselect the compression method
  1321. std::vector<std::string> types = VectorizeString(Target.Option(IndexTarget::COMPRESSIONTYPES), ' ');
  1322. types.erase(std::remove_if(types.begin(), types.end(), [&](std::string const &t) {
  1323. if (t == "uncompressed")
  1324. return TransactionManager->MetaIndexParser->Exists(Target.MetaKey) == false;
  1325. std::string const MetaKey = Target.MetaKey + "." + t;
  1326. return TransactionManager->MetaIndexParser->Exists(MetaKey) == false;
  1327. }), types.end());
  1328. if (types.empty() == false)
  1329. {
  1330. std::ostringstream os;
  1331. // add the special compressiontype byhash first if supported
  1332. std::string const useByHashConf = Target.Option(IndexTarget::BY_HASH);
  1333. bool useByHash = false;
  1334. if(useByHashConf == "force")
  1335. useByHash = true;
  1336. else
  1337. useByHash = StringToBool(useByHashConf) == true && metaBaseSupportsByHash;
  1338. if (useByHash == true)
  1339. os << "by-hash ";
  1340. std::copy(types.begin(), types.end()-1, std::ostream_iterator<std::string>(os, " "));
  1341. os << *types.rbegin();
  1342. Target.Options["COMPRESSIONTYPES"] = os.str();
  1343. }
  1344. else
  1345. Target.Options["COMPRESSIONTYPES"].clear();
  1346. std::string filename = GetExistingFilename(GetFinalFileNameFromURI(Target.URI));
  1347. if (filename.empty() == false)
  1348. {
  1349. // if the Release file is a hit and we have an index it must be the current one
  1350. if (TransactionManager->IMSHit == true)
  1351. ;
  1352. else if (TransactionManager->LastMetaIndexParser != NULL)
  1353. {
  1354. // see if the file changed since the last Release file
  1355. // we use the uncompressed files as we might compress differently compared to the server,
  1356. // so the hashes might not match, even if they contain the same data.
  1357. HashStringList const newFile = GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, Target.MetaKey);
  1358. HashStringList const oldFile = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target.MetaKey);
  1359. if (newFile != oldFile)
  1360. filename.clear();
  1361. }
  1362. else
  1363. filename.clear();
  1364. }
  1365. else
  1366. trypdiff = false; // no file to patch
  1367. if (filename.empty() == false)
  1368. {
  1369. new NoActionItem(Owner, Target, filename);
  1370. std::string const idxfilename = GetFinalFileNameFromURI(GetDiffIndexURI(Target));
  1371. if (FileExists(idxfilename))
  1372. new NoActionItem(Owner, Target, idxfilename);
  1373. targetsSeen.emplace(Target.Option(IndexTarget::CREATED_BY));
  1374. continue;
  1375. }
  1376. // check if we have patches available
  1377. trypdiff &= TransactionManager->MetaIndexParser->Exists(GetDiffIndexFileName(Target.MetaKey));
  1378. }
  1379. else
  1380. {
  1381. // if we have no file to patch, no point in trying
  1382. trypdiff &= (GetExistingFilename(GetFinalFileNameFromURI(Target.URI)).empty() == false);
  1383. }
  1384. // no point in patching from local sources
  1385. if (trypdiff)
  1386. {
  1387. std::string const proto = Target.URI.substr(0, strlen("file:/"));
  1388. if (proto == "file:/" || proto == "copy:/" || proto == "cdrom:")
  1389. trypdiff = false;
  1390. }
  1391. // Queue the Index file (Packages, Sources, Translation-$foo, …)
  1392. targetsSeen.emplace(Target.Option(IndexTarget::CREATED_BY));
  1393. if (trypdiff)
  1394. new pkgAcqDiffIndex(Owner, TransactionManager, Target);
  1395. else
  1396. new pkgAcqIndex(Owner, TransactionManager, Target);
  1397. }
  1398. }
  1399. /*}}}*/
  1400. bool pkgAcqMetaBase::VerifyVendor(string const &) /*{{{*/
  1401. {
  1402. string Transformed = TransactionManager->MetaIndexParser->GetExpectedDist();
  1403. if (Transformed == "../project/experimental")
  1404. {
  1405. Transformed = "experimental";
  1406. }
  1407. auto pos = Transformed.rfind('/');
  1408. if (pos != string::npos)
  1409. {
  1410. Transformed = Transformed.substr(0, pos);
  1411. }
  1412. if (Transformed == ".")
  1413. {
  1414. Transformed = "";
  1415. }
  1416. if (TransactionManager->MetaIndexParser->GetValidUntil() > 0)
  1417. {
  1418. time_t const invalid_since = time(NULL) - TransactionManager->MetaIndexParser->GetValidUntil();
  1419. if (invalid_since > 0)
  1420. {
  1421. std::string errmsg;
  1422. strprintf(errmsg,
  1423. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1424. // the time since then the file is invalid - formatted in the same way as in
  1425. // the download progress display (e.g. 7d 3h 42min 1s)
  1426. _("Release file for %s is expired (invalid since %s). "
  1427. "Updates for this repository will not be applied."),
  1428. Target.URI.c_str(), TimeToStr(invalid_since).c_str());
  1429. if (ErrorText.empty())
  1430. ErrorText = errmsg;
  1431. return _error->Error("%s", errmsg.c_str());
  1432. }
  1433. }
  1434. /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
  1435. as a prevention of downgrading us to older (still valid) files */
  1436. if (TransactionManager->IMSHit == false && TransactionManager->LastMetaIndexParser != NULL &&
  1437. TransactionManager->LastMetaIndexParser->GetDate() > TransactionManager->MetaIndexParser->GetDate())
  1438. {
  1439. TransactionManager->IMSHit = true;
  1440. RemoveFile("VerifyVendor", DestFile);
  1441. PartialFile = DestFile = GetFinalFilename();
  1442. // load the 'old' file in the 'new' one instead of flipping pointers as
  1443. // the new one isn't owned by us, while the old one is so cleanup would be confused.
  1444. TransactionManager->MetaIndexParser->swapLoad(TransactionManager->LastMetaIndexParser);
  1445. delete TransactionManager->LastMetaIndexParser;
  1446. TransactionManager->LastMetaIndexParser = NULL;
  1447. }
  1448. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1449. {
  1450. std::cerr << "Got Codename: " << TransactionManager->MetaIndexParser->GetCodename() << std::endl;
  1451. std::cerr << "Expecting Dist: " << TransactionManager->MetaIndexParser->GetExpectedDist() << std::endl;
  1452. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1453. }
  1454. if (TransactionManager->MetaIndexParser->CheckDist(Transformed) == false)
  1455. {
  1456. // This might become fatal one day
  1457. // Status = StatAuthError;
  1458. // ErrorText = "Conflicting distribution; expected "
  1459. // + MetaIndexParser->GetExpectedDist() + " but got "
  1460. // + MetaIndexParser->GetCodename();
  1461. // return false;
  1462. if (!Transformed.empty())
  1463. {
  1464. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1465. Desc.Description.c_str(),
  1466. Transformed.c_str(),
  1467. TransactionManager->MetaIndexParser->GetCodename().c_str());
  1468. }
  1469. }
  1470. return true;
  1471. }
  1472. /*}}}*/
  1473. pkgAcqMetaBase::~pkgAcqMetaBase()
  1474. {
  1475. }
  1476. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire * const Owner, /*{{{*/
  1477. IndexTarget const &ClearsignedTarget,
  1478. IndexTarget const &DetachedDataTarget, IndexTarget const &DetachedSigTarget,
  1479. metaIndex * const MetaIndexParser) :
  1480. pkgAcqMetaIndex(Owner, this, ClearsignedTarget, DetachedSigTarget),
  1481. d(NULL), DetachedDataTarget(DetachedDataTarget),
  1482. MetaIndexParser(MetaIndexParser), LastMetaIndexParser(NULL)
  1483. {
  1484. // index targets + (worst case:) Release/Release.gpg
  1485. ExpectedAdditionalItems = std::numeric_limits<decltype(ExpectedAdditionalItems)>::max();
  1486. TransactionManager->Add(this);
  1487. }
  1488. /*}}}*/
  1489. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1490. {
  1491. if (LastMetaIndexParser != NULL)
  1492. delete LastMetaIndexParser;
  1493. }
  1494. /*}}}*/
  1495. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1496. string pkgAcqMetaClearSig::Custom600Headers() const
  1497. {
  1498. string Header = pkgAcqMetaBase::Custom600Headers();
  1499. Header += "\nFail-Ignore: true";
  1500. std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
  1501. if (key.empty() == false)
  1502. Header += "\nSigned-By: " + key;
  1503. return Header;
  1504. }
  1505. /*}}}*/
  1506. void pkgAcqMetaClearSig::Finished() /*{{{*/
  1507. {
  1508. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1509. std::clog << "Finished: " << DestFile <<std::endl;
  1510. if(TransactionManager->State == TransactionStarted &&
  1511. TransactionManager->TransactionHasError() == false)
  1512. TransactionManager->CommitTransaction();
  1513. }
  1514. /*}}}*/
  1515. bool pkgAcqMetaClearSig::VerifyDone(std::string const &Message, /*{{{*/
  1516. pkgAcquire::MethodConfig const * const Cnf)
  1517. {
  1518. Item::VerifyDone(Message, Cnf);
  1519. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  1520. return RenameOnError(NotClearsigned);
  1521. return true;
  1522. }
  1523. /*}}}*/
  1524. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  1525. void pkgAcqMetaClearSig::Done(std::string const &Message,
  1526. HashStringList const &Hashes,
  1527. pkgAcquire::MethodConfig const * const Cnf)
  1528. {
  1529. Item::Done(Message, Hashes, Cnf);
  1530. if(AuthPass == false)
  1531. {
  1532. if(CheckDownloadDone(this, Message, Hashes) == true)
  1533. QueueForSignatureVerify(this, DestFile, DestFile);
  1534. return;
  1535. }
  1536. else if(CheckAuthDone(Message) == true)
  1537. {
  1538. if (TransactionManager->IMSHit == false)
  1539. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1540. else if (RealFileExists(GetFinalFilename()) == false)
  1541. {
  1542. // We got an InRelease file IMSHit, but we haven't one, which means
  1543. // we had a valid Release/Release.gpg combo stepping in, which we have
  1544. // to 'acquire' now to ensure list cleanup isn't removing them
  1545. new NoActionItem(Owner, DetachedDataTarget);
  1546. new NoActionItem(Owner, DetachedSigTarget);
  1547. }
  1548. }
  1549. else if (Status != StatAuthError)
  1550. {
  1551. string const FinalFile = GetFinalFileNameFromURI(DetachedDataTarget.URI);
  1552. string const OldFile = GetFinalFilename();
  1553. if (TransactionManager->IMSHit == false)
  1554. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1555. else if (RealFileExists(OldFile) == false)
  1556. new NoActionItem(Owner, DetachedDataTarget);
  1557. else
  1558. TransactionManager->TransactionStageCopy(this, OldFile, FinalFile);
  1559. }
  1560. }
  1561. /*}}}*/
  1562. void pkgAcqMetaClearSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf) /*{{{*/
  1563. {
  1564. Item::Failed(Message, Cnf);
  1565. if (AuthPass == false)
  1566. {
  1567. if (Status == StatAuthError || Status == StatTransientNetworkError)
  1568. {
  1569. // if we expected a ClearTextSignature (InRelease) but got a network
  1570. // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
  1571. // As these is usually called by web-portals we do not try Release/Release.gpg
  1572. // as this is gonna fail anyway and instead abort our try (LP#346386)
  1573. TransactionManager->AbortTransaction();
  1574. return;
  1575. }
  1576. // Queue the 'old' InRelease file for removal if we try Release.gpg
  1577. // as otherwise the file will stay around and gives a false-auth
  1578. // impression (CVE-2012-0214)
  1579. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1580. Status = StatDone;
  1581. new pkgAcqMetaIndex(Owner, TransactionManager, DetachedDataTarget, DetachedSigTarget);
  1582. }
  1583. else
  1584. {
  1585. if(CheckStopAuthentication(this, Message))
  1586. return;
  1587. if(AllowInsecureRepositories(InsecureType::UNSIGNED, Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1588. {
  1589. Status = StatDone;
  1590. /* InRelease files become Release files, otherwise
  1591. * they would be considered as trusted later on */
  1592. string const FinalRelease = GetFinalFileNameFromURI(DetachedDataTarget.URI);
  1593. string const PartialRelease = GetPartialFileNameFromURI(DetachedDataTarget.URI);
  1594. string const FinalReleasegpg = GetFinalFileNameFromURI(DetachedSigTarget.URI);
  1595. string const FinalInRelease = GetFinalFilename();
  1596. Rename(DestFile, PartialRelease);
  1597. TransactionManager->TransactionStageCopy(this, PartialRelease, FinalRelease);
  1598. LoadLastMetaIndexParser(TransactionManager, FinalRelease, FinalInRelease);
  1599. // we parse the indexes here because at this point the user wanted
  1600. // a repository that may potentially harm him
  1601. if (TransactionManager->MetaIndexParser->Load(PartialRelease, &ErrorText) == false || VerifyVendor(Message) == false)
  1602. /* expired Release files are still a problem you need extra force for */;
  1603. else
  1604. TransactionManager->QueueIndexes(true);
  1605. }
  1606. }
  1607. }
  1608. /*}}}*/
  1609. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire * const Owner, /*{{{*/
  1610. pkgAcqMetaClearSig * const TransactionManager,
  1611. IndexTarget const &DataTarget,
  1612. IndexTarget const &DetachedSigTarget) :
  1613. pkgAcqMetaBase(Owner, TransactionManager, DataTarget), d(NULL),
  1614. DetachedSigTarget(DetachedSigTarget)
  1615. {
  1616. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1617. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1618. << this->TransactionManager << std::endl;
  1619. DestFile = GetPartialFileNameFromURI(DataTarget.URI);
  1620. // Create the item
  1621. Desc.Description = DataTarget.Description;
  1622. Desc.Owner = this;
  1623. Desc.ShortDesc = DataTarget.ShortDesc;
  1624. Desc.URI = DataTarget.URI;
  1625. QueueURI(Desc);
  1626. }
  1627. /*}}}*/
  1628. void pkgAcqMetaIndex::Done(string const &Message, /*{{{*/
  1629. HashStringList const &Hashes,
  1630. pkgAcquire::MethodConfig const * const Cfg)
  1631. {
  1632. Item::Done(Message,Hashes,Cfg);
  1633. if(CheckDownloadDone(this, Message, Hashes))
  1634. {
  1635. // we have a Release file, now download the Signature, all further
  1636. // verify/queue for additional downloads will be done in the
  1637. // pkgAcqMetaSig::Done() code
  1638. new pkgAcqMetaSig(Owner, TransactionManager, DetachedSigTarget, this);
  1639. }
  1640. }
  1641. /*}}}*/
  1642. // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
  1643. void pkgAcqMetaIndex::Failed(string const &Message,
  1644. pkgAcquire::MethodConfig const * const Cnf)
  1645. {
  1646. pkgAcquire::Item::Failed(Message, Cnf);
  1647. Status = StatDone;
  1648. // No Release file was present so fall
  1649. // back to queueing Packages files without verification
  1650. // only allow going further if the user explicitly wants it
  1651. if(AllowInsecureRepositories(InsecureType::NORELEASE, Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1652. {
  1653. // ensure old Release files are removed
  1654. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1655. // queue without any kind of hashsum support
  1656. TransactionManager->QueueIndexes(false);
  1657. }
  1658. }
  1659. /*}}}*/
  1660. std::string pkgAcqMetaIndex::DescURI() const /*{{{*/
  1661. {
  1662. return Target.URI;
  1663. }
  1664. /*}}}*/
  1665. pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
  1666. // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
  1667. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire * const Owner,
  1668. pkgAcqMetaClearSig * const TransactionManager,
  1669. IndexTarget const &Target,
  1670. pkgAcqMetaIndex * const MetaIndex) :
  1671. pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL), MetaIndex(MetaIndex)
  1672. {
  1673. DestFile = GetPartialFileNameFromURI(Target.URI);
  1674. // remove any partial downloaded sig-file in partial/.
  1675. // it may confuse proxies and is too small to warrant a
  1676. // partial download anyway
  1677. RemoveFile("pkgAcqMetaSig", DestFile);
  1678. // set the TransactionManager
  1679. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1680. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1681. << TransactionManager << std::endl;
  1682. // Create the item
  1683. Desc.Description = Target.Description;
  1684. Desc.Owner = this;
  1685. Desc.ShortDesc = Target.ShortDesc;
  1686. Desc.URI = Target.URI;
  1687. // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
  1688. // so we skip the download step and go instantly to verification
  1689. if (TransactionManager->IMSHit == true && RealFileExists(GetFinalFilename()))
  1690. {
  1691. Complete = true;
  1692. Status = StatDone;
  1693. PartialFile = DestFile = GetFinalFilename();
  1694. MetaIndexFileSignature = DestFile;
  1695. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1696. }
  1697. else
  1698. QueueURI(Desc);
  1699. }
  1700. /*}}}*/
  1701. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1702. {
  1703. }
  1704. /*}}}*/
  1705. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1706. std::string pkgAcqMetaSig::Custom600Headers() const
  1707. {
  1708. std::string Header = pkgAcqTransactionItem::Custom600Headers();
  1709. std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
  1710. if (key.empty() == false)
  1711. Header += "\nSigned-By: " + key;
  1712. return Header;
  1713. }
  1714. /*}}}*/
  1715. // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
  1716. void pkgAcqMetaSig::Done(string const &Message, HashStringList const &Hashes,
  1717. pkgAcquire::MethodConfig const * const Cfg)
  1718. {
  1719. if (MetaIndexFileSignature.empty() == false)
  1720. {
  1721. DestFile = MetaIndexFileSignature;
  1722. MetaIndexFileSignature.clear();
  1723. }
  1724. Item::Done(Message, Hashes, Cfg);
  1725. if(MetaIndex->AuthPass == false)
  1726. {
  1727. if(MetaIndex->CheckDownloadDone(this, Message, Hashes) == true)
  1728. {
  1729. // destfile will be modified to point to MetaIndexFile for the
  1730. // gpgv method, so we need to save it here
  1731. MetaIndexFileSignature = DestFile;
  1732. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1733. }
  1734. return;
  1735. }
  1736. else if(MetaIndex->CheckAuthDone(Message) == true)
  1737. {
  1738. if (TransactionManager->IMSHit == false)
  1739. {
  1740. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1741. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1742. }
  1743. }
  1744. else if (MetaIndex->Status != StatAuthError)
  1745. {
  1746. std::string const FinalFile = MetaIndex->GetFinalFilename();
  1747. if (TransactionManager->IMSHit == false)
  1748. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, FinalFile);
  1749. else
  1750. TransactionManager->TransactionStageCopy(MetaIndex, FinalFile, FinalFile);
  1751. }
  1752. }
  1753. /*}}}*/
  1754. void pkgAcqMetaSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1755. {
  1756. Item::Failed(Message,Cnf);
  1757. // check if we need to fail at this point
  1758. if (MetaIndex->AuthPass == true && MetaIndex->CheckStopAuthentication(this, Message))
  1759. return;
  1760. // ensures that a Release.gpg file in the lists/ is removed by the transaction
  1761. TransactionManager->TransactionStageRemoval(this, DestFile);
  1762. // only allow going further if the user explicitly wants it
  1763. if (AllowInsecureRepositories(InsecureType::UNSIGNED, MetaIndex->Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1764. {
  1765. string const FinalRelease = MetaIndex->GetFinalFilename();
  1766. string const FinalInRelease = TransactionManager->GetFinalFilename();
  1767. LoadLastMetaIndexParser(TransactionManager, FinalRelease, FinalInRelease);
  1768. // we parse the indexes here because at this point the user wanted
  1769. // a repository that may potentially harm him
  1770. bool const GoodLoad = TransactionManager->MetaIndexParser->Load(MetaIndex->DestFile, &ErrorText);
  1771. if (MetaIndex->VerifyVendor(Message) == false)
  1772. /* expired Release files are still a problem you need extra force for */;
  1773. else
  1774. TransactionManager->QueueIndexes(GoodLoad);
  1775. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, FinalRelease);
  1776. }
  1777. else if (TransactionManager->IMSHit == false)
  1778. Rename(MetaIndex->DestFile, MetaIndex->DestFile + ".FAILED");
  1779. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1780. if (Cnf->LocalOnly == true ||
  1781. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1782. {
  1783. // Ignore this
  1784. Status = StatDone;
  1785. }
  1786. }
  1787. /*}}}*/
  1788. // AcqBaseIndex - Constructor /*{{{*/
  1789. pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire * const Owner,
  1790. pkgAcqMetaClearSig * const TransactionManager,
  1791. IndexTarget const &Target)
  1792. : pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL)
  1793. {
  1794. }
  1795. /*}}}*/
  1796. void pkgAcqBaseIndex::Failed(std::string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1797. {
  1798. pkgAcquire::Item::Failed(Message, Cnf);
  1799. if (Status != StatAuthError)
  1800. return;
  1801. ErrorText.append("Release file created at: ");
  1802. auto const timespec = TransactionManager->MetaIndexParser->GetDate();
  1803. if (timespec == 0)
  1804. ErrorText.append("<unknown>");
  1805. else
  1806. ErrorText.append(TimeRFC1123(timespec, true));
  1807. ErrorText.append("\n");
  1808. }
  1809. /*}}}*/
  1810. pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
  1811. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  1812. // ---------------------------------------------------------------------
  1813. /* Get the DiffIndex file first and see if there are patches available
  1814. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  1815. * patches. If anything goes wrong in that process, it will fall back to
  1816. * the original packages file
  1817. */
  1818. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire * const Owner,
  1819. pkgAcqMetaClearSig * const TransactionManager,
  1820. IndexTarget const &Target)
  1821. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), diffs(NULL)
  1822. {
  1823. // FIXME: Magic number as an upper bound on pdiffs we will reasonably acquire
  1824. ExpectedAdditionalItems = 40;
  1825. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1826. Desc.Owner = this;
  1827. Desc.Description = GetDiffIndexFileName(Target.Description);
  1828. Desc.ShortDesc = Target.ShortDesc;
  1829. Desc.URI = GetDiffIndexURI(Target);
  1830. DestFile = GetPartialFileNameFromURI(Desc.URI);
  1831. if(Debug)
  1832. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  1833. QueueURI(Desc);
  1834. }
  1835. /*}}}*/
  1836. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1837. // ---------------------------------------------------------------------
  1838. /* The only header we use is the last-modified header. */
  1839. string pkgAcqDiffIndex::Custom600Headers() const
  1840. {
  1841. if (TransactionManager->LastMetaIndexParser != NULL)
  1842. return "\nIndex-File: true";
  1843. string const Final = GetFinalFilename();
  1844. if(Debug)
  1845. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  1846. struct stat Buf;
  1847. if (stat(Final.c_str(),&Buf) != 0)
  1848. return "\nIndex-File: true";
  1849. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime, false);
  1850. }
  1851. /*}}}*/
  1852. void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
  1853. {
  1854. // list cleanup needs to know that this file as well as the already
  1855. // present index is ours, so we create an empty diff to save it for us
  1856. new pkgAcqIndexDiffs(Owner, TransactionManager, Target);
  1857. }
  1858. /*}}}*/
  1859. static bool RemoveFileForBootstrapLinking(bool const Debug, std::string const &For, std::string const &Boot)/*{{{*/
  1860. {
  1861. if (FileExists(Boot) && RemoveFile("Bootstrap-linking", Boot) == false)
  1862. {
  1863. if (Debug)
  1864. std::clog << "Bootstrap-linking for patching " << For
  1865. << " by removing stale " << Boot << " failed!" << std::endl;
  1866. return false;
  1867. }
  1868. return true;
  1869. }
  1870. /*}}}*/
  1871. bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/
  1872. {
  1873. ExpectedAdditionalItems = 0;
  1874. // failing here is fine: our caller will take care of trying to
  1875. // get the complete file if patching fails
  1876. if(Debug)
  1877. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  1878. << std::endl;
  1879. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  1880. pkgTagFile TF(&Fd);
  1881. if (Fd.IsOpen() == false || Fd.Failed())
  1882. return false;
  1883. pkgTagSection Tags;
  1884. if(unlikely(TF.Step(Tags) == false))
  1885. return false;
  1886. HashStringList ServerHashes;
  1887. unsigned long long ServerSize = 0;
  1888. auto const &posix = std::locale("C.UTF-8");
  1889. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1890. {
  1891. std::string tagname = *type;
  1892. tagname.append("-Current");
  1893. std::string const tmp = Tags.FindS(tagname.c_str());
  1894. if (tmp.empty() == true)
  1895. continue;
  1896. string hash;
  1897. unsigned long long size;
  1898. std::stringstream ss(tmp);
  1899. ss.imbue(posix);
  1900. ss >> hash >> size;
  1901. if (unlikely(hash.empty() == true))
  1902. continue;
  1903. if (unlikely(ServerSize != 0 && ServerSize != size))
  1904. continue;
  1905. ServerHashes.push_back(HashString(*type, hash));
  1906. ServerSize = size;
  1907. }
  1908. if (ServerHashes.usable() == false)
  1909. {
  1910. if (Debug == true)
  1911. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
  1912. return false;
  1913. }
  1914. std::string const CurrentPackagesFile = GetFinalFileNameFromURI(Target.URI);
  1915. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
  1916. if (TargetFileHashes.usable() == false || ServerHashes != TargetFileHashes)
  1917. {
  1918. if (Debug == true)
  1919. {
  1920. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
  1921. printHashSumComparison(CurrentPackagesFile, ServerHashes, TargetFileHashes);
  1922. }
  1923. return false;
  1924. }
  1925. HashStringList LocalHashes;
  1926. // try avoiding calculating the hash here as this is costly
  1927. if (TransactionManager->LastMetaIndexParser != NULL)
  1928. LocalHashes = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target.MetaKey);
  1929. if (LocalHashes.usable() == false)
  1930. {
  1931. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly, FileFd::Auto);
  1932. Hashes LocalHashesCalc(ServerHashes);
  1933. LocalHashesCalc.AddFD(fd);
  1934. LocalHashes = LocalHashesCalc.GetHashStringList();
  1935. }
  1936. if (ServerHashes == LocalHashes)
  1937. {
  1938. // we have the same sha1 as the server so we are done here
  1939. if(Debug)
  1940. std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
  1941. QueueOnIMSHit();
  1942. return true;
  1943. }
  1944. if(Debug)
  1945. std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
  1946. << CurrentPackagesFile << " " << LocalHashes.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
  1947. // historically, older hashes have more info than newer ones, so start
  1948. // collecting with older ones first to avoid implementing complicated
  1949. // information merging techniques… a failure is after all always
  1950. // recoverable with a complete file and hashes aren't changed that often.
  1951. std::vector<char const *> types;
  1952. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1953. types.push_back(*type);
  1954. // parse all of (provided) history
  1955. vector<DiffInfo> available_patches;
  1956. bool firstAcceptedHashes = true;
  1957. for (auto type = types.crbegin(); type != types.crend(); ++type)
  1958. {
  1959. if (LocalHashes.find(*type) == NULL)
  1960. continue;
  1961. std::string tagname = *type;
  1962. tagname.append("-History");
  1963. std::string const tmp = Tags.FindS(tagname.c_str());
  1964. if (tmp.empty() == true)
  1965. continue;
  1966. string hash, filename;
  1967. unsigned long long size;
  1968. std::stringstream ss(tmp);
  1969. ss.imbue(posix);
  1970. while (ss >> hash >> size >> filename)
  1971. {
  1972. if (unlikely(hash.empty() == true || filename.empty() == true))
  1973. continue;
  1974. // see if we have a record for this file already
  1975. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1976. for (; cur != available_patches.end(); ++cur)
  1977. {
  1978. if (cur->file != filename)
  1979. continue;
  1980. cur->result_hashes.push_back(HashString(*type, hash));
  1981. break;
  1982. }
  1983. if (cur != available_patches.end())
  1984. continue;
  1985. if (firstAcceptedHashes == true)
  1986. {
  1987. DiffInfo next;
  1988. next.file = filename;
  1989. next.result_hashes.push_back(HashString(*type, hash));
  1990. next.result_hashes.FileSize(size);
  1991. available_patches.push_back(next);
  1992. }
  1993. else
  1994. {
  1995. if (Debug == true)
  1996. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1997. << " wasn't in the list for the first parsed hash! (history)" << std::endl;
  1998. break;
  1999. }
  2000. }
  2001. firstAcceptedHashes = false;
  2002. }
  2003. if (unlikely(available_patches.empty() == true))
  2004. {
  2005. if (Debug)
  2006. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  2007. << "Couldn't find any patches for the patch series." << std::endl;
  2008. return false;
  2009. }
  2010. for (auto type = types.crbegin(); type != types.crend(); ++type)
  2011. {
  2012. if (LocalHashes.find(*type) == NULL)
  2013. continue;
  2014. std::string tagname = *type;
  2015. tagname.append("-Patches");
  2016. std::string const tmp = Tags.FindS(tagname.c_str());
  2017. if (tmp.empty() == true)
  2018. continue;
  2019. string hash, filename;
  2020. unsigned long long size;
  2021. std::stringstream ss(tmp);
  2022. ss.imbue(posix);
  2023. while (ss >> hash >> size >> filename)
  2024. {
  2025. if (unlikely(hash.empty() == true || filename.empty() == true))
  2026. continue;
  2027. // see if we have a record for this file already
  2028. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  2029. for (; cur != available_patches.end(); ++cur)
  2030. {
  2031. if (cur->file != filename)
  2032. continue;
  2033. if (cur->patch_hashes.empty())
  2034. cur->patch_hashes.FileSize(size);
  2035. cur->patch_hashes.push_back(HashString(*type, hash));
  2036. break;
  2037. }
  2038. if (cur != available_patches.end())
  2039. continue;
  2040. if (Debug == true)
  2041. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  2042. << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
  2043. break;
  2044. }
  2045. }
  2046. for (auto type = types.crbegin(); type != types.crend(); ++type)
  2047. {
  2048. std::string tagname = *type;
  2049. tagname.append("-Download");
  2050. std::string const tmp = Tags.FindS(tagname.c_str());
  2051. if (tmp.empty() == true)
  2052. continue;
  2053. string hash, filename;
  2054. unsigned long long size;
  2055. std::stringstream ss(tmp);
  2056. ss.imbue(posix);
  2057. // FIXME: all of pdiff supports only .gz compressed patches
  2058. while (ss >> hash >> size >> filename)
  2059. {
  2060. if (unlikely(hash.empty() == true || filename.empty() == true))
  2061. continue;
  2062. if (unlikely(APT::String::Endswith(filename, ".gz") == false))
  2063. continue;
  2064. filename.erase(filename.length() - 3);
  2065. // see if we have a record for this file already
  2066. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  2067. for (; cur != available_patches.end(); ++cur)
  2068. {
  2069. if (cur->file != filename)
  2070. continue;
  2071. if (cur->download_hashes.empty())
  2072. cur->download_hashes.FileSize(size);
  2073. cur->download_hashes.push_back(HashString(*type, hash));
  2074. break;
  2075. }
  2076. if (cur != available_patches.end())
  2077. continue;
  2078. if (Debug == true)
  2079. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  2080. << " wasn't in the list for the first parsed hash! (download)" << std::endl;
  2081. break;
  2082. }
  2083. }
  2084. bool foundStart = false;
  2085. for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
  2086. cur != available_patches.end(); ++cur)
  2087. {
  2088. if (LocalHashes != cur->result_hashes)
  2089. continue;
  2090. available_patches.erase(available_patches.begin(), cur);
  2091. foundStart = true;
  2092. break;
  2093. }
  2094. if (foundStart == false || unlikely(available_patches.empty() == true))
  2095. {
  2096. if (Debug)
  2097. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  2098. << "Couldn't find the start of the patch series." << std::endl;
  2099. return false;
  2100. }
  2101. for (auto const &patch: available_patches)
  2102. if (patch.result_hashes.usable() == false ||
  2103. patch.patch_hashes.usable() == false ||
  2104. patch.download_hashes.usable() == false)
  2105. {
  2106. if (Debug)
  2107. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": provides no usable hashes for " << patch.file
  2108. << " so fallback to complete download" << std::endl;
  2109. return false;
  2110. }
  2111. // patching with too many files is rather slow compared to a fast download
  2112. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  2113. if (fileLimit != 0 && fileLimit < available_patches.size())
  2114. {
  2115. if (Debug)
  2116. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  2117. << ") so fallback to complete download" << std::endl;
  2118. return false;
  2119. }
  2120. // calculate the size of all patches we have to get
  2121. unsigned short const sizeLimitPercent = _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  2122. if (sizeLimitPercent > 0)
  2123. {
  2124. unsigned long long downloadSize = std::accumulate(available_patches.begin(),
  2125. available_patches.end(), 0llu, [](unsigned long long const T, DiffInfo const &I) {
  2126. return T + I.download_hashes.FileSize();
  2127. });
  2128. if (downloadSize != 0)
  2129. {
  2130. unsigned long long downloadSizeIdx = 0;
  2131. auto const types = VectorizeString(Target.Option(IndexTarget::COMPRESSIONTYPES), ' ');
  2132. for (auto const &t : types)
  2133. {
  2134. std::string MetaKey = Target.MetaKey;
  2135. if (t != "uncompressed")
  2136. MetaKey += '.' + t;
  2137. HashStringList const hsl = GetExpectedHashesFor(MetaKey);
  2138. if (unlikely(hsl.usable() == false))
  2139. continue;
  2140. downloadSizeIdx = hsl.FileSize();
  2141. break;
  2142. }
  2143. unsigned long long const sizeLimit = downloadSizeIdx * sizeLimitPercent;
  2144. if ((sizeLimit/100) < downloadSize)
  2145. {
  2146. if (Debug)
  2147. std::clog << "Need " << downloadSize << " compressed bytes (Limit is " << (sizeLimit/100) << ", "
  2148. << "original is " << downloadSizeIdx << ") so fallback to complete download" << std::endl;
  2149. return false;
  2150. }
  2151. }
  2152. }
  2153. // we have something, queue the diffs
  2154. string::size_type const last_space = Description.rfind(" ");
  2155. if(last_space != string::npos)
  2156. Description.erase(last_space, Description.size()-last_space);
  2157. /* decide if we should download patches one by one or in one go:
  2158. The first is good if the server merges patches, but many don't so client
  2159. based merging can be attempt in which case the second is better.
  2160. "bad things" will happen if patches are merged on the server,
  2161. but client side merging is attempt as well */
  2162. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  2163. if (pdiff_merge == true)
  2164. {
  2165. // reprepro adds this flag if it has merged patches on the server
  2166. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  2167. pdiff_merge = (precedence != "merged");
  2168. }
  2169. // clean the plate
  2170. {
  2171. std::string const Final = GetExistingFilename(CurrentPackagesFile);
  2172. if (unlikely(Final.empty())) // because we wouldn't be called in such a case
  2173. return false;
  2174. std::string const PartialFile = GetPartialFileNameFromURI(Target.URI);
  2175. std::string const PatchedFile = GetKeepCompressedFileName(PartialFile + "-patched", Target);
  2176. if (RemoveFileForBootstrapLinking(Debug, CurrentPackagesFile, PartialFile) == false ||
  2177. RemoveFileForBootstrapLinking(Debug, CurrentPackagesFile, PatchedFile) == false)
  2178. return false;
  2179. for (auto const &ext : APT::Configuration::getCompressorExtensions())
  2180. {
  2181. if (RemoveFileForBootstrapLinking(Debug, CurrentPackagesFile, PartialFile + ext) == false ||
  2182. RemoveFileForBootstrapLinking(Debug, CurrentPackagesFile, PatchedFile + ext) == false)
  2183. return false;
  2184. }
  2185. std::string const Ext = Final.substr(CurrentPackagesFile.length());
  2186. std::string const Partial = PartialFile + Ext;
  2187. if (symlink(Final.c_str(), Partial.c_str()) != 0)
  2188. {
  2189. if (Debug)
  2190. std::clog << "Bootstrap-linking for patching " << CurrentPackagesFile
  2191. << " by linking " << Final << " to " << Partial << " failed!" << std::endl;
  2192. return false;
  2193. }
  2194. }
  2195. if (pdiff_merge == false)
  2196. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
  2197. else
  2198. {
  2199. diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  2200. for(size_t i = 0; i < available_patches.size(); ++i)
  2201. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
  2202. Target,
  2203. available_patches[i],
  2204. diffs);
  2205. }
  2206. Complete = false;
  2207. Status = StatDone;
  2208. Dequeue();
  2209. return true;
  2210. }
  2211. /*}}}*/
  2212. void pkgAcqDiffIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  2213. {
  2214. pkgAcqBaseIndex::Failed(Message,Cnf);
  2215. Status = StatDone;
  2216. ExpectedAdditionalItems = 0;
  2217. if(Debug)
  2218. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  2219. << "Falling back to normal index file acquire" << std::endl;
  2220. new pkgAcqIndex(Owner, TransactionManager, Target);
  2221. }
  2222. /*}}}*/
  2223. void pkgAcqDiffIndex::Done(string const &Message,HashStringList const &Hashes, /*{{{*/
  2224. pkgAcquire::MethodConfig const * const Cnf)
  2225. {
  2226. if(Debug)
  2227. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  2228. Item::Done(Message, Hashes, Cnf);
  2229. string const FinalFile = GetFinalFilename();
  2230. if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
  2231. DestFile = FinalFile;
  2232. if(ParseDiffIndex(DestFile) == false)
  2233. {
  2234. Failed("Message: Couldn't parse pdiff index", Cnf);
  2235. // queue for final move - this should happen even if we fail
  2236. // while parsing (e.g. on sizelimit) and download the complete file.
  2237. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  2238. return;
  2239. }
  2240. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  2241. Complete = true;
  2242. Status = StatDone;
  2243. Dequeue();
  2244. return;
  2245. }
  2246. /*}}}*/
  2247. pkgAcqDiffIndex::~pkgAcqDiffIndex()
  2248. {
  2249. if (diffs != NULL)
  2250. delete diffs;
  2251. }
  2252. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  2253. // ---------------------------------------------------------------------
  2254. /* The package diff is added to the queue. one object is constructed
  2255. * for each diff and the index
  2256. */
  2257. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire * const Owner,
  2258. pkgAcqMetaClearSig * const TransactionManager,
  2259. IndexTarget const &Target,
  2260. vector<DiffInfo> const &diffs)
  2261. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
  2262. available_patches(diffs)
  2263. {
  2264. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2265. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  2266. Desc.Owner = this;
  2267. Description = Target.Description;
  2268. Desc.ShortDesc = Target.ShortDesc;
  2269. if(available_patches.empty() == true)
  2270. {
  2271. // we are done (yeah!), check hashes against the final file
  2272. DestFile = GetKeepCompressedFileName(GetFinalFileNameFromURI(Target.URI), Target);
  2273. Finish(true);
  2274. }
  2275. else
  2276. {
  2277. State = StateFetchDiff;
  2278. QueueNextDiff();
  2279. }
  2280. }
  2281. /*}}}*/
  2282. void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  2283. {
  2284. pkgAcqBaseIndex::Failed(Message,Cnf);
  2285. Status = StatDone;
  2286. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2287. if(Debug)
  2288. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  2289. << "Falling back to normal index file acquire " << std::endl;
  2290. RenameOnError(PDiffError);
  2291. std::string const patchname = GetDiffsPatchFileName(DestFile);
  2292. if (RealFileExists(patchname))
  2293. Rename(patchname, patchname + ".FAILED");
  2294. std::string const UnpatchedFile = GetExistingFilename(GetPartialFileNameFromURI(Target.URI));
  2295. if (UnpatchedFile.empty() == false && FileExists(UnpatchedFile))
  2296. Rename(UnpatchedFile, UnpatchedFile + ".FAILED");
  2297. new pkgAcqIndex(Owner, TransactionManager, Target);
  2298. Finish();
  2299. }
  2300. /*}}}*/
  2301. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  2302. void pkgAcqIndexDiffs::Finish(bool allDone)
  2303. {
  2304. if(Debug)
  2305. std::clog << "pkgAcqIndexDiffs::Finish(): "
  2306. << allDone << " "
  2307. << Desc.URI << std::endl;
  2308. // we restore the original name, this is required, otherwise
  2309. // the file will be cleaned
  2310. if(allDone)
  2311. {
  2312. std::string const Final = GetKeepCompressedFileName(GetFinalFilename(), Target);
  2313. TransactionManager->TransactionStageCopy(this, DestFile, Final);
  2314. // this is for the "real" finish
  2315. Complete = true;
  2316. Status = StatDone;
  2317. Dequeue();
  2318. if(Debug)
  2319. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  2320. return;
  2321. }
  2322. else
  2323. DestFile.clear();
  2324. if(Debug)
  2325. std::clog << "Finishing: " << Desc.URI << std::endl;
  2326. Complete = false;
  2327. Status = StatDone;
  2328. Dequeue();
  2329. return;
  2330. }
  2331. /*}}}*/
  2332. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  2333. {
  2334. // calc sha1 of the just patched file
  2335. std::string const PartialFile = GetExistingFilename(GetPartialFileNameFromURI(Target.URI));
  2336. if(unlikely(PartialFile.empty()))
  2337. {
  2338. Failed("Message: The file " + GetPartialFileNameFromURI(Target.URI) + " isn't available", NULL);
  2339. return false;
  2340. }
  2341. FileFd fd(PartialFile, FileFd::ReadOnly, FileFd::Extension);
  2342. Hashes LocalHashesCalc;
  2343. LocalHashesCalc.AddFD(fd);
  2344. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  2345. if(Debug)
  2346. std::clog << "QueueNextDiff: " << PartialFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
  2347. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
  2348. if (unlikely(LocalHashes.usable() == false || TargetFileHashes.usable() == false))
  2349. {
  2350. Failed("Local/Expected hashes are not usable for " + PartialFile, NULL);
  2351. return false;
  2352. }
  2353. // final file reached before all patches are applied
  2354. if(LocalHashes == TargetFileHashes)
  2355. {
  2356. Finish(true);
  2357. return true;
  2358. }
  2359. // remove all patches until the next matching patch is found
  2360. // this requires the Index file to be ordered
  2361. available_patches.erase(available_patches.begin(),
  2362. std::find_if(available_patches.begin(), available_patches.end(), [&](DiffInfo const &I) {
  2363. return I.result_hashes == LocalHashes;
  2364. }));
  2365. // error checking and falling back if no patch was found
  2366. if(available_patches.empty() == true)
  2367. {
  2368. Failed("No patches left to reach target for " + PartialFile, NULL);
  2369. return false;
  2370. }
  2371. // queue the right diff
  2372. Desc.URI = Target.URI + ".diff/" + available_patches[0].file + ".gz";
  2373. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  2374. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI + ".diff/" + available_patches[0].file), Target);
  2375. if(Debug)
  2376. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  2377. QueueURI(Desc);
  2378. return true;
  2379. }
  2380. /*}}}*/
  2381. void pkgAcqIndexDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  2382. pkgAcquire::MethodConfig const * const Cnf)
  2383. {
  2384. if (Debug)
  2385. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  2386. Item::Done(Message, Hashes, Cnf);
  2387. std::string const UncompressedUnpatchedFile = GetPartialFileNameFromURI(Target.URI);
  2388. std::string const UnpatchedFile = GetExistingFilename(UncompressedUnpatchedFile);
  2389. std::string const PatchFile = GetDiffsPatchFileName(UnpatchedFile);
  2390. std::string const PatchedFile = GetKeepCompressedFileName(UncompressedUnpatchedFile, Target);
  2391. switch (State)
  2392. {
  2393. // success in downloading a diff, enter ApplyDiff state
  2394. case StateFetchDiff:
  2395. Rename(DestFile, PatchFile);
  2396. DestFile = GetKeepCompressedFileName(UncompressedUnpatchedFile + "-patched", Target);
  2397. if(Debug)
  2398. std::clog << "Sending to rred method: " << UnpatchedFile << std::endl;
  2399. State = StateApplyDiff;
  2400. Local = true;
  2401. Desc.URI = "rred:" + UnpatchedFile;
  2402. QueueURI(Desc);
  2403. SetActiveSubprocess("rred");
  2404. return;
  2405. // success in download/apply a diff, queue next (if needed)
  2406. case StateApplyDiff:
  2407. // remove the just applied patch and base file
  2408. available_patches.erase(available_patches.begin());
  2409. RemoveFile("pkgAcqIndexDiffs::Done", PatchFile);
  2410. RemoveFile("pkgAcqIndexDiffs::Done", UnpatchedFile);
  2411. if(Debug)
  2412. std::clog << "Moving patched file in place: " << std::endl
  2413. << DestFile << " -> " << PatchedFile << std::endl;
  2414. Rename(DestFile, PatchedFile);
  2415. // see if there is more to download
  2416. if(available_patches.empty() == false)
  2417. {
  2418. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
  2419. Finish();
  2420. } else {
  2421. DestFile = PatchedFile;
  2422. Finish(true);
  2423. }
  2424. return;
  2425. }
  2426. }
  2427. /*}}}*/
  2428. std::string pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
  2429. {
  2430. if(State != StateApplyDiff)
  2431. return pkgAcqBaseIndex::Custom600Headers();
  2432. std::ostringstream patchhashes;
  2433. for (auto && hs : available_patches[0].result_hashes)
  2434. patchhashes << "\nStart-" << hs.HashType() << "-Hash: " << hs.HashValue();
  2435. for (auto && hs : available_patches[0].patch_hashes)
  2436. patchhashes << "\nPatch-0-" << hs.HashType() << "-Hash: " << hs.HashValue();
  2437. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  2438. return patchhashes.str();
  2439. }
  2440. /*}}}*/
  2441. pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
  2442. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  2443. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire * const Owner,
  2444. pkgAcqMetaClearSig * const TransactionManager,
  2445. IndexTarget const &Target,
  2446. DiffInfo const &patch,
  2447. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  2448. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
  2449. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  2450. {
  2451. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  2452. Desc.Owner = this;
  2453. Description = Target.Description;
  2454. Desc.ShortDesc = Target.ShortDesc;
  2455. Desc.URI = Target.URI + ".diff/" + patch.file + ".gz";
  2456. Desc.Description = Description + " " + patch.file + ".pdiff";
  2457. DestFile = GetPartialFileNameFromURI(Desc.URI);
  2458. if(Debug)
  2459. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  2460. QueueURI(Desc);
  2461. }
  2462. /*}}}*/
  2463. void pkgAcqIndexMergeDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  2464. {
  2465. if(Debug)
  2466. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  2467. pkgAcqBaseIndex::Failed(Message,Cnf);
  2468. Status = StatDone;
  2469. // check if we are the first to fail, otherwise we are done here
  2470. State = StateDoneDiff;
  2471. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2472. I != allPatches->end(); ++I)
  2473. if ((*I)->State == StateErrorDiff)
  2474. {
  2475. State = StateErrorDiff;
  2476. return;
  2477. }
  2478. // first failure means we should fallback
  2479. State = StateErrorDiff;
  2480. if (Debug)
  2481. std::clog << "Falling back to normal index file acquire" << std::endl;
  2482. RenameOnError(PDiffError);
  2483. if (RealFileExists(DestFile))
  2484. Rename(DestFile, DestFile + ".FAILED");
  2485. std::string const UnpatchedFile = GetExistingFilename(GetPartialFileNameFromURI(Target.URI));
  2486. if (UnpatchedFile.empty() == false && FileExists(UnpatchedFile))
  2487. Rename(UnpatchedFile, UnpatchedFile + ".FAILED");
  2488. DestFile.clear();
  2489. new pkgAcqIndex(Owner, TransactionManager, Target);
  2490. }
  2491. /*}}}*/
  2492. void pkgAcqIndexMergeDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  2493. pkgAcquire::MethodConfig const * const Cnf)
  2494. {
  2495. if(Debug)
  2496. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  2497. Item::Done(Message, Hashes, Cnf);
  2498. if (std::any_of(allPatches->begin(), allPatches->end(),
  2499. [](pkgAcqIndexMergeDiffs const * const P) { return P->State == StateErrorDiff; }))
  2500. {
  2501. if(Debug)
  2502. std::clog << "Another patch failed already, no point in processing this one." << std::endl;
  2503. State = StateErrorDiff;
  2504. return;
  2505. }
  2506. std::string const UncompressedUnpatchedFile = GetPartialFileNameFromURI(Target.URI);
  2507. std::string const UnpatchedFile = GetExistingFilename(UncompressedUnpatchedFile);
  2508. if (UnpatchedFile.empty())
  2509. {
  2510. _error->Fatal("Unpatched file %s doesn't exist (anymore)!", UncompressedUnpatchedFile.c_str());
  2511. State = StateErrorDiff;
  2512. return;
  2513. }
  2514. std::string const PatchFile = GetMergeDiffsPatchFileName(UnpatchedFile, patch.file);
  2515. std::string const PatchedFile = GetKeepCompressedFileName(UncompressedUnpatchedFile, Target);
  2516. switch (State)
  2517. {
  2518. case StateFetchDiff:
  2519. Rename(DestFile, PatchFile);
  2520. // check if this is the last completed diff
  2521. State = StateDoneDiff;
  2522. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2523. I != allPatches->end(); ++I)
  2524. if ((*I)->State != StateDoneDiff)
  2525. {
  2526. if(Debug)
  2527. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  2528. return;
  2529. }
  2530. // this is the last completed diff, so we are ready to apply now
  2531. DestFile = GetKeepCompressedFileName(UncompressedUnpatchedFile + "-patched", Target);
  2532. if(Debug)
  2533. std::clog << "Sending to rred method: " << UnpatchedFile << std::endl;
  2534. State = StateApplyDiff;
  2535. Local = true;
  2536. Desc.URI = "rred:" + UnpatchedFile;
  2537. QueueURI(Desc);
  2538. SetActiveSubprocess("rred");
  2539. return;
  2540. case StateApplyDiff:
  2541. // success in download & apply all diffs, finialize and clean up
  2542. if(Debug)
  2543. std::clog << "Queue patched file in place: " << std::endl
  2544. << DestFile << " -> " << PatchedFile << std::endl;
  2545. // queue for copy by the transaction manager
  2546. TransactionManager->TransactionStageCopy(this, DestFile, GetKeepCompressedFileName(GetFinalFilename(), Target));
  2547. // ensure the ed's are gone regardless of list-cleanup
  2548. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2549. I != allPatches->end(); ++I)
  2550. RemoveFile("pkgAcqIndexMergeDiffs::Done", GetMergeDiffsPatchFileName(UnpatchedFile, (*I)->patch.file));
  2551. RemoveFile("pkgAcqIndexMergeDiffs::Done", UnpatchedFile);
  2552. // all set and done
  2553. Complete = true;
  2554. if(Debug)
  2555. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  2556. return;
  2557. case StateDoneDiff: _error->Fatal("Done called for %s which is in an invalid Done state", PatchFile.c_str()); break;
  2558. case StateErrorDiff: _error->Fatal("Done called for %s which is in an invalid Error state", PatchFile.c_str()); break;
  2559. }
  2560. }
  2561. /*}}}*/
  2562. std::string pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
  2563. {
  2564. if(State != StateApplyDiff)
  2565. return pkgAcqBaseIndex::Custom600Headers();
  2566. std::ostringstream patchhashes;
  2567. unsigned int seen_patches = 0;
  2568. for (auto && hs : (*allPatches)[0]->patch.result_hashes)
  2569. patchhashes << "\nStart-" << hs.HashType() << "-Hash: " << hs.HashValue();
  2570. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2571. I != allPatches->end(); ++I)
  2572. {
  2573. HashStringList const ExpectedHashes = (*I)->patch.patch_hashes;
  2574. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  2575. patchhashes << "\nPatch-" << seen_patches << "-" << hs->HashType() << "-Hash: " << hs->HashValue();
  2576. ++seen_patches;
  2577. }
  2578. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  2579. return patchhashes.str();
  2580. }
  2581. /*}}}*/
  2582. pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
  2583. // AcqIndex::AcqIndex - Constructor /*{{{*/
  2584. pkgAcqIndex::pkgAcqIndex(pkgAcquire * const Owner,
  2585. pkgAcqMetaClearSig * const TransactionManager,
  2586. IndexTarget const &Target)
  2587. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), Stage(STAGE_DOWNLOAD),
  2588. CompressionExtensions(Target.Option(IndexTarget::COMPRESSIONTYPES))
  2589. {
  2590. Init(Target.URI, Target.Description, Target.ShortDesc);
  2591. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  2592. std::clog << "New pkgIndex with TransactionManager "
  2593. << TransactionManager << std::endl;
  2594. }
  2595. /*}}}*/
  2596. // AcqIndex::Init - defered Constructor /*{{{*/
  2597. static void NextCompressionExtension(std::string &CurrentCompressionExtension, std::string &CompressionExtensions, bool const preview)
  2598. {
  2599. size_t const nextExt = CompressionExtensions.find(' ');
  2600. if (nextExt == std::string::npos)
  2601. {
  2602. CurrentCompressionExtension = CompressionExtensions;
  2603. if (preview == false)
  2604. CompressionExtensions.clear();
  2605. }
  2606. else
  2607. {
  2608. CurrentCompressionExtension = CompressionExtensions.substr(0, nextExt);
  2609. if (preview == false)
  2610. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  2611. }
  2612. }
  2613. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  2614. string const &ShortDesc)
  2615. {
  2616. Stage = STAGE_DOWNLOAD;
  2617. DestFile = GetPartialFileNameFromURI(URI);
  2618. NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, false);
  2619. // store file size of the download to ensure the fetcher gives
  2620. // accurate progress reporting
  2621. FileSize = GetExpectedHashes().FileSize();
  2622. if (CurrentCompressionExtension == "uncompressed")
  2623. {
  2624. Desc.URI = URI;
  2625. }
  2626. else if (CurrentCompressionExtension == "by-hash")
  2627. {
  2628. NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, true);
  2629. if(unlikely(CurrentCompressionExtension.empty()))
  2630. return;
  2631. if (CurrentCompressionExtension != "uncompressed")
  2632. {
  2633. Desc.URI = URI + '.' + CurrentCompressionExtension;
  2634. DestFile = DestFile + '.' + CurrentCompressionExtension;
  2635. }
  2636. HashStringList const Hashes = GetExpectedHashes();
  2637. HashString const * const TargetHash = Hashes.find(NULL);
  2638. if (unlikely(TargetHash == nullptr))
  2639. return;
  2640. std::string const ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  2641. size_t const trailing_slash = Desc.URI.find_last_of("/");
  2642. if (unlikely(trailing_slash == std::string::npos))
  2643. return;
  2644. Desc.URI = Desc.URI.replace(
  2645. trailing_slash,
  2646. Desc.URI.substr(trailing_slash+1).size()+1,
  2647. ByHash);
  2648. }
  2649. else if (unlikely(CurrentCompressionExtension.empty()))
  2650. return;
  2651. else
  2652. {
  2653. Desc.URI = URI + '.' + CurrentCompressionExtension;
  2654. DestFile = DestFile + '.' + CurrentCompressionExtension;
  2655. }
  2656. Desc.Description = URIDesc;
  2657. Desc.Owner = this;
  2658. Desc.ShortDesc = ShortDesc;
  2659. QueueURI(Desc);
  2660. }
  2661. /*}}}*/
  2662. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2663. // ---------------------------------------------------------------------
  2664. /* The only header we use is the last-modified header. */
  2665. string pkgAcqIndex::Custom600Headers() const
  2666. {
  2667. string msg = "\nIndex-File: true";
  2668. if (TransactionManager->LastMetaIndexParser == NULL)
  2669. {
  2670. std::string const Final = GetFinalFilename();
  2671. struct stat Buf;
  2672. if (stat(Final.c_str(),&Buf) == 0)
  2673. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime, false);
  2674. }
  2675. if(Target.IsOptional)
  2676. msg += "\nFail-Ignore: true";
  2677. return msg;
  2678. }
  2679. /*}}}*/
  2680. // AcqIndex::Failed - getting the indexfile failed /*{{{*/
  2681. void pkgAcqIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2682. {
  2683. pkgAcqBaseIndex::Failed(Message,Cnf);
  2684. // authorisation matches will not be fixed by other compression types
  2685. if (Status != StatAuthError)
  2686. {
  2687. if (CompressionExtensions.empty() == false)
  2688. {
  2689. Init(Target.URI, Desc.Description, Desc.ShortDesc);
  2690. Status = StatIdle;
  2691. return;
  2692. }
  2693. }
  2694. if(Target.IsOptional && GetExpectedHashes().empty() && Stage == STAGE_DOWNLOAD)
  2695. Status = StatDone;
  2696. else
  2697. TransactionManager->AbortTransaction();
  2698. }
  2699. /*}}}*/
  2700. // AcqIndex::Done - Finished a fetch /*{{{*/
  2701. // ---------------------------------------------------------------------
  2702. /* This goes through a number of states.. On the initial fetch the
  2703. method could possibly return an alternate filename which points
  2704. to the uncompressed version of the file. If this is so the file
  2705. is copied into the partial directory. In all other cases the file
  2706. is decompressed with a compressed uri. */
  2707. void pkgAcqIndex::Done(string const &Message,
  2708. HashStringList const &Hashes,
  2709. pkgAcquire::MethodConfig const * const Cfg)
  2710. {
  2711. Item::Done(Message,Hashes,Cfg);
  2712. switch(Stage)
  2713. {
  2714. case STAGE_DOWNLOAD:
  2715. StageDownloadDone(Message);
  2716. break;
  2717. case STAGE_DECOMPRESS_AND_VERIFY:
  2718. StageDecompressDone();
  2719. break;
  2720. }
  2721. }
  2722. /*}}}*/
  2723. // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
  2724. void pkgAcqIndex::StageDownloadDone(string const &Message)
  2725. {
  2726. Local = true;
  2727. Complete = true;
  2728. std::string const AltFilename = LookupTag(Message,"Alt-Filename");
  2729. std::string Filename = LookupTag(Message,"Filename");
  2730. // we need to verify the file against the current Release file again
  2731. // on if-modfied-since hit to avoid a stale attack against us
  2732. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2733. {
  2734. // copy FinalFile into partial/ so that we check the hash again
  2735. string const FinalFile = GetExistingFilename(GetFinalFileNameFromURI(Target.URI));
  2736. if (symlink(FinalFile.c_str(), DestFile.c_str()) != 0)
  2737. _error->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking final file %s back to %s failed", FinalFile.c_str(), DestFile.c_str());
  2738. else
  2739. {
  2740. EraseFileName = DestFile;
  2741. Filename = DestFile;
  2742. }
  2743. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2744. Desc.URI = "store:" + Filename;
  2745. QueueURI(Desc);
  2746. SetActiveSubprocess(::URI(Desc.URI).Access);
  2747. return;
  2748. }
  2749. // methods like file:// give us an alternative (uncompressed) file
  2750. else if (Target.KeepCompressed == false && AltFilename.empty() == false)
  2751. {
  2752. Filename = AltFilename;
  2753. EraseFileName.clear();
  2754. }
  2755. // Methods like e.g. "file:" will give us a (compressed) FileName that is
  2756. // not the "DestFile" we set, in this case we uncompress from the local file
  2757. else if (Filename != DestFile && RealFileExists(DestFile) == false)
  2758. {
  2759. // symlinking ensures that the filename can be used for compression detection
  2760. // that is e.g. needed for by-hash which has no extension over file
  2761. if (symlink(Filename.c_str(),DestFile.c_str()) != 0)
  2762. _error->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking file %s to %s failed", Filename.c_str(), DestFile.c_str());
  2763. else
  2764. {
  2765. EraseFileName = DestFile;
  2766. Filename = DestFile;
  2767. }
  2768. }
  2769. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2770. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2771. if (Filename != DestFile && flExtension(Filename) == flExtension(DestFile))
  2772. Desc.URI = "copy:" + Filename;
  2773. else
  2774. Desc.URI = "store:" + Filename;
  2775. if (DestFile == Filename)
  2776. {
  2777. if (CurrentCompressionExtension == "uncompressed")
  2778. return StageDecompressDone();
  2779. DestFile = "/dev/null";
  2780. }
  2781. if (EraseFileName.empty() && Filename != AltFilename)
  2782. EraseFileName = Filename;
  2783. // queue uri for the next stage
  2784. QueueURI(Desc);
  2785. SetActiveSubprocess(::URI(Desc.URI).Access);
  2786. }
  2787. /*}}}*/
  2788. // AcqIndex::StageDecompressDone - Final verification /*{{{*/
  2789. void pkgAcqIndex::StageDecompressDone()
  2790. {
  2791. if (DestFile == "/dev/null")
  2792. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2793. // Done, queue for rename on transaction finished
  2794. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  2795. }
  2796. /*}}}*/
  2797. pkgAcqIndex::~pkgAcqIndex() {}
  2798. // AcqArchive::AcqArchive - Constructor /*{{{*/
  2799. // ---------------------------------------------------------------------
  2800. /* This just sets up the initial fetch environment and queues the first
  2801. possibilitiy */
  2802. pkgAcqArchive::pkgAcqArchive(pkgAcquire * const Owner,pkgSourceList * const Sources,
  2803. pkgRecords * const Recs,pkgCache::VerIterator const &Version,
  2804. string &StoreFilename) :
  2805. Item(Owner), d(NULL), LocalSource(false), Version(Version), Sources(Sources), Recs(Recs),
  2806. StoreFilename(StoreFilename), Vf(Version.FileList()),
  2807. Trusted(false)
  2808. {
  2809. Retries = _config->FindI("Acquire::Retries",0);
  2810. if (Version.Arch() == 0)
  2811. {
  2812. _error->Error(_("I wasn't able to locate a file for the %s package. "
  2813. "This might mean you need to manually fix this package. "
  2814. "(due to missing arch)"),
  2815. Version.ParentPkg().FullName().c_str());
  2816. return;
  2817. }
  2818. /* We need to find a filename to determine the extension. We make the
  2819. assumption here that all the available sources for this version share
  2820. the same extension.. */
  2821. // Skip not source sources, they do not have file fields.
  2822. for (; Vf.end() == false; ++Vf)
  2823. {
  2824. if (Vf.File().Flagged(pkgCache::Flag::NotSource))
  2825. continue;
  2826. break;
  2827. }
  2828. // Does not really matter here.. we are going to fail out below
  2829. if (Vf.end() != true)
  2830. {
  2831. // If this fails to get a file name we will bomb out below.
  2832. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2833. if (_error->PendingError() == true)
  2834. return;
  2835. // Generate the final file name as: package_version_arch.foo
  2836. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  2837. QuoteString(Version.VerStr(),"_:") + '_' +
  2838. QuoteString(Version.Arch(),"_:.") +
  2839. "." + flExtension(Parse.FileName());
  2840. }
  2841. // check if we have one trusted source for the package. if so, switch
  2842. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  2843. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  2844. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  2845. bool seenUntrusted = false;
  2846. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  2847. {
  2848. pkgIndexFile *Index;
  2849. if (Sources->FindIndex(i.File(),Index) == false)
  2850. continue;
  2851. if (debugAuth == true)
  2852. std::cerr << "Checking index: " << Index->Describe()
  2853. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  2854. if (Index->IsTrusted() == true)
  2855. {
  2856. Trusted = true;
  2857. if (allowUnauth == false)
  2858. break;
  2859. }
  2860. else
  2861. seenUntrusted = true;
  2862. }
  2863. // "allow-unauthenticated" restores apts old fetching behaviour
  2864. // that means that e.g. unauthenticated file:// uris are higher
  2865. // priority than authenticated http:// uris
  2866. if (allowUnauth == true && seenUntrusted == true)
  2867. Trusted = false;
  2868. // Select a source
  2869. if (QueueNext() == false && _error->PendingError() == false)
  2870. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  2871. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  2872. }
  2873. /*}}}*/
  2874. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  2875. // ---------------------------------------------------------------------
  2876. /* This queues the next available file version for download. It checks if
  2877. the archive is already available in the cache and stashs the MD5 for
  2878. checking later. */
  2879. bool pkgAcqArchive::QueueNext()
  2880. {
  2881. for (; Vf.end() == false; ++Vf)
  2882. {
  2883. pkgCache::PkgFileIterator const PkgF = Vf.File();
  2884. // Ignore not source sources
  2885. if (PkgF.Flagged(pkgCache::Flag::NotSource))
  2886. continue;
  2887. // Try to cross match against the source list
  2888. pkgIndexFile *Index;
  2889. if (Sources->FindIndex(PkgF, Index) == false)
  2890. continue;
  2891. LocalSource = PkgF.Flagged(pkgCache::Flag::LocalSource);
  2892. // only try to get a trusted package from another source if that source
  2893. // is also trusted
  2894. if(Trusted && !Index->IsTrusted())
  2895. continue;
  2896. // Grab the text package record
  2897. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2898. if (_error->PendingError() == true)
  2899. return false;
  2900. string PkgFile = Parse.FileName();
  2901. ExpectedHashes = Parse.Hashes();
  2902. if (PkgFile.empty() == true)
  2903. return _error->Error(_("The package index files are corrupted. No Filename: "
  2904. "field for package %s."),
  2905. Version.ParentPkg().Name());
  2906. Desc.URI = Index->ArchiveURI(PkgFile);
  2907. Desc.Description = Index->ArchiveInfo(Version);
  2908. Desc.Owner = this;
  2909. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  2910. // See if we already have the file. (Legacy filenames)
  2911. FileSize = Version->Size;
  2912. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  2913. struct stat Buf;
  2914. if (stat(FinalFile.c_str(),&Buf) == 0)
  2915. {
  2916. // Make sure the size matches
  2917. if ((unsigned long long)Buf.st_size == Version->Size)
  2918. {
  2919. Complete = true;
  2920. Local = true;
  2921. Status = StatDone;
  2922. StoreFilename = DestFile = FinalFile;
  2923. return true;
  2924. }
  2925. /* Hmm, we have a file and its size does not match, this means it is
  2926. an old style mismatched arch */
  2927. RemoveFile("pkgAcqArchive::QueueNext", FinalFile);
  2928. }
  2929. // Check it again using the new style output filenames
  2930. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2931. if (stat(FinalFile.c_str(),&Buf) == 0)
  2932. {
  2933. // Make sure the size matches
  2934. if ((unsigned long long)Buf.st_size == Version->Size)
  2935. {
  2936. Complete = true;
  2937. Local = true;
  2938. Status = StatDone;
  2939. StoreFilename = DestFile = FinalFile;
  2940. return true;
  2941. }
  2942. /* Hmm, we have a file and its size does not match, this shouldn't
  2943. happen.. */
  2944. RemoveFile("pkgAcqArchive::QueueNext", FinalFile);
  2945. }
  2946. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2947. // Check the destination file
  2948. if (stat(DestFile.c_str(),&Buf) == 0)
  2949. {
  2950. // Hmm, the partial file is too big, erase it
  2951. if ((unsigned long long)Buf.st_size > Version->Size)
  2952. RemoveFile("pkgAcqArchive::QueueNext", DestFile);
  2953. else
  2954. PartialSize = Buf.st_size;
  2955. }
  2956. // Disables download of archives - useful if no real installation follows,
  2957. // e.g. if we are just interested in proposed installation order
  2958. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2959. {
  2960. Complete = true;
  2961. Local = true;
  2962. Status = StatDone;
  2963. StoreFilename = DestFile = FinalFile;
  2964. return true;
  2965. }
  2966. // Create the item
  2967. Local = false;
  2968. QueueURI(Desc);
  2969. ++Vf;
  2970. return true;
  2971. }
  2972. return false;
  2973. }
  2974. /*}}}*/
  2975. // AcqArchive::Done - Finished fetching /*{{{*/
  2976. // ---------------------------------------------------------------------
  2977. /* */
  2978. void pkgAcqArchive::Done(string const &Message, HashStringList const &Hashes,
  2979. pkgAcquire::MethodConfig const * const Cfg)
  2980. {
  2981. Item::Done(Message, Hashes, Cfg);
  2982. // Grab the output filename
  2983. std::string const FileName = LookupTag(Message,"Filename");
  2984. if (DestFile != FileName && RealFileExists(DestFile) == false)
  2985. {
  2986. StoreFilename = DestFile = FileName;
  2987. Local = true;
  2988. Complete = true;
  2989. return;
  2990. }
  2991. // Done, move it into position
  2992. string const FinalFile = GetFinalFilename();
  2993. Rename(DestFile,FinalFile);
  2994. StoreFilename = DestFile = FinalFile;
  2995. Complete = true;
  2996. }
  2997. /*}}}*/
  2998. // AcqArchive::Failed - Failure handler /*{{{*/
  2999. // ---------------------------------------------------------------------
  3000. /* Here we try other sources */
  3001. void pkgAcqArchive::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  3002. {
  3003. Item::Failed(Message,Cnf);
  3004. /* We don't really want to retry on failed media swaps, this prevents
  3005. that. An interesting observation is that permanent failures are not
  3006. recorded. */
  3007. if (Cnf->Removable == true &&
  3008. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  3009. {
  3010. // Vf = Version.FileList();
  3011. while (Vf.end() == false) ++Vf;
  3012. StoreFilename = string();
  3013. return;
  3014. }
  3015. Status = StatIdle;
  3016. if (QueueNext() == false)
  3017. {
  3018. // This is the retry counter
  3019. if (Retries != 0 &&
  3020. Cnf->LocalOnly == false &&
  3021. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  3022. {
  3023. Retries--;
  3024. Vf = Version.FileList();
  3025. if (QueueNext() == true)
  3026. return;
  3027. }
  3028. StoreFilename = string();
  3029. Status = StatError;
  3030. }
  3031. }
  3032. /*}}}*/
  3033. APT_PURE bool pkgAcqArchive::IsTrusted() const /*{{{*/
  3034. {
  3035. return Trusted;
  3036. }
  3037. /*}}}*/
  3038. void pkgAcqArchive::Finished() /*{{{*/
  3039. {
  3040. if (Status == pkgAcquire::Item::StatDone &&
  3041. Complete == true)
  3042. return;
  3043. StoreFilename = string();
  3044. }
  3045. /*}}}*/
  3046. std::string pkgAcqArchive::DescURI() const /*{{{*/
  3047. {
  3048. return Desc.URI;
  3049. }
  3050. /*}}}*/
  3051. std::string pkgAcqArchive::ShortDesc() const /*{{{*/
  3052. {
  3053. return Desc.ShortDesc;
  3054. }
  3055. /*}}}*/
  3056. pkgAcqArchive::~pkgAcqArchive() {}
  3057. // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
  3058. class pkgAcqChangelog::Private
  3059. {
  3060. public:
  3061. std::string FinalFile;
  3062. };
  3063. pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::VerIterator const &Ver,
  3064. std::string const &DestDir, std::string const &DestFilename) :
  3065. pkgAcquire::Item(Owner), d(new pkgAcqChangelog::Private()), SrcName(Ver.SourcePkgName()), SrcVersion(Ver.SourceVerStr())
  3066. {
  3067. Desc.URI = URI(Ver);
  3068. Init(DestDir, DestFilename);
  3069. }
  3070. // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
  3071. pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::RlsFileIterator const &RlsFile,
  3072. char const * const Component, char const * const SrcName, char const * const SrcVersion,
  3073. const string &DestDir, const string &DestFilename) :
  3074. pkgAcquire::Item(Owner), d(new pkgAcqChangelog::Private()), SrcName(SrcName), SrcVersion(SrcVersion)
  3075. {
  3076. Desc.URI = URI(RlsFile, Component, SrcName, SrcVersion);
  3077. Init(DestDir, DestFilename);
  3078. }
  3079. pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner,
  3080. std::string const &URI, char const * const SrcName, char const * const SrcVersion,
  3081. const string &DestDir, const string &DestFilename) :
  3082. pkgAcquire::Item(Owner), d(new pkgAcqChangelog::Private()), SrcName(SrcName), SrcVersion(SrcVersion)
  3083. {
  3084. Desc.URI = URI;
  3085. Init(DestDir, DestFilename);
  3086. }
  3087. void pkgAcqChangelog::Init(std::string const &DestDir, std::string const &DestFilename)
  3088. {
  3089. if (Desc.URI.empty())
  3090. {
  3091. Status = StatError;
  3092. // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
  3093. strprintf(ErrorText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
  3094. // Let the error message print something sensible rather than "Failed to fetch /"
  3095. if (DestFilename.empty())
  3096. DestFile = SrcName + ".changelog";
  3097. else
  3098. DestFile = DestFilename;
  3099. Desc.URI = "changelog:/" + DestFile;
  3100. return;
  3101. }
  3102. std::string DestFileName;
  3103. if (DestFilename.empty())
  3104. DestFileName = flCombine(DestFile, SrcName + ".changelog");
  3105. else
  3106. DestFileName = flCombine(DestFile, DestFilename);
  3107. std::string const SandboxUser = _config->Find("APT::Sandbox::User");
  3108. std::string const systemTemp = GetTempDir(SandboxUser);
  3109. char tmpname[1000];
  3110. snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX", systemTemp.c_str());
  3111. if (NULL == mkdtemp(tmpname))
  3112. {
  3113. _error->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName.c_str(), SrcVersion.c_str());
  3114. Status = StatError;
  3115. return;
  3116. }
  3117. TemporaryDirectory = tmpname;
  3118. ChangeOwnerAndPermissionOfFile("Item::QueueURI", TemporaryDirectory.c_str(),
  3119. SandboxUser.c_str(), "root", 0700);
  3120. DestFile = flCombine(TemporaryDirectory, DestFileName);
  3121. if (DestDir.empty() == false)
  3122. {
  3123. d->FinalFile = flCombine(DestDir, DestFileName);
  3124. if (RealFileExists(d->FinalFile))
  3125. {
  3126. FileFd file1, file2;
  3127. if (file1.Open(DestFile, FileFd::WriteOnly | FileFd::Create | FileFd::Exclusive) &&
  3128. file2.Open(d->FinalFile, FileFd::ReadOnly) && CopyFile(file2, file1))
  3129. {
  3130. struct timeval times[2];
  3131. times[0].tv_sec = times[1].tv_sec = file2.ModificationTime();
  3132. times[0].tv_usec = times[1].tv_usec = 0;
  3133. utimes(DestFile.c_str(), times);
  3134. }
  3135. }
  3136. }
  3137. Desc.ShortDesc = "Changelog";
  3138. strprintf(Desc.Description, "%s %s %s Changelog", URI::SiteOnly(Desc.URI).c_str(), SrcName.c_str(), SrcVersion.c_str());
  3139. Desc.Owner = this;
  3140. QueueURI(Desc);
  3141. }
  3142. /*}}}*/
  3143. std::string pkgAcqChangelog::URI(pkgCache::VerIterator const &Ver) /*{{{*/
  3144. {
  3145. std::string const confOnline = "Acquire::Changelogs::AlwaysOnline";
  3146. bool AlwaysOnline = _config->FindB(confOnline, false);
  3147. if (AlwaysOnline == false)
  3148. for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
  3149. {
  3150. pkgCache::PkgFileIterator const PF = VF.File();
  3151. if (PF.Flagged(pkgCache::Flag::NotSource) || PF->Release == 0)
  3152. continue;
  3153. pkgCache::RlsFileIterator const RF = PF.ReleaseFile();
  3154. if (RF->Origin != 0 && _config->FindB(confOnline + "::Origin::" + RF.Origin(), false))
  3155. {
  3156. AlwaysOnline = true;
  3157. break;
  3158. }
  3159. }
  3160. if (AlwaysOnline == false)
  3161. {
  3162. pkgCache::PkgIterator const Pkg = Ver.ParentPkg();
  3163. if (Pkg->CurrentVer != 0 && Pkg.CurrentVer() == Ver)
  3164. {
  3165. std::string const basename = std::string("/usr/share/doc/") + Pkg.Name() + "/changelog";
  3166. std::string const debianname = basename + ".Debian";
  3167. if (FileExists(debianname))
  3168. return "copy://" + debianname;
  3169. else if (FileExists(debianname + ".gz"))
  3170. return "gzip://" + debianname + ".gz";
  3171. else if (FileExists(basename))
  3172. return "copy://" + basename;
  3173. else if (FileExists(basename + ".gz"))
  3174. return "gzip://" + basename + ".gz";
  3175. }
  3176. }
  3177. char const * const SrcName = Ver.SourcePkgName();
  3178. char const * const SrcVersion = Ver.SourceVerStr();
  3179. // find the first source for this version which promises a changelog
  3180. for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
  3181. {
  3182. pkgCache::PkgFileIterator const PF = VF.File();
  3183. if (PF.Flagged(pkgCache::Flag::NotSource) || PF->Release == 0)
  3184. continue;
  3185. pkgCache::RlsFileIterator const RF = PF.ReleaseFile();
  3186. std::string const uri = URI(RF, PF.Component(), SrcName, SrcVersion);
  3187. if (uri.empty())
  3188. continue;
  3189. return uri;
  3190. }
  3191. return "";
  3192. }
  3193. std::string pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator const &Rls)
  3194. {
  3195. if (Rls.end() == true || (Rls->Label == 0 && Rls->Origin == 0))
  3196. return "";
  3197. std::string const serverConfig = "Acquire::Changelogs::URI";
  3198. std::string server;
  3199. #define APT_EMPTY_SERVER \
  3200. if (server.empty() == false) \
  3201. { \
  3202. if (server != "no") \
  3203. return server; \
  3204. return ""; \
  3205. }
  3206. #define APT_CHECK_SERVER(X, Y) \
  3207. if (Rls->X != 0) \
  3208. { \
  3209. std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
  3210. server = _config->Find(specialServerConfig); \
  3211. APT_EMPTY_SERVER \
  3212. }
  3213. // this way e.g. Debian-Security can fallback to Debian
  3214. APT_CHECK_SERVER(Label, "Override::")
  3215. APT_CHECK_SERVER(Origin, "Override::")
  3216. if (RealFileExists(Rls.FileName()))
  3217. {
  3218. _error->PushToStack();
  3219. FileFd rf;
  3220. /* This can be costly. A caller wanting to get millions of URIs might
  3221. want to do this on its own once and use Override settings.
  3222. We don't do this here as Origin/Label are not as unique as they
  3223. should be so this could produce request order-dependent anomalies */
  3224. if (OpenMaybeClearSignedFile(Rls.FileName(), rf) == true)
  3225. {
  3226. pkgTagFile TagFile(&rf, rf.Size());
  3227. pkgTagSection Section;
  3228. if (TagFile.Step(Section) == true)
  3229. server = Section.FindS("Changelogs");
  3230. }
  3231. _error->RevertToStack();
  3232. APT_EMPTY_SERVER
  3233. }
  3234. APT_CHECK_SERVER(Label, "")
  3235. APT_CHECK_SERVER(Origin, "")
  3236. #undef APT_CHECK_SERVER
  3237. #undef APT_EMPTY_SERVER
  3238. return "";
  3239. }
  3240. std::string pkgAcqChangelog::URI(pkgCache::RlsFileIterator const &Rls,
  3241. char const * const Component, char const * const SrcName,
  3242. char const * const SrcVersion)
  3243. {
  3244. return URI(URITemplate(Rls), Component, SrcName, SrcVersion);
  3245. }
  3246. std::string pkgAcqChangelog::URI(std::string const &Template,
  3247. char const * const Component, char const * const SrcName,
  3248. char const * const SrcVersion)
  3249. {
  3250. if (Template.find("@CHANGEPATH@") == std::string::npos)
  3251. return "";
  3252. // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
  3253. std::string Src = SrcName;
  3254. std::string path = APT::String::Startswith(SrcName, "lib") ? Src.substr(0, 4) : Src.substr(0,1);
  3255. path.append("/").append(Src).append("/");
  3256. path.append(Src).append("_").append(StripEpoch(SrcVersion));
  3257. // we omit component for releases without one (= flat-style repositories)
  3258. if (Component != NULL && strlen(Component) != 0)
  3259. path = std::string(Component) + "/" + path;
  3260. return SubstVar(Template, "@CHANGEPATH@", path);
  3261. }
  3262. /*}}}*/
  3263. // AcqChangelog::Failed - Failure handler /*{{{*/
  3264. void pkgAcqChangelog::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
  3265. {
  3266. Item::Failed(Message,Cnf);
  3267. std::string errText;
  3268. // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
  3269. strprintf(errText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
  3270. // Error is probably something techy like 404 Not Found
  3271. if (ErrorText.empty())
  3272. ErrorText = errText;
  3273. else
  3274. ErrorText = errText + " (" + ErrorText + ")";
  3275. }
  3276. /*}}}*/
  3277. // AcqChangelog::Done - Item downloaded OK /*{{{*/
  3278. void pkgAcqChangelog::Done(string const &Message,HashStringList const &CalcHashes,
  3279. pkgAcquire::MethodConfig const * const Cnf)
  3280. {
  3281. Item::Done(Message,CalcHashes,Cnf);
  3282. if (d->FinalFile.empty() == false)
  3283. {
  3284. if (RemoveFile("pkgAcqChangelog::Done", d->FinalFile) == false ||
  3285. Rename(DestFile, d->FinalFile) == false)
  3286. Status = StatError;
  3287. }
  3288. Complete = true;
  3289. }
  3290. /*}}}*/
  3291. pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
  3292. {
  3293. if (TemporaryDirectory.empty() == false)
  3294. {
  3295. RemoveFile("~pkgAcqChangelog", DestFile);
  3296. rmdir(TemporaryDirectory.c_str());
  3297. }
  3298. delete d;
  3299. }
  3300. /*}}}*/
  3301. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  3302. pkgAcqFile::pkgAcqFile(pkgAcquire * const Owner,string const &URI, HashStringList const &Hashes,
  3303. unsigned long long const Size,string const &Dsc,string const &ShortDesc,
  3304. const string &DestDir, const string &DestFilename,
  3305. bool const IsIndexFile) :
  3306. Item(Owner), d(NULL), IsIndexFile(IsIndexFile), ExpectedHashes(Hashes)
  3307. {
  3308. Retries = _config->FindI("Acquire::Retries",0);
  3309. if(!DestFilename.empty())
  3310. DestFile = DestFilename;
  3311. else if(!DestDir.empty())
  3312. DestFile = DestDir + "/" + flNotDir(URI);
  3313. else
  3314. DestFile = flNotDir(URI);
  3315. // Create the item
  3316. Desc.URI = URI;
  3317. Desc.Description = Dsc;
  3318. Desc.Owner = this;
  3319. // Set the short description to the archive component
  3320. Desc.ShortDesc = ShortDesc;
  3321. // Get the transfer sizes
  3322. FileSize = Size;
  3323. struct stat Buf;
  3324. if (stat(DestFile.c_str(),&Buf) == 0)
  3325. {
  3326. // Hmm, the partial file is too big, erase it
  3327. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  3328. RemoveFile("pkgAcqFile", DestFile);
  3329. else
  3330. PartialSize = Buf.st_size;
  3331. }
  3332. QueueURI(Desc);
  3333. }
  3334. /*}}}*/
  3335. // AcqFile::Done - Item downloaded OK /*{{{*/
  3336. void pkgAcqFile::Done(string const &Message,HashStringList const &CalcHashes,
  3337. pkgAcquire::MethodConfig const * const Cnf)
  3338. {
  3339. Item::Done(Message,CalcHashes,Cnf);
  3340. std::string const FileName = LookupTag(Message,"Filename");
  3341. Complete = true;
  3342. // The files timestamp matches
  3343. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  3344. return;
  3345. // We have to copy it into place
  3346. if (RealFileExists(DestFile.c_str()) == false)
  3347. {
  3348. Local = true;
  3349. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  3350. Cnf->Removable == true)
  3351. {
  3352. Desc.URI = "copy:" + FileName;
  3353. QueueURI(Desc);
  3354. return;
  3355. }
  3356. // Erase the file if it is a symlink so we can overwrite it
  3357. struct stat St;
  3358. if (lstat(DestFile.c_str(),&St) == 0)
  3359. {
  3360. if (S_ISLNK(St.st_mode) != 0)
  3361. RemoveFile("pkgAcqFile::Done", DestFile);
  3362. }
  3363. // Symlink the file
  3364. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  3365. {
  3366. _error->PushToStack();
  3367. _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
  3368. std::stringstream msg;
  3369. _error->DumpErrors(msg, GlobalError::DEBUG, false);
  3370. _error->RevertToStack();
  3371. ErrorText = msg.str();
  3372. Status = StatError;
  3373. Complete = false;
  3374. }
  3375. }
  3376. }
  3377. /*}}}*/
  3378. // AcqFile::Failed - Failure handler /*{{{*/
  3379. // ---------------------------------------------------------------------
  3380. /* Here we try other sources */
  3381. void pkgAcqFile::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
  3382. {
  3383. Item::Failed(Message,Cnf);
  3384. // This is the retry counter
  3385. if (Retries != 0 &&
  3386. Cnf->LocalOnly == false &&
  3387. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  3388. {
  3389. --Retries;
  3390. QueueURI(Desc);
  3391. Status = StatIdle;
  3392. return;
  3393. }
  3394. }
  3395. /*}}}*/
  3396. string pkgAcqFile::Custom600Headers() const /*{{{*/
  3397. {
  3398. if (IsIndexFile)
  3399. return "\nIndex-File: true";
  3400. return "";
  3401. }
  3402. /*}}}*/
  3403. pkgAcqFile::~pkgAcqFile() {}