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.
 
 
 
 
 
 

4079 lines
143 KiB

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