1 // -*- mode: cpp; mode: fold -*-
3 // $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
4 /* ######################################################################
6 Acquire Item - Item to acquire
8 Each item can download to exactly one file at a time. This means you
9 cannot create an item that fetches two uri's to two files at the same
10 time. The pkgAcqIndex class creates a second class upon instantiation
11 to fetch the other index files because of this.
13 ##################################################################### */
15 // Include Files /*{{{*/
18 #include <apt-pkg/acquire-item.h>
19 #include <apt-pkg/configuration.h>
20 #include <apt-pkg/aptconfiguration.h>
21 #include <apt-pkg/sourcelist.h>
22 #include <apt-pkg/error.h>
23 #include <apt-pkg/strutl.h>
24 #include <apt-pkg/fileutl.h>
25 #include <apt-pkg/tagfile.h>
26 #include <apt-pkg/metaindex.h>
27 #include <apt-pkg/acquire.h>
28 #include <apt-pkg/hashes.h>
29 #include <apt-pkg/indexfile.h>
30 #include <apt-pkg/pkgcache.h>
31 #include <apt-pkg/cacheiterators.h>
32 #include <apt-pkg/pkgrecords.h>
33 #include <apt-pkg/gpgv.h>
56 static void printHashSumComparison(std::string
const &URI
, HashStringList
const &Expected
, HashStringList
const &Actual
) /*{{{*/
58 if (_config
->FindB("Debug::Acquire::HashSumMismatch", false) == false)
60 std::cerr
<< std::endl
<< URI
<< ":" << std::endl
<< " Expected Hash: " << std::endl
;
61 for (HashStringList::const_iterator hs
= Expected
.begin(); hs
!= Expected
.end(); ++hs
)
62 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
63 std::cerr
<< " Actual Hash: " << std::endl
;
64 for (HashStringList::const_iterator hs
= Actual
.begin(); hs
!= Actual
.end(); ++hs
)
65 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
68 static std::string
GetPartialFileName(std::string
const &file
) /*{{{*/
70 std::string DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
75 static std::string
GetPartialFileNameFromURI(std::string
const &uri
) /*{{{*/
77 return GetPartialFileName(URItoFileName(uri
));
80 static std::string
GetFinalFileNameFromURI(std::string
const &uri
) /*{{{*/
82 return _config
->FindDir("Dir::State::lists") + URItoFileName(uri
);
85 static std::string
GetKeepCompressedFileName(std::string file
, IndexTarget
const &Target
)/*{{{*/
87 if (Target
.KeepCompressed
== false)
90 std::string
const KeepCompressedAs
= Target
.Option(IndexTarget::KEEPCOMPRESSEDAS
);
91 if (KeepCompressedAs
.empty() == false)
93 std::string
const ext
= KeepCompressedAs
.substr(0, KeepCompressedAs
.find(' '));
94 if (ext
!= "uncompressed")
95 file
.append(".").append(ext
);
100 static std::string
GetMergeDiffsPatchFileName(std::string
const &Final
, std::string
const &Patch
)/*{{{*/
102 // rred expects the patch as $FinalFile.ed.$patchname.gz
103 return Final
+ ".ed." + Patch
+ ".gz";
106 static std::string
GetDiffsPatchFileName(std::string
const &Final
) /*{{{*/
108 // rred expects the patch as $FinalFile.ed
109 return Final
+ ".ed";
112 static std::string
GetExistingFilename(std::string
const &File
) /*{{{*/
114 if (RealFileExists(File
))
116 for (auto const &type
: APT::Configuration::getCompressorExtensions())
118 std::string
const Final
= File
+ type
;
119 if (RealFileExists(Final
))
125 static std::string
GetDiffIndexFileName(std::string
const &Name
) /*{{{*/
127 return Name
+ ".diff/Index";
130 static std::string
GetDiffIndexURI(IndexTarget
const &Target
) /*{{{*/
132 return Target
.URI
+ ".diff/Index";
136 static void ReportMirrorFailureToCentral(pkgAcquire::Item
const &I
, std::string
const &FailCode
, std::string
const &Details
)/*{{{*/
138 // we only act if a mirror was used at all
139 if(I
.UsedMirror
.empty())
142 std::cerr
<< "\nReportMirrorFailure: "
144 << " Uri: " << DescURI()
146 << FailCode
<< std::endl
;
148 string
const report
= _config
->Find("Methods::Mirror::ProblemReporting",
149 LIBEXEC_DIR
"/apt-report-mirror-failure");
150 if(!FileExists(report
))
153 std::vector
<char const*> const Args
= {
155 I
.UsedMirror
.c_str(),
162 pid_t pid
= ExecFork();
165 _error
->Error("ReportMirrorFailure Fork failed");
170 execvp(Args
[0], (char**)Args
.data());
171 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
174 if(!ExecWait(pid
, "report-mirror-failure"))
175 _error
->Warning("Couldn't report problem to '%s'", report
.c_str());
179 static APT_NONNULL(2) bool MessageInsecureRepository(bool const isError
, char const * const msg
, std::string
const &repo
)/*{{{*/
182 strprintf(m
, msg
, repo
.c_str());
185 _error
->Error("%s", m
.c_str());
186 _error
->Notice("%s", _("Updating from such a repository can't be done securely, and is therefore disabled by default."));
190 _error
->Warning("%s", m
.c_str());
191 _error
->Notice("%s", _("Data from such a repository can't be authenticated and is therefore potentially dangerous to use."));
193 _error
->Notice("%s", _("See apt-secure(8) manpage for repository creation and user configuration details."));
197 // AllowInsecureRepositories /*{{{*/
198 enum class InsecureType
{ UNSIGNED
, WEAK
, NORELEASE
};
199 static bool TargetIsAllowedToBe(IndexTarget
const &Target
, InsecureType
const type
)
201 if (_config
->FindB("Acquire::AllowInsecureRepositories"))
204 if (Target
.OptionBool(IndexTarget::ALLOW_INSECURE
))
209 case InsecureType::UNSIGNED
: break;
210 case InsecureType::NORELEASE
: break;
211 case InsecureType::WEAK
:
212 if (_config
->FindB("Acquire::AllowWeakRepositories"))
214 if (Target
.OptionBool(IndexTarget::ALLOW_WEAK
))
220 static bool APT_NONNULL(3, 4, 5) AllowInsecureRepositories(InsecureType
const msg
, std::string
const &repo
,
221 metaIndex
const * const MetaIndexParser
, pkgAcqMetaClearSig
* const TransactionManager
, pkgAcquire::Item
* const I
)
223 // we skip weak downgrades as its unlikely that a repository gets really weaker –
224 // its more realistic that apt got pickier in a newer version
225 if (msg
!= InsecureType::WEAK
)
227 std::string
const FinalInRelease
= TransactionManager
->GetFinalFilename();
228 std::string
const FinalReleasegpg
= FinalInRelease
.substr(0, FinalInRelease
.length() - strlen("InRelease")) + "Release.gpg";
229 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
231 char const * msgstr
= nullptr;
234 case InsecureType::UNSIGNED
: msgstr
= _("The repository '%s' is no longer signed."); break;
235 case InsecureType::NORELEASE
: msgstr
= _("The repository '%s' does no longer have a Release file."); break;
236 case InsecureType::WEAK
: /* unreachable */ break;
238 if (_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories") ||
239 TransactionManager
->Target
.OptionBool(IndexTarget::ALLOW_DOWNGRADE_TO_INSECURE
))
241 // meh, the users wants to take risks (we still mark the packages
242 // from this repository as unauthenticated)
243 _error
->Warning(msgstr
, repo
.c_str());
244 _error
->Warning(_("This is normally not allowed, but the option "
245 "Acquire::AllowDowngradeToInsecureRepositories was "
246 "given to override it."));
248 MessageInsecureRepository(true, msgstr
, repo
);
249 TransactionManager
->AbortTransaction();
250 I
->Status
= pkgAcquire::Item::StatError
;
256 if(MetaIndexParser
->GetTrusted() == metaIndex::TRI_YES
)
259 char const * msgstr
= nullptr;
262 case InsecureType::UNSIGNED
: msgstr
= _("The repository '%s' is not signed."); break;
263 case InsecureType::NORELEASE
: msgstr
= _("The repository '%s' does not have a Release file."); break;
264 case InsecureType::WEAK
: msgstr
= _("The repository '%s' provides only weak security information."); break;
267 if (TargetIsAllowedToBe(TransactionManager
->Target
, msg
) == true)
269 //MessageInsecureRepository(false, msgstr, repo);
273 MessageInsecureRepository(true, msgstr
, repo
);
274 TransactionManager
->AbortTransaction();
275 I
->Status
= pkgAcquire::Item::StatError
;
279 static HashStringList
GetExpectedHashesFromFor(metaIndex
* const Parser
, std::string
const &MetaKey
)/*{{{*/
282 return HashStringList();
283 metaIndex::checkSum
* const R
= Parser
->Lookup(MetaKey
);
285 return HashStringList();
290 // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
291 /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
292 It is best to implement it as broadly as possible, while ::HashesRequired defaults
293 to true and should be as restrictive as possible for false cases. Note that if
294 a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
295 ::HashesRequired is called to evaluate if its okay to have no hashes. */
296 APT_CONST
bool pkgAcqTransactionItem::HashesRequired() const
298 /* signed repositories obviously have a parser and good hashes.
299 unsigned repositories, too, as even if we can't trust them for security,
300 we can at least trust them for integrity of the download itself.
301 Only repositories without a Release file can (obviously) not have
302 hashes – and they are very uncommon and strongly discouraged */
303 if (TransactionManager
->MetaIndexParser
->GetLoadedSuccessfully() != metaIndex::TRI_YES
)
305 if (TargetIsAllowedToBe(Target
, InsecureType::WEAK
))
307 /* If we allow weak hashes, we check that we have some (weak) and then
308 declare hashes not needed. That will tip us in the right direction
309 as if hashes exist, they will be used, even if not required */
310 auto const hsl
= GetExpectedHashes();
313 if (hsl
.empty() == false)
318 HashStringList
pkgAcqTransactionItem::GetExpectedHashes() const
320 return GetExpectedHashesFor(GetMetaKey());
323 APT_CONST
bool pkgAcqMetaBase::HashesRequired() const
325 // Release and co have no hashes 'by design'.
328 HashStringList
pkgAcqMetaBase::GetExpectedHashes() const
330 return HashStringList();
333 APT_CONST
bool pkgAcqIndexDiffs::HashesRequired() const
335 /* We can't check hashes of rred result as we don't know what the
336 hash of the file will be. We just know the hash of the patch(es),
337 the hash of the file they will apply on and the hash of the resulting
339 if (State
== StateFetchDiff
)
343 HashStringList
pkgAcqIndexDiffs::GetExpectedHashes() const
345 if (State
== StateFetchDiff
)
346 return available_patches
[0].download_hashes
;
347 return HashStringList();
350 APT_CONST
bool pkgAcqIndexMergeDiffs::HashesRequired() const
352 /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
353 we can check the rred result after all patches are applied as
354 we know the expected result rather than potentially apply more patches */
355 if (State
== StateFetchDiff
)
357 return State
== StateApplyDiff
;
359 HashStringList
pkgAcqIndexMergeDiffs::GetExpectedHashes() const
361 if (State
== StateFetchDiff
)
362 return patch
.download_hashes
;
363 else if (State
== StateApplyDiff
)
364 return GetExpectedHashesFor(Target
.MetaKey
);
365 return HashStringList();
368 APT_CONST
bool pkgAcqArchive::HashesRequired() const
370 return LocalSource
== false;
372 HashStringList
pkgAcqArchive::GetExpectedHashes() const
374 // figured out while parsing the records
375 return ExpectedHashes
;
378 APT_CONST
bool pkgAcqFile::HashesRequired() const
380 // supplied as parameter at creation time, so the caller decides
381 return ExpectedHashes
.usable();
383 HashStringList
pkgAcqFile::GetExpectedHashes() const
385 return ExpectedHashes
;
388 // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
389 bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc
&Item
)
391 Owner
->Enqueue(Item
);
394 /* The idea here is that an item isn't queued if it exists on disk and the
395 transition manager was a hit as this means that the files it contains
396 the checksums for can't be updated either (or they are and we are asking
397 for a hashsum mismatch to happen which helps nobody) */
398 bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc
&Item
)
400 if (TransactionManager
->State
!= TransactionStarted
)
402 if (_config
->FindB("Debug::Acquire::Transaction", false))
403 std::clog
<< "Skip " << Target
.URI
<< " as transaction was already dealt with!" << std::endl
;
406 std::string
const FinalFile
= GetFinalFilename();
407 if (TransactionManager
->IMSHit
== true && FileExists(FinalFile
) == true)
409 PartialFile
= DestFile
= FinalFile
;
413 // If we got the InRelease file via a mirror, pick all indexes directly from this mirror, too
414 if (TransactionManager
->BaseURI
.empty() == false && UsedMirror
.empty() &&
415 URI::SiteOnly(Item
.URI
) != URI::SiteOnly(TransactionManager
->BaseURI
))
417 // this ensures we rewrite only once and only the first step
418 auto const OldBaseURI
= Target
.Option(IndexTarget::BASE_URI
);
419 if (OldBaseURI
.empty() == false && APT::String::Startswith(Item
.URI
, OldBaseURI
))
421 auto const ExtraPath
= Item
.URI
.substr(OldBaseURI
.length());
422 Item
.URI
= flCombine(TransactionManager
->BaseURI
, ExtraPath
);
423 UsedMirror
= TransactionManager
->UsedMirror
;
424 if (Item
.Description
.find(" ") != string::npos
)
425 Item
.Description
.replace(0, Item
.Description
.find(" "), UsedMirror
);
428 return pkgAcquire::Item::QueueURI(Item
);
430 /* The transition manager InRelease itself (or its older sisters-in-law
431 Release & Release.gpg) is always queued as this allows us to rerun gpgv
432 on it to verify that we aren't stalled with old files */
433 bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc
&Item
)
435 return pkgAcquire::Item::QueueURI(Item
);
437 /* the Diff/Index needs to queue also the up-to-date complete index file
438 to ensure that the list cleaner isn't eating it */
439 bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc
&Item
)
441 if (pkgAcqTransactionItem::QueueURI(Item
) == true)
447 // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
448 std::string
pkgAcquire::Item::GetFinalFilename() const
450 // Beware: Desc.URI is modified by redirections
451 return GetFinalFileNameFromURI(Desc
.URI
);
453 std::string
pkgAcqDiffIndex::GetFinalFilename() const
455 std::string
const FinalFile
= GetFinalFileNameFromURI(GetDiffIndexURI(Target
));
456 // we don't want recompress, so lets keep whatever we got
457 if (CurrentCompressionExtension
== "uncompressed")
459 return FinalFile
+ "." + CurrentCompressionExtension
;
461 std::string
pkgAcqIndex::GetFinalFilename() const
463 std::string
const FinalFile
= GetFinalFileNameFromURI(Target
.URI
);
464 return GetKeepCompressedFileName(FinalFile
, Target
);
466 std::string
pkgAcqMetaSig::GetFinalFilename() const
468 return GetFinalFileNameFromURI(Target
.URI
);
470 std::string
pkgAcqBaseIndex::GetFinalFilename() const
472 return GetFinalFileNameFromURI(Target
.URI
);
474 std::string
pkgAcqMetaBase::GetFinalFilename() const
476 return GetFinalFileNameFromURI(Target
.URI
);
478 std::string
pkgAcqArchive::GetFinalFilename() const
480 return _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
483 // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
484 std::string
pkgAcqTransactionItem::GetMetaKey() const
486 return Target
.MetaKey
;
488 std::string
pkgAcqIndex::GetMetaKey() const
490 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
|| CurrentCompressionExtension
== "uncompressed")
491 return Target
.MetaKey
;
492 return Target
.MetaKey
+ "." + CurrentCompressionExtension
;
494 std::string
pkgAcqDiffIndex::GetMetaKey() const
496 auto const metakey
= GetDiffIndexFileName(Target
.MetaKey
);
497 if (CurrentCompressionExtension
== "uncompressed")
499 return metakey
+ "." + CurrentCompressionExtension
;
502 //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
503 bool pkgAcqTransactionItem::TransactionState(TransactionStates
const state
)
505 bool const Debug
= _config
->FindB("Debug::Acquire::Transaction", false);
508 case TransactionStarted
: _error
->Fatal("Item %s changed to invalid transaction start state!", Target
.URI
.c_str()); break;
509 case TransactionAbort
:
511 std::clog
<< " Cancel: " << DestFile
<< std::endl
;
512 if (Status
== pkgAcquire::Item::StatIdle
)
514 Status
= pkgAcquire::Item::StatDone
;
518 case TransactionCommit
:
519 if(PartialFile
.empty() == false)
521 bool sameFile
= (PartialFile
== DestFile
);
522 // we use symlinks on IMS-Hit to avoid copies
523 if (RealFileExists(DestFile
))
526 if (lstat(PartialFile
.c_str(), &Buf
) != -1)
528 if (S_ISLNK(Buf
.st_mode
) && Buf
.st_size
> 0)
530 char partial
[Buf
.st_size
+ 1];
531 ssize_t
const sp
= readlink(PartialFile
.c_str(), partial
, Buf
.st_size
);
533 _error
->Errno("pkgAcqTransactionItem::TransactionState-sp", _("Failed to readlink %s"), PartialFile
.c_str());
537 sameFile
= (DestFile
== partial
);
542 _error
->Errno("pkgAcqTransactionItem::TransactionState-stat", _("Failed to stat %s"), PartialFile
.c_str());
544 if (sameFile
== false)
546 // ensure that even without lists-cleanup all compressions are nuked
547 std::string FinalFile
= GetFinalFileNameFromURI(Target
.URI
);
548 if (FileExists(FinalFile
))
551 std::clog
<< "rm " << FinalFile
<< " # " << DescURI() << std::endl
;
552 if (RemoveFile("TransactionStates-Cleanup", FinalFile
) == false)
555 for (auto const &ext
: APT::Configuration::getCompressorExtensions())
557 auto const Final
= FinalFile
+ ext
;
558 if (FileExists(Final
))
561 std::clog
<< "rm " << Final
<< " # " << DescURI() << std::endl
;
562 if (RemoveFile("TransactionStates-Cleanup", Final
) == false)
567 std::clog
<< "mv " << PartialFile
<< " -> "<< DestFile
<< " # " << DescURI() << std::endl
;
568 if (Rename(PartialFile
, DestFile
) == false)
571 else if(Debug
== true)
572 std::clog
<< "keep " << PartialFile
<< " # " << DescURI() << std::endl
;
576 std::clog
<< "rm " << DestFile
<< " # " << DescURI() << std::endl
;
577 if (RemoveFile("TransItem::TransactionCommit", DestFile
) == false)
584 bool pkgAcqMetaBase::TransactionState(TransactionStates
const state
)
586 // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
587 if (TransactionManager
->IMSHit
== false)
588 return pkgAcqTransactionItem::TransactionState(state
);
591 bool pkgAcqIndex::TransactionState(TransactionStates
const state
)
593 if (pkgAcqTransactionItem::TransactionState(state
) == false)
598 case TransactionStarted
: _error
->Fatal("AcqIndex %s changed to invalid transaction start state!", Target
.URI
.c_str()); break;
599 case TransactionAbort
:
600 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
602 // keep the compressed file, but drop the decompressed
603 EraseFileName
.clear();
604 if (PartialFile
.empty() == false && flExtension(PartialFile
) != CurrentCompressionExtension
)
605 RemoveFile("TransactionAbort", PartialFile
);
608 case TransactionCommit
:
609 if (EraseFileName
.empty() == false)
610 RemoveFile("AcqIndex::TransactionCommit", EraseFileName
);
615 bool pkgAcqDiffIndex::TransactionState(TransactionStates
const state
)
617 if (pkgAcqTransactionItem::TransactionState(state
) == false)
622 case TransactionStarted
: _error
->Fatal("Item %s changed to invalid transaction start state!", Target
.URI
.c_str()); break;
623 case TransactionCommit
:
625 case TransactionAbort
:
626 std::string
const Partial
= GetPartialFileNameFromURI(Target
.URI
);
627 RemoveFile("TransactionAbort", Partial
);
635 class APT_HIDDEN NoActionItem
: public pkgAcquire::Item
/*{{{*/
636 /* The sole purpose of this class is having an item which does nothing to
637 reach its done state to prevent cleanup deleting the mentioned file.
638 Handy in cases in which we know we have the file already, like IMS-Hits. */
640 IndexTarget
const Target
;
642 virtual std::string
DescURI() const APT_OVERRIDE
{return Target
.URI
;};
643 virtual HashStringList
GetExpectedHashes() const APT_OVERRIDE
{return HashStringList();};
645 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
) :
646 pkgAcquire::Item(Owner
), Target(Target
)
649 DestFile
= GetFinalFileNameFromURI(Target
.URI
);
651 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
, std::string
const &FinalFile
) :
652 pkgAcquire::Item(Owner
), Target(Target
)
655 DestFile
= FinalFile
;
659 class APT_HIDDEN CleanupItem
: public pkgAcqTransactionItem
/*{{{*/
660 /* This class ensures that a file which was configured but isn't downloaded
661 for various reasons isn't kept in an old version in the lists directory.
662 In a way its the reverse of NoActionItem as it helps with removing files
663 even if the lists-cleanup is deactivated. */
666 virtual std::string
DescURI() const APT_OVERRIDE
{return Target
.URI
;};
667 virtual HashStringList
GetExpectedHashes() const APT_OVERRIDE
{return HashStringList();};
669 CleanupItem(pkgAcquire
* const Owner
, pkgAcqMetaClearSig
* const TransactionManager
, IndexTarget
const &Target
) :
670 pkgAcqTransactionItem(Owner
, TransactionManager
, Target
)
673 DestFile
= GetFinalFileNameFromURI(Target
.URI
);
675 bool TransactionState(TransactionStates
const state
) APT_OVERRIDE
679 case TransactionStarted
:
681 case TransactionAbort
:
683 case TransactionCommit
:
684 if (_config
->FindB("Debug::Acquire::Transaction", false) == true)
685 std::clog
<< "rm " << DestFile
<< " # " << DescURI() << std::endl
;
686 if (RemoveFile("TransItem::TransactionCommit", DestFile
) == false)
695 // Acquire::Item::Item - Constructor /*{{{*/
696 class pkgAcquire::Item::Private
699 std::vector
<std::string
> PastRedirections
;
701 APT_IGNORE_DEPRECATED_PUSH
702 pkgAcquire::Item::Item(pkgAcquire
* const owner
) :
703 FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
704 QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner
), d(new Private())
709 APT_IGNORE_DEPRECATED_POP
711 // Acquire::Item::~Item - Destructor /*{{{*/
712 pkgAcquire::Item::~Item()
718 std::string
pkgAcquire::Item::Custom600Headers() const /*{{{*/
720 return std::string();
723 std::string
pkgAcquire::Item::ShortDesc() const /*{{{*/
728 APT_CONST
void pkgAcquire::Item::Finished() /*{{{*/
732 APT_PURE pkgAcquire
* pkgAcquire::Item::GetOwner() const /*{{{*/
737 APT_CONST
pkgAcquire::ItemDesc
&pkgAcquire::Item::GetItemDesc() /*{{{*/
742 APT_CONST
bool pkgAcquire::Item::IsTrusted() const /*{{{*/
747 // Acquire::Item::Failed - Item failed to download /*{{{*/
748 // ---------------------------------------------------------------------
749 /* We return to an idle state if there are still other queues that could
751 static void formatHashsum(std::ostream
&out
, HashString
const &hs
)
753 auto const type
= hs
.HashType();
754 if (type
== "Checksum-FileSize")
755 out
<< " - Filesize";
757 out
<< " - " << type
;
758 out
<< ':' << hs
.HashValue();
759 if (hs
.usable() == false)
763 void pkgAcquire::Item::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
765 if (QueueCounter
<= 1)
767 /* This indicates that the file is not available right now but might
768 be sometime later. If we do a retry cycle then this should be
770 if (Cnf
!= NULL
&& Cnf
->LocalOnly
== true &&
771 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
787 case StatTransientNetworkError
:
794 string
const FailReason
= LookupTag(Message
, "FailReason");
795 enum { MAXIMUM_SIZE_EXCEEDED
, HASHSUM_MISMATCH
, WEAK_HASHSUMS
, REDIRECTION_LOOP
, OTHER
} failreason
= OTHER
;
796 if ( FailReason
== "MaximumSizeExceeded")
797 failreason
= MAXIMUM_SIZE_EXCEEDED
;
798 else if ( FailReason
== "WeakHashSums")
799 failreason
= WEAK_HASHSUMS
;
800 else if (FailReason
== "RedirectionLoop")
801 failreason
= REDIRECTION_LOOP
;
802 else if (Status
== StatAuthError
)
803 failreason
= HASHSUM_MISMATCH
;
805 if(ErrorText
.empty())
807 std::ostringstream out
;
810 case HASHSUM_MISMATCH
:
811 out
<< _("Hash Sum mismatch") << std::endl
;
814 out
<< _("Insufficient information available to perform this download securely") << std::endl
;
816 case REDIRECTION_LOOP
:
817 out
<< "Redirection loop encountered" << std::endl
;
819 case MAXIMUM_SIZE_EXCEEDED
:
820 out
<< LookupTag(Message
, "Message") << std::endl
;
823 out
<< LookupTag(Message
, "Message");
827 if (Status
== StatAuthError
)
829 auto const ExpectedHashes
= GetExpectedHashes();
830 if (ExpectedHashes
.empty() == false)
832 out
<< "Hashes of expected file:" << std::endl
;
833 for (auto const &hs
: ExpectedHashes
)
834 formatHashsum(out
, hs
);
836 if (failreason
== HASHSUM_MISMATCH
)
838 out
<< "Hashes of received file:" << std::endl
;
839 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
841 std::string
const tagname
= std::string(*type
) + "-Hash";
842 std::string
const hashsum
= LookupTag(Message
, tagname
.c_str());
843 if (hashsum
.empty() == false)
844 formatHashsum(out
, HashString(*type
, hashsum
));
847 auto const lastmod
= LookupTag(Message
, "Last-Modified", "");
848 if (lastmod
.empty() == false)
849 out
<< "Last modification reported: " << lastmod
<< std::endl
;
851 ErrorText
= out
.str();
856 case MAXIMUM_SIZE_EXCEEDED
: RenameOnError(MaximumSizeExceeded
); break;
857 case HASHSUM_MISMATCH
: RenameOnError(HashSumMismatch
); break;
858 case WEAK_HASHSUMS
: break;
859 case REDIRECTION_LOOP
: break;
863 if (FailReason
.empty() == false)
864 ReportMirrorFailureToCentral(*this, FailReason
, ErrorText
);
866 ReportMirrorFailureToCentral(*this, ErrorText
, ErrorText
);
868 if (QueueCounter
> 1)
872 // Acquire::Item::Start - Item has begun to download /*{{{*/
873 // ---------------------------------------------------------------------
874 /* Stash status and the file size. Note that setting Complete means
875 sub-phases of the acquire process such as decompresion are operating */
876 void pkgAcquire::Item::Start(string
const &/*Message*/, unsigned long long const Size
)
878 Status
= StatFetching
;
880 if (FileSize
== 0 && Complete
== false)
884 // Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
885 /* Note that hash-verification is 'hardcoded' in acquire-worker and has
886 * already passed if this method is called. */
887 bool pkgAcquire::Item::VerifyDone(std::string
const &Message
,
888 pkgAcquire::MethodConfig
const * const /*Cnf*/)
890 std::string
const FileName
= LookupTag(Message
,"Filename");
891 if (FileName
.empty() == true)
894 ErrorText
= "Method gave a blank filename";
901 // Acquire::Item::Done - Item downloaded OK /*{{{*/
902 void pkgAcquire::Item::Done(string
const &/*Message*/, HashStringList
const &Hashes
,
903 pkgAcquire::MethodConfig
const * const /*Cnf*/)
905 // We just downloaded something..
908 unsigned long long const downloadedSize
= Hashes
.FileSize();
909 if (downloadedSize
!= 0)
911 FileSize
= downloadedSize
;
915 ErrorText
= string();
916 Owner
->Dequeue(this);
919 // Acquire::Item::Rename - Rename a file /*{{{*/
920 // ---------------------------------------------------------------------
921 /* This helper function is used by a lot of item methods as their final
923 bool pkgAcquire::Item::Rename(string
const &From
,string
const &To
)
925 if (From
== To
|| rename(From
.c_str(),To
.c_str()) == 0)
929 strprintf(S
, _("rename failed, %s (%s -> %s)."), strerror(errno
),
930 From
.c_str(),To
.c_str());
932 if (ErrorText
.empty())
935 ErrorText
= ErrorText
+ ": " + S
;
939 void pkgAcquire::Item::Dequeue() /*{{{*/
941 Owner
->Dequeue(this);
944 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
946 if (RealFileExists(DestFile
))
947 Rename(DestFile
, DestFile
+ ".FAILED");
952 case HashSumMismatch
:
953 errtext
= _("Hash Sum mismatch");
956 errtext
= _("Size mismatch");
957 Status
= StatAuthError
;
960 errtext
= _("Invalid file format");
962 // do not report as usually its not the mirrors fault, but Portal/Proxy
965 errtext
= _("Signature error");
969 strprintf(errtext
, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
970 Status
= StatAuthError
;
972 case MaximumSizeExceeded
:
973 // the method is expected to report a good error for this
976 // no handling here, done by callers
979 if (ErrorText
.empty())
984 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)/*{{{*/
986 ActiveSubprocess
= subprocess
;
987 APT_IGNORE_DEPRECATED(Mode
= ActiveSubprocess
.c_str();)
990 // Acquire::Item::ReportMirrorFailure /*{{{*/
991 void pkgAcquire::Item::ReportMirrorFailure(std::string
const &FailCode
)
993 ReportMirrorFailureToCentral(*this, FailCode
, FailCode
);
996 std::string
pkgAcquire::Item::HashSum() const /*{{{*/
998 HashStringList
const hashes
= GetExpectedHashes();
999 HashString
const * const hs
= hashes
.find(NULL
);
1000 return hs
!= NULL
? hs
->toStr() : "";
1003 bool pkgAcquire::Item::IsRedirectionLoop(std::string
const &NewURI
) /*{{{*/
1005 // store can fail due to permission errors and the item will "loop" then
1006 if (APT::String::Startswith(NewURI
, "store:"))
1008 if (d
->PastRedirections
.empty())
1010 d
->PastRedirections
.push_back(NewURI
);
1013 auto const LastURI
= std::prev(d
->PastRedirections
.end());
1014 // redirections to the same file are a way of restarting/resheduling,
1015 // individual methods will have to make sure that they aren't looping this way
1016 if (*LastURI
== NewURI
)
1018 if (std::find(d
->PastRedirections
.begin(), LastURI
, NewURI
) != LastURI
)
1020 d
->PastRedirections
.push_back(NewURI
);
1024 int pkgAcquire::Item::Priority() /*{{{*/
1026 // Stage 1: Meta indices and diff indices
1027 // - those need to be fetched first to have progress reporting working
1029 if (dynamic_cast<pkgAcqMetaSig
*>(this) != nullptr
1030 || dynamic_cast<pkgAcqMetaBase
*>(this) != nullptr
1031 || dynamic_cast<pkgAcqDiffIndex
*>(this) != nullptr)
1033 // Stage 2: Diff files
1034 // - fetch before complete indexes so we can apply the diffs while fetching
1036 if (dynamic_cast<pkgAcqIndexDiffs
*>(this) != nullptr ||
1037 dynamic_cast<pkgAcqIndexMergeDiffs
*>(this) != nullptr)
1040 // Stage 3: The rest - complete index files and other stuff
1045 pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire
* const Owner
, /*{{{*/
1046 pkgAcqMetaClearSig
* const transactionManager
, IndexTarget
const &target
) :
1047 pkgAcquire::Item(Owner
), d(NULL
), Target(target
), TransactionManager(transactionManager
)
1049 if (TransactionManager
!= this)
1050 TransactionManager
->Add(this);
1053 pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
1057 HashStringList
pkgAcqTransactionItem::GetExpectedHashesFor(std::string
const &MetaKey
) const /*{{{*/
1059 return GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, MetaKey
);
1063 static void LoadLastMetaIndexParser(pkgAcqMetaClearSig
* const TransactionManager
, std::string
const &FinalRelease
, std::string
const &FinalInRelease
)/*{{{*/
1065 if (TransactionManager
->IMSHit
== true)
1067 if (RealFileExists(FinalInRelease
) || RealFileExists(FinalRelease
))
1069 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1070 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1072 _error
->PushToStack();
1073 if (RealFileExists(FinalInRelease
))
1074 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1076 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1077 // its unlikely to happen, but if what we have is bad ignore it
1078 if (_error
->PendingError())
1080 delete TransactionManager
->LastMetaIndexParser
;
1081 TransactionManager
->LastMetaIndexParser
= NULL
;
1083 _error
->RevertToStack();
1089 // AcqMetaBase - Constructor /*{{{*/
1090 pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire
* const Owner
,
1091 pkgAcqMetaClearSig
* const TransactionManager
,
1092 IndexTarget
const &DataTarget
)
1093 : pkgAcqTransactionItem(Owner
, TransactionManager
, DataTarget
), d(NULL
),
1094 AuthPass(false), IMSHit(false), State(TransactionStarted
)
1098 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
1099 void pkgAcqMetaBase::Add(pkgAcqTransactionItem
* const I
)
1101 Transaction
.push_back(I
);
1104 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
1105 void pkgAcqMetaBase::AbortTransaction()
1107 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1108 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
1110 switch (TransactionManager
->State
)
1112 case TransactionStarted
: break;
1113 case TransactionAbort
: _error
->Fatal("Transaction %s was already aborted and is aborted again", TransactionManager
->Target
.URI
.c_str()); return;
1114 case TransactionCommit
: _error
->Fatal("Transaction %s was already aborted and is now committed", TransactionManager
->Target
.URI
.c_str()); return;
1116 TransactionManager
->State
= TransactionAbort
;
1118 // ensure the toplevel is in error state too
1119 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
1120 I
!= Transaction
.end(); ++I
)
1122 if ((*I
)->Status
!= pkgAcquire::Item::StatFetching
)
1124 (*I
)->TransactionState(TransactionAbort
);
1126 Transaction
.clear();
1129 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
1130 APT_PURE
bool pkgAcqMetaBase::TransactionHasError() const
1132 for (std::vector
<pkgAcqTransactionItem
*>::const_iterator I
= Transaction
.begin();
1133 I
!= Transaction
.end(); ++I
)
1135 switch((*I
)->Status
) {
1136 case StatDone
: break;
1137 case StatIdle
: break;
1138 case StatAuthError
: return true;
1139 case StatError
: return true;
1140 case StatTransientNetworkError
: return true;
1141 case StatFetching
: break;
1147 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
1148 void pkgAcqMetaBase::CommitTransaction()
1150 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1151 std::clog
<< "CommitTransaction: " << this << std::endl
;
1153 switch (TransactionManager
->State
)
1155 case TransactionStarted
: break;
1156 case TransactionAbort
: _error
->Fatal("Transaction %s was already committed and is now aborted", TransactionManager
->Target
.URI
.c_str()); return;
1157 case TransactionCommit
: _error
->Fatal("Transaction %s was already committed and is again committed", TransactionManager
->Target
.URI
.c_str()); return;
1159 TransactionManager
->State
= TransactionCommit
;
1161 // move new files into place *and* remove files that are not
1162 // part of the transaction but are still on disk
1163 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
1164 I
!= Transaction
.end(); ++I
)
1166 (*I
)->TransactionState(TransactionCommit
);
1168 Transaction
.clear();
1171 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
1172 void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem
* const I
,
1173 const std::string
&From
,
1174 const std::string
&To
)
1176 I
->PartialFile
= From
;
1180 // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
1181 void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem
* const I
,
1182 const std::string
&FinalFile
)
1184 I
->PartialFile
= "";
1185 I
->DestFile
= FinalFile
;
1188 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
1189 /* This method is called from ::Failed handlers. If it returns true,
1190 no fallback to other files or modi is performed */
1191 bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item
* const I
, const std::string
&Message
)
1193 string
const Final
= I
->GetFinalFilename();
1194 std::string
const GPGError
= LookupTag(Message
, "Message");
1195 if (FileExists(Final
))
1197 I
->Status
= StatTransientNetworkError
;
1198 _error
->Warning(_("An error occurred during the signature verification. "
1199 "The repository is not updated and the previous index files will be used. "
1200 "GPG error: %s: %s"),
1201 Desc
.Description
.c_str(),
1203 RunScripts("APT::Update::Auth-Failure");
1205 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
1206 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
1207 _error
->Error(_("GPG error: %s: %s"),
1208 Desc
.Description
.c_str(),
1210 I
->Status
= StatAuthError
;
1213 _error
->Warning(_("GPG error: %s: %s"),
1214 Desc
.Description
.c_str(),
1217 // gpgv method failed
1218 ReportMirrorFailureToCentral(*this, "GPGFailure", GPGError
);
1222 // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
1223 // ---------------------------------------------------------------------
1224 string
pkgAcqMetaBase::Custom600Headers() const
1226 std::string Header
= "\nIndex-File: true";
1227 std::string MaximumSize
;
1228 strprintf(MaximumSize
, "\nMaximum-Size: %i",
1229 _config
->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
1230 Header
+= MaximumSize
;
1232 string
const FinalFile
= GetFinalFilename();
1234 if (stat(FinalFile
.c_str(),&Buf
) == 0)
1235 Header
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
, false);
1240 // AcqMetaBase::QueueForSignatureVerify /*{{{*/
1241 void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem
* const I
, std::string
const &File
, std::string
const &Signature
)
1244 I
->Desc
.URI
= "gpgv:" + Signature
;
1247 I
->SetActiveSubprocess("gpgv");
1250 // AcqMetaBase::CheckDownloadDone /*{{{*/
1251 bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem
* const I
, const std::string
&Message
, HashStringList
const &Hashes
) const
1253 // We have just finished downloading a Release file (it is not
1256 // Save the final base URI we got this Release file from
1257 if (I
->UsedMirror
.empty() == false && _config
->FindB("Acquire::SameMirrorForAllIndexes", true))
1259 if (APT::String::Endswith(I
->Desc
.URI
, "InRelease"))
1261 TransactionManager
->BaseURI
= I
->Desc
.URI
.substr(0, I
->Desc
.URI
.length() - strlen("InRelease"));
1262 TransactionManager
->UsedMirror
= I
->UsedMirror
;
1264 else if (APT::String::Endswith(I
->Desc
.URI
, "Release"))
1266 TransactionManager
->BaseURI
= I
->Desc
.URI
.substr(0, I
->Desc
.URI
.length() - strlen("Release"));
1267 TransactionManager
->UsedMirror
= I
->UsedMirror
;
1271 std::string
const FileName
= LookupTag(Message
,"Filename");
1272 if (FileName
!= I
->DestFile
&& RealFileExists(I
->DestFile
) == false)
1275 I
->Desc
.URI
= "copy:" + FileName
;
1276 I
->QueueURI(I
->Desc
);
1280 // make sure to verify against the right file on I-M-S hit
1281 bool IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"), false);
1282 if (IMSHit
== false && Hashes
.usable())
1284 // detect IMS-Hits servers haven't detected by Hash comparison
1285 std::string
const FinalFile
= I
->GetFinalFilename();
1286 if (RealFileExists(FinalFile
) && Hashes
.VerifyFile(FinalFile
) == true)
1289 RemoveFile("CheckDownloadDone", I
->DestFile
);
1295 // for simplicity, the transaction manager is always InRelease
1296 // even if it doesn't exist.
1297 I
->PartialFile
= I
->DestFile
= I
->GetFinalFilename();
1300 // set Item to complete as the remaining work is all local (verify etc)
1306 bool pkgAcqMetaBase::CheckAuthDone(string
const &Message
) /*{{{*/
1308 // At this point, the gpgv method has succeeded, so there is a
1309 // valid signature from a key in the trusted keyring. We
1310 // perform additional verification of its contents, and use them
1311 // to verify the indexes we are about to download
1312 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1313 std::cerr
<< "Signature verification succeeded: " << DestFile
<< std::endl
;
1315 if (TransactionManager
->IMSHit
== false)
1317 // open the last (In)Release if we have it
1318 std::string
const FinalFile
= GetFinalFilename();
1319 std::string FinalRelease
;
1320 std::string FinalInRelease
;
1321 if (APT::String::Endswith(FinalFile
, "InRelease"))
1323 FinalInRelease
= FinalFile
;
1324 FinalRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("InRelease")) + "Release";
1328 FinalInRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("Release")) + "InRelease";
1329 FinalRelease
= FinalFile
;
1331 LoadLastMetaIndexParser(TransactionManager
, FinalRelease
, FinalInRelease
);
1334 bool const GoodAuth
= TransactionManager
->MetaIndexParser
->Load(DestFile
, &ErrorText
);
1335 if (GoodAuth
== false && AllowInsecureRepositories(InsecureType::WEAK
, Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == false)
1337 Status
= StatAuthError
;
1341 if (!VerifyVendor(Message
))
1343 Status
= StatAuthError
;
1347 // Download further indexes with verification
1348 TransactionManager
->QueueIndexes(GoodAuth
);
1353 void pkgAcqMetaClearSig::QueueIndexes(bool const verify
) /*{{{*/
1355 // at this point the real Items are loaded in the fetcher
1356 ExpectedAdditionalItems
= 0;
1358 std::set
<std::string
> targetsSeen
;
1359 bool const hasReleaseFile
= TransactionManager
->MetaIndexParser
!= NULL
;
1360 bool const metaBaseSupportsByHash
= hasReleaseFile
&& TransactionManager
->MetaIndexParser
->GetSupportsAcquireByHash();
1361 bool hasHashes
= true;
1362 auto IndexTargets
= TransactionManager
->MetaIndexParser
->GetIndexTargets();
1363 if (hasReleaseFile
&& verify
== false)
1364 hasHashes
= std::any_of(IndexTargets
.begin(), IndexTargets
.end(),
1365 [&](IndexTarget
const &Target
) { return TransactionManager
->MetaIndexParser
->Exists(Target
.MetaKey
); });
1366 if (_config
->FindB("Acquire::IndexTargets::Randomized", true) && likely(IndexTargets
.empty() == false))
1368 /* For fallback handling and to have some reasonable progress information
1369 we can't randomize everything, but at least the order in the same type
1370 can be as we shouldn't be telling the mirrors (and everyone else watching)
1371 which is native/foreign arch, specific order of preference of translations, … */
1372 auto range_start
= IndexTargets
.begin();
1373 std::random_device rd
;
1374 std::default_random_engine
g(rd());
1376 auto const type
= range_start
->Option(IndexTarget::CREATED_BY
);
1377 auto const range_end
= std::find_if_not(range_start
, IndexTargets
.end(),
1378 [&type
](IndexTarget
const &T
) { return type
== T
.Option(IndexTarget::CREATED_BY
); });
1379 std::shuffle(range_start
, range_end
, g
);
1380 range_start
= range_end
;
1381 } while (range_start
!= IndexTargets
.end());
1383 for (auto&& Target
: IndexTargets
)
1385 // if we have seen a target which is created-by a target this one here is declared a
1386 // fallback to, we skip acquiring the fallback (but we make sure we clean up)
1387 if (targetsSeen
.find(Target
.Option(IndexTarget::FALLBACK_OF
)) != targetsSeen
.end())
1389 targetsSeen
.emplace(Target
.Option(IndexTarget::CREATED_BY
));
1390 new CleanupItem(Owner
, TransactionManager
, Target
);
1393 // all is an implementation detail. Users shouldn't use this as arch
1394 // We need this support trickery here as e.g. Debian has binary-all files already,
1395 // but arch:all packages are still in the arch:any files, so we would waste precious
1396 // download time, bandwidth and diskspace for nothing, BUT Debian doesn't feature all
1397 // in the set of supported architectures, so we can filter based on this property rather
1398 // than invent an entirely new flag we would need to carry for all of eternity.
1399 if (hasReleaseFile
&& Target
.Option(IndexTarget::ARCHITECTURE
) == "all")
1401 if (TransactionManager
->MetaIndexParser
->IsArchitectureAllSupportedFor(Target
) == false)
1403 new CleanupItem(Owner
, TransactionManager
, Target
);
1408 bool trypdiff
= Target
.OptionBool(IndexTarget::PDIFFS
);
1409 if (hasReleaseFile
== true)
1411 if (TransactionManager
->MetaIndexParser
->Exists(Target
.MetaKey
) == false)
1413 // optional targets that we do not have in the Release file are skipped
1414 if (hasHashes
== true && Target
.IsOptional
)
1416 new CleanupItem(Owner
, TransactionManager
, Target
);
1420 std::string
const &arch
= Target
.Option(IndexTarget::ARCHITECTURE
);
1421 if (arch
.empty() == false)
1423 if (TransactionManager
->MetaIndexParser
->IsArchitectureSupported(arch
) == false)
1425 new CleanupItem(Owner
, TransactionManager
, Target
);
1426 _error
->Notice(_("Skipping acquire of configured file '%s' as repository '%s' doesn't support architecture '%s'"),
1427 Target
.MetaKey
.c_str(), TransactionManager
->Target
.Description
.c_str(), arch
.c_str());
1430 // if the architecture is officially supported but currently no packages for it available,
1431 // ignore silently as this is pretty much the same as just shipping an empty file.
1432 // if we don't know which architectures are supported, we do NOT ignore it to notify user about this
1433 if (hasHashes
== true && TransactionManager
->MetaIndexParser
->IsArchitectureSupported("*undefined*") == false)
1435 new CleanupItem(Owner
, TransactionManager
, Target
);
1440 if (hasHashes
== true)
1442 Status
= StatAuthError
;
1443 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target
.MetaKey
.c_str());
1448 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
1454 auto const hashes
= GetExpectedHashesFor(Target
.MetaKey
);
1455 if (hashes
.empty() == false)
1457 if (hashes
.usable() == false && TargetIsAllowedToBe(TransactionManager
->Target
, InsecureType::WEAK
) == false)
1459 new CleanupItem(Owner
, TransactionManager
, Target
);
1460 _error
->Warning(_("Skipping acquire of configured file '%s' as repository '%s' provides only weak security information for it"),
1461 Target
.MetaKey
.c_str(), TransactionManager
->Target
.Description
.c_str());
1464 // empty files are skipped as acquiring the very small compressed files is a waste of time
1465 else if (hashes
.FileSize() == 0)
1467 new CleanupItem(Owner
, TransactionManager
, Target
);
1468 targetsSeen
.emplace(Target
.Option(IndexTarget::CREATED_BY
));
1474 // autoselect the compression method
1475 std::vector
<std::string
> types
= VectorizeString(Target
.Option(IndexTarget::COMPRESSIONTYPES
), ' ');
1476 types
.erase(std::remove_if(types
.begin(), types
.end(), [&](std::string
const &t
) {
1477 if (t
== "uncompressed")
1478 return TransactionManager
->MetaIndexParser
->Exists(Target
.MetaKey
) == false;
1479 std::string
const MetaKey
= Target
.MetaKey
+ "." + t
;
1480 return TransactionManager
->MetaIndexParser
->Exists(MetaKey
) == false;
1482 if (types
.empty() == false)
1484 std::ostringstream os
;
1485 // add the special compressiontype byhash first if supported
1486 std::string
const useByHashConf
= Target
.Option(IndexTarget::BY_HASH
);
1487 bool useByHash
= false;
1488 if(useByHashConf
== "force")
1491 useByHash
= StringToBool(useByHashConf
) == true && metaBaseSupportsByHash
;
1492 if (useByHash
== true)
1494 std::copy(types
.begin(), types
.end()-1, std::ostream_iterator
<std::string
>(os
, " "));
1495 os
<< *types
.rbegin();
1496 Target
.Options
["COMPRESSIONTYPES"] = os
.str();
1499 Target
.Options
["COMPRESSIONTYPES"].clear();
1501 std::string filename
= GetExistingFilename(GetFinalFileNameFromURI(Target
.URI
));
1502 if (filename
.empty() == false)
1504 // if the Release file is a hit and we have an index it must be the current one
1505 if (TransactionManager
->IMSHit
== true)
1507 else if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1509 // see if the file changed since the last Release file
1510 // we use the uncompressed files as we might compress differently compared to the server,
1511 // so the hashes might not match, even if they contain the same data.
1512 HashStringList
const newFile
= GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, Target
.MetaKey
);
1513 HashStringList
const oldFile
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
.MetaKey
);
1514 if (newFile
!= oldFile
)
1521 trypdiff
= false; // no file to patch
1523 if (filename
.empty() == false)
1525 new NoActionItem(Owner
, Target
, filename
);
1526 std::string
const idxfilename
= GetFinalFileNameFromURI(GetDiffIndexURI(Target
));
1527 if (FileExists(idxfilename
))
1528 new NoActionItem(Owner
, Target
, idxfilename
);
1529 targetsSeen
.emplace(Target
.Option(IndexTarget::CREATED_BY
));
1533 // check if we have patches available
1534 trypdiff
&= TransactionManager
->MetaIndexParser
->Exists(GetDiffIndexFileName(Target
.MetaKey
));
1538 // if we have no file to patch, no point in trying
1539 trypdiff
&= (GetExistingFilename(GetFinalFileNameFromURI(Target
.URI
)).empty() == false);
1542 // no point in patching from local sources
1545 std::string
const proto
= Target
.URI
.substr(0, strlen("file:/"));
1546 if (proto
== "file:/" || proto
== "copy:/" || proto
== "cdrom:")
1550 // Queue the Index file (Packages, Sources, Translation-$foo, …)
1551 targetsSeen
.emplace(Target
.Option(IndexTarget::CREATED_BY
));
1553 new pkgAcqDiffIndex(Owner
, TransactionManager
, Target
);
1555 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
1559 bool pkgAcqMetaBase::VerifyVendor(string
const &) /*{{{*/
1561 if (TransactionManager
->MetaIndexParser
->GetValidUntil() > 0)
1563 time_t const invalid_since
= time(NULL
) - TransactionManager
->MetaIndexParser
->GetValidUntil();
1564 if (invalid_since
> 0)
1568 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1569 // the time since then the file is invalid - formatted in the same way as in
1570 // the download progress display (e.g. 7d 3h 42min 1s)
1571 _("Release file for %s is expired (invalid since %s). "
1572 "Updates for this repository will not be applied."),
1573 Target
.URI
.c_str(), TimeToStr(invalid_since
).c_str());
1574 if (ErrorText
.empty())
1576 return _error
->Error("%s", errmsg
.c_str());
1580 /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
1581 as a prevention of downgrading us to older (still valid) files */
1582 if (TransactionManager
->IMSHit
== false && TransactionManager
->LastMetaIndexParser
!= NULL
&&
1583 TransactionManager
->LastMetaIndexParser
->GetDate() > TransactionManager
->MetaIndexParser
->GetDate())
1585 TransactionManager
->IMSHit
= true;
1586 RemoveFile("VerifyVendor", DestFile
);
1587 PartialFile
= DestFile
= GetFinalFilename();
1588 // load the 'old' file in the 'new' one instead of flipping pointers as
1589 // the new one isn't owned by us, while the old one is so cleanup would be confused.
1590 TransactionManager
->MetaIndexParser
->swapLoad(TransactionManager
->LastMetaIndexParser
);
1591 delete TransactionManager
->LastMetaIndexParser
;
1592 TransactionManager
->LastMetaIndexParser
= NULL
;
1595 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1597 std::cerr
<< "Got Codename: " << TransactionManager
->MetaIndexParser
->GetCodename() << std::endl
;
1598 std::cerr
<< "Got Suite: " << TransactionManager
->MetaIndexParser
->GetSuite() << std::endl
;
1599 std::cerr
<< "Expecting Dist: " << TransactionManager
->MetaIndexParser
->GetExpectedDist() << std::endl
;
1602 // One day that might become fatal…
1603 auto const ExpectedDist
= TransactionManager
->MetaIndexParser
->GetExpectedDist();
1604 auto const NowCodename
= TransactionManager
->MetaIndexParser
->GetCodename();
1605 if (TransactionManager
->MetaIndexParser
->CheckDist(ExpectedDist
) == false)
1606 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1607 Desc
.Description
.c_str(), ExpectedDist
.c_str(), NowCodename
.c_str());
1608 // might be okay, might be not
1609 if (TransactionManager
->LastMetaIndexParser
!= nullptr)
1611 auto const LastCodename
= TransactionManager
->LastMetaIndexParser
->GetCodename();
1612 if (LastCodename
.empty() == false && NowCodename
.empty() == false && LastCodename
!= NowCodename
)
1613 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1614 Desc
.Description
.c_str(), LastCodename
.c_str(), NowCodename
.c_str());
1619 pkgAcqMetaBase::~pkgAcqMetaBase()
1623 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
* const Owner
, /*{{{*/
1624 IndexTarget
const &ClearsignedTarget
,
1625 IndexTarget
const &DetachedDataTarget
, IndexTarget
const &DetachedSigTarget
,
1626 metaIndex
* const MetaIndexParser
) :
1627 pkgAcqMetaIndex(Owner
, this, ClearsignedTarget
, DetachedSigTarget
),
1628 d(NULL
), DetachedDataTarget(DetachedDataTarget
),
1629 MetaIndexParser(MetaIndexParser
), LastMetaIndexParser(NULL
)
1631 // index targets + (worst case:) Release/Release.gpg
1632 ExpectedAdditionalItems
= std::numeric_limits
<decltype(ExpectedAdditionalItems
)>::max();
1633 TransactionManager
->Add(this);
1636 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
1638 if (LastMetaIndexParser
!= NULL
)
1639 delete LastMetaIndexParser
;
1642 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1643 string
pkgAcqMetaClearSig::Custom600Headers() const
1645 string Header
= pkgAcqMetaBase::Custom600Headers();
1646 Header
+= "\nFail-Ignore: true";
1647 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1648 if (key
.empty() == false)
1649 Header
+= "\nSigned-By: " + key
;
1654 void pkgAcqMetaClearSig::Finished() /*{{{*/
1656 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1657 std::clog
<< "Finished: " << DestFile
<<std::endl
;
1658 if(TransactionManager
->State
== TransactionStarted
&&
1659 TransactionManager
->TransactionHasError() == false)
1660 TransactionManager
->CommitTransaction();
1663 bool pkgAcqMetaClearSig::VerifyDone(std::string
const &Message
, /*{{{*/
1664 pkgAcquire::MethodConfig
const * const Cnf
)
1666 Item::VerifyDone(Message
, Cnf
);
1668 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
1669 return RenameOnError(NotClearsigned
);
1674 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
1675 void pkgAcqMetaClearSig::Done(std::string
const &Message
,
1676 HashStringList
const &Hashes
,
1677 pkgAcquire::MethodConfig
const * const Cnf
)
1679 Item::Done(Message
, Hashes
, Cnf
);
1681 if(AuthPass
== false)
1683 if(CheckDownloadDone(this, Message
, Hashes
) == true)
1684 QueueForSignatureVerify(this, DestFile
, DestFile
);
1687 else if(CheckAuthDone(Message
) == true)
1689 if (TransactionManager
->IMSHit
== false)
1690 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1691 else if (RealFileExists(GetFinalFilename()) == false)
1693 // We got an InRelease file IMSHit, but we haven't one, which means
1694 // we had a valid Release/Release.gpg combo stepping in, which we have
1695 // to 'acquire' now to ensure list cleanup isn't removing them
1696 new NoActionItem(Owner
, DetachedDataTarget
);
1697 new NoActionItem(Owner
, DetachedSigTarget
);
1700 else if (Status
!= StatAuthError
)
1702 string
const FinalFile
= GetFinalFileNameFromURI(DetachedDataTarget
.URI
);
1703 string
const OldFile
= GetFinalFilename();
1704 if (TransactionManager
->IMSHit
== false)
1705 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
1706 else if (RealFileExists(OldFile
) == false)
1707 new NoActionItem(Owner
, DetachedDataTarget
);
1709 TransactionManager
->TransactionStageCopy(this, OldFile
, FinalFile
);
1713 void pkgAcqMetaClearSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
) /*{{{*/
1715 Item::Failed(Message
, Cnf
);
1717 if (AuthPass
== false)
1719 if (Status
== StatAuthError
|| Status
== StatTransientNetworkError
)
1721 // if we expected a ClearTextSignature (InRelease) but got a network
1722 // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
1723 // As these is usually called by web-portals we do not try Release/Release.gpg
1724 // as this is gonna fail anyway and instead abort our try (LP#346386)
1725 TransactionManager
->AbortTransaction();
1729 // Queue the 'old' InRelease file for removal if we try Release.gpg
1730 // as otherwise the file will stay around and gives a false-auth
1731 // impression (CVE-2012-0214)
1732 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1735 new pkgAcqMetaIndex(Owner
, TransactionManager
, DetachedDataTarget
, DetachedSigTarget
);
1739 if(CheckStopAuthentication(this, Message
))
1742 if(AllowInsecureRepositories(InsecureType::UNSIGNED
, Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1746 /* InRelease files become Release files, otherwise
1747 * they would be considered as trusted later on */
1748 string
const FinalRelease
= GetFinalFileNameFromURI(DetachedDataTarget
.URI
);
1749 string
const PartialRelease
= GetPartialFileNameFromURI(DetachedDataTarget
.URI
);
1750 string
const FinalReleasegpg
= GetFinalFileNameFromURI(DetachedSigTarget
.URI
);
1751 string
const FinalInRelease
= GetFinalFilename();
1752 Rename(DestFile
, PartialRelease
);
1753 TransactionManager
->TransactionStageCopy(this, PartialRelease
, FinalRelease
);
1754 LoadLastMetaIndexParser(TransactionManager
, FinalRelease
, FinalInRelease
);
1756 // we parse the indexes here because at this point the user wanted
1757 // a repository that may potentially harm him
1758 if (TransactionManager
->MetaIndexParser
->Load(PartialRelease
, &ErrorText
) == false || VerifyVendor(Message
) == false)
1759 /* expired Release files are still a problem you need extra force for */;
1761 TransactionManager
->QueueIndexes(true);
1767 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
* const Owner
, /*{{{*/
1768 pkgAcqMetaClearSig
* const TransactionManager
,
1769 IndexTarget
const &DataTarget
,
1770 IndexTarget
const &DetachedSigTarget
) :
1771 pkgAcqMetaBase(Owner
, TransactionManager
, DataTarget
), d(NULL
),
1772 DetachedSigTarget(DetachedSigTarget
)
1774 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1775 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1776 << this->TransactionManager
<< std::endl
;
1778 DestFile
= GetPartialFileNameFromURI(DataTarget
.URI
);
1781 Desc
.Description
= DataTarget
.Description
;
1783 Desc
.ShortDesc
= DataTarget
.ShortDesc
;
1784 Desc
.URI
= DataTarget
.URI
;
1788 void pkgAcqMetaIndex::Done(string
const &Message
, /*{{{*/
1789 HashStringList
const &Hashes
,
1790 pkgAcquire::MethodConfig
const * const Cfg
)
1792 Item::Done(Message
,Hashes
,Cfg
);
1794 if(CheckDownloadDone(this, Message
, Hashes
))
1796 // we have a Release file, now download the Signature, all further
1797 // verify/queue for additional downloads will be done in the
1798 // pkgAcqMetaSig::Done() code
1799 new pkgAcqMetaSig(Owner
, TransactionManager
, DetachedSigTarget
, this);
1803 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
1804 void pkgAcqMetaIndex::Failed(string
const &Message
,
1805 pkgAcquire::MethodConfig
const * const Cnf
)
1807 pkgAcquire::Item::Failed(Message
, Cnf
);
1810 // No Release file was present so fall
1811 // back to queueing Packages files without verification
1812 // only allow going further if the user explicitly wants it
1813 if(AllowInsecureRepositories(InsecureType::NORELEASE
, Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1815 // ensure old Release files are removed
1816 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1818 // queue without any kind of hashsum support
1819 TransactionManager
->QueueIndexes(false);
1823 std::string
pkgAcqMetaIndex::DescURI() const /*{{{*/
1828 pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
1830 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1831 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
* const Owner
,
1832 pkgAcqMetaClearSig
* const TransactionManager
,
1833 IndexTarget
const &Target
,
1834 pkgAcqMetaIndex
* const MetaIndex
) :
1835 pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
), MetaIndex(MetaIndex
)
1837 DestFile
= GetPartialFileNameFromURI(Target
.URI
);
1839 // remove any partial downloaded sig-file in partial/.
1840 // it may confuse proxies and is too small to warrant a
1841 // partial download anyway
1842 RemoveFile("pkgAcqMetaSig", DestFile
);
1844 // set the TransactionManager
1845 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1846 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1847 << TransactionManager
<< std::endl
;
1850 Desc
.Description
= Target
.Description
;
1852 Desc
.ShortDesc
= Target
.ShortDesc
;
1853 Desc
.URI
= Target
.URI
;
1855 // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
1856 // so we skip the download step and go instantly to verification
1857 if (TransactionManager
->IMSHit
== true && RealFileExists(GetFinalFilename()))
1861 PartialFile
= DestFile
= GetFinalFilename();
1862 MetaIndexFileSignature
= DestFile
;
1863 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1869 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1873 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1874 std::string
pkgAcqMetaSig::Custom600Headers() const
1876 std::string Header
= pkgAcqTransactionItem::Custom600Headers();
1877 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1878 if (key
.empty() == false)
1879 Header
+= "\nSigned-By: " + key
;
1883 // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1884 void pkgAcqMetaSig::Done(string
const &Message
, HashStringList
const &Hashes
,
1885 pkgAcquire::MethodConfig
const * const Cfg
)
1887 if (MetaIndexFileSignature
.empty() == false)
1889 DestFile
= MetaIndexFileSignature
;
1890 MetaIndexFileSignature
.clear();
1892 Item::Done(Message
, Hashes
, Cfg
);
1894 if(MetaIndex
->AuthPass
== false)
1896 if(MetaIndex
->CheckDownloadDone(this, Message
, Hashes
) == true)
1898 // destfile will be modified to point to MetaIndexFile for the
1899 // gpgv method, so we need to save it here
1900 MetaIndexFileSignature
= DestFile
;
1901 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1905 else if(MetaIndex
->CheckAuthDone(Message
) == true)
1907 auto const Releasegpg
= GetFinalFilename();
1908 auto const Release
= MetaIndex
->GetFinalFilename();
1909 // if this is an IMS-Hit on Release ensure we also have the the Release.gpg file stored
1910 // (previously an unknown pubkey) – but only if the Release file exists locally (unlikely
1911 // event of InRelease removed from the mirror causing fallback but still an IMS-Hit)
1912 if (TransactionManager
->IMSHit
== false ||
1913 (FileExists(Releasegpg
) == false && FileExists(Release
) == true))
1915 TransactionManager
->TransactionStageCopy(this, DestFile
, Releasegpg
);
1916 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, Release
);
1919 else if (MetaIndex
->Status
!= StatAuthError
)
1921 std::string
const FinalFile
= MetaIndex
->GetFinalFilename();
1922 if (TransactionManager
->IMSHit
== false)
1923 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, FinalFile
);
1925 TransactionManager
->TransactionStageCopy(MetaIndex
, FinalFile
, FinalFile
);
1929 void pkgAcqMetaSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
1931 Item::Failed(Message
,Cnf
);
1933 // check if we need to fail at this point
1934 if (MetaIndex
->AuthPass
== true && MetaIndex
->CheckStopAuthentication(this, Message
))
1937 // ensures that a Release.gpg file in the lists/ is removed by the transaction
1938 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1940 // only allow going further if the user explicitly wants it
1941 if (AllowInsecureRepositories(InsecureType::UNSIGNED
, MetaIndex
->Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1943 string
const FinalRelease
= MetaIndex
->GetFinalFilename();
1944 string
const FinalInRelease
= TransactionManager
->GetFinalFilename();
1945 LoadLastMetaIndexParser(TransactionManager
, FinalRelease
, FinalInRelease
);
1947 // we parse the indexes here because at this point the user wanted
1948 // a repository that may potentially harm him
1949 bool const GoodLoad
= TransactionManager
->MetaIndexParser
->Load(MetaIndex
->DestFile
, &ErrorText
);
1950 if (MetaIndex
->VerifyVendor(Message
) == false)
1951 /* expired Release files are still a problem you need extra force for */;
1953 TransactionManager
->QueueIndexes(GoodLoad
);
1955 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, FinalRelease
);
1957 else if (TransactionManager
->IMSHit
== false)
1958 Rename(MetaIndex
->DestFile
, MetaIndex
->DestFile
+ ".FAILED");
1960 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1961 if (Cnf
->LocalOnly
== true ||
1962 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1971 // AcqBaseIndex - Constructor /*{{{*/
1972 pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire
* const Owner
,
1973 pkgAcqMetaClearSig
* const TransactionManager
,
1974 IndexTarget
const &Target
)
1975 : pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
)
1979 void pkgAcqBaseIndex::Failed(std::string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
1981 pkgAcquire::Item::Failed(Message
, Cnf
);
1982 if (Status
!= StatAuthError
)
1985 ErrorText
.append("Release file created at: ");
1986 auto const timespec
= TransactionManager
->MetaIndexParser
->GetDate();
1988 ErrorText
.append("<unknown>");
1990 ErrorText
.append(TimeRFC1123(timespec
, true));
1991 ErrorText
.append("\n");
1994 pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
1996 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
1997 // ---------------------------------------------------------------------
1998 /* Get the DiffIndex file first and see if there are patches available
1999 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
2000 * patches. If anything goes wrong in that process, it will fall back to
2001 * the original packages file
2003 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
* const Owner
,
2004 pkgAcqMetaClearSig
* const TransactionManager
,
2005 IndexTarget
const &Target
)
2006 : pkgAcqIndex(Owner
, TransactionManager
, Target
, true), d(NULL
), diffs(NULL
)
2008 // FIXME: Magic number as an upper bound on pdiffs we will reasonably acquire
2009 ExpectedAdditionalItems
= 40;
2010 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2012 CompressionExtensions
.clear();
2014 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
2015 if (types
.empty() == false)
2017 std::ostringstream os
;
2018 std::copy_if(types
.begin(), types
.end()-1, std::ostream_iterator
<std::string
>(os
, " "), [&](std::string
const type
) {
2019 if (type
== "uncompressed")
2021 return TransactionManager
->MetaIndexParser
->Exists(GetDiffIndexFileName(Target
.MetaKey
) + '.' + type
);
2023 os
<< *types
.rbegin();
2024 CompressionExtensions
= os
.str();
2027 if (Target
.Option(IndexTarget::COMPRESSIONTYPES
).find("by-hash") != std::string::npos
)
2028 CompressionExtensions
= "by-hash " + CompressionExtensions
;
2029 Init(GetDiffIndexURI(Target
), GetDiffIndexFileName(Target
.Description
), Target
.ShortDesc
);
2032 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
2035 void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
2037 // list cleanup needs to know that this file as well as the already
2038 // present index is ours, so we create an empty diff to save it for us
2039 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, UsedMirror
, Target
.URI
);
2042 static bool RemoveFileForBootstrapLinking(bool const Debug
, std::string
const &For
, std::string
const &Boot
)/*{{{*/
2044 if (FileExists(Boot
) && RemoveFile("Bootstrap-linking", Boot
) == false)
2047 std::clog
<< "Bootstrap-linking for patching " << For
2048 << " by removing stale " << Boot
<< " failed!" << std::endl
;
2054 bool pkgAcqDiffIndex::ParseDiffIndex(string
const &IndexDiffFile
) /*{{{*/
2056 ExpectedAdditionalItems
= 0;
2057 // failing here is fine: our caller will take care of trying to
2058 // get the complete file if patching fails
2060 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
2063 FileFd
Fd(IndexDiffFile
, FileFd::ReadOnly
, FileFd::Extension
);
2065 if (Fd
.IsOpen() == false || Fd
.Failed())
2069 if(unlikely(TF
.Step(Tags
) == false))
2072 HashStringList ServerHashes
;
2073 unsigned long long ServerSize
= 0;
2075 auto const &posix
= std::locale::classic();
2076 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
2078 std::string tagname
= *type
;
2079 tagname
.append("-Current");
2080 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
2081 if (tmp
.empty() == true)
2085 unsigned long long size
;
2086 std::stringstream
ss(tmp
);
2089 if (unlikely(hash
.empty() == true))
2091 if (unlikely(ServerSize
!= 0 && ServerSize
!= size
))
2093 ServerHashes
.push_back(HashString(*type
, hash
));
2097 if (ServerHashes
.usable() == false)
2100 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Did not find a good hashsum in the index" << std::endl
;
2104 std::string
const CurrentPackagesFile
= GetFinalFileNameFromURI(Target
.URI
);
2105 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
2106 if (TargetFileHashes
.usable() == false || ServerHashes
!= TargetFileHashes
)
2110 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl
;
2111 printHashSumComparison(CurrentPackagesFile
, ServerHashes
, TargetFileHashes
);
2116 HashStringList LocalHashes
;
2117 // try avoiding calculating the hash here as this is costly
2118 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
2119 LocalHashes
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
.MetaKey
);
2120 if (LocalHashes
.usable() == false)
2122 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
, FileFd::Auto
);
2123 Hashes
LocalHashesCalc(ServerHashes
);
2124 LocalHashesCalc
.AddFD(fd
);
2125 LocalHashes
= LocalHashesCalc
.GetHashStringList();
2128 if (ServerHashes
== LocalHashes
)
2130 // we have the same sha1 as the server so we are done here
2132 std::clog
<< "pkgAcqDiffIndex: Package file " << CurrentPackagesFile
<< " is up-to-date" << std::endl
;
2138 std::clog
<< "Server-Current: " << ServerHashes
.find(NULL
)->toStr() << " and we start at "
2139 << CurrentPackagesFile
<< " " << LocalHashes
.FileSize() << " " << LocalHashes
.find(NULL
)->toStr() << std::endl
;
2141 // historically, older hashes have more info than newer ones, so start
2142 // collecting with older ones first to avoid implementing complicated
2143 // information merging techniques… a failure is after all always
2144 // recoverable with a complete file and hashes aren't changed that often.
2145 std::vector
<char const *> types
;
2146 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
2147 types
.push_back(*type
);
2149 // parse all of (provided) history
2150 vector
<DiffInfo
> available_patches
;
2151 bool firstAcceptedHashes
= true;
2152 for (auto type
= types
.crbegin(); type
!= types
.crend(); ++type
)
2154 if (LocalHashes
.find(*type
) == NULL
)
2157 std::string tagname
= *type
;
2158 tagname
.append("-History");
2159 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
2160 if (tmp
.empty() == true)
2163 string hash
, filename
;
2164 unsigned long long size
;
2165 std::stringstream
ss(tmp
);
2168 while (ss
>> hash
>> size
>> filename
)
2170 if (unlikely(hash
.empty() == true || filename
.empty() == true))
2173 // see if we have a record for this file already
2174 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
2175 for (; cur
!= available_patches
.end(); ++cur
)
2177 if (cur
->file
!= filename
)
2179 cur
->result_hashes
.push_back(HashString(*type
, hash
));
2182 if (cur
!= available_patches
.end())
2184 if (firstAcceptedHashes
== true)
2187 next
.file
= filename
;
2188 next
.result_hashes
.push_back(HashString(*type
, hash
));
2189 next
.result_hashes
.FileSize(size
);
2190 available_patches
.push_back(next
);
2195 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
2196 << " wasn't in the list for the first parsed hash! (history)" << std::endl
;
2200 firstAcceptedHashes
= false;
2203 if (unlikely(available_patches
.empty() == true))
2206 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
2207 << "Couldn't find any patches for the patch series." << std::endl
;
2211 for (auto type
= types
.crbegin(); type
!= types
.crend(); ++type
)
2213 if (LocalHashes
.find(*type
) == NULL
)
2216 std::string tagname
= *type
;
2217 tagname
.append("-Patches");
2218 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
2219 if (tmp
.empty() == true)
2222 string hash
, filename
;
2223 unsigned long long size
;
2224 std::stringstream
ss(tmp
);
2227 while (ss
>> hash
>> size
>> filename
)
2229 if (unlikely(hash
.empty() == true || filename
.empty() == true))
2232 // see if we have a record for this file already
2233 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
2234 for (; cur
!= available_patches
.end(); ++cur
)
2236 if (cur
->file
!= filename
)
2238 if (cur
->patch_hashes
.empty())
2239 cur
->patch_hashes
.FileSize(size
);
2240 cur
->patch_hashes
.push_back(HashString(*type
, hash
));
2243 if (cur
!= available_patches
.end())
2246 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
2247 << " wasn't in the list for the first parsed hash! (patches)" << std::endl
;
2252 for (auto type
= types
.crbegin(); type
!= types
.crend(); ++type
)
2254 std::string tagname
= *type
;
2255 tagname
.append("-Download");
2256 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
2257 if (tmp
.empty() == true)
2260 string hash
, filename
;
2261 unsigned long long size
;
2262 std::stringstream
ss(tmp
);
2265 // FIXME: all of pdiff supports only .gz compressed patches
2266 while (ss
>> hash
>> size
>> filename
)
2268 if (unlikely(hash
.empty() == true || filename
.empty() == true))
2270 if (unlikely(APT::String::Endswith(filename
, ".gz") == false))
2272 filename
.erase(filename
.length() - 3);
2274 // see if we have a record for this file already
2275 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
2276 for (; cur
!= available_patches
.end(); ++cur
)
2278 if (cur
->file
!= filename
)
2280 if (cur
->download_hashes
.empty())
2281 cur
->download_hashes
.FileSize(size
);
2282 cur
->download_hashes
.push_back(HashString(*type
, hash
));
2285 if (cur
!= available_patches
.end())
2288 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
2289 << " wasn't in the list for the first parsed hash! (download)" << std::endl
;
2295 bool foundStart
= false;
2296 for (std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
2297 cur
!= available_patches
.end(); ++cur
)
2299 if (LocalHashes
!= cur
->result_hashes
)
2302 available_patches
.erase(available_patches
.begin(), cur
);
2307 if (foundStart
== false || unlikely(available_patches
.empty() == true))
2310 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
2311 << "Couldn't find the start of the patch series." << std::endl
;
2315 for (auto const &patch
: available_patches
)
2316 if (patch
.result_hashes
.usable() == false ||
2317 patch
.patch_hashes
.usable() == false ||
2318 patch
.download_hashes
.usable() == false)
2321 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": provides no usable hashes for " << patch
.file
2322 << " so fallback to complete download" << std::endl
;
2326 // patching with too many files is rather slow compared to a fast download
2327 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
2328 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
2331 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
2332 << ") so fallback to complete download" << std::endl
;
2336 // calculate the size of all patches we have to get
2337 unsigned short const sizeLimitPercent
= _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
2338 if (sizeLimitPercent
> 0)
2340 unsigned long long downloadSize
= std::accumulate(available_patches
.begin(),
2341 available_patches
.end(), 0llu, [](unsigned long long const T
, DiffInfo
const &I
) {
2342 return T
+ I
.download_hashes
.FileSize();
2344 if (downloadSize
!= 0)
2346 unsigned long long downloadSizeIdx
= 0;
2347 auto const types
= VectorizeString(Target
.Option(IndexTarget::COMPRESSIONTYPES
), ' ');
2348 for (auto const &t
: types
)
2350 std::string MetaKey
= Target
.MetaKey
;
2351 if (t
!= "uncompressed")
2353 HashStringList
const hsl
= GetExpectedHashesFor(MetaKey
);
2354 if (unlikely(hsl
.usable() == false))
2356 downloadSizeIdx
= hsl
.FileSize();
2359 unsigned long long const sizeLimit
= downloadSizeIdx
* sizeLimitPercent
;
2360 if ((sizeLimit
/100) < downloadSize
)
2363 std::clog
<< "Need " << downloadSize
<< " compressed bytes (Limit is " << (sizeLimit
/100) << ", "
2364 << "original is " << downloadSizeIdx
<< ") so fallback to complete download" << std::endl
;
2370 // we have something, queue the diffs
2371 string::size_type
const last_space
= Description
.rfind(" ");
2372 if(last_space
!= string::npos
)
2373 Description
.erase(last_space
, Description
.size()-last_space
);
2375 /* decide if we should download patches one by one or in one go:
2376 The first is good if the server merges patches, but many don't so client
2377 based merging can be attempt in which case the second is better.
2378 "bad things" will happen if patches are merged on the server,
2379 but client side merging is attempt as well */
2380 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
2381 if (pdiff_merge
== true)
2383 // reprepro adds this flag if it has merged patches on the server
2384 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
2385 pdiff_merge
= (precedence
!= "merged");
2390 std::string
const Final
= GetExistingFilename(CurrentPackagesFile
);
2391 if (unlikely(Final
.empty())) // because we wouldn't be called in such a case
2393 std::string
const PartialFile
= GetPartialFileNameFromURI(Target
.URI
);
2394 std::string
const PatchedFile
= GetKeepCompressedFileName(PartialFile
+ "-patched", Target
);
2395 if (RemoveFileForBootstrapLinking(Debug
, CurrentPackagesFile
, PartialFile
) == false ||
2396 RemoveFileForBootstrapLinking(Debug
, CurrentPackagesFile
, PatchedFile
) == false)
2398 for (auto const &ext
: APT::Configuration::getCompressorExtensions())
2400 if (RemoveFileForBootstrapLinking(Debug
, CurrentPackagesFile
, PartialFile
+ ext
) == false ||
2401 RemoveFileForBootstrapLinking(Debug
, CurrentPackagesFile
, PatchedFile
+ ext
) == false)
2404 std::string
const Ext
= Final
.substr(CurrentPackagesFile
.length());
2405 std::string
const Partial
= PartialFile
+ Ext
;
2406 if (symlink(Final
.c_str(), Partial
.c_str()) != 0)
2409 std::clog
<< "Bootstrap-linking for patching " << CurrentPackagesFile
2410 << " by linking " << Final
<< " to " << Partial
<< " failed!" << std::endl
;
2415 std::string indexURI
= Desc
.URI
;
2416 auto const byhashidx
= indexURI
.find("/by-hash/");
2417 if (byhashidx
!= std::string::npos
)
2418 indexURI
= indexURI
.substr(0, byhashidx
- strlen(".diff"));
2421 auto end
= indexURI
.length() - strlen(".diff/Index");
2422 if (CurrentCompressionExtension
!= "uncompressed")
2423 end
-= (1 + CurrentCompressionExtension
.length());
2424 indexURI
= indexURI
.substr(0, end
);
2427 if (pdiff_merge
== false)
2428 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, UsedMirror
, indexURI
, available_patches
);
2431 diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
2432 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
2433 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
, TransactionManager
,
2434 Target
, UsedMirror
, indexURI
,
2435 available_patches
[i
],
2445 void pkgAcqDiffIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2447 if (CommonFailed(GetDiffIndexURI(Target
), GetDiffIndexFileName(Target
.Description
), Message
, Cnf
))
2451 ExpectedAdditionalItems
= 0;
2454 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2455 << "Falling back to normal index file acquire" << std::endl
;
2457 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2460 void pkgAcqDiffIndex::Done(string
const &Message
,HashStringList
const &Hashes
, /*{{{*/
2461 pkgAcquire::MethodConfig
const * const Cnf
)
2464 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
2466 Item::Done(Message
, Hashes
, Cnf
);
2468 string
const FinalFile
= GetFinalFilename();
2469 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false))
2470 DestFile
= FinalFile
;
2472 if(ParseDiffIndex(DestFile
) == false)
2474 Failed("Message: Couldn't parse pdiff index", Cnf
);
2475 // queue for final move - this should happen even if we fail
2476 // while parsing (e.g. on sizelimit) and download the complete file.
2477 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2481 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2490 pkgAcqDiffIndex::~pkgAcqDiffIndex()
2496 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
2497 // ---------------------------------------------------------------------
2498 /* The package diff is added to the queue. one object is constructed
2499 * for each diff and the index
2501 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
* const Owner
,
2502 pkgAcqMetaClearSig
* const TransactionManager
,
2503 IndexTarget
const &Target
,
2504 std::string
const &indexUsedMirror
, std::string
const &indexURI
,
2505 vector
<DiffInfo
> const &diffs
)
2506 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), indexURI(indexURI
),
2507 available_patches(diffs
)
2509 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2511 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2514 Description
= Target
.Description
;
2515 Desc
.ShortDesc
= Target
.ShortDesc
;
2517 UsedMirror
= indexUsedMirror
;
2518 if (UsedMirror
== "DIRECT")
2520 else if (UsedMirror
.empty() == false && Description
.find(" ") != string::npos
)
2521 Description
.replace(0, Description
.find(" "), UsedMirror
);
2523 if(available_patches
.empty() == true)
2525 // we are done (yeah!), check hashes against the final file
2526 DestFile
= GetKeepCompressedFileName(GetFinalFileNameFromURI(Target
.URI
), Target
);
2531 State
= StateFetchDiff
;
2536 void pkgAcqIndexDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2538 pkgAcqBaseIndex::Failed(Message
,Cnf
);
2541 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2543 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2544 << "Falling back to normal index file acquire " << std::endl
;
2545 RenameOnError(PDiffError
);
2546 std::string
const patchname
= GetDiffsPatchFileName(DestFile
);
2547 if (RealFileExists(patchname
))
2548 Rename(patchname
, patchname
+ ".FAILED");
2549 std::string
const UnpatchedFile
= GetExistingFilename(GetPartialFileNameFromURI(Target
.URI
));
2550 if (UnpatchedFile
.empty() == false && FileExists(UnpatchedFile
))
2551 Rename(UnpatchedFile
, UnpatchedFile
+ ".FAILED");
2552 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2556 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
2557 void pkgAcqIndexDiffs::Finish(bool allDone
)
2560 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
2562 << Desc
.URI
<< std::endl
;
2564 // we restore the original name, this is required, otherwise
2565 // the file will be cleaned
2568 std::string
const Final
= GetKeepCompressedFileName(GetFinalFilename(), Target
);
2569 TransactionManager
->TransactionStageCopy(this, DestFile
, Final
);
2571 // this is for the "real" finish
2576 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
2583 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
2590 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
2592 // calc sha1 of the just patched file
2593 std::string
const PartialFile
= GetExistingFilename(GetPartialFileNameFromURI(Target
.URI
));
2594 if(unlikely(PartialFile
.empty()))
2596 Failed("Message: The file " + GetPartialFileNameFromURI(Target
.URI
) + " isn't available", NULL
);
2600 FileFd
fd(PartialFile
, FileFd::ReadOnly
, FileFd::Extension
);
2601 Hashes LocalHashesCalc
;
2602 LocalHashesCalc
.AddFD(fd
);
2603 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
2606 std::clog
<< "QueueNextDiff: " << PartialFile
<< " (" << LocalHashes
.find(NULL
)->toStr() << ")" << std::endl
;
2608 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
2609 if (unlikely(LocalHashes
.usable() == false || TargetFileHashes
.usable() == false))
2611 Failed("Local/Expected hashes are not usable for " + PartialFile
, NULL
);
2615 // final file reached before all patches are applied
2616 if(LocalHashes
== TargetFileHashes
)
2622 // remove all patches until the next matching patch is found
2623 // this requires the Index file to be ordered
2624 available_patches
.erase(available_patches
.begin(),
2625 std::find_if(available_patches
.begin(), available_patches
.end(), [&](DiffInfo
const &I
) {
2626 return I
.result_hashes
== LocalHashes
;
2629 // error checking and falling back if no patch was found
2630 if(available_patches
.empty() == true)
2632 Failed("No patches left to reach target for " + PartialFile
, NULL
);
2636 // queue the right diff
2637 Desc
.URI
= indexURI
+ ".diff/" + available_patches
[0].file
+ ".gz";
2638 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
2639 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + available_patches
[0].file
), Target
);
2642 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
2649 void pkgAcqIndexDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2650 pkgAcquire::MethodConfig
const * const Cnf
)
2653 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
2655 Item::Done(Message
, Hashes
, Cnf
);
2657 std::string
const UncompressedUnpatchedFile
= GetPartialFileNameFromURI(Target
.URI
);
2658 std::string
const UnpatchedFile
= GetExistingFilename(UncompressedUnpatchedFile
);
2659 std::string
const PatchFile
= GetDiffsPatchFileName(UnpatchedFile
);
2660 std::string
const PatchedFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
, Target
);
2664 // success in downloading a diff, enter ApplyDiff state
2665 case StateFetchDiff
:
2666 Rename(DestFile
, PatchFile
);
2667 DestFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
+ "-patched", Target
);
2669 std::clog
<< "Sending to rred method: " << UnpatchedFile
<< std::endl
;
2670 State
= StateApplyDiff
;
2672 Desc
.URI
= "rred:" + UnpatchedFile
;
2674 SetActiveSubprocess("rred");
2676 // success in download/apply a diff, queue next (if needed)
2677 case StateApplyDiff
:
2678 // remove the just applied patch and base file
2679 available_patches
.erase(available_patches
.begin());
2680 RemoveFile("pkgAcqIndexDiffs::Done", PatchFile
);
2681 RemoveFile("pkgAcqIndexDiffs::Done", UnpatchedFile
);
2683 std::clog
<< "Moving patched file in place: " << std::endl
2684 << DestFile
<< " -> " << PatchedFile
<< std::endl
;
2685 Rename(DestFile
, PatchedFile
);
2687 // see if there is more to download
2688 if(available_patches
.empty() == false)
2690 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, UsedMirror
, indexURI
, available_patches
);
2693 DestFile
= PatchedFile
;
2700 std::string
pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
2702 if(State
!= StateApplyDiff
)
2703 return pkgAcqBaseIndex::Custom600Headers();
2704 std::ostringstream patchhashes
;
2705 for (auto && hs
: available_patches
[0].result_hashes
)
2706 patchhashes
<< "\nStart-" << hs
.HashType() << "-Hash: " << hs
.HashValue();
2707 for (auto && hs
: available_patches
[0].patch_hashes
)
2708 patchhashes
<< "\nPatch-0-" << hs
.HashType() << "-Hash: " << hs
.HashValue();
2709 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2710 return patchhashes
.str();
2713 pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
2715 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
2716 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
* const Owner
,
2717 pkgAcqMetaClearSig
* const TransactionManager
,
2718 IndexTarget
const &Target
,
2719 std::string
const &indexUsedMirror
, std::string
const &indexURI
,
2720 DiffInfo
const &patch
,
2721 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
2722 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), indexURI(indexURI
),
2723 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
2725 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2727 Description
= Target
.Description
;
2728 UsedMirror
= indexUsedMirror
;
2729 if (UsedMirror
== "DIRECT")
2731 else if (UsedMirror
.empty() == false && Description
.find(" ") != string::npos
)
2732 Description
.replace(0, Description
.find(" "), UsedMirror
);
2735 Desc
.ShortDesc
= Target
.ShortDesc
;
2736 Desc
.URI
= indexURI
+ ".diff/" + patch
.file
+ ".gz";
2737 Desc
.Description
= Description
+ " " + patch
.file
+ ".pdiff";
2738 DestFile
= GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + patch
.file
+ ".gz");
2741 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
2746 void pkgAcqIndexMergeDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2749 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
2751 pkgAcqBaseIndex::Failed(Message
,Cnf
);
2754 // check if we are the first to fail, otherwise we are done here
2755 State
= StateDoneDiff
;
2756 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2757 I
!= allPatches
->end(); ++I
)
2758 if ((*I
)->State
== StateErrorDiff
)
2760 State
= StateErrorDiff
;
2764 // first failure means we should fallback
2765 State
= StateErrorDiff
;
2767 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
2768 RenameOnError(PDiffError
);
2769 if (RealFileExists(DestFile
))
2770 Rename(DestFile
, DestFile
+ ".FAILED");
2771 std::string
const UnpatchedFile
= GetExistingFilename(GetPartialFileNameFromURI(Target
.URI
));
2772 if (UnpatchedFile
.empty() == false && FileExists(UnpatchedFile
))
2773 Rename(UnpatchedFile
, UnpatchedFile
+ ".FAILED");
2775 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2778 void pkgAcqIndexMergeDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2779 pkgAcquire::MethodConfig
const * const Cnf
)
2782 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
2784 Item::Done(Message
, Hashes
, Cnf
);
2786 if (std::any_of(allPatches
->begin(), allPatches
->end(),
2787 [](pkgAcqIndexMergeDiffs
const * const P
) { return P
->State
== StateErrorDiff
; }))
2790 std::clog
<< "Another patch failed already, no point in processing this one." << std::endl
;
2791 State
= StateErrorDiff
;
2795 std::string
const UncompressedUnpatchedFile
= GetPartialFileNameFromURI(Target
.URI
);
2796 std::string
const UnpatchedFile
= GetExistingFilename(UncompressedUnpatchedFile
);
2797 if (UnpatchedFile
.empty())
2799 _error
->Fatal("Unpatched file %s doesn't exist (anymore)!", UncompressedUnpatchedFile
.c_str());
2800 State
= StateErrorDiff
;
2803 std::string
const PatchFile
= GetMergeDiffsPatchFileName(UnpatchedFile
, patch
.file
);
2804 std::string
const PatchedFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
, Target
);
2808 case StateFetchDiff
:
2809 Rename(DestFile
, PatchFile
);
2811 // check if this is the last completed diff
2812 State
= StateDoneDiff
;
2813 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2814 I
!= allPatches
->end(); ++I
)
2815 if ((*I
)->State
!= StateDoneDiff
)
2818 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
2821 // this is the last completed diff, so we are ready to apply now
2822 DestFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
+ "-patched", Target
);
2824 std::clog
<< "Sending to rred method: " << UnpatchedFile
<< std::endl
;
2825 State
= StateApplyDiff
;
2827 Desc
.URI
= "rred:" + UnpatchedFile
;
2829 SetActiveSubprocess("rred");
2831 case StateApplyDiff
:
2832 // success in download & apply all diffs, finialize and clean up
2834 std::clog
<< "Queue patched file in place: " << std::endl
2835 << DestFile
<< " -> " << PatchedFile
<< std::endl
;
2837 // queue for copy by the transaction manager
2838 TransactionManager
->TransactionStageCopy(this, DestFile
, GetKeepCompressedFileName(GetFinalFilename(), Target
));
2840 // ensure the ed's are gone regardless of list-cleanup
2841 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2842 I
!= allPatches
->end(); ++I
)
2843 RemoveFile("pkgAcqIndexMergeDiffs::Done", GetMergeDiffsPatchFileName(UnpatchedFile
, (*I
)->patch
.file
));
2844 RemoveFile("pkgAcqIndexMergeDiffs::Done", UnpatchedFile
);
2849 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
2851 case StateDoneDiff
: _error
->Fatal("Done called for %s which is in an invalid Done state", PatchFile
.c_str()); break;
2852 case StateErrorDiff
: _error
->Fatal("Done called for %s which is in an invalid Error state", PatchFile
.c_str()); break;
2856 std::string
pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
2858 if(State
!= StateApplyDiff
)
2859 return pkgAcqBaseIndex::Custom600Headers();
2860 std::ostringstream patchhashes
;
2861 unsigned int seen_patches
= 0;
2862 for (auto && hs
: (*allPatches
)[0]->patch
.result_hashes
)
2863 patchhashes
<< "\nStart-" << hs
.HashType() << "-Hash: " << hs
.HashValue();
2864 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2865 I
!= allPatches
->end(); ++I
)
2867 HashStringList
const ExpectedHashes
= (*I
)->patch
.patch_hashes
;
2868 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2869 patchhashes
<< "\nPatch-" << std::to_string(seen_patches
) << "-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2872 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2873 return patchhashes
.str();
2876 pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
2878 // AcqIndex::AcqIndex - Constructor /*{{{*/
2879 pkgAcqIndex::pkgAcqIndex(pkgAcquire
* const Owner
,
2880 pkgAcqMetaClearSig
* const TransactionManager
,
2881 IndexTarget
const &Target
, bool const Derived
)
2882 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), Stage(STAGE_DOWNLOAD
),
2883 CompressionExtensions(Target
.Option(IndexTarget::COMPRESSIONTYPES
))
2887 Init(Target
.URI
, Target
.Description
, Target
.ShortDesc
);
2889 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2890 std::clog
<< "New pkgIndex with TransactionManager "
2891 << TransactionManager
<< std::endl
;
2894 // AcqIndex::Init - defered Constructor /*{{{*/
2895 static void NextCompressionExtension(std::string
&CurrentCompressionExtension
, std::string
&CompressionExtensions
, bool const preview
)
2897 size_t const nextExt
= CompressionExtensions
.find(' ');
2898 if (nextExt
== std::string::npos
)
2900 CurrentCompressionExtension
= CompressionExtensions
;
2901 if (preview
== false)
2902 CompressionExtensions
.clear();
2906 CurrentCompressionExtension
= CompressionExtensions
.substr(0, nextExt
);
2907 if (preview
== false)
2908 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
2911 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
2912 string
const &ShortDesc
)
2914 Stage
= STAGE_DOWNLOAD
;
2916 DestFile
= GetPartialFileNameFromURI(URI
);
2917 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, false);
2919 if (CurrentCompressionExtension
== "uncompressed")
2923 else if (CurrentCompressionExtension
== "by-hash")
2925 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, true);
2926 if(unlikely(CurrentCompressionExtension
.empty()))
2928 if (CurrentCompressionExtension
!= "uncompressed")
2930 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2931 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2936 HashStringList
const Hashes
= GetExpectedHashes();
2937 HashString
const * const TargetHash
= Hashes
.find(NULL
);
2938 if (unlikely(TargetHash
== nullptr))
2940 std::string
const ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
2941 size_t const trailing_slash
= Desc
.URI
.find_last_of("/");
2942 if (unlikely(trailing_slash
== std::string::npos
))
2944 Desc
.URI
= Desc
.URI
.replace(
2946 Desc
.URI
.substr(trailing_slash
+1).size()+1,
2949 else if (unlikely(CurrentCompressionExtension
.empty()))
2953 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2954 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2957 // store file size of the download to ensure the fetcher gives
2958 // accurate progress reporting
2959 FileSize
= GetExpectedHashes().FileSize();
2961 Desc
.Description
= URIDesc
;
2963 Desc
.ShortDesc
= ShortDesc
;
2968 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2969 // ---------------------------------------------------------------------
2970 /* The only header we use is the last-modified header. */
2971 string
pkgAcqIndex::Custom600Headers() const
2974 string msg
= "\nIndex-File: true";
2976 if (TransactionManager
->LastMetaIndexParser
== NULL
)
2978 std::string
const Final
= GetFinalFilename();
2981 if (stat(Final
.c_str(),&Buf
) == 0)
2982 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
, false);
2985 if(Target
.IsOptional
)
2986 msg
+= "\nFail-Ignore: true";
2991 // AcqIndex::Failed - getting the indexfile failed /*{{{*/
2992 bool pkgAcqIndex::CommonFailed(std::string
const &TargetURI
, std::string
const TargetDesc
,
2993 std::string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
2995 pkgAcqBaseIndex::Failed(Message
,Cnf
);
2997 if (UsedMirror
.empty() == false && UsedMirror
!= "DIRECT" &&
2998 LookupTag(Message
, "FailReason") == "HttpError404")
3000 UsedMirror
= "DIRECT";
3001 if (Desc
.URI
.find("/by-hash/") != std::string::npos
)
3002 CompressionExtensions
= "by-hash " + CompressionExtensions
;
3004 CompressionExtensions
= CurrentCompressionExtension
+ ' ' + CompressionExtensions
;
3005 Init(TargetURI
, TargetDesc
, Desc
.ShortDesc
);
3010 // authorisation matches will not be fixed by other compression types
3011 if (Status
!= StatAuthError
)
3013 if (CompressionExtensions
.empty() == false)
3015 Init(TargetURI
, Desc
.Description
, Desc
.ShortDesc
);
3022 void pkgAcqIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
3024 if (CommonFailed(Target
.URI
, Target
.Description
, Message
, Cnf
))
3027 if(Target
.IsOptional
&& GetExpectedHashes().empty() && Stage
== STAGE_DOWNLOAD
)
3030 TransactionManager
->AbortTransaction();
3033 // AcqIndex::Done - Finished a fetch /*{{{*/
3034 // ---------------------------------------------------------------------
3035 /* This goes through a number of states.. On the initial fetch the
3036 method could possibly return an alternate filename which points
3037 to the uncompressed version of the file. If this is so the file
3038 is copied into the partial directory. In all other cases the file
3039 is decompressed with a compressed uri. */
3040 void pkgAcqIndex::Done(string
const &Message
,
3041 HashStringList
const &Hashes
,
3042 pkgAcquire::MethodConfig
const * const Cfg
)
3044 Item::Done(Message
,Hashes
,Cfg
);
3048 case STAGE_DOWNLOAD
:
3049 StageDownloadDone(Message
);
3051 case STAGE_DECOMPRESS_AND_VERIFY
:
3052 StageDecompressDone();
3057 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
3058 void pkgAcqIndex::StageDownloadDone(string
const &Message
)
3063 std::string
const AltFilename
= LookupTag(Message
,"Alt-Filename");
3064 std::string Filename
= LookupTag(Message
,"Filename");
3066 // we need to verify the file against the current Release file again
3067 // on if-modfied-since hit to avoid a stale attack against us
3068 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
3070 // copy FinalFile into partial/ so that we check the hash again
3071 string
const FinalFile
= GetExistingFilename(GetFinalFileNameFromURI(Target
.URI
));
3072 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
3073 unlink(DestFile
.c_str());
3074 if (symlink(FinalFile
.c_str(), DestFile
.c_str()) != 0)
3075 _error
->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking final file %s back to %s failed", FinalFile
.c_str(), DestFile
.c_str());
3078 EraseFileName
= DestFile
;
3079 Filename
= DestFile
;
3081 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
3082 if (Filename
!= DestFile
&& flExtension(Filename
) == flExtension(DestFile
))
3083 Desc
.URI
= "copy:" + Filename
;
3085 Desc
.URI
= "store:" + Filename
;
3087 SetActiveSubprocess(::URI(Desc
.URI
).Access
);
3090 // methods like file:// give us an alternative (uncompressed) file
3091 else if (Target
.KeepCompressed
== false && AltFilename
.empty() == false)
3093 Filename
= AltFilename
;
3094 EraseFileName
.clear();
3096 // Methods like e.g. "file:" will give us a (compressed) FileName that is
3097 // not the "DestFile" we set, in this case we uncompress from the local file
3098 else if (Filename
!= DestFile
&& RealFileExists(DestFile
) == false)
3100 // symlinking ensures that the filename can be used for compression detection
3101 // that is e.g. needed for by-hash which has no extension over file
3102 if (symlink(Filename
.c_str(),DestFile
.c_str()) != 0)
3103 _error
->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking file %s to %s failed", Filename
.c_str(), DestFile
.c_str());
3106 EraseFileName
= DestFile
;
3107 Filename
= DestFile
;
3111 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
3112 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
3113 if (Filename
!= DestFile
&& flExtension(Filename
) == flExtension(DestFile
))
3114 Desc
.URI
= "copy:" + Filename
;
3116 Desc
.URI
= "store:" + Filename
;
3117 if (DestFile
== Filename
)
3119 if (CurrentCompressionExtension
== "uncompressed")
3120 return StageDecompressDone();
3121 DestFile
= "/dev/null";
3124 if (EraseFileName
.empty() && Filename
!= AltFilename
)
3125 EraseFileName
= Filename
;
3127 // queue uri for the next stage
3129 SetActiveSubprocess(::URI(Desc
.URI
).Access
);
3132 // AcqIndex::StageDecompressDone - Final verification /*{{{*/
3133 void pkgAcqIndex::StageDecompressDone()
3135 if (DestFile
== "/dev/null")
3136 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
3138 // Done, queue for rename on transaction finished
3139 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
3142 pkgAcqIndex::~pkgAcqIndex() {}
3145 // AcqArchive::AcqArchive - Constructor /*{{{*/
3146 // ---------------------------------------------------------------------
3147 /* This just sets up the initial fetch environment and queues the first
3149 pkgAcqArchive::pkgAcqArchive(pkgAcquire
* const Owner
,pkgSourceList
* const Sources
,
3150 pkgRecords
* const Recs
,pkgCache::VerIterator
const &Version
,
3151 string
&StoreFilename
) :
3152 Item(Owner
), d(NULL
), LocalSource(false), Version(Version
), Sources(Sources
), Recs(Recs
),
3153 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
3156 Retries
= _config
->FindI("Acquire::Retries",0);
3158 if (Version
.Arch() == 0)
3160 _error
->Error(_("I wasn't able to locate a file for the %s package. "
3161 "This might mean you need to manually fix this package. "
3162 "(due to missing arch)"),
3163 Version
.ParentPkg().FullName().c_str());
3167 /* We need to find a filename to determine the extension. We make the
3168 assumption here that all the available sources for this version share
3169 the same extension.. */
3170 // Skip not source sources, they do not have file fields.
3171 for (; Vf
.end() == false; ++Vf
)
3173 if (Vf
.File().Flagged(pkgCache::Flag::NotSource
))
3178 // Does not really matter here.. we are going to fail out below
3179 if (Vf
.end() != true)
3181 // If this fails to get a file name we will bomb out below.
3182 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
3183 if (_error
->PendingError() == true)
3186 // Generate the final file name as: package_version_arch.foo
3187 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
3188 QuoteString(Version
.VerStr(),"_:") + '_' +
3189 QuoteString(Version
.Arch(),"_:.") +
3190 "." + flExtension(Parse
.FileName());
3193 // check if we have one trusted source for the package. if so, switch
3194 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
3195 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
3196 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
3197 bool seenUntrusted
= false;
3198 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
3200 pkgIndexFile
*Index
;
3201 if (Sources
->FindIndex(i
.File(),Index
) == false)
3204 if (debugAuth
== true)
3205 std::cerr
<< "Checking index: " << Index
->Describe()
3206 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
3208 if (Index
->IsTrusted() == true)
3211 if (allowUnauth
== false)
3215 seenUntrusted
= true;
3218 // "allow-unauthenticated" restores apts old fetching behaviour
3219 // that means that e.g. unauthenticated file:// uris are higher
3220 // priority than authenticated http:// uris
3221 if (allowUnauth
== true && seenUntrusted
== true)
3225 if (QueueNext() == false && _error
->PendingError() == false)
3226 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
3227 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
3230 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
3231 // ---------------------------------------------------------------------
3232 /* This queues the next available file version for download. It checks if
3233 the archive is already available in the cache and stashs the MD5 for
3235 bool pkgAcqArchive::QueueNext()
3237 for (; Vf
.end() == false; ++Vf
)
3239 pkgCache::PkgFileIterator
const PkgF
= Vf
.File();
3240 // Ignore not source sources
3241 if (PkgF
.Flagged(pkgCache::Flag::NotSource
))
3244 // Try to cross match against the source list
3245 pkgIndexFile
*Index
;
3246 if (Sources
->FindIndex(PkgF
, Index
) == false)
3248 LocalSource
= PkgF
.Flagged(pkgCache::Flag::LocalSource
);
3250 // only try to get a trusted package from another source if that source
3252 if(Trusted
&& !Index
->IsTrusted())
3255 // Grab the text package record
3256 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
3257 if (_error
->PendingError() == true)
3260 string PkgFile
= Parse
.FileName();
3261 ExpectedHashes
= Parse
.Hashes();
3263 if (PkgFile
.empty() == true)
3264 return _error
->Error(_("The package index files are corrupted. No Filename: "
3265 "field for package %s."),
3266 Version
.ParentPkg().Name());
3268 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
3269 Desc
.Description
= Index
->ArchiveInfo(Version
);
3271 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
3273 // See if we already have the file. (Legacy filenames)
3274 FileSize
= Version
->Size
;
3275 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
3277 if (stat(FinalFile
.c_str(),&Buf
) == 0)
3279 // Make sure the size matches
3280 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
3285 StoreFilename
= DestFile
= FinalFile
;
3289 /* Hmm, we have a file and its size does not match, this means it is
3290 an old style mismatched arch */
3291 RemoveFile("pkgAcqArchive::QueueNext", FinalFile
);
3294 // Check it again using the new style output filenames
3295 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
3296 if (stat(FinalFile
.c_str(),&Buf
) == 0)
3298 // Make sure the size matches
3299 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
3304 StoreFilename
= DestFile
= FinalFile
;
3308 /* Hmm, we have a file and its size does not match, this shouldn't
3310 RemoveFile("pkgAcqArchive::QueueNext", FinalFile
);
3313 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
3315 // Check the destination file
3316 if (stat(DestFile
.c_str(),&Buf
) == 0)
3318 // Hmm, the partial file is too big, erase it
3319 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
3320 RemoveFile("pkgAcqArchive::QueueNext", DestFile
);
3322 PartialSize
= Buf
.st_size
;
3325 // Disables download of archives - useful if no real installation follows,
3326 // e.g. if we are just interested in proposed installation order
3327 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
3332 StoreFilename
= DestFile
= FinalFile
;
3345 // AcqArchive::Done - Finished fetching /*{{{*/
3346 // ---------------------------------------------------------------------
3348 void pkgAcqArchive::Done(string
const &Message
, HashStringList
const &Hashes
,
3349 pkgAcquire::MethodConfig
const * const Cfg
)
3351 Item::Done(Message
, Hashes
, Cfg
);
3353 // Grab the output filename
3354 std::string
const FileName
= LookupTag(Message
,"Filename");
3355 if (DestFile
!= FileName
&& RealFileExists(DestFile
) == false)
3357 StoreFilename
= DestFile
= FileName
;
3363 // Done, move it into position
3364 string
const FinalFile
= GetFinalFilename();
3365 Rename(DestFile
,FinalFile
);
3366 StoreFilename
= DestFile
= FinalFile
;
3370 // AcqArchive::Failed - Failure handler /*{{{*/
3371 // ---------------------------------------------------------------------
3372 /* Here we try other sources */
3373 void pkgAcqArchive::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
3375 Item::Failed(Message
,Cnf
);
3377 /* We don't really want to retry on failed media swaps, this prevents
3378 that. An interesting observation is that permanent failures are not
3380 if (Cnf
->Removable
== true &&
3381 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3383 // Vf = Version.FileList();
3384 while (Vf
.end() == false) ++Vf
;
3385 StoreFilename
= string();
3390 if (QueueNext() == false)
3392 // This is the retry counter
3394 Cnf
->LocalOnly
== false &&
3395 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3398 Vf
= Version
.FileList();
3399 if (QueueNext() == true)
3403 StoreFilename
= string();
3408 APT_PURE
bool pkgAcqArchive::IsTrusted() const /*{{{*/
3413 void pkgAcqArchive::Finished() /*{{{*/
3415 if (Status
== pkgAcquire::Item::StatDone
&&
3418 StoreFilename
= string();
3421 std::string
pkgAcqArchive::DescURI() const /*{{{*/
3426 std::string
pkgAcqArchive::ShortDesc() const /*{{{*/
3428 return Desc
.ShortDesc
;
3431 pkgAcqArchive::~pkgAcqArchive() {}
3433 // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
3434 class pkgAcqChangelog::Private
3437 std::string FinalFile
;
3439 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::VerIterator
const &Ver
,
3440 std::string
const &DestDir
, std::string
const &DestFilename
) :
3441 pkgAcquire::Item(Owner
), d(new pkgAcqChangelog::Private()), SrcName(Ver
.SourcePkgName()), SrcVersion(Ver
.SourceVerStr())
3443 Desc
.URI
= URI(Ver
);
3444 Init(DestDir
, DestFilename
);
3446 // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
3447 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::RlsFileIterator
const &RlsFile
,
3448 char const * const Component
, char const * const SrcName
, char const * const SrcVersion
,
3449 const string
&DestDir
, const string
&DestFilename
) :
3450 pkgAcquire::Item(Owner
), d(new pkgAcqChangelog::Private()), SrcName(SrcName
), SrcVersion(SrcVersion
)
3452 Desc
.URI
= URI(RlsFile
, Component
, SrcName
, SrcVersion
);
3453 Init(DestDir
, DestFilename
);
3455 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
,
3456 std::string
const &URI
, char const * const SrcName
, char const * const SrcVersion
,
3457 const string
&DestDir
, const string
&DestFilename
) :
3458 pkgAcquire::Item(Owner
), d(new pkgAcqChangelog::Private()), SrcName(SrcName
), SrcVersion(SrcVersion
)
3461 Init(DestDir
, DestFilename
);
3463 void pkgAcqChangelog::Init(std::string
const &DestDir
, std::string
const &DestFilename
)
3465 if (Desc
.URI
.empty())
3468 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3469 strprintf(ErrorText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3470 // Let the error message print something sensible rather than "Failed to fetch /"
3471 if (DestFilename
.empty())
3472 DestFile
= SrcName
+ ".changelog";
3474 DestFile
= DestFilename
;
3475 Desc
.URI
= "changelog:/" + DestFile
;
3479 std::string DestFileName
;
3480 if (DestFilename
.empty())
3481 DestFileName
= flCombine(DestFile
, SrcName
+ ".changelog");
3483 DestFileName
= flCombine(DestFile
, DestFilename
);
3485 std::string
const SandboxUser
= _config
->Find("APT::Sandbox::User");
3486 std::string
const systemTemp
= GetTempDir(SandboxUser
);
3488 snprintf(tmpname
, sizeof(tmpname
), "%s/apt-changelog-XXXXXX", systemTemp
.c_str());
3489 if (NULL
== mkdtemp(tmpname
))
3491 _error
->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName
.c_str(), SrcVersion
.c_str());
3495 TemporaryDirectory
= tmpname
;
3497 ChangeOwnerAndPermissionOfFile("Item::QueueURI", TemporaryDirectory
.c_str(),
3498 SandboxUser
.c_str(), ROOT_GROUP
, 0700);
3500 DestFile
= flCombine(TemporaryDirectory
, DestFileName
);
3501 if (DestDir
.empty() == false)
3503 d
->FinalFile
= flCombine(DestDir
, DestFileName
);
3504 if (RealFileExists(d
->FinalFile
))
3506 FileFd file1
, file2
;
3507 if (file1
.Open(DestFile
, FileFd::WriteOnly
| FileFd::Create
| FileFd::Exclusive
) &&
3508 file2
.Open(d
->FinalFile
, FileFd::ReadOnly
) && CopyFile(file2
, file1
))
3510 struct timeval times
[2];
3511 times
[0].tv_sec
= times
[1].tv_sec
= file2
.ModificationTime();
3512 times
[0].tv_usec
= times
[1].tv_usec
= 0;
3513 utimes(DestFile
.c_str(), times
);
3518 Desc
.ShortDesc
= "Changelog";
3519 strprintf(Desc
.Description
, "%s %s %s Changelog", URI::SiteOnly(Desc
.URI
).c_str(), SrcName
.c_str(), SrcVersion
.c_str());
3524 std::string
pkgAcqChangelog::URI(pkgCache::VerIterator
const &Ver
) /*{{{*/
3526 std::string
const confOnline
= "Acquire::Changelogs::AlwaysOnline";
3527 bool AlwaysOnline
= _config
->FindB(confOnline
, false);
3528 if (AlwaysOnline
== false)
3529 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
3531 pkgCache::PkgFileIterator
const PF
= VF
.File();
3532 if (PF
.Flagged(pkgCache::Flag::NotSource
) || PF
->Release
== 0)
3534 pkgCache::RlsFileIterator
const RF
= PF
.ReleaseFile();
3535 if (RF
->Origin
!= 0 && _config
->FindB(confOnline
+ "::Origin::" + RF
.Origin(), false))
3537 AlwaysOnline
= true;
3541 if (AlwaysOnline
== false)
3543 pkgCache::PkgIterator
const Pkg
= Ver
.ParentPkg();
3544 if (Pkg
->CurrentVer
!= 0 && Pkg
.CurrentVer() == Ver
)
3546 std::string
const root
= _config
->FindDir("Dir");
3547 std::string
const basename
= root
+ std::string("usr/share/doc/") + Pkg
.Name() + "/changelog";
3548 std::string
const debianname
= basename
+ ".Debian";
3549 if (FileExists(debianname
))
3550 return "copy://" + debianname
;
3551 else if (FileExists(debianname
+ ".gz"))
3552 return "gzip://" + debianname
+ ".gz";
3553 else if (FileExists(basename
))
3554 return "copy://" + basename
;
3555 else if (FileExists(basename
+ ".gz"))
3556 return "gzip://" + basename
+ ".gz";
3560 char const * const SrcName
= Ver
.SourcePkgName();
3561 char const * const SrcVersion
= Ver
.SourceVerStr();
3562 // find the first source for this version which promises a changelog
3563 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
3565 pkgCache::PkgFileIterator
const PF
= VF
.File();
3566 if (PF
.Flagged(pkgCache::Flag::NotSource
) || PF
->Release
== 0)
3568 pkgCache::RlsFileIterator
const RF
= PF
.ReleaseFile();
3569 std::string
const uri
= URI(RF
, PF
.Component(), SrcName
, SrcVersion
);
3576 std::string
pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator
const &Rls
)
3578 if (Rls
.end() == true || (Rls
->Label
== 0 && Rls
->Origin
== 0))
3580 std::string
const serverConfig
= "Acquire::Changelogs::URI";
3582 #define APT_EMPTY_SERVER \
3583 if (server.empty() == false) \
3585 if (server != "no") \
3589 #define APT_CHECK_SERVER(X, Y) \
3592 std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
3593 server = _config->Find(specialServerConfig); \
3596 // this way e.g. Debian-Security can fallback to Debian
3597 APT_CHECK_SERVER(Label
, "Override::")
3598 APT_CHECK_SERVER(Origin
, "Override::")
3600 if (RealFileExists(Rls
.FileName()))
3602 _error
->PushToStack();
3604 /* This can be costly. A caller wanting to get millions of URIs might
3605 want to do this on its own once and use Override settings.
3606 We don't do this here as Origin/Label are not as unique as they
3607 should be so this could produce request order-dependent anomalies */
3608 if (OpenMaybeClearSignedFile(Rls
.FileName(), rf
) == true)
3610 pkgTagFile
TagFile(&rf
);
3611 pkgTagSection Section
;
3612 if (TagFile
.Step(Section
) == true)
3613 server
= Section
.FindS("Changelogs");
3615 _error
->RevertToStack();
3619 APT_CHECK_SERVER(Label
, "")
3620 APT_CHECK_SERVER(Origin
, "")
3621 #undef APT_CHECK_SERVER
3622 #undef APT_EMPTY_SERVER
3625 std::string
pkgAcqChangelog::URI(pkgCache::RlsFileIterator
const &Rls
,
3626 char const * const Component
, char const * const SrcName
,
3627 char const * const SrcVersion
)
3629 return URI(URITemplate(Rls
), Component
, SrcName
, SrcVersion
);
3631 std::string
pkgAcqChangelog::URI(std::string
const &Template
,
3632 char const * const Component
, char const * const SrcName
,
3633 char const * const SrcVersion
)
3635 if (Template
.find("@CHANGEPATH@") == std::string::npos
)
3638 // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
3639 std::string Src
= SrcName
;
3640 std::string path
= APT::String::Startswith(SrcName
, "lib") ? Src
.substr(0, 4) : Src
.substr(0,1);
3641 path
.append("/").append(Src
).append("/");
3642 path
.append(Src
).append("_").append(StripEpoch(SrcVersion
));
3643 // we omit component for releases without one (= flat-style repositories)
3644 if (Component
!= NULL
&& strlen(Component
) != 0)
3645 path
= std::string(Component
) + "/" + path
;
3647 return SubstVar(Template
, "@CHANGEPATH@", path
);
3650 // AcqChangelog::Failed - Failure handler /*{{{*/
3651 void pkgAcqChangelog::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3653 Item::Failed(Message
,Cnf
);
3655 std::string errText
;
3656 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3657 strprintf(errText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3659 // Error is probably something techy like 404 Not Found
3660 if (ErrorText
.empty())
3661 ErrorText
= errText
;
3663 ErrorText
= errText
+ " (" + ErrorText
+ ")";
3666 // AcqChangelog::Done - Item downloaded OK /*{{{*/
3667 void pkgAcqChangelog::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3668 pkgAcquire::MethodConfig
const * const Cnf
)
3670 Item::Done(Message
,CalcHashes
,Cnf
);
3671 if (d
->FinalFile
.empty() == false)
3673 if (RemoveFile("pkgAcqChangelog::Done", d
->FinalFile
) == false ||
3674 Rename(DestFile
, d
->FinalFile
) == false)
3681 pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
3683 if (TemporaryDirectory
.empty() == false)
3685 RemoveFile("~pkgAcqChangelog", DestFile
);
3686 rmdir(TemporaryDirectory
.c_str());
3692 // AcqFile::pkgAcqFile - Constructor /*{{{*/
3693 pkgAcqFile::pkgAcqFile(pkgAcquire
* const Owner
,string
const &URI
, HashStringList
const &Hashes
,
3694 unsigned long long const Size
,string
const &Dsc
,string
const &ShortDesc
,
3695 const string
&DestDir
, const string
&DestFilename
,
3696 bool const IsIndexFile
) :
3697 Item(Owner
), d(NULL
), IsIndexFile(IsIndexFile
), ExpectedHashes(Hashes
)
3699 Retries
= _config
->FindI("Acquire::Retries",0);
3701 if(!DestFilename
.empty())
3702 DestFile
= DestFilename
;
3703 else if(!DestDir
.empty())
3704 DestFile
= DestDir
+ "/" + flNotDir(URI
);
3706 DestFile
= flNotDir(URI
);
3710 Desc
.Description
= Dsc
;
3713 // Set the short description to the archive component
3714 Desc
.ShortDesc
= ShortDesc
;
3716 // Get the transfer sizes
3719 if (stat(DestFile
.c_str(),&Buf
) == 0)
3721 // Hmm, the partial file is too big, erase it
3722 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
3723 RemoveFile("pkgAcqFile", DestFile
);
3725 PartialSize
= Buf
.st_size
;
3731 // AcqFile::Done - Item downloaded OK /*{{{*/
3732 void pkgAcqFile::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3733 pkgAcquire::MethodConfig
const * const Cnf
)
3735 Item::Done(Message
,CalcHashes
,Cnf
);
3737 std::string
const FileName
= LookupTag(Message
,"Filename");
3740 // The files timestamp matches
3741 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
3744 // We have to copy it into place
3745 if (RealFileExists(DestFile
.c_str()) == false)
3748 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
3749 Cnf
->Removable
== true)
3751 Desc
.URI
= "copy:" + FileName
;
3756 // Erase the file if it is a symlink so we can overwrite it
3758 if (lstat(DestFile
.c_str(),&St
) == 0)
3760 if (S_ISLNK(St
.st_mode
) != 0)
3761 RemoveFile("pkgAcqFile::Done", DestFile
);
3765 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
3767 _error
->PushToStack();
3768 _error
->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile
.c_str());
3769 std::stringstream msg
;
3770 _error
->DumpErrors(msg
, GlobalError::DEBUG
, false);
3771 _error
->RevertToStack();
3772 ErrorText
= msg
.str();
3779 // AcqFile::Failed - Failure handler /*{{{*/
3780 // ---------------------------------------------------------------------
3781 /* Here we try other sources */
3782 void pkgAcqFile::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3784 Item::Failed(Message
,Cnf
);
3786 // This is the retry counter
3788 Cnf
->LocalOnly
== false &&
3789 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3799 string
pkgAcqFile::Custom600Headers() const /*{{{*/
3802 return "\nIndex-File: true";
3806 pkgAcqFile::~pkgAcqFile() {}