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.
 
 
 
 
 
 

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