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.
 
 
 
 
 
 

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