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.
 
 
 
 
 
 

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