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.
 
 
 
 
 
 

3751 lines
128 KiB

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