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.
 
 
 
 
 
 

2960 lines
96 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/sha1.h>
  22. #include <apt-pkg/tagfile.h>
  23. #include <apt-pkg/indexrecords.h>
  24. #include <apt-pkg/acquire.h>
  25. #include <apt-pkg/hashes.h>
  26. #include <apt-pkg/indexfile.h>
  27. #include <apt-pkg/pkgcache.h>
  28. #include <apt-pkg/cacheiterators.h>
  29. #include <apt-pkg/pkgrecords.h>
  30. #include <stddef.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <iostream>
  34. #include <vector>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <errno.h>
  38. #include <string>
  39. #include <sstream>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <apti18n.h>
  43. /*}}}*/
  44. using namespace std;
  45. static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  46. {
  47. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  48. return;
  49. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  50. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  51. std::cerr << "\t- " << hs->toStr() << std::endl;
  52. std::cerr << " Actual Hash: " << std::endl;
  53. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  54. std::cerr << "\t- " << hs->toStr() << std::endl;
  55. }
  56. /*}}}*/
  57. static std::string GetPartialFileName(std::string const &file) /*{{{*/
  58. {
  59. std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  60. DestFile += file;
  61. return DestFile;
  62. }
  63. /*}}}*/
  64. static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
  65. {
  66. return GetPartialFileName(URItoFileName(uri));
  67. }
  68. /*}}}*/
  69. static std::string GetFinalFileNameFromURI(std::string const &uri) /*{{{*/
  70. {
  71. return _config->FindDir("Dir::State::lists") + URItoFileName(uri);
  72. }
  73. /*}}}*/
  74. static std::string GetCompressedFileName(std::string const &URI, std::string const &Name, std::string const &Ext) /*{{{*/
  75. {
  76. if (Ext.empty() || Ext == "uncompressed")
  77. return Name;
  78. // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
  79. // file when its doing the indexcopy
  80. if (URI.substr(0,6) == "cdrom:")
  81. return Name;
  82. // adjust DestFile if its compressed on disk
  83. if (_config->FindB("Acquire::GzipIndexes",false) == true)
  84. return Name + '.' + Ext;
  85. return Name;
  86. }
  87. /*}}}*/
  88. static std::string GetMergeDiffsPatchFileName(std::string const &Final, std::string const &Patch)/*{{{*/
  89. {
  90. // rred expects the patch as $FinalFile.ed.$patchname.gz
  91. return Final + ".ed." + Patch + ".gz";
  92. }
  93. /*}}}*/
  94. static std::string GetDiffsPatchFileName(std::string const &Final) /*{{{*/
  95. {
  96. // rred expects the patch as $FinalFile.ed
  97. return Final + ".ed";
  98. }
  99. /*}}}*/
  100. static bool AllowInsecureRepositories(indexRecords const * const MetaIndexParser, pkgAcqMetaBase * const TransactionManager, pkgAcquire::Item * const I) /*{{{*/
  101. {
  102. if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
  103. return true;
  104. _error->Error(_("Use --allow-insecure-repositories to force the update"));
  105. TransactionManager->AbortTransaction();
  106. I->Status = pkgAcquire::Item::StatError;
  107. return false;
  108. }
  109. /*}}}*/
  110. static HashStringList GetExpectedHashesFromFor(indexRecords * const Parser, std::string const MetaKey)/*{{{*/
  111. {
  112. if (Parser == NULL)
  113. return HashStringList();
  114. indexRecords::checkSum * const R = Parser->Lookup(MetaKey);
  115. if (R == NULL)
  116. return HashStringList();
  117. return R->Hashes;
  118. }
  119. /*}}}*/
  120. // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
  121. /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
  122. It is best to implement it as broadly as possible, while ::HashesRequired defaults
  123. to true and should be as restrictive as possible for false cases. Note that if
  124. a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
  125. ::HashesRequired is called to evaluate if its okay to have no hashes. */
  126. APT_CONST bool pkgAcqTransactionItem::HashesRequired() const
  127. {
  128. /* signed repositories obviously have a parser and good hashes.
  129. unsigned repositories, too, as even if we can't trust them for security,
  130. we can at least trust them for integrity of the download itself.
  131. Only repositories without a Release file can (obviously) not have
  132. hashes – and they are very uncommon and strongly discouraged */
  133. return TransactionManager->MetaIndexParser != NULL;
  134. }
  135. HashStringList pkgAcqTransactionItem::GetExpectedHashes() const
  136. {
  137. return GetExpectedHashesFor(GetMetaKey());
  138. }
  139. APT_CONST bool pkgAcqMetaBase::HashesRequired() const
  140. {
  141. // Release and co have no hashes 'by design'.
  142. return false;
  143. }
  144. HashStringList pkgAcqMetaBase::GetExpectedHashes() const
  145. {
  146. return HashStringList();
  147. }
  148. APT_CONST bool pkgAcqIndexDiffs::HashesRequired() const
  149. {
  150. /* We don't always have the diff of the downloaded pdiff file.
  151. What we have for sure is hashes for the uncompressed file,
  152. but rred uncompresses them on the fly while parsing, so not handled here.
  153. Hashes are (also) checked while searching for (next) patch to apply. */
  154. if (State == StateFetchDiff)
  155. return available_patches[0].download_hashes.empty() == false;
  156. return false;
  157. }
  158. HashStringList pkgAcqIndexDiffs::GetExpectedHashes() const
  159. {
  160. if (State == StateFetchDiff)
  161. return available_patches[0].download_hashes;
  162. return HashStringList();
  163. }
  164. APT_CONST bool pkgAcqIndexMergeDiffs::HashesRequired() const
  165. {
  166. /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
  167. we can check the rred result after all patches are applied as
  168. we know the expected result rather than potentially apply more patches */
  169. if (State == StateFetchDiff)
  170. return patch.download_hashes.empty() == false;
  171. return State == StateApplyDiff;
  172. }
  173. HashStringList pkgAcqIndexMergeDiffs::GetExpectedHashes() const
  174. {
  175. if (State == StateFetchDiff)
  176. return patch.download_hashes;
  177. else if (State == StateApplyDiff)
  178. return GetExpectedHashesFor(Target.MetaKey);
  179. return HashStringList();
  180. }
  181. APT_CONST bool pkgAcqArchive::HashesRequired() const
  182. {
  183. return LocalSource == false;
  184. }
  185. HashStringList pkgAcqArchive::GetExpectedHashes() const
  186. {
  187. // figured out while parsing the records
  188. return ExpectedHashes;
  189. }
  190. APT_CONST bool pkgAcqFile::HashesRequired() const
  191. {
  192. // supplied as parameter at creation time, so the caller decides
  193. return ExpectedHashes.usable();
  194. }
  195. HashStringList pkgAcqFile::GetExpectedHashes() const
  196. {
  197. return ExpectedHashes;
  198. }
  199. /*}}}*/
  200. // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
  201. bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc &Item)
  202. {
  203. Owner->Enqueue(Item);
  204. return true;
  205. }
  206. /* The idea here is that an item isn't queued if it exists on disk and the
  207. transition manager was a hit as this means that the files it contains
  208. the checksums for can't be updated either (or they are and we are asking
  209. for a hashsum mismatch to happen which helps nobody) */
  210. bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc &Item)
  211. {
  212. std::string const FinalFile = GetFinalFilename();
  213. if (TransactionManager != NULL && TransactionManager->IMSHit == true &&
  214. FileExists(FinalFile) == true)
  215. {
  216. PartialFile = DestFile = FinalFile;
  217. Status = StatDone;
  218. return false;
  219. }
  220. return pkgAcquire::Item::QueueURI(Item);
  221. }
  222. /* The transition manager InRelease itself (or its older sisters-in-law
  223. Release & Release.gpg) is always queued as this allows us to rerun gpgv
  224. on it to verify that we aren't stalled with old files */
  225. bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc &Item)
  226. {
  227. return pkgAcquire::Item::QueueURI(Item);
  228. }
  229. /* the Diff/Index needs to queue also the up-to-date complete index file
  230. to ensure that the list cleaner isn't eating it */
  231. bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc &Item)
  232. {
  233. if (pkgAcqTransactionItem::QueueURI(Item) == true)
  234. return true;
  235. QueueOnIMSHit();
  236. return false;
  237. }
  238. /*}}}*/
  239. // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
  240. std::string pkgAcquire::Item::GetFinalFilename() const
  241. {
  242. return GetFinalFileNameFromURI(Desc.URI);
  243. }
  244. std::string pkgAcqDiffIndex::GetFinalFilename() const
  245. {
  246. // the logic we inherent from pkgAcqBaseIndex isn't what we need here
  247. return pkgAcquire::Item::GetFinalFilename();
  248. }
  249. std::string pkgAcqIndex::GetFinalFilename() const
  250. {
  251. std::string const FinalFile = GetFinalFileNameFromURI(Target.URI);
  252. return GetCompressedFileName(Target.URI, FinalFile, CurrentCompressionExtension);
  253. }
  254. std::string pkgAcqMetaSig::GetFinalFilename() const
  255. {
  256. return GetFinalFileNameFromURI(Target.URI);
  257. }
  258. std::string pkgAcqBaseIndex::GetFinalFilename() const
  259. {
  260. return GetFinalFileNameFromURI(Target.URI);
  261. }
  262. std::string pkgAcqMetaBase::GetFinalFilename() const
  263. {
  264. return GetFinalFileNameFromURI(Target.URI);
  265. }
  266. std::string pkgAcqArchive::GetFinalFilename() const
  267. {
  268. return _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  269. }
  270. /*}}}*/
  271. // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
  272. std::string pkgAcqTransactionItem::GetMetaKey() const
  273. {
  274. return Target.MetaKey;
  275. }
  276. std::string pkgAcqIndex::GetMetaKey() const
  277. {
  278. if (Stage == STAGE_DECOMPRESS_AND_VERIFY || CurrentCompressionExtension == "uncompressed")
  279. return Target.MetaKey;
  280. return Target.MetaKey + "." + CurrentCompressionExtension;
  281. }
  282. std::string pkgAcqDiffIndex::GetMetaKey() const
  283. {
  284. return Target.MetaKey + ".diff/Index";
  285. }
  286. /*}}}*/
  287. //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
  288. bool pkgAcqTransactionItem::TransactionState(TransactionStates const state)
  289. {
  290. bool const Debug = _config->FindB("Debug::Acquire::Transaction", false);
  291. switch(state)
  292. {
  293. case TransactionAbort:
  294. if(Debug == true)
  295. std::clog << " Cancel: " << DestFile << std::endl;
  296. if (Status == pkgAcquire::Item::StatIdle)
  297. {
  298. Status = pkgAcquire::Item::StatDone;
  299. Dequeue();
  300. }
  301. break;
  302. case TransactionCommit:
  303. if(PartialFile != "")
  304. {
  305. if(Debug == true)
  306. std::clog << "mv " << PartialFile << " -> "<< DestFile << " # " << DescURI() << std::endl;
  307. Rename(PartialFile, DestFile);
  308. } else {
  309. if(Debug == true)
  310. std::clog << "rm " << DestFile << " # " << DescURI() << std::endl;
  311. unlink(DestFile.c_str());
  312. }
  313. break;
  314. }
  315. return true;
  316. }
  317. bool pkgAcqMetaBase::TransactionState(TransactionStates const state)
  318. {
  319. // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
  320. if (TransactionManager->IMSHit == false)
  321. return pkgAcqTransactionItem::TransactionState(state);
  322. return true;
  323. }
  324. bool pkgAcqIndex::TransactionState(TransactionStates const state)
  325. {
  326. if (pkgAcqTransactionItem::TransactionState(state) == false)
  327. return false;
  328. switch (state)
  329. {
  330. case TransactionAbort:
  331. if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
  332. {
  333. // keep the compressed file, but drop the decompressed
  334. EraseFileName.clear();
  335. if (PartialFile.empty() == false && flExtension(PartialFile) == "decomp")
  336. unlink(PartialFile.c_str());
  337. }
  338. break;
  339. case TransactionCommit:
  340. if (EraseFileName.empty() == false)
  341. unlink(EraseFileName.c_str());
  342. break;
  343. }
  344. return true;
  345. }
  346. bool pkgAcqDiffIndex::TransactionState(TransactionStates const state)
  347. {
  348. if (pkgAcqTransactionItem::TransactionState(state) == false)
  349. return false;
  350. switch (state)
  351. {
  352. case TransactionCommit:
  353. break;
  354. case TransactionAbort:
  355. std::string const Partial = GetPartialFileNameFromURI(Target.URI);
  356. unlink(Partial.c_str());
  357. break;
  358. }
  359. return true;
  360. }
  361. /*}}}*/
  362. class APT_HIDDEN NoActionItem : public pkgAcquire::Item /*{{{*/
  363. /* The sole purpose of this class is having an item which does nothing to
  364. reach its done state to prevent cleanup deleting the mentioned file.
  365. Handy in cases in which we know we have the file already, like IMS-Hits. */
  366. {
  367. IndexTarget const Target;
  368. public:
  369. virtual std::string DescURI() const {return Target.URI;};
  370. virtual HashStringList GetExpectedHashes() const {return HashStringList();};
  371. NoActionItem(pkgAcquire * const Owner, IndexTarget const Target) :
  372. pkgAcquire::Item(Owner), Target(Target)
  373. {
  374. Status = StatDone;
  375. DestFile = GetFinalFileNameFromURI(Target.URI);
  376. }
  377. };
  378. /*}}}*/
  379. // Acquire::Item::Item - Constructor /*{{{*/
  380. APT_IGNORE_DEPRECATED_PUSH
  381. pkgAcquire::Item::Item(pkgAcquire * const Owner) :
  382. FileSize(0), PartialSize(0), Mode(0), Complete(false), Local(false),
  383. QueueCounter(0), ExpectedAdditionalItems(0), Owner(Owner)
  384. {
  385. Owner->Add(this);
  386. Status = StatIdle;
  387. }
  388. APT_IGNORE_DEPRECATED_POP
  389. /*}}}*/
  390. // Acquire::Item::~Item - Destructor /*{{{*/
  391. pkgAcquire::Item::~Item()
  392. {
  393. Owner->Remove(this);
  394. }
  395. /*}}}*/
  396. std::string pkgAcquire::Item::Custom600Headers() const /*{{{*/
  397. {
  398. return std::string();
  399. }
  400. /*}}}*/
  401. std::string pkgAcquire::Item::ShortDesc() const /*{{{*/
  402. {
  403. return DescURI();
  404. }
  405. /*}}}*/
  406. APT_CONST void pkgAcquire::Item::Finished() /*{{{*/
  407. {
  408. }
  409. /*}}}*/
  410. APT_PURE pkgAcquire * pkgAcquire::Item::GetOwner() const /*{{{*/
  411. {
  412. return Owner;
  413. }
  414. /*}}}*/
  415. APT_CONST bool pkgAcquire::Item::IsTrusted() const /*{{{*/
  416. {
  417. return false;
  418. }
  419. /*}}}*/
  420. // Acquire::Item::Failed - Item failed to download /*{{{*/
  421. // ---------------------------------------------------------------------
  422. /* We return to an idle state if there are still other queues that could
  423. fetch this object */
  424. void pkgAcquire::Item::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  425. {
  426. if(ErrorText.empty())
  427. ErrorText = LookupTag(Message,"Message");
  428. UsedMirror = LookupTag(Message,"UsedMirror");
  429. if (QueueCounter <= 1)
  430. {
  431. /* This indicates that the file is not available right now but might
  432. be sometime later. If we do a retry cycle then this should be
  433. retried [CDROMs] */
  434. if (Cnf != NULL && Cnf->LocalOnly == true &&
  435. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  436. {
  437. Status = StatIdle;
  438. Dequeue();
  439. return;
  440. }
  441. switch (Status)
  442. {
  443. case StatIdle:
  444. case StatFetching:
  445. case StatDone:
  446. Status = StatError;
  447. break;
  448. case StatAuthError:
  449. case StatError:
  450. case StatTransientNetworkError:
  451. break;
  452. }
  453. Complete = false;
  454. Dequeue();
  455. }
  456. string const FailReason = LookupTag(Message, "FailReason");
  457. if (FailReason == "MaximumSizeExceeded")
  458. RenameOnError(MaximumSizeExceeded);
  459. else if (Status == StatAuthError)
  460. RenameOnError(HashSumMismatch);
  461. // report mirror failure back to LP if we actually use a mirror
  462. if (FailReason.empty() == false)
  463. ReportMirrorFailure(FailReason);
  464. else
  465. ReportMirrorFailure(ErrorText);
  466. if (QueueCounter > 1)
  467. Status = StatIdle;
  468. }
  469. /*}}}*/
  470. // Acquire::Item::Start - Item has begun to download /*{{{*/
  471. // ---------------------------------------------------------------------
  472. /* Stash status and the file size. Note that setting Complete means
  473. sub-phases of the acquire process such as decompresion are operating */
  474. void pkgAcquire::Item::Start(string const &/*Message*/, unsigned long long const Size)
  475. {
  476. Status = StatFetching;
  477. ErrorText.clear();
  478. if (FileSize == 0 && Complete == false)
  479. FileSize = Size;
  480. }
  481. /*}}}*/
  482. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  483. void pkgAcquire::Item::Done(string const &Message, HashStringList const &Hashes,
  484. pkgAcquire::MethodConfig const * const /*Cnf*/)
  485. {
  486. // We just downloaded something..
  487. string FileName = LookupTag(Message,"Filename");
  488. UsedMirror = LookupTag(Message,"UsedMirror");
  489. unsigned long long const downloadedSize = Hashes.FileSize();
  490. if (downloadedSize != 0)
  491. {
  492. if (Complete == false && !Local && FileName == DestFile)
  493. {
  494. if (Owner->Log != 0)
  495. Owner->Log->Fetched(Hashes.FileSize(),atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  496. }
  497. if (FileSize == 0)
  498. FileSize= downloadedSize;
  499. }
  500. Status = StatDone;
  501. ErrorText = string();
  502. Owner->Dequeue(this);
  503. }
  504. /*}}}*/
  505. // Acquire::Item::Rename - Rename a file /*{{{*/
  506. // ---------------------------------------------------------------------
  507. /* This helper function is used by a lot of item methods as their final
  508. step */
  509. bool pkgAcquire::Item::Rename(string const &From,string const &To)
  510. {
  511. if (From == To || rename(From.c_str(),To.c_str()) == 0)
  512. return true;
  513. std::string S;
  514. strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
  515. From.c_str(),To.c_str());
  516. Status = StatError;
  517. if (ErrorText.empty())
  518. ErrorText = S;
  519. else
  520. ErrorText = ErrorText + ": " + S;
  521. return false;
  522. }
  523. /*}}}*/
  524. void pkgAcquire::Item::Dequeue() /*{{{*/
  525. {
  526. Owner->Dequeue(this);
  527. }
  528. /*}}}*/
  529. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  530. {
  531. if (RealFileExists(DestFile))
  532. Rename(DestFile, DestFile + ".FAILED");
  533. std::string errtext;
  534. switch (error)
  535. {
  536. case HashSumMismatch:
  537. errtext = _("Hash Sum mismatch");
  538. Status = StatAuthError;
  539. ReportMirrorFailure("HashChecksumFailure");
  540. break;
  541. case SizeMismatch:
  542. errtext = _("Size mismatch");
  543. Status = StatAuthError;
  544. ReportMirrorFailure("SizeFailure");
  545. break;
  546. case InvalidFormat:
  547. errtext = _("Invalid file format");
  548. Status = StatError;
  549. // do not report as usually its not the mirrors fault, but Portal/Proxy
  550. break;
  551. case SignatureError:
  552. errtext = _("Signature error");
  553. Status = StatError;
  554. break;
  555. case NotClearsigned:
  556. errtext = _("Does not start with a cleartext signature");
  557. Status = StatError;
  558. break;
  559. case MaximumSizeExceeded:
  560. // the method is expected to report a good error for this
  561. Status = StatError;
  562. break;
  563. case PDiffError:
  564. // no handling here, done by callers
  565. break;
  566. }
  567. if (ErrorText.empty())
  568. ErrorText = errtext;
  569. return false;
  570. }
  571. /*}}}*/
  572. void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
  573. {
  574. ActiveSubprocess = subprocess;
  575. APT_IGNORE_DEPRECATED(Mode = ActiveSubprocess.c_str();)
  576. }
  577. /*}}}*/
  578. // Acquire::Item::ReportMirrorFailure /*{{{*/
  579. void pkgAcquire::Item::ReportMirrorFailure(string const &FailCode)
  580. {
  581. // we only act if a mirror was used at all
  582. if(UsedMirror.empty())
  583. return;
  584. #if 0
  585. std::cerr << "\nReportMirrorFailure: "
  586. << UsedMirror
  587. << " Uri: " << DescURI()
  588. << " FailCode: "
  589. << FailCode << std::endl;
  590. #endif
  591. string report = _config->Find("Methods::Mirror::ProblemReporting",
  592. "/usr/lib/apt/apt-report-mirror-failure");
  593. if(!FileExists(report))
  594. return;
  595. std::vector<char const*> Args;
  596. Args.push_back(report.c_str());
  597. Args.push_back(UsedMirror.c_str());
  598. Args.push_back(DescURI().c_str());
  599. Args.push_back(FailCode.c_str());
  600. Args.push_back(NULL);
  601. pid_t pid = ExecFork();
  602. if(pid < 0)
  603. {
  604. _error->Error("ReportMirrorFailure Fork failed");
  605. return;
  606. }
  607. else if(pid == 0)
  608. {
  609. execvp(Args[0], (char**)Args.data());
  610. std::cerr << "Could not exec " << Args[0] << std::endl;
  611. _exit(100);
  612. }
  613. if(!ExecWait(pid, "report-mirror-failure"))
  614. {
  615. _error->Warning("Couldn't report problem to '%s'",
  616. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  617. }
  618. }
  619. /*}}}*/
  620. std::string pkgAcquire::Item::HashSum() const /*{{{*/
  621. {
  622. HashStringList const hashes = GetExpectedHashes();
  623. HashString const * const hs = hashes.find(NULL);
  624. return hs != NULL ? hs->toStr() : "";
  625. }
  626. /*}}}*/
  627. pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire * const Owner, /*{{{*/
  628. pkgAcqMetaBase * const TransactionManager, IndexTarget const Target) :
  629. pkgAcquire::Item(Owner), Target(Target), TransactionManager(TransactionManager)
  630. {
  631. if (TransactionManager != this)
  632. TransactionManager->Add(this);
  633. }
  634. /*}}}*/
  635. pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
  636. {
  637. }
  638. /*}}}*/
  639. HashStringList pkgAcqTransactionItem::GetExpectedHashesFor(std::string const MetaKey) const /*{{{*/
  640. {
  641. return GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, MetaKey);
  642. }
  643. /*}}}*/
  644. // AcqMetaBase - Constructor /*{{{*/
  645. pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire * const Owner,
  646. pkgAcqMetaBase * const TransactionManager,
  647. std::vector<IndexTarget> const IndexTargets,
  648. IndexTarget const &DataTarget,
  649. indexRecords * const MetaIndexParser)
  650. : pkgAcqTransactionItem(Owner, TransactionManager, DataTarget),
  651. MetaIndexParser(MetaIndexParser), LastMetaIndexParser(NULL), IndexTargets(IndexTargets),
  652. AuthPass(false), IMSHit(false)
  653. {
  654. }
  655. /*}}}*/
  656. // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
  657. void pkgAcqMetaBase::Add(pkgAcqTransactionItem * const I)
  658. {
  659. Transaction.push_back(I);
  660. }
  661. /*}}}*/
  662. // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
  663. void pkgAcqMetaBase::AbortTransaction()
  664. {
  665. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  666. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  667. // ensure the toplevel is in error state too
  668. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  669. I != Transaction.end(); ++I)
  670. {
  671. (*I)->TransactionState(TransactionAbort);
  672. }
  673. Transaction.clear();
  674. }
  675. /*}}}*/
  676. // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
  677. APT_PURE bool pkgAcqMetaBase::TransactionHasError() const
  678. {
  679. for (std::vector<pkgAcqTransactionItem*>::const_iterator I = Transaction.begin();
  680. I != Transaction.end(); ++I)
  681. {
  682. switch((*I)->Status) {
  683. case StatDone: break;
  684. case StatIdle: break;
  685. case StatAuthError: return true;
  686. case StatError: return true;
  687. case StatTransientNetworkError: return true;
  688. case StatFetching: break;
  689. }
  690. }
  691. return false;
  692. }
  693. /*}}}*/
  694. // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
  695. void pkgAcqMetaBase::CommitTransaction()
  696. {
  697. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  698. std::clog << "CommitTransaction: " << this << std::endl;
  699. // move new files into place *and* remove files that are not
  700. // part of the transaction but are still on disk
  701. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  702. I != Transaction.end(); ++I)
  703. {
  704. (*I)->TransactionState(TransactionCommit);
  705. }
  706. Transaction.clear();
  707. }
  708. /*}}}*/
  709. // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
  710. void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem * const I,
  711. const std::string &From,
  712. const std::string &To)
  713. {
  714. I->PartialFile = From;
  715. I->DestFile = To;
  716. }
  717. /*}}}*/
  718. // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
  719. void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem * const I,
  720. const std::string &FinalFile)
  721. {
  722. I->PartialFile = "";
  723. I->DestFile = FinalFile;
  724. }
  725. /*}}}*/
  726. // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
  727. bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item * const I, const std::string &Message)
  728. {
  729. // FIXME: this entire function can do now that we disallow going to
  730. // a unauthenticated state and can cleanly rollback
  731. string const Final = I->GetFinalFilename();
  732. if(FileExists(Final))
  733. {
  734. I->Status = StatTransientNetworkError;
  735. _error->Warning(_("An error occurred during the signature "
  736. "verification. The repository is not updated "
  737. "and the previous index files will be used. "
  738. "GPG error: %s: %s\n"),
  739. Desc.Description.c_str(),
  740. LookupTag(Message,"Message").c_str());
  741. RunScripts("APT::Update::Auth-Failure");
  742. return true;
  743. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  744. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  745. _error->Error(_("GPG error: %s: %s"),
  746. Desc.Description.c_str(),
  747. LookupTag(Message,"Message").c_str());
  748. I->Status = StatError;
  749. return true;
  750. } else {
  751. _error->Warning(_("GPG error: %s: %s"),
  752. Desc.Description.c_str(),
  753. LookupTag(Message,"Message").c_str());
  754. }
  755. // gpgv method failed
  756. ReportMirrorFailure("GPGFailure");
  757. return false;
  758. }
  759. /*}}}*/
  760. // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
  761. // ---------------------------------------------------------------------
  762. string pkgAcqMetaBase::Custom600Headers() const
  763. {
  764. std::string Header = "\nIndex-File: true";
  765. std::string MaximumSize;
  766. strprintf(MaximumSize, "\nMaximum-Size: %i",
  767. _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
  768. Header += MaximumSize;
  769. string const FinalFile = GetFinalFilename();
  770. struct stat Buf;
  771. if (stat(FinalFile.c_str(),&Buf) == 0)
  772. Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  773. return Header;
  774. }
  775. /*}}}*/
  776. // AcqMetaBase::QueueForSignatureVerify /*{{{*/
  777. void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem * const I, std::string const &File, std::string const &Signature)
  778. {
  779. AuthPass = true;
  780. I->Desc.URI = "gpgv:" + Signature;
  781. I->DestFile = File;
  782. QueueURI(I->Desc);
  783. I->SetActiveSubprocess("gpgv");
  784. }
  785. /*}}}*/
  786. // AcqMetaBase::CheckDownloadDone /*{{{*/
  787. bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem * const I, const std::string &Message, HashStringList const &Hashes) const
  788. {
  789. // We have just finished downloading a Release file (it is not
  790. // verified yet)
  791. string const FileName = LookupTag(Message,"Filename");
  792. if (FileName.empty() == true)
  793. {
  794. I->Status = StatError;
  795. I->ErrorText = "Method gave a blank filename";
  796. return false;
  797. }
  798. if (FileName != I->DestFile)
  799. {
  800. I->Local = true;
  801. I->Desc.URI = "copy:" + FileName;
  802. I->QueueURI(I->Desc);
  803. return false;
  804. }
  805. // make sure to verify against the right file on I-M-S hit
  806. bool IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"), false);
  807. if (IMSHit == false && Hashes.usable())
  808. {
  809. // detect IMS-Hits servers haven't detected by Hash comparison
  810. std::string const FinalFile = I->GetFinalFilename();
  811. if (RealFileExists(FinalFile) && Hashes.VerifyFile(FinalFile) == true)
  812. {
  813. IMSHit = true;
  814. unlink(I->DestFile.c_str());
  815. }
  816. }
  817. if(IMSHit == true)
  818. {
  819. // for simplicity, the transaction manager is always InRelease
  820. // even if it doesn't exist.
  821. if (TransactionManager != NULL)
  822. TransactionManager->IMSHit = true;
  823. I->PartialFile = I->DestFile = I->GetFinalFilename();
  824. }
  825. // set Item to complete as the remaining work is all local (verify etc)
  826. I->Complete = true;
  827. return true;
  828. }
  829. /*}}}*/
  830. bool pkgAcqMetaBase::CheckAuthDone(string const &Message) /*{{{*/
  831. {
  832. // At this point, the gpgv method has succeeded, so there is a
  833. // valid signature from a key in the trusted keyring. We
  834. // perform additional verification of its contents, and use them
  835. // to verify the indexes we are about to download
  836. if (TransactionManager->IMSHit == false)
  837. {
  838. // open the last (In)Release if we have it
  839. std::string const FinalFile = GetFinalFilename();
  840. std::string FinalRelease;
  841. std::string FinalInRelease;
  842. if (APT::String::Endswith(FinalFile, "InRelease"))
  843. {
  844. FinalInRelease = FinalFile;
  845. FinalRelease = FinalFile.substr(0, FinalFile.length() - strlen("InRelease")) + "Release";
  846. }
  847. else
  848. {
  849. FinalInRelease = FinalFile.substr(0, FinalFile.length() - strlen("Release")) + "InRelease";
  850. FinalRelease = FinalFile;
  851. }
  852. if (RealFileExists(FinalInRelease) || RealFileExists(FinalRelease))
  853. {
  854. TransactionManager->LastMetaIndexParser = new indexRecords;
  855. _error->PushToStack();
  856. if (RealFileExists(FinalInRelease))
  857. TransactionManager->LastMetaIndexParser->Load(FinalInRelease);
  858. else
  859. TransactionManager->LastMetaIndexParser->Load(FinalRelease);
  860. // its unlikely to happen, but if what we have is bad ignore it
  861. if (_error->PendingError())
  862. {
  863. delete TransactionManager->LastMetaIndexParser;
  864. TransactionManager->LastMetaIndexParser = NULL;
  865. }
  866. _error->RevertToStack();
  867. }
  868. }
  869. if (TransactionManager->MetaIndexParser->Load(DestFile) == false)
  870. {
  871. Status = StatAuthError;
  872. ErrorText = TransactionManager->MetaIndexParser->ErrorText;
  873. return false;
  874. }
  875. if (!VerifyVendor(Message))
  876. {
  877. Status = StatAuthError;
  878. return false;
  879. }
  880. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  881. std::cerr << "Signature verification succeeded: "
  882. << DestFile << std::endl;
  883. // Download further indexes with verification
  884. QueueIndexes(true);
  885. return true;
  886. }
  887. /*}}}*/
  888. void pkgAcqMetaBase::QueueIndexes(bool const verify) /*{{{*/
  889. {
  890. // at this point the real Items are loaded in the fetcher
  891. ExpectedAdditionalItems = 0;
  892. for (std::vector <IndexTarget>::const_iterator Target = IndexTargets.begin();
  893. Target != IndexTargets.end();
  894. ++Target)
  895. {
  896. bool trypdiff = _config->FindB("Acquire::PDiffs", true);
  897. if (verify == true)
  898. {
  899. if (TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false)
  900. {
  901. // optional targets that we do not have in the Release file are skipped
  902. if (Target->IsOptional)
  903. continue;
  904. Status = StatAuthError;
  905. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target->MetaKey.c_str());
  906. return;
  907. }
  908. if (RealFileExists(GetFinalFileNameFromURI(Target->URI)))
  909. {
  910. if (TransactionManager->LastMetaIndexParser != NULL)
  911. {
  912. HashStringList const newFile = GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, Target->MetaKey);
  913. HashStringList const oldFile = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target->MetaKey);
  914. if (newFile == oldFile)
  915. {
  916. // we have the file already, no point in trying to acquire it again
  917. new NoActionItem(Owner, *Target);
  918. continue;
  919. }
  920. }
  921. }
  922. else
  923. trypdiff = false; // no file to patch
  924. // check if we have patches available
  925. trypdiff &= TransactionManager->MetaIndexParser->Exists(Target->MetaKey + ".diff/Index");
  926. }
  927. // if we have no file to patch, no point in trying
  928. trypdiff &= RealFileExists(GetFinalFileNameFromURI(Target->URI));
  929. // no point in patching from local sources
  930. if (trypdiff)
  931. {
  932. std::string const proto = Target->URI.substr(0, strlen("file:/"));
  933. if (proto == "file:/" || proto == "copy:/" || proto == "cdrom:")
  934. trypdiff = false;
  935. }
  936. // Queue the Index file (Packages, Sources, Translation-$foo, …)
  937. if (trypdiff)
  938. new pkgAcqDiffIndex(Owner, TransactionManager, *Target);
  939. else
  940. new pkgAcqIndex(Owner, TransactionManager, *Target);
  941. }
  942. }
  943. /*}}}*/
  944. bool pkgAcqMetaBase::VerifyVendor(string const &Message) /*{{{*/
  945. {
  946. string::size_type pos;
  947. // check for missing sigs (that where not fatal because otherwise we had
  948. // bombed earlier)
  949. string missingkeys;
  950. string msg = _("There is no public key available for the "
  951. "following key IDs:\n");
  952. pos = Message.find("NO_PUBKEY ");
  953. if (pos != std::string::npos)
  954. {
  955. string::size_type start = pos+strlen("NO_PUBKEY ");
  956. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  957. missingkeys += (Fingerprint);
  958. }
  959. if(!missingkeys.empty())
  960. _error->Warning("%s", (msg + missingkeys).c_str());
  961. string Transformed = TransactionManager->MetaIndexParser->GetExpectedDist();
  962. if (Transformed == "../project/experimental")
  963. {
  964. Transformed = "experimental";
  965. }
  966. pos = Transformed.rfind('/');
  967. if (pos != string::npos)
  968. {
  969. Transformed = Transformed.substr(0, pos);
  970. }
  971. if (Transformed == ".")
  972. {
  973. Transformed = "";
  974. }
  975. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  976. TransactionManager->MetaIndexParser->GetValidUntil() > 0) {
  977. time_t const invalid_since = time(NULL) - TransactionManager->MetaIndexParser->GetValidUntil();
  978. if (invalid_since > 0)
  979. {
  980. std::string errmsg;
  981. strprintf(errmsg,
  982. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  983. // the time since then the file is invalid - formated in the same way as in
  984. // the download progress display (e.g. 7d 3h 42min 1s)
  985. _("Release file for %s is expired (invalid since %s). "
  986. "Updates for this repository will not be applied."),
  987. Target.URI.c_str(), TimeToStr(invalid_since).c_str());
  988. if (ErrorText.empty())
  989. ErrorText = errmsg;
  990. return _error->Error("%s", errmsg.c_str());
  991. }
  992. }
  993. /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
  994. as a prevention of downgrading us to older (still valid) files */
  995. if (TransactionManager->IMSHit == false && TransactionManager->LastMetaIndexParser != NULL &&
  996. TransactionManager->LastMetaIndexParser->GetDate() > TransactionManager->MetaIndexParser->GetDate())
  997. {
  998. TransactionManager->IMSHit = true;
  999. unlink(DestFile.c_str());
  1000. PartialFile = DestFile = GetFinalFilename();
  1001. delete TransactionManager->MetaIndexParser;
  1002. TransactionManager->MetaIndexParser = TransactionManager->LastMetaIndexParser;
  1003. TransactionManager->LastMetaIndexParser = NULL;
  1004. }
  1005. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1006. {
  1007. std::cerr << "Got Codename: " << TransactionManager->MetaIndexParser->GetDist() << std::endl;
  1008. std::cerr << "Expecting Dist: " << TransactionManager->MetaIndexParser->GetExpectedDist() << std::endl;
  1009. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1010. }
  1011. if (TransactionManager->MetaIndexParser->CheckDist(Transformed) == false)
  1012. {
  1013. // This might become fatal one day
  1014. // Status = StatAuthError;
  1015. // ErrorText = "Conflicting distribution; expected "
  1016. // + MetaIndexParser->GetExpectedDist() + " but got "
  1017. // + MetaIndexParser->GetDist();
  1018. // return false;
  1019. if (!Transformed.empty())
  1020. {
  1021. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1022. Desc.Description.c_str(),
  1023. Transformed.c_str(),
  1024. TransactionManager->MetaIndexParser->GetDist().c_str());
  1025. }
  1026. }
  1027. return true;
  1028. }
  1029. /*}}}*/
  1030. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire * const Owner, /*{{{*/
  1031. IndexTarget const &ClearsignedTarget,
  1032. IndexTarget const &DetachedDataTarget, IndexTarget const &DetachedSigTarget,
  1033. std::vector<IndexTarget> const IndexTargets,
  1034. indexRecords * const MetaIndexParser) :
  1035. pkgAcqMetaIndex(Owner, this, ClearsignedTarget, DetachedSigTarget, IndexTargets, MetaIndexParser),
  1036. ClearsignedTarget(ClearsignedTarget),
  1037. DetachedDataTarget(DetachedDataTarget), DetachedSigTarget(DetachedSigTarget)
  1038. {
  1039. // index targets + (worst case:) Release/Release.gpg
  1040. ExpectedAdditionalItems = IndexTargets.size() + 2;
  1041. TransactionManager->Add(this);
  1042. }
  1043. /*}}}*/
  1044. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1045. {
  1046. }
  1047. /*}}}*/
  1048. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1049. string pkgAcqMetaClearSig::Custom600Headers() const
  1050. {
  1051. string Header = pkgAcqMetaBase::Custom600Headers();
  1052. Header += "\nFail-Ignore: true";
  1053. return Header;
  1054. }
  1055. /*}}}*/
  1056. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  1057. void pkgAcqMetaClearSig::Done(std::string const &Message,
  1058. HashStringList const &Hashes,
  1059. pkgAcquire::MethodConfig const * const Cnf)
  1060. {
  1061. Item::Done(Message, Hashes, Cnf);
  1062. // if we expect a ClearTextSignature (InRelease), ensure that
  1063. // this is what we get and if not fail to queue a
  1064. // Release/Release.gpg, see #346386
  1065. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  1066. {
  1067. pkgAcquire::Item::Failed(Message, Cnf);
  1068. RenameOnError(NotClearsigned);
  1069. TransactionManager->AbortTransaction();
  1070. return;
  1071. }
  1072. if(AuthPass == false)
  1073. {
  1074. if(CheckDownloadDone(this, Message, Hashes) == true)
  1075. QueueForSignatureVerify(this, DestFile, DestFile);
  1076. return;
  1077. }
  1078. else if(CheckAuthDone(Message) == true)
  1079. {
  1080. if (TransactionManager->IMSHit == false)
  1081. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1082. else if (RealFileExists(GetFinalFilename()) == false)
  1083. {
  1084. // We got an InRelease file IMSHit, but we haven't one, which means
  1085. // we had a valid Release/Release.gpg combo stepping in, which we have
  1086. // to 'acquire' now to ensure list cleanup isn't removing them
  1087. new NoActionItem(Owner, DetachedDataTarget);
  1088. new NoActionItem(Owner, DetachedSigTarget);
  1089. }
  1090. }
  1091. }
  1092. /*}}}*/
  1093. void pkgAcqMetaClearSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf) /*{{{*/
  1094. {
  1095. Item::Failed(Message, Cnf);
  1096. // we failed, we will not get additional items from this method
  1097. ExpectedAdditionalItems = 0;
  1098. if (AuthPass == false)
  1099. {
  1100. // Queue the 'old' InRelease file for removal if we try Release.gpg
  1101. // as otherwise the file will stay around and gives a false-auth
  1102. // impression (CVE-2012-0214)
  1103. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1104. Status = StatDone;
  1105. new pkgAcqMetaIndex(Owner, TransactionManager, DetachedDataTarget, DetachedSigTarget, IndexTargets, TransactionManager->MetaIndexParser);
  1106. }
  1107. else
  1108. {
  1109. if(CheckStopAuthentication(this, Message))
  1110. return;
  1111. _error->Warning(_("The data from '%s' is not signed. Packages "
  1112. "from that repository can not be authenticated."),
  1113. ClearsignedTarget.Description.c_str());
  1114. // No Release file was present, or verification failed, so fall
  1115. // back to queueing Packages files without verification
  1116. // only allow going further if the users explicitely wants it
  1117. if(AllowInsecureRepositories(TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1118. {
  1119. Status = StatDone;
  1120. /* InRelease files become Release files, otherwise
  1121. * they would be considered as trusted later on */
  1122. string const FinalRelease = GetFinalFileNameFromURI(DetachedDataTarget.URI);
  1123. string const PartialRelease = GetPartialFileNameFromURI(DetachedDataTarget.URI);
  1124. string const FinalReleasegpg = GetFinalFileNameFromURI(DetachedSigTarget.URI);
  1125. string const FinalInRelease = GetFinalFilename();
  1126. Rename(DestFile, PartialRelease);
  1127. TransactionManager->TransactionStageCopy(this, PartialRelease, FinalRelease);
  1128. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1129. {
  1130. // open the last Release if we have it
  1131. if (TransactionManager->IMSHit == false)
  1132. {
  1133. TransactionManager->LastMetaIndexParser = new indexRecords;
  1134. _error->PushToStack();
  1135. if (RealFileExists(FinalInRelease))
  1136. TransactionManager->LastMetaIndexParser->Load(FinalInRelease);
  1137. else
  1138. TransactionManager->LastMetaIndexParser->Load(FinalRelease);
  1139. // its unlikely to happen, but if what we have is bad ignore it
  1140. if (_error->PendingError())
  1141. {
  1142. delete TransactionManager->LastMetaIndexParser;
  1143. TransactionManager->LastMetaIndexParser = NULL;
  1144. }
  1145. _error->RevertToStack();
  1146. }
  1147. }
  1148. // we parse the indexes here because at this point the user wanted
  1149. // a repository that may potentially harm him
  1150. if (TransactionManager->MetaIndexParser->Load(PartialRelease) == false || VerifyVendor(Message) == false)
  1151. /* expired Release files are still a problem you need extra force for */;
  1152. else
  1153. QueueIndexes(true);
  1154. }
  1155. }
  1156. }
  1157. /*}}}*/
  1158. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire * const Owner, /*{{{*/
  1159. pkgAcqMetaBase * const TransactionManager,
  1160. IndexTarget const &DataTarget,
  1161. IndexTarget const &DetachedSigTarget,
  1162. vector<IndexTarget> const IndexTargets,
  1163. indexRecords * const MetaIndexParser) :
  1164. pkgAcqMetaBase(Owner, TransactionManager, IndexTargets, DataTarget, MetaIndexParser),
  1165. DetachedSigTarget(DetachedSigTarget)
  1166. {
  1167. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1168. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1169. << this->TransactionManager << std::endl;
  1170. DestFile = GetPartialFileNameFromURI(DataTarget.URI);
  1171. // Create the item
  1172. Desc.Description = DataTarget.Description;
  1173. Desc.Owner = this;
  1174. Desc.ShortDesc = DataTarget.ShortDesc;
  1175. Desc.URI = DataTarget.URI;
  1176. // we expect more item
  1177. ExpectedAdditionalItems = IndexTargets.size();
  1178. QueueURI(Desc);
  1179. }
  1180. /*}}}*/
  1181. void pkgAcqMetaIndex::Done(string const &Message, /*{{{*/
  1182. HashStringList const &Hashes,
  1183. pkgAcquire::MethodConfig const * const Cfg)
  1184. {
  1185. Item::Done(Message,Hashes,Cfg);
  1186. if(CheckDownloadDone(this, Message, Hashes))
  1187. {
  1188. // we have a Release file, now download the Signature, all further
  1189. // verify/queue for additional downloads will be done in the
  1190. // pkgAcqMetaSig::Done() code
  1191. new pkgAcqMetaSig(Owner, TransactionManager, DetachedSigTarget, this);
  1192. }
  1193. }
  1194. /*}}}*/
  1195. // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
  1196. void pkgAcqMetaIndex::Failed(string const &Message,
  1197. pkgAcquire::MethodConfig const * const Cnf)
  1198. {
  1199. pkgAcquire::Item::Failed(Message, Cnf);
  1200. Status = StatDone;
  1201. _error->Warning(_("The repository '%s' does not have a Release file. "
  1202. "This is deprecated, please contact the owner of the "
  1203. "repository."), Target.Description.c_str());
  1204. // No Release file was present so fall
  1205. // back to queueing Packages files without verification
  1206. // only allow going further if the users explicitely wants it
  1207. if(AllowInsecureRepositories(TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1208. {
  1209. // ensure old Release files are removed
  1210. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1211. delete TransactionManager->MetaIndexParser;
  1212. TransactionManager->MetaIndexParser = NULL;
  1213. // queue without any kind of hashsum support
  1214. QueueIndexes(false);
  1215. }
  1216. }
  1217. /*}}}*/
  1218. void pkgAcqMetaIndex::Finished() /*{{{*/
  1219. {
  1220. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1221. std::clog << "Finished: " << DestFile <<std::endl;
  1222. if(TransactionManager != NULL &&
  1223. TransactionManager->TransactionHasError() == false)
  1224. TransactionManager->CommitTransaction();
  1225. }
  1226. /*}}}*/
  1227. std::string pkgAcqMetaIndex::DescURI() const /*{{{*/
  1228. {
  1229. return Target.URI;
  1230. }
  1231. /*}}}*/
  1232. // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
  1233. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire * const Owner,
  1234. pkgAcqMetaBase * const TransactionManager,
  1235. IndexTarget const Target,
  1236. pkgAcqMetaIndex * const MetaIndex) :
  1237. pkgAcqTransactionItem(Owner, TransactionManager, Target), MetaIndex(MetaIndex)
  1238. {
  1239. DestFile = GetPartialFileNameFromURI(Target.URI);
  1240. // remove any partial downloaded sig-file in partial/.
  1241. // it may confuse proxies and is too small to warrant a
  1242. // partial download anyway
  1243. unlink(DestFile.c_str());
  1244. // set the TransactionManager
  1245. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1246. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1247. << TransactionManager << std::endl;
  1248. // Create the item
  1249. Desc.Description = Target.Description;
  1250. Desc.Owner = this;
  1251. Desc.ShortDesc = Target.ShortDesc;
  1252. Desc.URI = Target.URI;
  1253. // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
  1254. // so we skip the download step and go instantly to verification
  1255. if (TransactionManager->IMSHit == true && RealFileExists(GetFinalFilename()))
  1256. {
  1257. Complete = true;
  1258. Status = StatDone;
  1259. PartialFile = DestFile = GetFinalFilename();
  1260. MetaIndexFileSignature = DestFile;
  1261. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1262. }
  1263. else
  1264. QueueURI(Desc);
  1265. }
  1266. /*}}}*/
  1267. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1268. {
  1269. }
  1270. /*}}}*/
  1271. // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
  1272. void pkgAcqMetaSig::Done(string const &Message, HashStringList const &Hashes,
  1273. pkgAcquire::MethodConfig const * const Cfg)
  1274. {
  1275. if (MetaIndexFileSignature.empty() == false)
  1276. {
  1277. DestFile = MetaIndexFileSignature;
  1278. MetaIndexFileSignature.clear();
  1279. }
  1280. Item::Done(Message, Hashes, Cfg);
  1281. if(MetaIndex->AuthPass == false)
  1282. {
  1283. if(MetaIndex->CheckDownloadDone(this, Message, Hashes) == true)
  1284. {
  1285. // destfile will be modified to point to MetaIndexFile for the
  1286. // gpgv method, so we need to save it here
  1287. MetaIndexFileSignature = DestFile;
  1288. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1289. }
  1290. return;
  1291. }
  1292. else if(MetaIndex->CheckAuthDone(Message) == true)
  1293. {
  1294. if (TransactionManager->IMSHit == false)
  1295. {
  1296. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1297. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1298. }
  1299. }
  1300. }
  1301. /*}}}*/
  1302. void pkgAcqMetaSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1303. {
  1304. Item::Failed(Message,Cnf);
  1305. // check if we need to fail at this point
  1306. if (MetaIndex->AuthPass == true && MetaIndex->CheckStopAuthentication(this, Message))
  1307. return;
  1308. string const FinalRelease = MetaIndex->GetFinalFilename();
  1309. string const FinalReleasegpg = GetFinalFilename();
  1310. string const FinalInRelease = TransactionManager->GetFinalFilename();
  1311. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1312. {
  1313. std::string downgrade_msg;
  1314. strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
  1315. MetaIndex->Target.Description.c_str());
  1316. if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
  1317. {
  1318. // meh, the users wants to take risks (we still mark the packages
  1319. // from this repository as unauthenticated)
  1320. _error->Warning("%s", downgrade_msg.c_str());
  1321. _error->Warning(_("This is normally not allowed, but the option "
  1322. "Acquire::AllowDowngradeToInsecureRepositories was "
  1323. "given to override it."));
  1324. Status = StatDone;
  1325. } else {
  1326. _error->Error("%s", downgrade_msg.c_str());
  1327. if (TransactionManager->IMSHit == false)
  1328. Rename(MetaIndex->DestFile, MetaIndex->DestFile + ".FAILED");
  1329. Item::Failed("Message: " + downgrade_msg, Cnf);
  1330. TransactionManager->AbortTransaction();
  1331. return;
  1332. }
  1333. }
  1334. else
  1335. _error->Warning(_("The data from '%s' is not signed. Packages "
  1336. "from that repository can not be authenticated."),
  1337. MetaIndex->Target.Description.c_str());
  1338. // ensures that a Release.gpg file in the lists/ is removed by the transaction
  1339. TransactionManager->TransactionStageRemoval(this, DestFile);
  1340. // only allow going further if the users explicitely wants it
  1341. if(AllowInsecureRepositories(TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1342. {
  1343. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1344. {
  1345. // open the last Release if we have it
  1346. if (TransactionManager->IMSHit == false)
  1347. {
  1348. TransactionManager->LastMetaIndexParser = new indexRecords;
  1349. _error->PushToStack();
  1350. if (RealFileExists(FinalInRelease))
  1351. TransactionManager->LastMetaIndexParser->Load(FinalInRelease);
  1352. else
  1353. TransactionManager->LastMetaIndexParser->Load(FinalRelease);
  1354. // its unlikely to happen, but if what we have is bad ignore it
  1355. if (_error->PendingError())
  1356. {
  1357. delete TransactionManager->LastMetaIndexParser;
  1358. TransactionManager->LastMetaIndexParser = NULL;
  1359. }
  1360. _error->RevertToStack();
  1361. }
  1362. }
  1363. // we parse the indexes here because at this point the user wanted
  1364. // a repository that may potentially harm him
  1365. if (TransactionManager->MetaIndexParser->Load(MetaIndex->DestFile) == false || MetaIndex->VerifyVendor(Message) == false)
  1366. /* expired Release files are still a problem you need extra force for */;
  1367. else
  1368. MetaIndex->QueueIndexes(true);
  1369. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1370. }
  1371. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1372. if (Cnf->LocalOnly == true ||
  1373. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1374. {
  1375. // Ignore this
  1376. Status = StatDone;
  1377. }
  1378. }
  1379. /*}}}*/
  1380. // AcqBaseIndex - Constructor /*{{{*/
  1381. pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire * const Owner,
  1382. pkgAcqMetaBase * const TransactionManager,
  1383. IndexTarget const Target)
  1384. : pkgAcqTransactionItem(Owner, TransactionManager, Target)
  1385. {
  1386. }
  1387. /*}}}*/
  1388. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  1389. // ---------------------------------------------------------------------
  1390. /* Get the DiffIndex file first and see if there are patches available
  1391. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  1392. * patches. If anything goes wrong in that process, it will fall back to
  1393. * the original packages file
  1394. */
  1395. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire * const Owner,
  1396. pkgAcqMetaBase * const TransactionManager,
  1397. IndexTarget const Target)
  1398. : pkgAcqBaseIndex(Owner, TransactionManager, Target)
  1399. {
  1400. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1401. Desc.Owner = this;
  1402. Desc.Description = Target.Description + ".diff/Index";
  1403. Desc.ShortDesc = Target.ShortDesc;
  1404. Desc.URI = Target.URI + ".diff/Index";
  1405. DestFile = GetPartialFileNameFromURI(Desc.URI);
  1406. if(Debug)
  1407. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  1408. QueueURI(Desc);
  1409. }
  1410. /*}}}*/
  1411. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1412. // ---------------------------------------------------------------------
  1413. /* The only header we use is the last-modified header. */
  1414. string pkgAcqDiffIndex::Custom600Headers() const
  1415. {
  1416. string const Final = GetFinalFilename();
  1417. if(Debug)
  1418. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  1419. struct stat Buf;
  1420. if (stat(Final.c_str(),&Buf) != 0)
  1421. return "\nIndex-File: true";
  1422. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1423. }
  1424. /*}}}*/
  1425. void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
  1426. {
  1427. // list cleanup needs to know that this file as well as the already
  1428. // present index is ours, so we create an empty diff to save it for us
  1429. new pkgAcqIndexDiffs(Owner, TransactionManager, Target);
  1430. }
  1431. /*}}}*/
  1432. bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/
  1433. {
  1434. // failing here is fine: our caller will take care of trying to
  1435. // get the complete file if patching fails
  1436. if(Debug)
  1437. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  1438. << std::endl;
  1439. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  1440. pkgTagFile TF(&Fd);
  1441. if (_error->PendingError() == true)
  1442. return false;
  1443. pkgTagSection Tags;
  1444. if(unlikely(TF.Step(Tags) == false))
  1445. return false;
  1446. HashStringList ServerHashes;
  1447. unsigned long long ServerSize = 0;
  1448. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1449. {
  1450. std::string tagname = *type;
  1451. tagname.append("-Current");
  1452. std::string const tmp = Tags.FindS(tagname.c_str());
  1453. if (tmp.empty() == true)
  1454. continue;
  1455. string hash;
  1456. unsigned long long size;
  1457. std::stringstream ss(tmp);
  1458. ss >> hash >> size;
  1459. if (unlikely(hash.empty() == true))
  1460. continue;
  1461. if (unlikely(ServerSize != 0 && ServerSize != size))
  1462. continue;
  1463. ServerHashes.push_back(HashString(*type, hash));
  1464. ServerSize = size;
  1465. }
  1466. if (ServerHashes.usable() == false)
  1467. {
  1468. if (Debug == true)
  1469. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
  1470. return false;
  1471. }
  1472. std::string const CurrentPackagesFile = GetFinalFileNameFromURI(Target.URI);
  1473. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
  1474. if (TargetFileHashes.usable() == false || ServerHashes != TargetFileHashes)
  1475. {
  1476. if (Debug == true)
  1477. {
  1478. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
  1479. printHashSumComparision(CurrentPackagesFile, ServerHashes, TargetFileHashes);
  1480. }
  1481. return false;
  1482. }
  1483. HashStringList LocalHashes;
  1484. // try avoiding calculating the hash here as this is costly
  1485. if (TransactionManager->LastMetaIndexParser != NULL)
  1486. LocalHashes = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target.MetaKey);
  1487. if (LocalHashes.usable() == false)
  1488. {
  1489. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  1490. Hashes LocalHashesCalc(ServerHashes);
  1491. LocalHashesCalc.AddFD(fd);
  1492. LocalHashes = LocalHashesCalc.GetHashStringList();
  1493. }
  1494. if (ServerHashes == LocalHashes)
  1495. {
  1496. // we have the same sha1 as the server so we are done here
  1497. if(Debug)
  1498. std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
  1499. QueueOnIMSHit();
  1500. return true;
  1501. }
  1502. if(Debug)
  1503. std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
  1504. << CurrentPackagesFile << " " << LocalHashes.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
  1505. // parse all of (provided) history
  1506. vector<DiffInfo> available_patches;
  1507. bool firstAcceptedHashes = true;
  1508. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1509. {
  1510. if (LocalHashes.find(*type) == NULL)
  1511. continue;
  1512. std::string tagname = *type;
  1513. tagname.append("-History");
  1514. std::string const tmp = Tags.FindS(tagname.c_str());
  1515. if (tmp.empty() == true)
  1516. continue;
  1517. string hash, filename;
  1518. unsigned long long size;
  1519. std::stringstream ss(tmp);
  1520. while (ss >> hash >> size >> filename)
  1521. {
  1522. if (unlikely(hash.empty() == true || filename.empty() == true))
  1523. continue;
  1524. // see if we have a record for this file already
  1525. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1526. for (; cur != available_patches.end(); ++cur)
  1527. {
  1528. if (cur->file != filename)
  1529. continue;
  1530. cur->result_hashes.push_back(HashString(*type, hash));
  1531. break;
  1532. }
  1533. if (cur != available_patches.end())
  1534. continue;
  1535. if (firstAcceptedHashes == true)
  1536. {
  1537. DiffInfo next;
  1538. next.file = filename;
  1539. next.result_hashes.push_back(HashString(*type, hash));
  1540. next.result_hashes.FileSize(size);
  1541. available_patches.push_back(next);
  1542. }
  1543. else
  1544. {
  1545. if (Debug == true)
  1546. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1547. << " wasn't in the list for the first parsed hash! (history)" << std::endl;
  1548. break;
  1549. }
  1550. }
  1551. firstAcceptedHashes = false;
  1552. }
  1553. if (unlikely(available_patches.empty() == true))
  1554. {
  1555. if (Debug)
  1556. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  1557. << "Couldn't find any patches for the patch series." << std::endl;
  1558. return false;
  1559. }
  1560. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1561. {
  1562. if (LocalHashes.find(*type) == NULL)
  1563. continue;
  1564. std::string tagname = *type;
  1565. tagname.append("-Patches");
  1566. std::string const tmp = Tags.FindS(tagname.c_str());
  1567. if (tmp.empty() == true)
  1568. continue;
  1569. string hash, filename;
  1570. unsigned long long size;
  1571. std::stringstream ss(tmp);
  1572. while (ss >> hash >> size >> filename)
  1573. {
  1574. if (unlikely(hash.empty() == true || filename.empty() == true))
  1575. continue;
  1576. // see if we have a record for this file already
  1577. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1578. for (; cur != available_patches.end(); ++cur)
  1579. {
  1580. if (cur->file != filename)
  1581. continue;
  1582. if (cur->patch_hashes.empty())
  1583. cur->patch_hashes.FileSize(size);
  1584. cur->patch_hashes.push_back(HashString(*type, hash));
  1585. break;
  1586. }
  1587. if (cur != available_patches.end())
  1588. continue;
  1589. if (Debug == true)
  1590. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1591. << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
  1592. break;
  1593. }
  1594. }
  1595. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1596. {
  1597. std::string tagname = *type;
  1598. tagname.append("-Download");
  1599. std::string const tmp = Tags.FindS(tagname.c_str());
  1600. if (tmp.empty() == true)
  1601. continue;
  1602. string hash, filename;
  1603. unsigned long long size;
  1604. std::stringstream ss(tmp);
  1605. // FIXME: all of pdiff supports only .gz compressed patches
  1606. while (ss >> hash >> size >> filename)
  1607. {
  1608. if (unlikely(hash.empty() == true || filename.empty() == true))
  1609. continue;
  1610. if (unlikely(APT::String::Endswith(filename, ".gz") == false))
  1611. continue;
  1612. filename.erase(filename.length() - 3);
  1613. // see if we have a record for this file already
  1614. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1615. for (; cur != available_patches.end(); ++cur)
  1616. {
  1617. if (cur->file != filename)
  1618. continue;
  1619. if (cur->download_hashes.empty())
  1620. cur->download_hashes.FileSize(size);
  1621. cur->download_hashes.push_back(HashString(*type, hash));
  1622. break;
  1623. }
  1624. if (cur != available_patches.end())
  1625. continue;
  1626. if (Debug == true)
  1627. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1628. << " wasn't in the list for the first parsed hash! (download)" << std::endl;
  1629. break;
  1630. }
  1631. }
  1632. bool foundStart = false;
  1633. for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1634. cur != available_patches.end(); ++cur)
  1635. {
  1636. if (LocalHashes != cur->result_hashes)
  1637. continue;
  1638. available_patches.erase(available_patches.begin(), cur);
  1639. foundStart = true;
  1640. break;
  1641. }
  1642. if (foundStart == false || unlikely(available_patches.empty() == true))
  1643. {
  1644. if (Debug)
  1645. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  1646. << "Couldn't find the start of the patch series." << std::endl;
  1647. return false;
  1648. }
  1649. // patching with too many files is rather slow compared to a fast download
  1650. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  1651. if (fileLimit != 0 && fileLimit < available_patches.size())
  1652. {
  1653. if (Debug)
  1654. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  1655. << ") so fallback to complete download" << std::endl;
  1656. return false;
  1657. }
  1658. // calculate the size of all patches we have to get
  1659. // note that all sizes are uncompressed, while we download compressed files
  1660. unsigned long long patchesSize = 0;
  1661. for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
  1662. cur != available_patches.end(); ++cur)
  1663. patchesSize += cur->patch_hashes.FileSize();
  1664. unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  1665. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  1666. {
  1667. if (Debug)
  1668. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  1669. << ") so fallback to complete download" << std::endl;
  1670. return false;
  1671. }
  1672. // we have something, queue the diffs
  1673. string::size_type const last_space = Description.rfind(" ");
  1674. if(last_space != string::npos)
  1675. Description.erase(last_space, Description.size()-last_space);
  1676. /* decide if we should download patches one by one or in one go:
  1677. The first is good if the server merges patches, but many don't so client
  1678. based merging can be attempt in which case the second is better.
  1679. "bad things" will happen if patches are merged on the server,
  1680. but client side merging is attempt as well */
  1681. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  1682. if (pdiff_merge == true)
  1683. {
  1684. // reprepro adds this flag if it has merged patches on the server
  1685. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  1686. pdiff_merge = (precedence != "merged");
  1687. }
  1688. if (pdiff_merge == false)
  1689. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
  1690. else
  1691. {
  1692. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  1693. for(size_t i = 0; i < available_patches.size(); ++i)
  1694. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
  1695. Target,
  1696. available_patches[i],
  1697. diffs);
  1698. }
  1699. Complete = false;
  1700. Status = StatDone;
  1701. Dequeue();
  1702. return true;
  1703. }
  1704. /*}}}*/
  1705. void pkgAcqDiffIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1706. {
  1707. Item::Failed(Message,Cnf);
  1708. Status = StatDone;
  1709. if(Debug)
  1710. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  1711. << "Falling back to normal index file acquire" << std::endl;
  1712. new pkgAcqIndex(Owner, TransactionManager, Target);
  1713. }
  1714. /*}}}*/
  1715. void pkgAcqDiffIndex::Done(string const &Message,HashStringList const &Hashes, /*{{{*/
  1716. pkgAcquire::MethodConfig const * const Cnf)
  1717. {
  1718. if(Debug)
  1719. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  1720. Item::Done(Message, Hashes, Cnf);
  1721. string const FinalFile = GetFinalFilename();
  1722. if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
  1723. DestFile = FinalFile;
  1724. if(ParseDiffIndex(DestFile) == false)
  1725. {
  1726. Failed("Message: Couldn't parse pdiff index", Cnf);
  1727. // queue for final move - this should happen even if we fail
  1728. // while parsing (e.g. on sizelimit) and download the complete file.
  1729. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1730. return;
  1731. }
  1732. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1733. Complete = true;
  1734. Status = StatDone;
  1735. Dequeue();
  1736. return;
  1737. }
  1738. /*}}}*/
  1739. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  1740. // ---------------------------------------------------------------------
  1741. /* The package diff is added to the queue. one object is constructed
  1742. * for each diff and the index
  1743. */
  1744. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire * const Owner,
  1745. pkgAcqMetaBase * const TransactionManager,
  1746. IndexTarget const Target,
  1747. vector<DiffInfo> const &diffs)
  1748. : pkgAcqBaseIndex(Owner, TransactionManager, Target),
  1749. available_patches(diffs)
  1750. {
  1751. DestFile = GetPartialFileNameFromURI(Target.URI);
  1752. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1753. Desc.Owner = this;
  1754. Description = Target.Description;
  1755. Desc.ShortDesc = Target.ShortDesc;
  1756. if(available_patches.empty() == true)
  1757. {
  1758. // we are done (yeah!), check hashes against the final file
  1759. DestFile = GetFinalFileNameFromURI(Target.URI);
  1760. Finish(true);
  1761. }
  1762. else
  1763. {
  1764. // patching needs to be bootstrapped with the 'old' version
  1765. std::string const PartialFile = GetPartialFileNameFromURI(Target.URI);
  1766. if (RealFileExists(PartialFile) == false)
  1767. {
  1768. if (symlink(GetFinalFilename().c_str(), PartialFile.c_str()) != 0)
  1769. {
  1770. Failed("Link creation of " + PartialFile + " to " + GetFinalFilename() + " failed", NULL);
  1771. return;
  1772. }
  1773. }
  1774. // get the next diff
  1775. State = StateFetchDiff;
  1776. QueueNextDiff();
  1777. }
  1778. }
  1779. /*}}}*/
  1780. void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1781. {
  1782. Item::Failed(Message,Cnf);
  1783. Status = StatDone;
  1784. if(Debug)
  1785. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  1786. << "Falling back to normal index file acquire" << std::endl;
  1787. DestFile = GetPartialFileNameFromURI(Target.URI);
  1788. RenameOnError(PDiffError);
  1789. std::string const patchname = GetDiffsPatchFileName(DestFile);
  1790. if (RealFileExists(patchname))
  1791. rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
  1792. new pkgAcqIndex(Owner, TransactionManager, Target);
  1793. Finish();
  1794. }
  1795. /*}}}*/
  1796. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  1797. void pkgAcqIndexDiffs::Finish(bool allDone)
  1798. {
  1799. if(Debug)
  1800. std::clog << "pkgAcqIndexDiffs::Finish(): "
  1801. << allDone << " "
  1802. << Desc.URI << std::endl;
  1803. // we restore the original name, this is required, otherwise
  1804. // the file will be cleaned
  1805. if(allDone)
  1806. {
  1807. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1808. // this is for the "real" finish
  1809. Complete = true;
  1810. Status = StatDone;
  1811. Dequeue();
  1812. if(Debug)
  1813. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  1814. return;
  1815. }
  1816. if(Debug)
  1817. std::clog << "Finishing: " << Desc.URI << std::endl;
  1818. Complete = false;
  1819. Status = StatDone;
  1820. Dequeue();
  1821. return;
  1822. }
  1823. /*}}}*/
  1824. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  1825. {
  1826. // calc sha1 of the just patched file
  1827. std::string const FinalFile = GetPartialFileNameFromURI(Target.URI);
  1828. if(!FileExists(FinalFile))
  1829. {
  1830. Failed("Message: No FinalFile " + FinalFile + " available", NULL);
  1831. return false;
  1832. }
  1833. FileFd fd(FinalFile, FileFd::ReadOnly);
  1834. Hashes LocalHashesCalc;
  1835. LocalHashesCalc.AddFD(fd);
  1836. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  1837. if(Debug)
  1838. std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
  1839. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
  1840. if (unlikely(LocalHashes.usable() == false || TargetFileHashes.usable() == false))
  1841. {
  1842. Failed("Local/Expected hashes are not usable", NULL);
  1843. return false;
  1844. }
  1845. // final file reached before all patches are applied
  1846. if(LocalHashes == TargetFileHashes)
  1847. {
  1848. Finish(true);
  1849. return true;
  1850. }
  1851. // remove all patches until the next matching patch is found
  1852. // this requires the Index file to be ordered
  1853. for(vector<DiffInfo>::iterator I = available_patches.begin();
  1854. available_patches.empty() == false &&
  1855. I != available_patches.end() &&
  1856. I->result_hashes != LocalHashes;
  1857. ++I)
  1858. {
  1859. available_patches.erase(I);
  1860. }
  1861. // error checking and falling back if no patch was found
  1862. if(available_patches.empty() == true)
  1863. {
  1864. Failed("No patches left to reach target", NULL);
  1865. return false;
  1866. }
  1867. // queue the right diff
  1868. Desc.URI = Target.URI + ".diff/" + available_patches[0].file + ".gz";
  1869. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  1870. DestFile = GetPartialFileNameFromURI(Target.URI + ".diff/" + available_patches[0].file);
  1871. if(Debug)
  1872. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  1873. QueueURI(Desc);
  1874. return true;
  1875. }
  1876. /*}}}*/
  1877. void pkgAcqIndexDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  1878. pkgAcquire::MethodConfig const * const Cnf)
  1879. {
  1880. if(Debug)
  1881. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  1882. Item::Done(Message, Hashes, Cnf);
  1883. std::string const FinalFile = GetPartialFileNameFromURI(Target.URI);
  1884. std::string const PatchFile = GetDiffsPatchFileName(FinalFile);
  1885. // success in downloading a diff, enter ApplyDiff state
  1886. if(State == StateFetchDiff)
  1887. {
  1888. Rename(DestFile, PatchFile);
  1889. if(Debug)
  1890. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  1891. State = StateApplyDiff;
  1892. Local = true;
  1893. Desc.URI = "rred:" + FinalFile;
  1894. QueueURI(Desc);
  1895. SetActiveSubprocess("rred");
  1896. return;
  1897. }
  1898. // success in download/apply a diff, queue next (if needed)
  1899. if(State == StateApplyDiff)
  1900. {
  1901. // remove the just applied patch
  1902. available_patches.erase(available_patches.begin());
  1903. unlink(PatchFile.c_str());
  1904. // move into place
  1905. if(Debug)
  1906. {
  1907. std::clog << "Moving patched file in place: " << std::endl
  1908. << DestFile << " -> " << FinalFile << std::endl;
  1909. }
  1910. Rename(DestFile,FinalFile);
  1911. chmod(FinalFile.c_str(),0644);
  1912. // see if there is more to download
  1913. if(available_patches.empty() == false) {
  1914. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  1915. available_patches);
  1916. return Finish();
  1917. } else
  1918. // update
  1919. DestFile = FinalFile;
  1920. return Finish(true);
  1921. }
  1922. }
  1923. /*}}}*/
  1924. std::string pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
  1925. {
  1926. if(State != StateApplyDiff)
  1927. return pkgAcqBaseIndex::Custom600Headers();
  1928. std::ostringstream patchhashes;
  1929. HashStringList const ExpectedHashes = available_patches[0].patch_hashes;
  1930. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  1931. patchhashes << "\nPatch-0-" << hs->HashType() << "-Hash: " << hs->HashValue();
  1932. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  1933. return patchhashes.str();
  1934. }
  1935. /*}}}*/
  1936. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  1937. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire * const Owner,
  1938. pkgAcqMetaBase * const TransactionManager,
  1939. IndexTarget const Target,
  1940. DiffInfo const &patch,
  1941. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  1942. : pkgAcqBaseIndex(Owner, TransactionManager, Target),
  1943. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  1944. {
  1945. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1946. Desc.Owner = this;
  1947. Description = Target.Description;
  1948. Desc.ShortDesc = Target.ShortDesc;
  1949. Desc.URI = Target.URI + ".diff/" + patch.file + ".gz";
  1950. Desc.Description = Description + " " + patch.file + string(".pdiff");
  1951. DestFile = GetPartialFileNameFromURI(Target.URI + ".diff/" + patch.file);
  1952. if(Debug)
  1953. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  1954. QueueURI(Desc);
  1955. }
  1956. /*}}}*/
  1957. void pkgAcqIndexMergeDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1958. {
  1959. if(Debug)
  1960. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  1961. Item::Failed(Message,Cnf);
  1962. Status = StatDone;
  1963. // check if we are the first to fail, otherwise we are done here
  1964. State = StateDoneDiff;
  1965. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  1966. I != allPatches->end(); ++I)
  1967. if ((*I)->State == StateErrorDiff)
  1968. return;
  1969. // first failure means we should fallback
  1970. State = StateErrorDiff;
  1971. if (Debug)
  1972. std::clog << "Falling back to normal index file acquire" << std::endl;
  1973. DestFile = GetPartialFileNameFromURI(Target.URI);
  1974. RenameOnError(PDiffError);
  1975. std::string const patchname = GetMergeDiffsPatchFileName(DestFile, patch.file);
  1976. if (RealFileExists(patchname))
  1977. rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
  1978. new pkgAcqIndex(Owner, TransactionManager, Target);
  1979. }
  1980. /*}}}*/
  1981. void pkgAcqIndexMergeDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  1982. pkgAcquire::MethodConfig const * const Cnf)
  1983. {
  1984. if(Debug)
  1985. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  1986. Item::Done(Message, Hashes, Cnf);
  1987. string const FinalFile = GetPartialFileNameFromURI(Target.URI);
  1988. if (State == StateFetchDiff)
  1989. {
  1990. Rename(DestFile, GetMergeDiffsPatchFileName(FinalFile, patch.file));
  1991. // check if this is the last completed diff
  1992. State = StateDoneDiff;
  1993. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  1994. I != allPatches->end(); ++I)
  1995. if ((*I)->State != StateDoneDiff)
  1996. {
  1997. if(Debug)
  1998. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  1999. return;
  2000. }
  2001. // this is the last completed diff, so we are ready to apply now
  2002. State = StateApplyDiff;
  2003. // patching needs to be bootstrapped with the 'old' version
  2004. if (symlink(GetFinalFilename().c_str(), FinalFile.c_str()) != 0)
  2005. {
  2006. Failed("Link creation of " + FinalFile + " to " + GetFinalFilename() + " failed", NULL);
  2007. return;
  2008. }
  2009. if(Debug)
  2010. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  2011. Local = true;
  2012. Desc.URI = "rred:" + FinalFile;
  2013. QueueURI(Desc);
  2014. SetActiveSubprocess("rred");
  2015. return;
  2016. }
  2017. // success in download/apply all diffs, clean up
  2018. else if (State == StateApplyDiff)
  2019. {
  2020. // move the result into place
  2021. std::string const Final = GetFinalFilename();
  2022. if(Debug)
  2023. std::clog << "Queue patched file in place: " << std::endl
  2024. << DestFile << " -> " << Final << std::endl;
  2025. // queue for copy by the transaction manager
  2026. TransactionManager->TransactionStageCopy(this, DestFile, Final);
  2027. // ensure the ed's are gone regardless of list-cleanup
  2028. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2029. I != allPatches->end(); ++I)
  2030. {
  2031. std::string const PartialFile = GetPartialFileNameFromURI(Target.URI);
  2032. std::string const patch = GetMergeDiffsPatchFileName(PartialFile, (*I)->patch.file);
  2033. unlink(patch.c_str());
  2034. }
  2035. unlink(FinalFile.c_str());
  2036. // all set and done
  2037. Complete = true;
  2038. if(Debug)
  2039. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  2040. }
  2041. }
  2042. /*}}}*/
  2043. std::string pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
  2044. {
  2045. if(State != StateApplyDiff)
  2046. return pkgAcqBaseIndex::Custom600Headers();
  2047. std::ostringstream patchhashes;
  2048. unsigned int seen_patches = 0;
  2049. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2050. I != allPatches->end(); ++I)
  2051. {
  2052. HashStringList const ExpectedHashes = (*I)->patch.patch_hashes;
  2053. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  2054. patchhashes << "\nPatch-" << seen_patches << "-" << hs->HashType() << "-Hash: " << hs->HashValue();
  2055. ++seen_patches;
  2056. }
  2057. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  2058. return patchhashes.str();
  2059. }
  2060. /*}}}*/
  2061. // AcqIndex::AcqIndex - Constructor /*{{{*/
  2062. pkgAcqIndex::pkgAcqIndex(pkgAcquire * const Owner,
  2063. pkgAcqMetaBase * const TransactionManager,
  2064. IndexTarget const Target)
  2065. : pkgAcqBaseIndex(Owner, TransactionManager, Target)
  2066. {
  2067. // autoselect the compression method
  2068. AutoSelectCompression();
  2069. Init(Target.URI, Target.Description, Target.ShortDesc);
  2070. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  2071. std::clog << "New pkgIndex with TransactionManager "
  2072. << TransactionManager << std::endl;
  2073. }
  2074. /*}}}*/
  2075. // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
  2076. void pkgAcqIndex::AutoSelectCompression()
  2077. {
  2078. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  2079. CompressionExtensions = "";
  2080. if (TransactionManager->MetaIndexParser != NULL && TransactionManager->MetaIndexParser->Exists(Target.MetaKey))
  2081. {
  2082. for (std::vector<std::string>::const_iterator t = types.begin();
  2083. t != types.end(); ++t)
  2084. {
  2085. std::string CompressedMetaKey = string(Target.MetaKey).append(".").append(*t);
  2086. if (*t == "uncompressed" ||
  2087. TransactionManager->MetaIndexParser->Exists(CompressedMetaKey) == true)
  2088. CompressionExtensions.append(*t).append(" ");
  2089. }
  2090. }
  2091. else
  2092. {
  2093. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  2094. CompressionExtensions.append(*t).append(" ");
  2095. }
  2096. if (CompressionExtensions.empty() == false)
  2097. CompressionExtensions.erase(CompressionExtensions.end()-1);
  2098. }
  2099. /*}}}*/
  2100. // AcqIndex::Init - defered Constructor /*{{{*/
  2101. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  2102. string const &ShortDesc)
  2103. {
  2104. Stage = STAGE_DOWNLOAD;
  2105. DestFile = GetPartialFileNameFromURI(URI);
  2106. size_t const nextExt = CompressionExtensions.find(' ');
  2107. if (nextExt == std::string::npos)
  2108. {
  2109. CurrentCompressionExtension = CompressionExtensions;
  2110. CompressionExtensions.clear();
  2111. }
  2112. else
  2113. {
  2114. CurrentCompressionExtension = CompressionExtensions.substr(0, nextExt);
  2115. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  2116. }
  2117. if (CurrentCompressionExtension == "uncompressed")
  2118. {
  2119. Desc.URI = URI;
  2120. }
  2121. else if (unlikely(CurrentCompressionExtension.empty()))
  2122. return;
  2123. else
  2124. {
  2125. Desc.URI = URI + '.' + CurrentCompressionExtension;
  2126. DestFile = DestFile + '.' + CurrentCompressionExtension;
  2127. }
  2128. if(TransactionManager->MetaIndexParser != NULL)
  2129. InitByHashIfNeeded();
  2130. Desc.Description = URIDesc;
  2131. Desc.Owner = this;
  2132. Desc.ShortDesc = ShortDesc;
  2133. QueueURI(Desc);
  2134. }
  2135. /*}}}*/
  2136. // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
  2137. void pkgAcqIndex::InitByHashIfNeeded()
  2138. {
  2139. // TODO:
  2140. // - (maybe?) add support for by-hash into the sources.list as flag
  2141. // - make apt-ftparchive generate the hashes (and expire?)
  2142. std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
  2143. if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
  2144. _config->FindB(HostKnob, false) == true ||
  2145. TransactionManager->MetaIndexParser->GetSupportsAcquireByHash())
  2146. {
  2147. HashStringList const Hashes = GetExpectedHashes();
  2148. if(Hashes.usable())
  2149. {
  2150. // FIXME: should we really use the best hash here? or a fixed one?
  2151. HashString const * const TargetHash = Hashes.find("");
  2152. std::string const ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  2153. size_t const trailing_slash = Desc.URI.find_last_of("/");
  2154. Desc.URI = Desc.URI.replace(
  2155. trailing_slash,
  2156. Desc.URI.substr(trailing_slash+1).size()+1,
  2157. ByHash);
  2158. } else {
  2159. _error->Warning(
  2160. "Fetching ByHash requested but can not find record for %s",
  2161. GetMetaKey().c_str());
  2162. }
  2163. }
  2164. }
  2165. /*}}}*/
  2166. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2167. // ---------------------------------------------------------------------
  2168. /* The only header we use is the last-modified header. */
  2169. string pkgAcqIndex::Custom600Headers() const
  2170. {
  2171. string Final = GetFinalFilename();
  2172. string msg = "\nIndex-File: true";
  2173. struct stat Buf;
  2174. if (stat(Final.c_str(),&Buf) == 0)
  2175. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  2176. if(Target.IsOptional)
  2177. msg += "\nFail-Ignore: true";
  2178. return msg;
  2179. }
  2180. /*}}}*/
  2181. // AcqIndex::Failed - getting the indexfile failed /*{{{*/
  2182. void pkgAcqIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2183. {
  2184. Item::Failed(Message,Cnf);
  2185. // authorisation matches will not be fixed by other compression types
  2186. if (Status != StatAuthError)
  2187. {
  2188. if (CompressionExtensions.empty() == false)
  2189. {
  2190. Init(Target.URI, Desc.Description, Desc.ShortDesc);
  2191. Status = StatIdle;
  2192. return;
  2193. }
  2194. }
  2195. if(Target.IsOptional && GetExpectedHashes().empty() && Stage == STAGE_DOWNLOAD)
  2196. Status = StatDone;
  2197. else
  2198. TransactionManager->AbortTransaction();
  2199. }
  2200. /*}}}*/
  2201. // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
  2202. void pkgAcqIndex::ReverifyAfterIMS()
  2203. {
  2204. // update destfile to *not* include the compression extension when doing
  2205. // a reverify (as its uncompressed on disk already)
  2206. DestFile = GetCompressedFileName(Target.URI, GetPartialFileNameFromURI(Target.URI), CurrentCompressionExtension);
  2207. // copy FinalFile into partial/ so that we check the hash again
  2208. string FinalFile = GetFinalFilename();
  2209. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2210. Desc.URI = "copy:" + FinalFile;
  2211. QueueURI(Desc);
  2212. }
  2213. /*}}}*/
  2214. // AcqIndex::Done - Finished a fetch /*{{{*/
  2215. // ---------------------------------------------------------------------
  2216. /* This goes through a number of states.. On the initial fetch the
  2217. method could possibly return an alternate filename which points
  2218. to the uncompressed version of the file. If this is so the file
  2219. is copied into the partial directory. In all other cases the file
  2220. is decompressed with a compressed uri. */
  2221. void pkgAcqIndex::Done(string const &Message,
  2222. HashStringList const &Hashes,
  2223. pkgAcquire::MethodConfig const * const Cfg)
  2224. {
  2225. Item::Done(Message,Hashes,Cfg);
  2226. switch(Stage)
  2227. {
  2228. case STAGE_DOWNLOAD:
  2229. StageDownloadDone(Message, Hashes, Cfg);
  2230. break;
  2231. case STAGE_DECOMPRESS_AND_VERIFY:
  2232. StageDecompressDone(Message, Hashes, Cfg);
  2233. break;
  2234. }
  2235. }
  2236. /*}}}*/
  2237. // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
  2238. void pkgAcqIndex::StageDownloadDone(string const &Message, HashStringList const &,
  2239. pkgAcquire::MethodConfig const * const)
  2240. {
  2241. Complete = true;
  2242. // Handle the unzipd case
  2243. string FileName = LookupTag(Message,"Alt-Filename");
  2244. if (FileName.empty() == false)
  2245. {
  2246. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2247. Local = true;
  2248. DestFile += ".decomp";
  2249. Desc.URI = "copy:" + FileName;
  2250. QueueURI(Desc);
  2251. SetActiveSubprocess("copy");
  2252. return;
  2253. }
  2254. FileName = LookupTag(Message,"Filename");
  2255. if (FileName.empty() == true)
  2256. {
  2257. Status = StatError;
  2258. ErrorText = "Method gave a blank filename";
  2259. }
  2260. // Methods like e.g. "file:" will give us a (compressed) FileName that is
  2261. // not the "DestFile" we set, in this case we uncompress from the local file
  2262. if (FileName != DestFile)
  2263. Local = true;
  2264. else
  2265. EraseFileName = FileName;
  2266. // we need to verify the file against the current Release file again
  2267. // on if-modfied-since hit to avoid a stale attack against us
  2268. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2269. {
  2270. // The files timestamp matches, reverify by copy into partial/
  2271. EraseFileName = "";
  2272. ReverifyAfterIMS();
  2273. return;
  2274. }
  2275. // If we have compressed indexes enabled, queue for hash verification
  2276. if (_config->FindB("Acquire::GzipIndexes",false))
  2277. {
  2278. DestFile = GetPartialFileNameFromURI(Target.URI + '.' + CurrentCompressionExtension);
  2279. EraseFileName = "";
  2280. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2281. Desc.URI = "copy:" + FileName;
  2282. QueueURI(Desc);
  2283. SetActiveSubprocess("copy");
  2284. return;
  2285. }
  2286. // get the binary name for your used compression type
  2287. string decompProg;
  2288. if(CurrentCompressionExtension == "uncompressed")
  2289. decompProg = "copy";
  2290. else
  2291. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
  2292. if(decompProg.empty() == true)
  2293. {
  2294. _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
  2295. return;
  2296. }
  2297. // queue uri for the next stage
  2298. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2299. DestFile += ".decomp";
  2300. Desc.URI = decompProg + ":" + FileName;
  2301. QueueURI(Desc);
  2302. SetActiveSubprocess(decompProg);
  2303. }
  2304. /*}}}*/
  2305. // AcqIndex::StageDecompressDone - Final verification /*{{{*/
  2306. void pkgAcqIndex::StageDecompressDone(string const &,
  2307. HashStringList const &,
  2308. pkgAcquire::MethodConfig const * const)
  2309. {
  2310. // Done, queue for rename on transaction finished
  2311. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  2312. return;
  2313. }
  2314. /*}}}*/
  2315. // AcqArchive::AcqArchive - Constructor /*{{{*/
  2316. // ---------------------------------------------------------------------
  2317. /* This just sets up the initial fetch environment and queues the first
  2318. possibilitiy */
  2319. pkgAcqArchive::pkgAcqArchive(pkgAcquire * const Owner,pkgSourceList * const Sources,
  2320. pkgRecords * const Recs,pkgCache::VerIterator const &Version,
  2321. string &StoreFilename) :
  2322. Item(Owner), LocalSource(false), Version(Version), Sources(Sources), Recs(Recs),
  2323. StoreFilename(StoreFilename), Vf(Version.FileList()),
  2324. Trusted(false)
  2325. {
  2326. Retries = _config->FindI("Acquire::Retries",0);
  2327. if (Version.Arch() == 0)
  2328. {
  2329. _error->Error(_("I wasn't able to locate a file for the %s package. "
  2330. "This might mean you need to manually fix this package. "
  2331. "(due to missing arch)"),
  2332. Version.ParentPkg().FullName().c_str());
  2333. return;
  2334. }
  2335. /* We need to find a filename to determine the extension. We make the
  2336. assumption here that all the available sources for this version share
  2337. the same extension.. */
  2338. // Skip not source sources, they do not have file fields.
  2339. for (; Vf.end() == false; ++Vf)
  2340. {
  2341. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  2342. continue;
  2343. break;
  2344. }
  2345. // Does not really matter here.. we are going to fail out below
  2346. if (Vf.end() != true)
  2347. {
  2348. // If this fails to get a file name we will bomb out below.
  2349. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2350. if (_error->PendingError() == true)
  2351. return;
  2352. // Generate the final file name as: package_version_arch.foo
  2353. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  2354. QuoteString(Version.VerStr(),"_:") + '_' +
  2355. QuoteString(Version.Arch(),"_:.") +
  2356. "." + flExtension(Parse.FileName());
  2357. }
  2358. // check if we have one trusted source for the package. if so, switch
  2359. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  2360. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  2361. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  2362. bool seenUntrusted = false;
  2363. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  2364. {
  2365. pkgIndexFile *Index;
  2366. if (Sources->FindIndex(i.File(),Index) == false)
  2367. continue;
  2368. if (debugAuth == true)
  2369. std::cerr << "Checking index: " << Index->Describe()
  2370. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  2371. if (Index->IsTrusted() == true)
  2372. {
  2373. Trusted = true;
  2374. if (allowUnauth == false)
  2375. break;
  2376. }
  2377. else
  2378. seenUntrusted = true;
  2379. }
  2380. // "allow-unauthenticated" restores apts old fetching behaviour
  2381. // that means that e.g. unauthenticated file:// uris are higher
  2382. // priority than authenticated http:// uris
  2383. if (allowUnauth == true && seenUntrusted == true)
  2384. Trusted = false;
  2385. // Select a source
  2386. if (QueueNext() == false && _error->PendingError() == false)
  2387. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  2388. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  2389. }
  2390. /*}}}*/
  2391. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  2392. // ---------------------------------------------------------------------
  2393. /* This queues the next available file version for download. It checks if
  2394. the archive is already available in the cache and stashs the MD5 for
  2395. checking later. */
  2396. bool pkgAcqArchive::QueueNext()
  2397. {
  2398. for (; Vf.end() == false; ++Vf)
  2399. {
  2400. pkgCache::PkgFileIterator const PkgF = Vf.File();
  2401. // Ignore not source sources
  2402. if ((PkgF->Flags & pkgCache::Flag::NotSource) != 0)
  2403. continue;
  2404. // Try to cross match against the source list
  2405. pkgIndexFile *Index;
  2406. if (Sources->FindIndex(PkgF, Index) == false)
  2407. continue;
  2408. LocalSource = (PkgF->Flags & pkgCache::Flag::LocalSource) == pkgCache::Flag::LocalSource;
  2409. // only try to get a trusted package from another source if that source
  2410. // is also trusted
  2411. if(Trusted && !Index->IsTrusted())
  2412. continue;
  2413. // Grab the text package record
  2414. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2415. if (_error->PendingError() == true)
  2416. return false;
  2417. string PkgFile = Parse.FileName();
  2418. ExpectedHashes = Parse.Hashes();
  2419. if (PkgFile.empty() == true)
  2420. return _error->Error(_("The package index files are corrupted. No Filename: "
  2421. "field for package %s."),
  2422. Version.ParentPkg().Name());
  2423. Desc.URI = Index->ArchiveURI(PkgFile);
  2424. Desc.Description = Index->ArchiveInfo(Version);
  2425. Desc.Owner = this;
  2426. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  2427. // See if we already have the file. (Legacy filenames)
  2428. FileSize = Version->Size;
  2429. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  2430. struct stat Buf;
  2431. if (stat(FinalFile.c_str(),&Buf) == 0)
  2432. {
  2433. // Make sure the size matches
  2434. if ((unsigned long long)Buf.st_size == Version->Size)
  2435. {
  2436. Complete = true;
  2437. Local = true;
  2438. Status = StatDone;
  2439. StoreFilename = DestFile = FinalFile;
  2440. return true;
  2441. }
  2442. /* Hmm, we have a file and its size does not match, this means it is
  2443. an old style mismatched arch */
  2444. unlink(FinalFile.c_str());
  2445. }
  2446. // Check it again using the new style output filenames
  2447. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2448. if (stat(FinalFile.c_str(),&Buf) == 0)
  2449. {
  2450. // Make sure the size matches
  2451. if ((unsigned long long)Buf.st_size == Version->Size)
  2452. {
  2453. Complete = true;
  2454. Local = true;
  2455. Status = StatDone;
  2456. StoreFilename = DestFile = FinalFile;
  2457. return true;
  2458. }
  2459. /* Hmm, we have a file and its size does not match, this shouldn't
  2460. happen.. */
  2461. unlink(FinalFile.c_str());
  2462. }
  2463. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2464. // Check the destination file
  2465. if (stat(DestFile.c_str(),&Buf) == 0)
  2466. {
  2467. // Hmm, the partial file is too big, erase it
  2468. if ((unsigned long long)Buf.st_size > Version->Size)
  2469. unlink(DestFile.c_str());
  2470. else
  2471. PartialSize = Buf.st_size;
  2472. }
  2473. // Disables download of archives - useful if no real installation follows,
  2474. // e.g. if we are just interested in proposed installation order
  2475. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2476. {
  2477. Complete = true;
  2478. Local = true;
  2479. Status = StatDone;
  2480. StoreFilename = DestFile = FinalFile;
  2481. return true;
  2482. }
  2483. // Create the item
  2484. Local = false;
  2485. QueueURI(Desc);
  2486. ++Vf;
  2487. return true;
  2488. }
  2489. return false;
  2490. }
  2491. /*}}}*/
  2492. // AcqArchive::Done - Finished fetching /*{{{*/
  2493. // ---------------------------------------------------------------------
  2494. /* */
  2495. void pkgAcqArchive::Done(string const &Message, HashStringList const &Hashes,
  2496. pkgAcquire::MethodConfig const * const Cfg)
  2497. {
  2498. Item::Done(Message, Hashes, Cfg);
  2499. // Grab the output filename
  2500. string FileName = LookupTag(Message,"Filename");
  2501. if (FileName.empty() == true)
  2502. {
  2503. Status = StatError;
  2504. ErrorText = "Method gave a blank filename";
  2505. return;
  2506. }
  2507. // Reference filename
  2508. if (FileName != DestFile)
  2509. {
  2510. StoreFilename = DestFile = FileName;
  2511. Local = true;
  2512. Complete = true;
  2513. return;
  2514. }
  2515. // Done, move it into position
  2516. string const FinalFile = GetFinalFilename();
  2517. Rename(DestFile,FinalFile);
  2518. StoreFilename = DestFile = FinalFile;
  2519. Complete = true;
  2520. }
  2521. /*}}}*/
  2522. // AcqArchive::Failed - Failure handler /*{{{*/
  2523. // ---------------------------------------------------------------------
  2524. /* Here we try other sources */
  2525. void pkgAcqArchive::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2526. {
  2527. Item::Failed(Message,Cnf);
  2528. /* We don't really want to retry on failed media swaps, this prevents
  2529. that. An interesting observation is that permanent failures are not
  2530. recorded. */
  2531. if (Cnf->Removable == true &&
  2532. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2533. {
  2534. // Vf = Version.FileList();
  2535. while (Vf.end() == false) ++Vf;
  2536. StoreFilename = string();
  2537. return;
  2538. }
  2539. Status = StatIdle;
  2540. if (QueueNext() == false)
  2541. {
  2542. // This is the retry counter
  2543. if (Retries != 0 &&
  2544. Cnf->LocalOnly == false &&
  2545. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2546. {
  2547. Retries--;
  2548. Vf = Version.FileList();
  2549. if (QueueNext() == true)
  2550. return;
  2551. }
  2552. StoreFilename = string();
  2553. Status = StatError;
  2554. }
  2555. }
  2556. /*}}}*/
  2557. APT_PURE bool pkgAcqArchive::IsTrusted() const /*{{{*/
  2558. {
  2559. return Trusted;
  2560. }
  2561. /*}}}*/
  2562. void pkgAcqArchive::Finished() /*{{{*/
  2563. {
  2564. if (Status == pkgAcquire::Item::StatDone &&
  2565. Complete == true)
  2566. return;
  2567. StoreFilename = string();
  2568. }
  2569. /*}}}*/
  2570. std::string pkgAcqArchive::DescURI() const /*{{{*/
  2571. {
  2572. return Desc.URI;
  2573. }
  2574. /*}}}*/
  2575. std::string pkgAcqArchive::ShortDesc() const /*{{{*/
  2576. {
  2577. return Desc.ShortDesc;
  2578. }
  2579. /*}}}*/
  2580. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  2581. pkgAcqFile::pkgAcqFile(pkgAcquire * const Owner,string const &URI, HashStringList const &Hashes,
  2582. unsigned long long const Size,string const &Dsc,string const &ShortDesc,
  2583. const string &DestDir, const string &DestFilename,
  2584. bool const IsIndexFile) :
  2585. Item(Owner), IsIndexFile(IsIndexFile), ExpectedHashes(Hashes)
  2586. {
  2587. Retries = _config->FindI("Acquire::Retries",0);
  2588. if(!DestFilename.empty())
  2589. DestFile = DestFilename;
  2590. else if(!DestDir.empty())
  2591. DestFile = DestDir + "/" + flNotDir(URI);
  2592. else
  2593. DestFile = flNotDir(URI);
  2594. // Create the item
  2595. Desc.URI = URI;
  2596. Desc.Description = Dsc;
  2597. Desc.Owner = this;
  2598. // Set the short description to the archive component
  2599. Desc.ShortDesc = ShortDesc;
  2600. // Get the transfer sizes
  2601. FileSize = Size;
  2602. struct stat Buf;
  2603. if (stat(DestFile.c_str(),&Buf) == 0)
  2604. {
  2605. // Hmm, the partial file is too big, erase it
  2606. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  2607. unlink(DestFile.c_str());
  2608. else
  2609. PartialSize = Buf.st_size;
  2610. }
  2611. QueueURI(Desc);
  2612. }
  2613. /*}}}*/
  2614. // AcqFile::Done - Item downloaded OK /*{{{*/
  2615. void pkgAcqFile::Done(string const &Message,HashStringList const &CalcHashes,
  2616. pkgAcquire::MethodConfig const * const Cnf)
  2617. {
  2618. Item::Done(Message,CalcHashes,Cnf);
  2619. string FileName = LookupTag(Message,"Filename");
  2620. if (FileName.empty() == true)
  2621. {
  2622. Status = StatError;
  2623. ErrorText = "Method gave a blank filename";
  2624. return;
  2625. }
  2626. Complete = true;
  2627. // The files timestamp matches
  2628. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2629. return;
  2630. // We have to copy it into place
  2631. if (FileName != DestFile)
  2632. {
  2633. Local = true;
  2634. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  2635. Cnf->Removable == true)
  2636. {
  2637. Desc.URI = "copy:" + FileName;
  2638. QueueURI(Desc);
  2639. return;
  2640. }
  2641. // Erase the file if it is a symlink so we can overwrite it
  2642. struct stat St;
  2643. if (lstat(DestFile.c_str(),&St) == 0)
  2644. {
  2645. if (S_ISLNK(St.st_mode) != 0)
  2646. unlink(DestFile.c_str());
  2647. }
  2648. // Symlink the file
  2649. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2650. {
  2651. _error->PushToStack();
  2652. _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
  2653. std::stringstream msg;
  2654. _error->DumpErrors(msg);
  2655. _error->RevertToStack();
  2656. ErrorText = msg.str();
  2657. Status = StatError;
  2658. Complete = false;
  2659. }
  2660. }
  2661. }
  2662. /*}}}*/
  2663. // AcqFile::Failed - Failure handler /*{{{*/
  2664. // ---------------------------------------------------------------------
  2665. /* Here we try other sources */
  2666. void pkgAcqFile::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
  2667. {
  2668. Item::Failed(Message,Cnf);
  2669. // This is the retry counter
  2670. if (Retries != 0 &&
  2671. Cnf->LocalOnly == false &&
  2672. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2673. {
  2674. --Retries;
  2675. QueueURI(Desc);
  2676. Status = StatIdle;
  2677. return;
  2678. }
  2679. }
  2680. /*}}}*/
  2681. string pkgAcqFile::Custom600Headers() const /*{{{*/
  2682. {
  2683. if (IsIndexFile)
  2684. return "\nIndex-File: true";
  2685. return "";
  2686. }
  2687. /*}}}*/