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.
 
 
 
 
 
 

4031 lines
141 KiB

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