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>
54 static void printHashSumComparision(std::string
const &URI
, HashStringList
const &Expected
, HashStringList
const &Actual
) /*{{{*/
56 if (_config
->FindB("Debug::Acquire::HashSumMismatch", false) == false)
58 std::cerr
<< std::endl
<< URI
<< ":" << std::endl
<< " Expected Hash: " << std::endl
;
59 for (HashStringList::const_iterator hs
= Expected
.begin(); hs
!= Expected
.end(); ++hs
)
60 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
61 std::cerr
<< " Actual Hash: " << std::endl
;
62 for (HashStringList::const_iterator hs
= Actual
.begin(); hs
!= Actual
.end(); ++hs
)
63 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
66 static std::string
GetPartialFileName(std::string
const &file
) /*{{{*/
68 std::string DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
73 static std::string
GetPartialFileNameFromURI(std::string
const &uri
) /*{{{*/
75 return GetPartialFileName(URItoFileName(uri
));
78 static std::string
GetFinalFileNameFromURI(std::string
const &uri
) /*{{{*/
80 return _config
->FindDir("Dir::State::lists") + URItoFileName(uri
);
83 static std::string
GetKeepCompressedFileName(std::string file
, IndexTarget
const &Target
)/*{{{*/
85 if (Target
.KeepCompressed
== false)
88 std::string
const CompressionTypes
= Target
.Option(IndexTarget::COMPRESSIONTYPES
);
89 if (CompressionTypes
.empty() == false)
91 std::string
const ext
= CompressionTypes
.substr(0, CompressionTypes
.find(' '));
92 if (ext
!= "uncompressed")
93 file
.append(".").append(ext
);
98 static std::string
GetCompressedFileName(IndexTarget
const &Target
, std::string
const &Name
, std::string
const &Ext
) /*{{{*/
100 if (Ext
.empty() || Ext
== "uncompressed")
103 // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
104 // file when its doing the indexcopy
105 if (Target
.URI
.substr(0,6) == "cdrom:")
108 // adjust DestFile if its compressed on disk
109 if (Target
.KeepCompressed
== true)
110 return Name
+ '.' + Ext
;
114 static std::string
GetMergeDiffsPatchFileName(std::string
const &Final
, std::string
const &Patch
)/*{{{*/
116 // rred expects the patch as $FinalFile.ed.$patchname.gz
117 return Final
+ ".ed." + Patch
+ ".gz";
120 static std::string
GetDiffsPatchFileName(std::string
const &Final
) /*{{{*/
122 // rred expects the patch as $FinalFile.ed
123 return Final
+ ".ed";
126 static bool BootstrapPDiffWith(std::string
const &PartialFile
, std::string
const &FinalFile
, IndexTarget
const &Target
)/*{{{*/
128 // patching needs to be bootstrapped with the 'old' version
129 std::vector
<std::string
> types
= VectorizeString(Target
.Option(IndexTarget::COMPRESSIONTYPES
), ' ');
130 auto typeItr
= types
.cbegin();
131 for (; typeItr
!= types
.cend(); ++typeItr
)
133 std::string Final
= FinalFile
;
134 if (*typeItr
!= "uncompressed")
135 Final
.append(".").append(*typeItr
);
136 if (RealFileExists(Final
) == false)
138 std::string Partial
= PartialFile
;
139 if (*typeItr
!= "uncompressed")
140 Partial
.append(".").append(*typeItr
);
141 if (FileExists(Partial
.c_str()) == true)
143 if (symlink(Final
.c_str(), Partial
.c_str()) != 0)
147 return typeItr
!= types
.cend();
150 static bool RemoveFile(char const * const Function
, std::string
const &FileName
)/*{{{*/
152 if (FileName
== "/dev/null")
155 if (unlink(FileName
.c_str()) != 0)
159 return _error
->WarningE(Function
, "Removal of file %s failed", FileName
.c_str());
165 static bool MessageInsecureRepository(bool const isError
, std::string
const &msg
)/*{{{*/
169 _error
->Error("%s", msg
.c_str());
170 _error
->Notice("%s", _("Updating such a repository securily is impossible and therefore disabled by default."));
174 _error
->Warning("%s", msg
.c_str());
175 _error
->Notice("%s", _("Data from such a repository can not be authenticated and is therefore potentially dangerous to use."));
177 _error
->Notice("%s", _("See apt-secure(8) manpage for repository creation and user configuration details."));
180 static bool MessageInsecureRepository(bool const isError
, char const * const msg
, std::string
const &repo
)
183 strprintf(m
, msg
, repo
.c_str());
184 return MessageInsecureRepository(isError
, m
);
187 static bool AllowInsecureRepositories(char const * const msg
, std::string
const &repo
,/*{{{*/
188 metaIndex
const * const MetaIndexParser
, pkgAcqMetaClearSig
* const TransactionManager
, pkgAcquire::Item
* const I
)
190 if(MetaIndexParser
->GetTrusted() == metaIndex::TRI_YES
)
193 if (_config
->FindB("Acquire::AllowInsecureRepositories") == true)
195 MessageInsecureRepository(false, msg
, repo
);
199 MessageInsecureRepository(true, msg
, repo
);
200 TransactionManager
->AbortTransaction();
201 I
->Status
= pkgAcquire::Item::StatError
;
205 static HashStringList
GetExpectedHashesFromFor(metaIndex
* const Parser
, std::string
const &MetaKey
)/*{{{*/
208 return HashStringList();
209 metaIndex::checkSum
* const R
= Parser
->Lookup(MetaKey
);
211 return HashStringList();
216 // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
217 /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
218 It is best to implement it as broadly as possible, while ::HashesRequired defaults
219 to true and should be as restrictive as possible for false cases. Note that if
220 a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
221 ::HashesRequired is called to evaluate if its okay to have no hashes. */
222 APT_CONST
bool pkgAcqTransactionItem::HashesRequired() const
224 /* signed repositories obviously have a parser and good hashes.
225 unsigned repositories, too, as even if we can't trust them for security,
226 we can at least trust them for integrity of the download itself.
227 Only repositories without a Release file can (obviously) not have
228 hashes – and they are very uncommon and strongly discouraged */
229 return TransactionManager
->MetaIndexParser
!= NULL
&&
230 TransactionManager
->MetaIndexParser
->GetLoadedSuccessfully() != metaIndex::TRI_UNSET
;
232 HashStringList
pkgAcqTransactionItem::GetExpectedHashes() const
234 return GetExpectedHashesFor(GetMetaKey());
237 APT_CONST
bool pkgAcqMetaBase::HashesRequired() const
239 // Release and co have no hashes 'by design'.
242 HashStringList
pkgAcqMetaBase::GetExpectedHashes() const
244 return HashStringList();
247 APT_CONST
bool pkgAcqIndexDiffs::HashesRequired() const
249 /* We don't always have the diff of the downloaded pdiff file.
250 What we have for sure is hashes for the uncompressed file,
251 but rred uncompresses them on the fly while parsing, so not handled here.
252 Hashes are (also) checked while searching for (next) patch to apply. */
253 if (State
== StateFetchDiff
)
254 return available_patches
[0].download_hashes
.empty() == false;
257 HashStringList
pkgAcqIndexDiffs::GetExpectedHashes() const
259 if (State
== StateFetchDiff
)
260 return available_patches
[0].download_hashes
;
261 return HashStringList();
264 APT_CONST
bool pkgAcqIndexMergeDiffs::HashesRequired() const
266 /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
267 we can check the rred result after all patches are applied as
268 we know the expected result rather than potentially apply more patches */
269 if (State
== StateFetchDiff
)
270 return patch
.download_hashes
.empty() == false;
271 return State
== StateApplyDiff
;
273 HashStringList
pkgAcqIndexMergeDiffs::GetExpectedHashes() const
275 if (State
== StateFetchDiff
)
276 return patch
.download_hashes
;
277 else if (State
== StateApplyDiff
)
278 return GetExpectedHashesFor(Target
.MetaKey
);
279 return HashStringList();
282 APT_CONST
bool pkgAcqArchive::HashesRequired() const
284 return LocalSource
== false;
286 HashStringList
pkgAcqArchive::GetExpectedHashes() const
288 // figured out while parsing the records
289 return ExpectedHashes
;
292 APT_CONST
bool pkgAcqFile::HashesRequired() const
294 // supplied as parameter at creation time, so the caller decides
295 return ExpectedHashes
.usable();
297 HashStringList
pkgAcqFile::GetExpectedHashes() const
299 return ExpectedHashes
;
302 // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
303 bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc
&Item
)
305 Owner
->Enqueue(Item
);
308 /* The idea here is that an item isn't queued if it exists on disk and the
309 transition manager was a hit as this means that the files it contains
310 the checksums for can't be updated either (or they are and we are asking
311 for a hashsum mismatch to happen which helps nobody) */
312 bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc
&Item
)
314 std::string
const FinalFile
= GetFinalFilename();
315 if (TransactionManager
!= NULL
&& TransactionManager
->IMSHit
== true &&
316 FileExists(FinalFile
) == true)
318 PartialFile
= DestFile
= FinalFile
;
322 return pkgAcquire::Item::QueueURI(Item
);
324 /* The transition manager InRelease itself (or its older sisters-in-law
325 Release & Release.gpg) is always queued as this allows us to rerun gpgv
326 on it to verify that we aren't stalled with old files */
327 bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc
&Item
)
329 return pkgAcquire::Item::QueueURI(Item
);
331 /* the Diff/Index needs to queue also the up-to-date complete index file
332 to ensure that the list cleaner isn't eating it */
333 bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc
&Item
)
335 if (pkgAcqTransactionItem::QueueURI(Item
) == true)
341 // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
342 std::string
pkgAcquire::Item::GetFinalFilename() const
344 return GetFinalFileNameFromURI(Desc
.URI
);
346 std::string
pkgAcqDiffIndex::GetFinalFilename() const
348 // the logic we inherent from pkgAcqBaseIndex isn't what we need here
349 return pkgAcquire::Item::GetFinalFilename();
351 std::string
pkgAcqIndex::GetFinalFilename() const
353 std::string
const FinalFile
= GetFinalFileNameFromURI(Target
.URI
);
354 return GetCompressedFileName(Target
, FinalFile
, CurrentCompressionExtension
);
356 std::string
pkgAcqMetaSig::GetFinalFilename() const
358 return GetFinalFileNameFromURI(Target
.URI
);
360 std::string
pkgAcqBaseIndex::GetFinalFilename() const
362 return GetFinalFileNameFromURI(Target
.URI
);
364 std::string
pkgAcqMetaBase::GetFinalFilename() const
366 return GetFinalFileNameFromURI(Target
.URI
);
368 std::string
pkgAcqArchive::GetFinalFilename() const
370 return _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
373 // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
374 std::string
pkgAcqTransactionItem::GetMetaKey() const
376 return Target
.MetaKey
;
378 std::string
pkgAcqIndex::GetMetaKey() const
380 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
|| CurrentCompressionExtension
== "uncompressed")
381 return Target
.MetaKey
;
382 return Target
.MetaKey
+ "." + CurrentCompressionExtension
;
384 std::string
pkgAcqDiffIndex::GetMetaKey() const
386 return Target
.MetaKey
+ ".diff/Index";
389 //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
390 bool pkgAcqTransactionItem::TransactionState(TransactionStates
const state
)
392 bool const Debug
= _config
->FindB("Debug::Acquire::Transaction", false);
395 case TransactionAbort
:
397 std::clog
<< " Cancel: " << DestFile
<< std::endl
;
398 if (Status
== pkgAcquire::Item::StatIdle
)
400 Status
= pkgAcquire::Item::StatDone
;
404 case TransactionCommit
:
405 if(PartialFile
!= "")
408 std::clog
<< "mv " << PartialFile
<< " -> "<< DestFile
<< " # " << DescURI() << std::endl
;
410 Rename(PartialFile
, DestFile
);
413 std::clog
<< "rm " << DestFile
<< " # " << DescURI() << std::endl
;
414 RemoveFile("TransactionCommit", DestFile
);
420 bool pkgAcqMetaBase::TransactionState(TransactionStates
const state
)
422 // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
423 if (TransactionManager
->IMSHit
== false)
424 return pkgAcqTransactionItem::TransactionState(state
);
427 bool pkgAcqIndex::TransactionState(TransactionStates
const state
)
429 if (pkgAcqTransactionItem::TransactionState(state
) == false)
434 case TransactionAbort
:
435 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
437 // keep the compressed file, but drop the decompressed
438 EraseFileName
.clear();
439 if (PartialFile
.empty() == false && flExtension(PartialFile
) == "decomp")
440 RemoveFile("TransactionAbort", PartialFile
);
443 case TransactionCommit
:
444 if (EraseFileName
.empty() == false)
445 RemoveFile("TransactionCommit", EraseFileName
);
450 bool pkgAcqDiffIndex::TransactionState(TransactionStates
const state
)
452 if (pkgAcqTransactionItem::TransactionState(state
) == false)
457 case TransactionCommit
:
459 case TransactionAbort
:
460 std::string
const Partial
= GetPartialFileNameFromURI(Target
.URI
);
461 RemoveFile("TransactionAbort", Partial
);
469 class APT_HIDDEN NoActionItem
: public pkgAcquire::Item
/*{{{*/
470 /* The sole purpose of this class is having an item which does nothing to
471 reach its done state to prevent cleanup deleting the mentioned file.
472 Handy in cases in which we know we have the file already, like IMS-Hits. */
474 IndexTarget
const Target
;
476 virtual std::string
DescURI() const APT_OVERRIDE
{return Target
.URI
;};
477 virtual HashStringList
GetExpectedHashes() const APT_OVERRIDE
{return HashStringList();};
479 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
) :
480 pkgAcquire::Item(Owner
), Target(Target
)
483 DestFile
= GetFinalFileNameFromURI(Target
.URI
);
485 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
, std::string
const &FinalFile
) :
486 pkgAcquire::Item(Owner
), Target(Target
)
489 DestFile
= FinalFile
;
494 // Acquire::Item::Item - Constructor /*{{{*/
495 APT_IGNORE_DEPRECATED_PUSH
496 pkgAcquire::Item::Item(pkgAcquire
* const owner
) :
497 FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
498 QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner
), d(NULL
)
503 APT_IGNORE_DEPRECATED_POP
505 // Acquire::Item::~Item - Destructor /*{{{*/
506 pkgAcquire::Item::~Item()
511 std::string
pkgAcquire::Item::Custom600Headers() const /*{{{*/
513 return std::string();
516 std::string
pkgAcquire::Item::ShortDesc() const /*{{{*/
521 APT_CONST
void pkgAcquire::Item::Finished() /*{{{*/
525 APT_PURE pkgAcquire
* pkgAcquire::Item::GetOwner() const /*{{{*/
530 APT_CONST
pkgAcquire::ItemDesc
&pkgAcquire::Item::GetItemDesc() /*{{{*/
535 APT_CONST
bool pkgAcquire::Item::IsTrusted() const /*{{{*/
540 // Acquire::Item::Failed - Item failed to download /*{{{*/
541 // ---------------------------------------------------------------------
542 /* We return to an idle state if there are still other queues that could
544 void pkgAcquire::Item::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
546 if(ErrorText
.empty())
547 ErrorText
= LookupTag(Message
,"Message");
548 if (QueueCounter
<= 1)
550 /* This indicates that the file is not available right now but might
551 be sometime later. If we do a retry cycle then this should be
553 if (Cnf
!= NULL
&& Cnf
->LocalOnly
== true &&
554 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
570 case StatTransientNetworkError
:
577 string
const FailReason
= LookupTag(Message
, "FailReason");
578 if (FailReason
== "MaximumSizeExceeded")
579 RenameOnError(MaximumSizeExceeded
);
580 else if (Status
== StatAuthError
)
581 RenameOnError(HashSumMismatch
);
583 // report mirror failure back to LP if we actually use a mirror
584 if (FailReason
.empty() == false)
585 ReportMirrorFailure(FailReason
);
587 ReportMirrorFailure(ErrorText
);
589 if (QueueCounter
> 1)
593 // Acquire::Item::Start - Item has begun to download /*{{{*/
594 // ---------------------------------------------------------------------
595 /* Stash status and the file size. Note that setting Complete means
596 sub-phases of the acquire process such as decompresion are operating */
597 void pkgAcquire::Item::Start(string
const &/*Message*/, unsigned long long const Size
)
599 Status
= StatFetching
;
601 if (FileSize
== 0 && Complete
== false)
605 // Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
606 /* Note that hash-verification is 'hardcoded' in acquire-worker and has
607 * already passed if this method is called. */
608 bool pkgAcquire::Item::VerifyDone(std::string
const &Message
,
609 pkgAcquire::MethodConfig
const * const /*Cnf*/)
611 std::string
const FileName
= LookupTag(Message
,"Filename");
612 if (FileName
.empty() == true)
615 ErrorText
= "Method gave a blank filename";
622 // Acquire::Item::Done - Item downloaded OK /*{{{*/
623 void pkgAcquire::Item::Done(string
const &/*Message*/, HashStringList
const &Hashes
,
624 pkgAcquire::MethodConfig
const * const /*Cnf*/)
626 // We just downloaded something..
629 unsigned long long const downloadedSize
= Hashes
.FileSize();
630 if (downloadedSize
!= 0)
632 FileSize
= downloadedSize
;
636 ErrorText
= string();
637 Owner
->Dequeue(this);
640 // Acquire::Item::Rename - Rename a file /*{{{*/
641 // ---------------------------------------------------------------------
642 /* This helper function is used by a lot of item methods as their final
644 bool pkgAcquire::Item::Rename(string
const &From
,string
const &To
)
646 if (From
== To
|| rename(From
.c_str(),To
.c_str()) == 0)
650 strprintf(S
, _("rename failed, %s (%s -> %s)."), strerror(errno
),
651 From
.c_str(),To
.c_str());
653 if (ErrorText
.empty())
656 ErrorText
= ErrorText
+ ": " + S
;
660 void pkgAcquire::Item::Dequeue() /*{{{*/
662 Owner
->Dequeue(this);
665 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
667 if (RealFileExists(DestFile
))
668 Rename(DestFile
, DestFile
+ ".FAILED");
673 case HashSumMismatch
:
674 errtext
= _("Hash Sum mismatch");
675 Status
= StatAuthError
;
676 ReportMirrorFailure("HashChecksumFailure");
679 errtext
= _("Size mismatch");
680 Status
= StatAuthError
;
681 ReportMirrorFailure("SizeFailure");
684 errtext
= _("Invalid file format");
686 // do not report as usually its not the mirrors fault, but Portal/Proxy
689 errtext
= _("Signature error");
693 strprintf(errtext
, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
694 Status
= StatAuthError
;
696 case MaximumSizeExceeded
:
697 // the method is expected to report a good error for this
701 // no handling here, done by callers
704 if (ErrorText
.empty())
709 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)/*{{{*/
711 ActiveSubprocess
= subprocess
;
712 APT_IGNORE_DEPRECATED(Mode
= ActiveSubprocess
.c_str();)
715 // Acquire::Item::ReportMirrorFailure /*{{{*/
716 void pkgAcquire::Item::ReportMirrorFailure(string
const &FailCode
)
718 // we only act if a mirror was used at all
719 if(UsedMirror
.empty())
722 std::cerr
<< "\nReportMirrorFailure: "
724 << " Uri: " << DescURI()
726 << FailCode
<< std::endl
;
728 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
729 "/usr/lib/apt/apt-report-mirror-failure");
730 if(!FileExists(report
))
733 std::vector
<char const*> Args
;
734 Args
.push_back(report
.c_str());
735 Args
.push_back(UsedMirror
.c_str());
736 Args
.push_back(DescURI().c_str());
737 Args
.push_back(FailCode
.c_str());
738 Args
.push_back(NULL
);
740 pid_t pid
= ExecFork();
743 _error
->Error("ReportMirrorFailure Fork failed");
748 execvp(Args
[0], (char**)Args
.data());
749 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
752 if(!ExecWait(pid
, "report-mirror-failure"))
754 _error
->Warning("Couldn't report problem to '%s'",
755 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
759 std::string
pkgAcquire::Item::HashSum() const /*{{{*/
761 HashStringList
const hashes
= GetExpectedHashes();
762 HashString
const * const hs
= hashes
.find(NULL
);
763 return hs
!= NULL
? hs
->toStr() : "";
767 pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire
* const Owner
, /*{{{*/
768 pkgAcqMetaClearSig
* const transactionManager
, IndexTarget
const &target
) :
769 pkgAcquire::Item(Owner
), d(NULL
), Target(target
), TransactionManager(transactionManager
)
771 if (TransactionManager
!= this)
772 TransactionManager
->Add(this);
775 pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
779 HashStringList
pkgAcqTransactionItem::GetExpectedHashesFor(std::string
const &MetaKey
) const /*{{{*/
781 return GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, MetaKey
);
785 // AcqMetaBase - Constructor /*{{{*/
786 pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire
* const Owner
,
787 pkgAcqMetaClearSig
* const TransactionManager
,
788 std::vector
<IndexTarget
> const &IndexTargets
,
789 IndexTarget
const &DataTarget
)
790 : pkgAcqTransactionItem(Owner
, TransactionManager
, DataTarget
), d(NULL
),
791 IndexTargets(IndexTargets
),
792 AuthPass(false), IMSHit(false)
796 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
797 void pkgAcqMetaBase::Add(pkgAcqTransactionItem
* const I
)
799 Transaction
.push_back(I
);
802 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
803 void pkgAcqMetaBase::AbortTransaction()
805 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
806 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
808 // ensure the toplevel is in error state too
809 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
810 I
!= Transaction
.end(); ++I
)
812 (*I
)->TransactionState(TransactionAbort
);
817 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
818 APT_PURE
bool pkgAcqMetaBase::TransactionHasError() const
820 for (std::vector
<pkgAcqTransactionItem
*>::const_iterator I
= Transaction
.begin();
821 I
!= Transaction
.end(); ++I
)
823 switch((*I
)->Status
) {
824 case StatDone
: break;
825 case StatIdle
: break;
826 case StatAuthError
: return true;
827 case StatError
: return true;
828 case StatTransientNetworkError
: return true;
829 case StatFetching
: break;
835 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
836 void pkgAcqMetaBase::CommitTransaction()
838 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
839 std::clog
<< "CommitTransaction: " << this << std::endl
;
841 // move new files into place *and* remove files that are not
842 // part of the transaction but are still on disk
843 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
844 I
!= Transaction
.end(); ++I
)
846 (*I
)->TransactionState(TransactionCommit
);
851 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
852 void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem
* const I
,
853 const std::string
&From
,
854 const std::string
&To
)
856 I
->PartialFile
= From
;
860 // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
861 void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem
* const I
,
862 const std::string
&FinalFile
)
865 I
->DestFile
= FinalFile
;
868 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
869 bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item
* const I
, const std::string
&Message
)
871 // FIXME: this entire function can do now that we disallow going to
872 // a unauthenticated state and can cleanly rollback
874 string
const Final
= I
->GetFinalFilename();
875 if(FileExists(Final
))
877 I
->Status
= StatTransientNetworkError
;
878 _error
->Warning(_("An error occurred during the signature "
879 "verification. The repository is not updated "
880 "and the previous index files will be used. "
881 "GPG error: %s: %s"),
882 Desc
.Description
.c_str(),
883 LookupTag(Message
,"Message").c_str());
884 RunScripts("APT::Update::Auth-Failure");
886 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
887 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
888 _error
->Error(_("GPG error: %s: %s"),
889 Desc
.Description
.c_str(),
890 LookupTag(Message
,"Message").c_str());
891 I
->Status
= StatAuthError
;
894 _error
->Warning(_("GPG error: %s: %s"),
895 Desc
.Description
.c_str(),
896 LookupTag(Message
,"Message").c_str());
898 // gpgv method failed
899 ReportMirrorFailure("GPGFailure");
903 // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
904 // ---------------------------------------------------------------------
905 string
pkgAcqMetaBase::Custom600Headers() const
907 std::string Header
= "\nIndex-File: true";
908 std::string MaximumSize
;
909 strprintf(MaximumSize
, "\nMaximum-Size: %i",
910 _config
->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
911 Header
+= MaximumSize
;
913 string
const FinalFile
= GetFinalFilename();
915 if (stat(FinalFile
.c_str(),&Buf
) == 0)
916 Header
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
921 // AcqMetaBase::QueueForSignatureVerify /*{{{*/
922 void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem
* const I
, std::string
const &File
, std::string
const &Signature
)
925 I
->Desc
.URI
= "gpgv:" + Signature
;
928 I
->SetActiveSubprocess("gpgv");
931 // AcqMetaBase::CheckDownloadDone /*{{{*/
932 bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem
* const I
, const std::string
&Message
, HashStringList
const &Hashes
) const
934 // We have just finished downloading a Release file (it is not
937 std::string
const FileName
= LookupTag(Message
,"Filename");
938 if (FileName
!= I
->DestFile
&& RealFileExists(I
->DestFile
) == false)
941 I
->Desc
.URI
= "copy:" + FileName
;
942 I
->QueueURI(I
->Desc
);
946 // make sure to verify against the right file on I-M-S hit
947 bool IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"), false);
948 if (IMSHit
== false && Hashes
.usable())
950 // detect IMS-Hits servers haven't detected by Hash comparison
951 std::string
const FinalFile
= I
->GetFinalFilename();
952 if (RealFileExists(FinalFile
) && Hashes
.VerifyFile(FinalFile
) == true)
955 RemoveFile("CheckDownloadDone", I
->DestFile
);
961 // for simplicity, the transaction manager is always InRelease
962 // even if it doesn't exist.
963 if (TransactionManager
!= NULL
)
964 TransactionManager
->IMSHit
= true;
965 I
->PartialFile
= I
->DestFile
= I
->GetFinalFilename();
968 // set Item to complete as the remaining work is all local (verify etc)
974 bool pkgAcqMetaBase::CheckAuthDone(string
const &Message
) /*{{{*/
976 // At this point, the gpgv method has succeeded, so there is a
977 // valid signature from a key in the trusted keyring. We
978 // perform additional verification of its contents, and use them
979 // to verify the indexes we are about to download
981 if (TransactionManager
->IMSHit
== false)
983 // open the last (In)Release if we have it
984 std::string
const FinalFile
= GetFinalFilename();
985 std::string FinalRelease
;
986 std::string FinalInRelease
;
987 if (APT::String::Endswith(FinalFile
, "InRelease"))
989 FinalInRelease
= FinalFile
;
990 FinalRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("InRelease")) + "Release";
994 FinalInRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("Release")) + "InRelease";
995 FinalRelease
= FinalFile
;
997 if (RealFileExists(FinalInRelease
) || RealFileExists(FinalRelease
))
999 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1000 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1002 _error
->PushToStack();
1003 if (RealFileExists(FinalInRelease
))
1004 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1006 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1007 // its unlikely to happen, but if what we have is bad ignore it
1008 if (_error
->PendingError())
1010 delete TransactionManager
->LastMetaIndexParser
;
1011 TransactionManager
->LastMetaIndexParser
= NULL
;
1013 _error
->RevertToStack();
1018 if (TransactionManager
->MetaIndexParser
->Load(DestFile
, &ErrorText
) == false)
1020 Status
= StatAuthError
;
1024 if (!VerifyVendor(Message
))
1026 Status
= StatAuthError
;
1030 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1031 std::cerr
<< "Signature verification succeeded: "
1032 << DestFile
<< std::endl
;
1034 // Download further indexes with verification
1040 void pkgAcqMetaBase::QueueIndexes(bool const verify
) /*{{{*/
1042 // at this point the real Items are loaded in the fetcher
1043 ExpectedAdditionalItems
= 0;
1045 bool metaBaseSupportsByHash
= false;
1046 if (TransactionManager
!= NULL
&& TransactionManager
->MetaIndexParser
!= NULL
)
1047 metaBaseSupportsByHash
= TransactionManager
->MetaIndexParser
->GetSupportsAcquireByHash();
1049 for (std::vector
<IndexTarget
>::iterator Target
= IndexTargets
.begin();
1050 Target
!= IndexTargets
.end();
1053 // all is an implementation detail. Users shouldn't use this as arch
1054 // We need this support trickery here as e.g. Debian has binary-all files already,
1055 // but arch:all packages are still in the arch:any files, so we would waste precious
1056 // download time, bandwidth and diskspace for nothing, BUT Debian doesn't feature all
1057 // in the set of supported architectures, so we can filter based on this property rather
1058 // than invent an entirely new flag we would need to carry for all of eternity.
1059 if (Target
->Option(IndexTarget::ARCHITECTURE
) == "all" &&
1060 TransactionManager
->MetaIndexParser
->IsArchitectureSupported("all") == false)
1063 bool trypdiff
= Target
->OptionBool(IndexTarget::PDIFFS
);
1066 if (TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
) == false)
1068 // optional targets that we do not have in the Release file are skipped
1069 if (Target
->IsOptional
)
1072 std::string
const &arch
= Target
->Option(IndexTarget::ARCHITECTURE
);
1073 if (arch
.empty() == false)
1075 if (TransactionManager
->MetaIndexParser
->IsArchitectureSupported(arch
) == false)
1077 _error
->Notice(_("Skipping acquire of configured file '%s' as repository '%s' doesn't support architecture '%s'"),
1078 Target
->MetaKey
.c_str(), TransactionManager
->Target
.Description
.c_str(), arch
.c_str());
1081 // if the architecture is officially supported but currently no packages for it available,
1082 // ignore silently as this is pretty much the same as just shipping an empty file.
1083 // if we don't know which architectures are supported, we do NOT ignore it to notify user about this
1084 if (TransactionManager
->MetaIndexParser
->IsArchitectureSupported("*undefined*") == false)
1088 Status
= StatAuthError
;
1089 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target
->MetaKey
.c_str());
1093 // autoselect the compression method
1094 std::vector
<std::string
> types
= VectorizeString(Target
->Option(IndexTarget::COMPRESSIONTYPES
), ' ');
1095 types
.erase(std::remove_if(types
.begin(), types
.end(), [&](std::string
const &t
) {
1096 if (t
== "uncompressed")
1097 return TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
) == false;
1098 std::string
const MetaKey
= Target
->MetaKey
+ "." + t
;
1099 return TransactionManager
->MetaIndexParser
->Exists(MetaKey
) == false;
1101 if (types
.empty() == false)
1103 std::ostringstream os
;
1104 // add the special compressiontype byhash first if supported
1105 std::string
const useByHashConf
= Target
->Option(IndexTarget::BY_HASH
);
1106 bool useByHash
= false;
1107 if(useByHashConf
== "force")
1110 useByHash
= StringToBool(useByHashConf
) == true && metaBaseSupportsByHash
;
1111 if (useByHash
== true)
1113 std::copy(types
.begin(), types
.end()-1, std::ostream_iterator
<std::string
>(os
, " "));
1114 os
<< *types
.rbegin();
1115 Target
->Options
["COMPRESSIONTYPES"] = os
.str();
1118 Target
->Options
["COMPRESSIONTYPES"].clear();
1120 std::string filename
= GetFinalFileNameFromURI(Target
->URI
);
1121 if (RealFileExists(filename
) == false)
1123 if (Target
->KeepCompressed
)
1125 filename
= GetKeepCompressedFileName(filename
, *Target
);
1126 if (RealFileExists(filename
) == false)
1133 if (filename
.empty() == false)
1135 // if the Release file is a hit and we have an index it must be the current one
1136 if (TransactionManager
->IMSHit
== true)
1138 else if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1140 // see if the file changed since the last Release file
1141 // we use the uncompressed files as we might compress differently compared to the server,
1142 // so the hashes might not match, even if they contain the same data.
1143 HashStringList
const newFile
= GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, Target
->MetaKey
);
1144 HashStringList
const oldFile
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
->MetaKey
);
1145 if (newFile
!= oldFile
)
1152 trypdiff
= false; // no file to patch
1154 if (filename
.empty() == false)
1156 new NoActionItem(Owner
, *Target
, filename
);
1157 std::string
const idxfilename
= GetFinalFileNameFromURI(Target
->URI
+ ".diff/Index");
1158 if (FileExists(idxfilename
))
1159 new NoActionItem(Owner
, *Target
, idxfilename
);
1163 // check if we have patches available
1164 trypdiff
&= TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
+ ".diff/Index");
1168 // if we have no file to patch, no point in trying
1169 std::string filename
= GetFinalFileNameFromURI(Target
->URI
);
1170 if (RealFileExists(filename
) == false)
1172 if (Target
->KeepCompressed
)
1174 filename
= GetKeepCompressedFileName(filename
, *Target
);
1175 if (RealFileExists(filename
) == false)
1181 trypdiff
&= (filename
.empty() == false);
1184 // no point in patching from local sources
1187 std::string
const proto
= Target
->URI
.substr(0, strlen("file:/"));
1188 if (proto
== "file:/" || proto
== "copy:/" || proto
== "cdrom:")
1192 // Queue the Index file (Packages, Sources, Translation-$foo, …)
1194 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
);
1196 new pkgAcqIndex(Owner
, TransactionManager
, *Target
);
1200 bool pkgAcqMetaBase::VerifyVendor(string
const &Message
) /*{{{*/
1202 string::size_type pos
;
1204 // check for missing sigs (that where not fatal because otherwise we had
1207 string msg
= _("There is no public key available for the "
1208 "following key IDs:\n");
1209 pos
= Message
.find("NO_PUBKEY ");
1210 if (pos
!= std::string::npos
)
1212 string::size_type start
= pos
+strlen("NO_PUBKEY ");
1213 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
1214 missingkeys
+= (Fingerprint
);
1216 if(!missingkeys
.empty())
1217 _error
->Warning("%s", (msg
+ missingkeys
).c_str());
1219 string Transformed
= TransactionManager
->MetaIndexParser
->GetExpectedDist();
1221 if (Transformed
== "../project/experimental")
1223 Transformed
= "experimental";
1226 pos
= Transformed
.rfind('/');
1227 if (pos
!= string::npos
)
1229 Transformed
= Transformed
.substr(0, pos
);
1232 if (Transformed
== ".")
1237 if (TransactionManager
->MetaIndexParser
->GetValidUntil() > 0)
1239 time_t const invalid_since
= time(NULL
) - TransactionManager
->MetaIndexParser
->GetValidUntil();
1240 if (invalid_since
> 0)
1244 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1245 // the time since then the file is invalid - formatted in the same way as in
1246 // the download progress display (e.g. 7d 3h 42min 1s)
1247 _("Release file for %s is expired (invalid since %s). "
1248 "Updates for this repository will not be applied."),
1249 Target
.URI
.c_str(), TimeToStr(invalid_since
).c_str());
1250 if (ErrorText
.empty())
1252 return _error
->Error("%s", errmsg
.c_str());
1256 /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
1257 as a prevention of downgrading us to older (still valid) files */
1258 if (TransactionManager
->IMSHit
== false && TransactionManager
->LastMetaIndexParser
!= NULL
&&
1259 TransactionManager
->LastMetaIndexParser
->GetDate() > TransactionManager
->MetaIndexParser
->GetDate())
1261 TransactionManager
->IMSHit
= true;
1262 RemoveFile("VerifyVendor", DestFile
);
1263 PartialFile
= DestFile
= GetFinalFilename();
1264 // load the 'old' file in the 'new' one instead of flipping pointers as
1265 // the new one isn't owned by us, while the old one is so cleanup would be confused.
1266 TransactionManager
->MetaIndexParser
->swapLoad(TransactionManager
->LastMetaIndexParser
);
1267 delete TransactionManager
->LastMetaIndexParser
;
1268 TransactionManager
->LastMetaIndexParser
= NULL
;
1271 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1273 std::cerr
<< "Got Codename: " << TransactionManager
->MetaIndexParser
->GetCodename() << std::endl
;
1274 std::cerr
<< "Expecting Dist: " << TransactionManager
->MetaIndexParser
->GetExpectedDist() << std::endl
;
1275 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
1278 if (TransactionManager
->MetaIndexParser
->CheckDist(Transformed
) == false)
1280 // This might become fatal one day
1281 // Status = StatAuthError;
1282 // ErrorText = "Conflicting distribution; expected "
1283 // + MetaIndexParser->GetExpectedDist() + " but got "
1284 // + MetaIndexParser->GetCodename();
1286 if (!Transformed
.empty())
1288 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1289 Desc
.Description
.c_str(),
1290 Transformed
.c_str(),
1291 TransactionManager
->MetaIndexParser
->GetCodename().c_str());
1298 pkgAcqMetaBase::~pkgAcqMetaBase()
1302 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
* const Owner
, /*{{{*/
1303 IndexTarget
const &ClearsignedTarget
,
1304 IndexTarget
const &DetachedDataTarget
, IndexTarget
const &DetachedSigTarget
,
1305 std::vector
<IndexTarget
> const &IndexTargets
,
1306 metaIndex
* const MetaIndexParser
) :
1307 pkgAcqMetaIndex(Owner
, this, ClearsignedTarget
, DetachedSigTarget
, IndexTargets
),
1308 d(NULL
), ClearsignedTarget(ClearsignedTarget
),
1309 DetachedDataTarget(DetachedDataTarget
),
1310 MetaIndexParser(MetaIndexParser
), LastMetaIndexParser(NULL
)
1312 // index targets + (worst case:) Release/Release.gpg
1313 ExpectedAdditionalItems
= IndexTargets
.size() + 2;
1314 TransactionManager
->Add(this);
1317 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
1319 if (LastMetaIndexParser
!= NULL
)
1320 delete LastMetaIndexParser
;
1323 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1324 string
pkgAcqMetaClearSig::Custom600Headers() const
1326 string Header
= pkgAcqMetaBase::Custom600Headers();
1327 Header
+= "\nFail-Ignore: true";
1328 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1329 if (key
.empty() == false)
1330 Header
+= "\nSigned-By: " + key
;
1335 bool pkgAcqMetaClearSig::VerifyDone(std::string
const &Message
, /*{{{*/
1336 pkgAcquire::MethodConfig
const * const Cnf
)
1338 Item::VerifyDone(Message
, Cnf
);
1340 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
1341 return RenameOnError(NotClearsigned
);
1346 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
1347 void pkgAcqMetaClearSig::Done(std::string
const &Message
,
1348 HashStringList
const &Hashes
,
1349 pkgAcquire::MethodConfig
const * const Cnf
)
1351 Item::Done(Message
, Hashes
, Cnf
);
1353 if(AuthPass
== false)
1355 if(CheckDownloadDone(this, Message
, Hashes
) == true)
1356 QueueForSignatureVerify(this, DestFile
, DestFile
);
1359 else if(CheckAuthDone(Message
) == true)
1361 if (TransactionManager
->IMSHit
== false)
1362 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1363 else if (RealFileExists(GetFinalFilename()) == false)
1365 // We got an InRelease file IMSHit, but we haven't one, which means
1366 // we had a valid Release/Release.gpg combo stepping in, which we have
1367 // to 'acquire' now to ensure list cleanup isn't removing them
1368 new NoActionItem(Owner
, DetachedDataTarget
);
1369 new NoActionItem(Owner
, DetachedSigTarget
);
1374 void pkgAcqMetaClearSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
) /*{{{*/
1376 Item::Failed(Message
, Cnf
);
1378 // we failed, we will not get additional items from this method
1379 ExpectedAdditionalItems
= 0;
1381 if (AuthPass
== false)
1383 if (Status
== StatAuthError
|| Status
== StatTransientNetworkError
)
1385 // if we expected a ClearTextSignature (InRelease) but got a network
1386 // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
1387 // As these is usually called by web-portals we do not try Release/Release.gpg
1388 // as this is gonna fail anyway and instead abort our try (LP#346386)
1389 TransactionManager
->AbortTransaction();
1393 // Queue the 'old' InRelease file for removal if we try Release.gpg
1394 // as otherwise the file will stay around and gives a false-auth
1395 // impression (CVE-2012-0214)
1396 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1399 new pkgAcqMetaIndex(Owner
, TransactionManager
, DetachedDataTarget
, DetachedSigTarget
, IndexTargets
);
1403 if(CheckStopAuthentication(this, Message
))
1406 // No Release file was present, or verification failed, so fall
1407 // back to queueing Packages files without verification
1408 // only allow going further if the users explicitely wants it
1409 if(AllowInsecureRepositories(_("The repository '%s' is not signed."), ClearsignedTarget
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1413 /* InRelease files become Release files, otherwise
1414 * they would be considered as trusted later on */
1415 string
const FinalRelease
= GetFinalFileNameFromURI(DetachedDataTarget
.URI
);
1416 string
const PartialRelease
= GetPartialFileNameFromURI(DetachedDataTarget
.URI
);
1417 string
const FinalReleasegpg
= GetFinalFileNameFromURI(DetachedSigTarget
.URI
);
1418 string
const FinalInRelease
= GetFinalFilename();
1419 Rename(DestFile
, PartialRelease
);
1420 TransactionManager
->TransactionStageCopy(this, PartialRelease
, FinalRelease
);
1422 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1424 // open the last Release if we have it
1425 if (TransactionManager
->IMSHit
== false)
1427 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1428 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1430 _error
->PushToStack();
1431 if (RealFileExists(FinalInRelease
))
1432 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1434 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1435 // its unlikely to happen, but if what we have is bad ignore it
1436 if (_error
->PendingError())
1438 delete TransactionManager
->LastMetaIndexParser
;
1439 TransactionManager
->LastMetaIndexParser
= NULL
;
1441 _error
->RevertToStack();
1446 // we parse the indexes here because at this point the user wanted
1447 // a repository that may potentially harm him
1448 if (TransactionManager
->MetaIndexParser
->Load(PartialRelease
, &ErrorText
) == false || VerifyVendor(Message
) == false)
1449 /* expired Release files are still a problem you need extra force for */;
1457 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
* const Owner
, /*{{{*/
1458 pkgAcqMetaClearSig
* const TransactionManager
,
1459 IndexTarget
const &DataTarget
,
1460 IndexTarget
const &DetachedSigTarget
,
1461 vector
<IndexTarget
> const &IndexTargets
) :
1462 pkgAcqMetaBase(Owner
, TransactionManager
, IndexTargets
, DataTarget
), d(NULL
),
1463 DetachedSigTarget(DetachedSigTarget
)
1465 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1466 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1467 << this->TransactionManager
<< std::endl
;
1469 DestFile
= GetPartialFileNameFromURI(DataTarget
.URI
);
1472 Desc
.Description
= DataTarget
.Description
;
1474 Desc
.ShortDesc
= DataTarget
.ShortDesc
;
1475 Desc
.URI
= DataTarget
.URI
;
1477 // we expect more item
1478 ExpectedAdditionalItems
= IndexTargets
.size();
1482 void pkgAcqMetaIndex::Done(string
const &Message
, /*{{{*/
1483 HashStringList
const &Hashes
,
1484 pkgAcquire::MethodConfig
const * const Cfg
)
1486 Item::Done(Message
,Hashes
,Cfg
);
1488 if(CheckDownloadDone(this, Message
, Hashes
))
1490 // we have a Release file, now download the Signature, all further
1491 // verify/queue for additional downloads will be done in the
1492 // pkgAcqMetaSig::Done() code
1493 new pkgAcqMetaSig(Owner
, TransactionManager
, DetachedSigTarget
, this);
1497 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
1498 void pkgAcqMetaIndex::Failed(string
const &Message
,
1499 pkgAcquire::MethodConfig
const * const Cnf
)
1501 pkgAcquire::Item::Failed(Message
, Cnf
);
1504 // No Release file was present so fall
1505 // back to queueing Packages files without verification
1506 // only allow going further if the users explicitely wants it
1507 if(AllowInsecureRepositories(_("The repository '%s' does not have a Release file."), Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1509 // ensure old Release files are removed
1510 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1512 // queue without any kind of hashsum support
1513 QueueIndexes(false);
1517 void pkgAcqMetaIndex::Finished() /*{{{*/
1519 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1520 std::clog
<< "Finished: " << DestFile
<<std::endl
;
1521 if(TransactionManager
!= NULL
&&
1522 TransactionManager
->TransactionHasError() == false)
1523 TransactionManager
->CommitTransaction();
1526 std::string
pkgAcqMetaIndex::DescURI() const /*{{{*/
1531 pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
1533 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1534 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
* const Owner
,
1535 pkgAcqMetaClearSig
* const TransactionManager
,
1536 IndexTarget
const &Target
,
1537 pkgAcqMetaIndex
* const MetaIndex
) :
1538 pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
), MetaIndex(MetaIndex
)
1540 DestFile
= GetPartialFileNameFromURI(Target
.URI
);
1542 // remove any partial downloaded sig-file in partial/.
1543 // it may confuse proxies and is too small to warrant a
1544 // partial download anyway
1545 RemoveFile("pkgAcqMetaSig", DestFile
);
1547 // set the TransactionManager
1548 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1549 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1550 << TransactionManager
<< std::endl
;
1553 Desc
.Description
= Target
.Description
;
1555 Desc
.ShortDesc
= Target
.ShortDesc
;
1556 Desc
.URI
= Target
.URI
;
1558 // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
1559 // so we skip the download step and go instantly to verification
1560 if (TransactionManager
->IMSHit
== true && RealFileExists(GetFinalFilename()))
1564 PartialFile
= DestFile
= GetFinalFilename();
1565 MetaIndexFileSignature
= DestFile
;
1566 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1572 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1576 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1577 std::string
pkgAcqMetaSig::Custom600Headers() const
1579 std::string Header
= pkgAcqTransactionItem::Custom600Headers();
1580 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1581 if (key
.empty() == false)
1582 Header
+= "\nSigned-By: " + key
;
1586 // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1587 void pkgAcqMetaSig::Done(string
const &Message
, HashStringList
const &Hashes
,
1588 pkgAcquire::MethodConfig
const * const Cfg
)
1590 if (MetaIndexFileSignature
.empty() == false)
1592 DestFile
= MetaIndexFileSignature
;
1593 MetaIndexFileSignature
.clear();
1595 Item::Done(Message
, Hashes
, Cfg
);
1597 if(MetaIndex
->AuthPass
== false)
1599 if(MetaIndex
->CheckDownloadDone(this, Message
, Hashes
) == true)
1601 // destfile will be modified to point to MetaIndexFile for the
1602 // gpgv method, so we need to save it here
1603 MetaIndexFileSignature
= DestFile
;
1604 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1608 else if(MetaIndex
->CheckAuthDone(Message
) == true)
1610 if (TransactionManager
->IMSHit
== false)
1612 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1613 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, MetaIndex
->GetFinalFilename());
1618 void pkgAcqMetaSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
1620 Item::Failed(Message
,Cnf
);
1622 // check if we need to fail at this point
1623 if (MetaIndex
->AuthPass
== true && MetaIndex
->CheckStopAuthentication(this, Message
))
1626 string
const FinalRelease
= MetaIndex
->GetFinalFilename();
1627 string
const FinalReleasegpg
= GetFinalFilename();
1628 string
const FinalInRelease
= TransactionManager
->GetFinalFilename();
1630 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1632 std::string downgrade_msg
;
1633 strprintf(downgrade_msg
, _("The repository '%s' is no longer signed."),
1634 MetaIndex
->Target
.Description
.c_str());
1635 if(_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1637 // meh, the users wants to take risks (we still mark the packages
1638 // from this repository as unauthenticated)
1639 _error
->Warning("%s", downgrade_msg
.c_str());
1640 _error
->Warning(_("This is normally not allowed, but the option "
1641 "Acquire::AllowDowngradeToInsecureRepositories was "
1642 "given to override it."));
1645 MessageInsecureRepository(true, downgrade_msg
);
1646 if (TransactionManager
->IMSHit
== false)
1647 Rename(MetaIndex
->DestFile
, MetaIndex
->DestFile
+ ".FAILED");
1648 Item::Failed("Message: " + downgrade_msg
, Cnf
);
1649 TransactionManager
->AbortTransaction();
1654 // ensures that a Release.gpg file in the lists/ is removed by the transaction
1655 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1657 // only allow going further if the users explicitely wants it
1658 if (AllowInsecureRepositories(_("The repository '%s' is not signed."), MetaIndex
->Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1660 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1662 // open the last Release if we have it
1663 if (TransactionManager
->IMSHit
== false)
1665 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1666 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1668 _error
->PushToStack();
1669 if (RealFileExists(FinalInRelease
))
1670 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1672 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1673 // its unlikely to happen, but if what we have is bad ignore it
1674 if (_error
->PendingError())
1676 delete TransactionManager
->LastMetaIndexParser
;
1677 TransactionManager
->LastMetaIndexParser
= NULL
;
1679 _error
->RevertToStack();
1684 // we parse the indexes here because at this point the user wanted
1685 // a repository that may potentially harm him
1686 if (TransactionManager
->MetaIndexParser
->Load(MetaIndex
->DestFile
, &ErrorText
) == false || MetaIndex
->VerifyVendor(Message
) == false)
1687 /* expired Release files are still a problem you need extra force for */;
1689 MetaIndex
->QueueIndexes(true);
1691 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, MetaIndex
->GetFinalFilename());
1694 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1695 if (Cnf
->LocalOnly
== true ||
1696 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1705 // AcqBaseIndex - Constructor /*{{{*/
1706 pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire
* const Owner
,
1707 pkgAcqMetaClearSig
* const TransactionManager
,
1708 IndexTarget
const &Target
)
1709 : pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
)
1713 pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
1715 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
1716 // ---------------------------------------------------------------------
1717 /* Get the DiffIndex file first and see if there are patches available
1718 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
1719 * patches. If anything goes wrong in that process, it will fall back to
1720 * the original packages file
1722 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
* const Owner
,
1723 pkgAcqMetaClearSig
* const TransactionManager
,
1724 IndexTarget
const &Target
)
1725 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), diffs(NULL
)
1727 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
1730 Desc
.Description
= Target
.Description
+ ".diff/Index";
1731 Desc
.ShortDesc
= Target
.ShortDesc
;
1732 Desc
.URI
= Target
.URI
+ ".diff/Index";
1734 DestFile
= GetPartialFileNameFromURI(Desc
.URI
);
1737 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
1742 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1743 // ---------------------------------------------------------------------
1744 /* The only header we use is the last-modified header. */
1745 string
pkgAcqDiffIndex::Custom600Headers() const
1747 string
const Final
= GetFinalFilename();
1750 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
1753 if (stat(Final
.c_str(),&Buf
) != 0)
1754 return "\nIndex-File: true";
1756 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1759 void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
1761 // list cleanup needs to know that this file as well as the already
1762 // present index is ours, so we create an empty diff to save it for us
1763 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
);
1766 bool pkgAcqDiffIndex::ParseDiffIndex(string
const &IndexDiffFile
) /*{{{*/
1768 // failing here is fine: our caller will take care of trying to
1769 // get the complete file if patching fails
1771 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
1774 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
1776 if (Fd
.IsOpen() == false || Fd
.Failed())
1780 if(unlikely(TF
.Step(Tags
) == false))
1783 HashStringList ServerHashes
;
1784 unsigned long long ServerSize
= 0;
1786 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1788 std::string tagname
= *type
;
1789 tagname
.append("-Current");
1790 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1791 if (tmp
.empty() == true)
1795 unsigned long long size
;
1796 std::stringstream
ss(tmp
);
1798 if (unlikely(hash
.empty() == true))
1800 if (unlikely(ServerSize
!= 0 && ServerSize
!= size
))
1802 ServerHashes
.push_back(HashString(*type
, hash
));
1806 if (ServerHashes
.usable() == false)
1809 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Did not find a good hashsum in the index" << std::endl
;
1813 std::string
const CurrentPackagesFile
= GetFinalFileNameFromURI(Target
.URI
);
1814 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
1815 if (TargetFileHashes
.usable() == false || ServerHashes
!= TargetFileHashes
)
1819 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl
;
1820 printHashSumComparision(CurrentPackagesFile
, ServerHashes
, TargetFileHashes
);
1825 HashStringList LocalHashes
;
1826 // try avoiding calculating the hash here as this is costly
1827 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1828 LocalHashes
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
.MetaKey
);
1829 if (LocalHashes
.usable() == false)
1831 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
, FileFd::Auto
);
1832 Hashes
LocalHashesCalc(ServerHashes
);
1833 LocalHashesCalc
.AddFD(fd
);
1834 LocalHashes
= LocalHashesCalc
.GetHashStringList();
1837 if (ServerHashes
== LocalHashes
)
1839 // we have the same sha1 as the server so we are done here
1841 std::clog
<< "pkgAcqDiffIndex: Package file " << CurrentPackagesFile
<< " is up-to-date" << std::endl
;
1847 std::clog
<< "Server-Current: " << ServerHashes
.find(NULL
)->toStr() << " and we start at "
1848 << CurrentPackagesFile
<< " " << LocalHashes
.FileSize() << " " << LocalHashes
.find(NULL
)->toStr() << std::endl
;
1850 // parse all of (provided) history
1851 vector
<DiffInfo
> available_patches
;
1852 bool firstAcceptedHashes
= true;
1853 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1855 if (LocalHashes
.find(*type
) == NULL
)
1858 std::string tagname
= *type
;
1859 tagname
.append("-History");
1860 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1861 if (tmp
.empty() == true)
1864 string hash
, filename
;
1865 unsigned long long size
;
1866 std::stringstream
ss(tmp
);
1868 while (ss
>> hash
>> size
>> filename
)
1870 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1873 // see if we have a record for this file already
1874 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1875 for (; cur
!= available_patches
.end(); ++cur
)
1877 if (cur
->file
!= filename
)
1879 cur
->result_hashes
.push_back(HashString(*type
, hash
));
1882 if (cur
!= available_patches
.end())
1884 if (firstAcceptedHashes
== true)
1887 next
.file
= filename
;
1888 next
.result_hashes
.push_back(HashString(*type
, hash
));
1889 next
.result_hashes
.FileSize(size
);
1890 available_patches
.push_back(next
);
1895 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1896 << " wasn't in the list for the first parsed hash! (history)" << std::endl
;
1900 firstAcceptedHashes
= false;
1903 if (unlikely(available_patches
.empty() == true))
1906 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
1907 << "Couldn't find any patches for the patch series." << std::endl
;
1911 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1913 if (LocalHashes
.find(*type
) == NULL
)
1916 std::string tagname
= *type
;
1917 tagname
.append("-Patches");
1918 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1919 if (tmp
.empty() == true)
1922 string hash
, filename
;
1923 unsigned long long size
;
1924 std::stringstream
ss(tmp
);
1926 while (ss
>> hash
>> size
>> filename
)
1928 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1931 // see if we have a record for this file already
1932 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1933 for (; cur
!= available_patches
.end(); ++cur
)
1935 if (cur
->file
!= filename
)
1937 if (cur
->patch_hashes
.empty())
1938 cur
->patch_hashes
.FileSize(size
);
1939 cur
->patch_hashes
.push_back(HashString(*type
, hash
));
1942 if (cur
!= available_patches
.end())
1945 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1946 << " wasn't in the list for the first parsed hash! (patches)" << std::endl
;
1951 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1953 std::string tagname
= *type
;
1954 tagname
.append("-Download");
1955 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1956 if (tmp
.empty() == true)
1959 string hash
, filename
;
1960 unsigned long long size
;
1961 std::stringstream
ss(tmp
);
1963 // FIXME: all of pdiff supports only .gz compressed patches
1964 while (ss
>> hash
>> size
>> filename
)
1966 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1968 if (unlikely(APT::String::Endswith(filename
, ".gz") == false))
1970 filename
.erase(filename
.length() - 3);
1972 // see if we have a record for this file already
1973 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1974 for (; cur
!= available_patches
.end(); ++cur
)
1976 if (cur
->file
!= filename
)
1978 if (cur
->download_hashes
.empty())
1979 cur
->download_hashes
.FileSize(size
);
1980 cur
->download_hashes
.push_back(HashString(*type
, hash
));
1983 if (cur
!= available_patches
.end())
1986 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1987 << " wasn't in the list for the first parsed hash! (download)" << std::endl
;
1993 bool foundStart
= false;
1994 for (std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1995 cur
!= available_patches
.end(); ++cur
)
1997 if (LocalHashes
!= cur
->result_hashes
)
2000 available_patches
.erase(available_patches
.begin(), cur
);
2005 if (foundStart
== false || unlikely(available_patches
.empty() == true))
2008 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
2009 << "Couldn't find the start of the patch series." << std::endl
;
2013 // patching with too many files is rather slow compared to a fast download
2014 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
2015 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
2018 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
2019 << ") so fallback to complete download" << std::endl
;
2023 // calculate the size of all patches we have to get
2024 // note that all sizes are uncompressed, while we download compressed files
2025 unsigned long long patchesSize
= 0;
2026 for (std::vector
<DiffInfo
>::const_iterator cur
= available_patches
.begin();
2027 cur
!= available_patches
.end(); ++cur
)
2028 patchesSize
+= cur
->patch_hashes
.FileSize();
2029 unsigned long long const sizeLimit
= ServerSize
* _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
2030 if (sizeLimit
> 0 && (sizeLimit
/100) < patchesSize
)
2033 std::clog
<< "Need " << patchesSize
<< " bytes (Limit is " << sizeLimit
/100
2034 << ") so fallback to complete download" << std::endl
;
2038 // we have something, queue the diffs
2039 string::size_type
const last_space
= Description
.rfind(" ");
2040 if(last_space
!= string::npos
)
2041 Description
.erase(last_space
, Description
.size()-last_space
);
2043 /* decide if we should download patches one by one or in one go:
2044 The first is good if the server merges patches, but many don't so client
2045 based merging can be attempt in which case the second is better.
2046 "bad things" will happen if patches are merged on the server,
2047 but client side merging is attempt as well */
2048 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
2049 if (pdiff_merge
== true)
2051 // reprepro adds this flag if it has merged patches on the server
2052 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
2053 pdiff_merge
= (precedence
!= "merged");
2056 if (pdiff_merge
== false)
2057 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, available_patches
);
2060 diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
2061 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
2062 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
, TransactionManager
,
2064 available_patches
[i
],
2074 void pkgAcqDiffIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2076 Item::Failed(Message
,Cnf
);
2080 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2081 << "Falling back to normal index file acquire" << std::endl
;
2083 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2086 void pkgAcqDiffIndex::Done(string
const &Message
,HashStringList
const &Hashes
, /*{{{*/
2087 pkgAcquire::MethodConfig
const * const Cnf
)
2090 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
2092 Item::Done(Message
, Hashes
, Cnf
);
2094 string
const FinalFile
= GetFinalFilename();
2095 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false))
2096 DestFile
= FinalFile
;
2098 if(ParseDiffIndex(DestFile
) == false)
2100 Failed("Message: Couldn't parse pdiff index", Cnf
);
2101 // queue for final move - this should happen even if we fail
2102 // while parsing (e.g. on sizelimit) and download the complete file.
2103 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2107 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2116 pkgAcqDiffIndex::~pkgAcqDiffIndex()
2122 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
2123 // ---------------------------------------------------------------------
2124 /* The package diff is added to the queue. one object is constructed
2125 * for each diff and the index
2127 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
* const Owner
,
2128 pkgAcqMetaClearSig
* const TransactionManager
,
2129 IndexTarget
const &Target
,
2130 vector
<DiffInfo
> const &diffs
)
2131 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
),
2132 available_patches(diffs
)
2134 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2136 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2139 Description
= Target
.Description
;
2140 Desc
.ShortDesc
= Target
.ShortDesc
;
2142 if(available_patches
.empty() == true)
2144 // we are done (yeah!), check hashes against the final file
2145 DestFile
= GetKeepCompressedFileName(GetFinalFileNameFromURI(Target
.URI
), Target
);
2150 if (BootstrapPDiffWith(GetPartialFileNameFromURI(Target
.URI
), GetFinalFilename(), Target
) == false)
2152 Failed("Bootstrapping of " + DestFile
+ " failed", NULL
);
2156 // get the next diff
2157 State
= StateFetchDiff
;
2162 void pkgAcqIndexDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2164 Item::Failed(Message
,Cnf
);
2167 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2169 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2170 << "Falling back to normal index file acquire " << std::endl
;
2171 RenameOnError(PDiffError
);
2172 std::string
const patchname
= GetDiffsPatchFileName(DestFile
);
2173 if (RealFileExists(patchname
))
2174 rename(patchname
.c_str(), std::string(patchname
+ ".FAILED").c_str());
2175 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2179 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
2180 void pkgAcqIndexDiffs::Finish(bool allDone
)
2183 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
2185 << Desc
.URI
<< std::endl
;
2187 // we restore the original name, this is required, otherwise
2188 // the file will be cleaned
2191 std::string Final
= GetFinalFilename();
2192 if (Target
.KeepCompressed
)
2194 std::string
const ext
= flExtension(DestFile
);
2195 if (ext
.empty() == false)
2196 Final
.append(".").append(ext
);
2198 TransactionManager
->TransactionStageCopy(this, DestFile
, Final
);
2200 // this is for the "real" finish
2205 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
2212 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
2219 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
2221 // calc sha1 of the just patched file
2222 std::string
const FinalFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2223 if(!FileExists(FinalFile
))
2225 Failed("Message: No FinalFile " + FinalFile
+ " available", NULL
);
2229 FileFd
fd(FinalFile
, FileFd::ReadOnly
, FileFd::Extension
);
2230 Hashes LocalHashesCalc
;
2231 LocalHashesCalc
.AddFD(fd
);
2232 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
2235 std::clog
<< "QueueNextDiff: " << FinalFile
<< " (" << LocalHashes
.find(NULL
)->toStr() << ")" << std::endl
;
2237 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
2238 if (unlikely(LocalHashes
.usable() == false || TargetFileHashes
.usable() == false))
2240 Failed("Local/Expected hashes are not usable", NULL
);
2245 // final file reached before all patches are applied
2246 if(LocalHashes
== TargetFileHashes
)
2252 // remove all patches until the next matching patch is found
2253 // this requires the Index file to be ordered
2254 for(vector
<DiffInfo
>::iterator I
= available_patches
.begin();
2255 available_patches
.empty() == false &&
2256 I
!= available_patches
.end() &&
2257 I
->result_hashes
!= LocalHashes
;
2260 available_patches
.erase(I
);
2263 // error checking and falling back if no patch was found
2264 if(available_patches
.empty() == true)
2266 Failed("No patches left to reach target", NULL
);
2270 // queue the right diff
2271 Desc
.URI
= Target
.URI
+ ".diff/" + available_patches
[0].file
+ ".gz";
2272 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
2273 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + available_patches
[0].file
), Target
);
2276 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
2283 void pkgAcqIndexDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2284 pkgAcquire::MethodConfig
const * const Cnf
)
2287 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
2289 Item::Done(Message
, Hashes
, Cnf
);
2291 std::string
const FinalFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2292 std::string
const PatchFile
= GetDiffsPatchFileName(FinalFile
);
2294 // success in downloading a diff, enter ApplyDiff state
2295 if(State
== StateFetchDiff
)
2297 Rename(DestFile
, PatchFile
);
2300 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
2302 State
= StateApplyDiff
;
2304 Desc
.URI
= "rred:" + FinalFile
;
2306 SetActiveSubprocess("rred");
2310 // success in download/apply a diff, queue next (if needed)
2311 if(State
== StateApplyDiff
)
2313 // remove the just applied patch
2314 available_patches
.erase(available_patches
.begin());
2315 RemoveFile("pkgAcqIndexDiffs::Done", PatchFile
);
2320 std::clog
<< "Moving patched file in place: " << std::endl
2321 << DestFile
<< " -> " << FinalFile
<< std::endl
;
2323 Rename(DestFile
,FinalFile
);
2324 chmod(FinalFile
.c_str(),0644);
2326 // see if there is more to download
2327 if(available_patches
.empty() == false) {
2328 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
2333 DestFile
= FinalFile
;
2334 return Finish(true);
2338 std::string
pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
2340 if(State
!= StateApplyDiff
)
2341 return pkgAcqBaseIndex::Custom600Headers();
2342 std::ostringstream patchhashes
;
2343 HashStringList
const ExpectedHashes
= available_patches
[0].patch_hashes
;
2344 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2345 patchhashes
<< "\nPatch-0-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2346 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2347 return patchhashes
.str();
2350 pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
2352 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
2353 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
* const Owner
,
2354 pkgAcqMetaClearSig
* const TransactionManager
,
2355 IndexTarget
const &Target
,
2356 DiffInfo
const &patch
,
2357 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
2358 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
),
2359 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
2361 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2364 Description
= Target
.Description
;
2365 Desc
.ShortDesc
= Target
.ShortDesc
;
2367 Desc
.URI
= Target
.URI
+ ".diff/" + patch
.file
+ ".gz";
2368 Desc
.Description
= Description
+ " " + patch
.file
+ string(".pdiff");
2370 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + patch
.file
), Target
);
2373 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
2378 void pkgAcqIndexMergeDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2381 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
2383 Item::Failed(Message
,Cnf
);
2386 // check if we are the first to fail, otherwise we are done here
2387 State
= StateDoneDiff
;
2388 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2389 I
!= allPatches
->end(); ++I
)
2390 if ((*I
)->State
== StateErrorDiff
)
2393 // first failure means we should fallback
2394 State
= StateErrorDiff
;
2396 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
2397 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2398 RenameOnError(PDiffError
);
2399 std::string
const patchname
= GetMergeDiffsPatchFileName(DestFile
, patch
.file
);
2400 if (RealFileExists(patchname
))
2401 rename(patchname
.c_str(), std::string(patchname
+ ".FAILED").c_str());
2402 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2406 void pkgAcqIndexMergeDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2407 pkgAcquire::MethodConfig
const * const Cnf
)
2410 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
2412 Item::Done(Message
, Hashes
, Cnf
);
2414 std::string
const UncompressedFinalFile
= GetPartialFileNameFromURI(Target
.URI
);
2415 std::string
const FinalFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2416 if (State
== StateFetchDiff
)
2418 Rename(DestFile
, GetMergeDiffsPatchFileName(FinalFile
, patch
.file
));
2420 // check if this is the last completed diff
2421 State
= StateDoneDiff
;
2422 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2423 I
!= allPatches
->end(); ++I
)
2424 if ((*I
)->State
!= StateDoneDiff
)
2427 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
2431 // this is the last completed diff, so we are ready to apply now
2432 State
= StateApplyDiff
;
2434 if (BootstrapPDiffWith(UncompressedFinalFile
, GetFinalFilename(), Target
) == false)
2436 Failed("Bootstrapping of " + DestFile
+ " failed", NULL
);
2441 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
2444 Desc
.URI
= "rred:" + FinalFile
;
2446 SetActiveSubprocess("rred");
2449 // success in download/apply all diffs, clean up
2450 else if (State
== StateApplyDiff
)
2452 // move the result into place
2453 std::string
const Final
= GetKeepCompressedFileName(GetFinalFilename(), Target
);
2455 std::clog
<< "Queue patched file in place: " << std::endl
2456 << DestFile
<< " -> " << Final
<< std::endl
;
2458 // queue for copy by the transaction manager
2459 TransactionManager
->TransactionStageCopy(this, DestFile
, Final
);
2461 // ensure the ed's are gone regardless of list-cleanup
2462 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2463 I
!= allPatches
->end(); ++I
)
2465 std::string
const PartialFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2466 std::string
const patch
= GetMergeDiffsPatchFileName(PartialFile
, (*I
)->patch
.file
);
2467 RemoveFile("pkgAcqIndexMergeDiffs::Done", patch
);
2469 RemoveFile("pkgAcqIndexMergeDiffs::Done", FinalFile
);
2474 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
2478 std::string
pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
2480 if(State
!= StateApplyDiff
)
2481 return pkgAcqBaseIndex::Custom600Headers();
2482 std::ostringstream patchhashes
;
2483 unsigned int seen_patches
= 0;
2484 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2485 I
!= allPatches
->end(); ++I
)
2487 HashStringList
const ExpectedHashes
= (*I
)->patch
.patch_hashes
;
2488 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2489 patchhashes
<< "\nPatch-" << seen_patches
<< "-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2492 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2493 return patchhashes
.str();
2496 pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
2498 // AcqIndex::AcqIndex - Constructor /*{{{*/
2499 pkgAcqIndex::pkgAcqIndex(pkgAcquire
* const Owner
,
2500 pkgAcqMetaClearSig
* const TransactionManager
,
2501 IndexTarget
const &Target
)
2502 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), Stage(STAGE_DOWNLOAD
),
2503 CompressionExtensions(Target
.Option(IndexTarget::COMPRESSIONTYPES
))
2505 Init(Target
.URI
, Target
.Description
, Target
.ShortDesc
);
2507 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2508 std::clog
<< "New pkgIndex with TransactionManager "
2509 << TransactionManager
<< std::endl
;
2512 // AcqIndex::Init - defered Constructor /*{{{*/
2513 static void NextCompressionExtension(std::string
&CurrentCompressionExtension
, std::string
&CompressionExtensions
, bool const preview
)
2515 size_t const nextExt
= CompressionExtensions
.find(' ');
2516 if (nextExt
== std::string::npos
)
2518 CurrentCompressionExtension
= CompressionExtensions
;
2519 if (preview
== false)
2520 CompressionExtensions
.clear();
2524 CurrentCompressionExtension
= CompressionExtensions
.substr(0, nextExt
);
2525 if (preview
== false)
2526 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
2529 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
2530 string
const &ShortDesc
)
2532 Stage
= STAGE_DOWNLOAD
;
2534 DestFile
= GetPartialFileNameFromURI(URI
);
2535 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, false);
2537 if (CurrentCompressionExtension
== "uncompressed")
2541 else if (CurrentCompressionExtension
== "by-hash")
2543 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, true);
2544 if(unlikely(TransactionManager
->MetaIndexParser
== NULL
|| CurrentCompressionExtension
.empty()))
2546 if (CurrentCompressionExtension
!= "uncompressed")
2548 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2549 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2552 HashStringList
const Hashes
= GetExpectedHashes();
2553 HashString
const * const TargetHash
= Hashes
.find(NULL
);
2554 if (unlikely(TargetHash
== nullptr))
2556 std::string
const ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
2557 size_t const trailing_slash
= Desc
.URI
.find_last_of("/");
2558 if (unlikely(trailing_slash
== std::string::npos
))
2560 Desc
.URI
= Desc
.URI
.replace(
2562 Desc
.URI
.substr(trailing_slash
+1).size()+1,
2565 else if (unlikely(CurrentCompressionExtension
.empty()))
2569 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2570 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2574 Desc
.Description
= URIDesc
;
2576 Desc
.ShortDesc
= ShortDesc
;
2581 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2582 // ---------------------------------------------------------------------
2583 /* The only header we use is the last-modified header. */
2584 string
pkgAcqIndex::Custom600Headers() const
2586 string Final
= GetFinalFilename();
2588 string msg
= "\nIndex-File: true";
2590 if (stat(Final
.c_str(),&Buf
) == 0)
2591 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
2593 if(Target
.IsOptional
)
2594 msg
+= "\nFail-Ignore: true";
2599 // AcqIndex::Failed - getting the indexfile failed /*{{{*/
2600 void pkgAcqIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
2602 Item::Failed(Message
,Cnf
);
2604 // authorisation matches will not be fixed by other compression types
2605 if (Status
!= StatAuthError
)
2607 if (CompressionExtensions
.empty() == false)
2609 Init(Target
.URI
, Desc
.Description
, Desc
.ShortDesc
);
2615 if(Target
.IsOptional
&& GetExpectedHashes().empty() && Stage
== STAGE_DOWNLOAD
)
2618 TransactionManager
->AbortTransaction();
2621 // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
2622 void pkgAcqIndex::ReverifyAfterIMS()
2624 // update destfile to *not* include the compression extension when doing
2625 // a reverify (as its uncompressed on disk already)
2626 DestFile
= GetCompressedFileName(Target
, GetPartialFileNameFromURI(Target
.URI
), CurrentCompressionExtension
);
2628 // copy FinalFile into partial/ so that we check the hash again
2629 string FinalFile
= GetFinalFilename();
2630 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2631 Desc
.URI
= "copy:" + FinalFile
;
2635 // AcqIndex::Done - Finished a fetch /*{{{*/
2636 // ---------------------------------------------------------------------
2637 /* This goes through a number of states.. On the initial fetch the
2638 method could possibly return an alternate filename which points
2639 to the uncompressed version of the file. If this is so the file
2640 is copied into the partial directory. In all other cases the file
2641 is decompressed with a compressed uri. */
2642 void pkgAcqIndex::Done(string
const &Message
,
2643 HashStringList
const &Hashes
,
2644 pkgAcquire::MethodConfig
const * const Cfg
)
2646 Item::Done(Message
,Hashes
,Cfg
);
2650 case STAGE_DOWNLOAD
:
2651 StageDownloadDone(Message
, Hashes
, Cfg
);
2653 case STAGE_DECOMPRESS_AND_VERIFY
:
2654 StageDecompressDone(Message
, Hashes
, Cfg
);
2659 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
2660 void pkgAcqIndex::StageDownloadDone(string
const &Message
, HashStringList
const &,
2661 pkgAcquire::MethodConfig
const * const)
2665 // Handle the unzipd case
2666 std::string FileName
= LookupTag(Message
,"Alt-Filename");
2667 if (FileName
.empty() == false)
2669 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2671 DestFile
+= ".decomp";
2672 Desc
.URI
= "copy:" + FileName
;
2674 SetActiveSubprocess("copy");
2677 FileName
= LookupTag(Message
,"Filename");
2679 // Methods like e.g. "file:" will give us a (compressed) FileName that is
2680 // not the "DestFile" we set, in this case we uncompress from the local file
2681 if (FileName
!= DestFile
&& RealFileExists(DestFile
) == false)
2684 if (Target
.KeepCompressed
== true)
2686 // but if we don't keep the uncompress we copy the compressed file first
2687 Stage
= STAGE_DOWNLOAD
;
2688 Desc
.URI
= "copy:" + FileName
;
2690 SetActiveSubprocess("copy");
2695 EraseFileName
= FileName
;
2697 // we need to verify the file against the current Release file again
2698 // on if-modfied-since hit to avoid a stale attack against us
2699 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
2701 // The files timestamp matches, reverify by copy into partial/
2707 // get the binary name for your used compression type
2709 if(CurrentCompressionExtension
== "uncompressed")
2710 decompProg
= "copy";
2712 decompProg
= _config
->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension
),"");
2713 if(decompProg
.empty() == true)
2715 _error
->Error("Unsupported extension: %s", CurrentCompressionExtension
.c_str());
2719 if (Target
.KeepCompressed
== true)
2721 DestFile
= "/dev/null";
2722 EraseFileName
.clear();
2725 DestFile
+= ".decomp";
2727 // queue uri for the next stage
2728 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2729 Desc
.URI
= decompProg
+ ":" + FileName
;
2731 SetActiveSubprocess(decompProg
);
2734 // AcqIndex::StageDecompressDone - Final verification /*{{{*/
2735 void pkgAcqIndex::StageDecompressDone(string
const &,
2736 HashStringList
const &,
2737 pkgAcquire::MethodConfig
const * const)
2739 if (Target
.KeepCompressed
== true && DestFile
== "/dev/null")
2740 DestFile
= GetPartialFileNameFromURI(Target
.URI
+ '.' + CurrentCompressionExtension
);
2742 // Done, queue for rename on transaction finished
2743 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
2747 pkgAcqIndex::~pkgAcqIndex() {}
2750 // AcqArchive::AcqArchive - Constructor /*{{{*/
2751 // ---------------------------------------------------------------------
2752 /* This just sets up the initial fetch environment and queues the first
2754 pkgAcqArchive::pkgAcqArchive(pkgAcquire
* const Owner
,pkgSourceList
* const Sources
,
2755 pkgRecords
* const Recs
,pkgCache::VerIterator
const &Version
,
2756 string
&StoreFilename
) :
2757 Item(Owner
), d(NULL
), LocalSource(false), Version(Version
), Sources(Sources
), Recs(Recs
),
2758 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
2761 Retries
= _config
->FindI("Acquire::Retries",0);
2763 if (Version
.Arch() == 0)
2765 _error
->Error(_("I wasn't able to locate a file for the %s package. "
2766 "This might mean you need to manually fix this package. "
2767 "(due to missing arch)"),
2768 Version
.ParentPkg().FullName().c_str());
2772 /* We need to find a filename to determine the extension. We make the
2773 assumption here that all the available sources for this version share
2774 the same extension.. */
2775 // Skip not source sources, they do not have file fields.
2776 for (; Vf
.end() == false; ++Vf
)
2778 if (Vf
.File().Flagged(pkgCache::Flag::NotSource
))
2783 // Does not really matter here.. we are going to fail out below
2784 if (Vf
.end() != true)
2786 // If this fails to get a file name we will bomb out below.
2787 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2788 if (_error
->PendingError() == true)
2791 // Generate the final file name as: package_version_arch.foo
2792 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
2793 QuoteString(Version
.VerStr(),"_:") + '_' +
2794 QuoteString(Version
.Arch(),"_:.") +
2795 "." + flExtension(Parse
.FileName());
2798 // check if we have one trusted source for the package. if so, switch
2799 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2800 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
2801 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
2802 bool seenUntrusted
= false;
2803 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
2805 pkgIndexFile
*Index
;
2806 if (Sources
->FindIndex(i
.File(),Index
) == false)
2809 if (debugAuth
== true)
2810 std::cerr
<< "Checking index: " << Index
->Describe()
2811 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
2813 if (Index
->IsTrusted() == true)
2816 if (allowUnauth
== false)
2820 seenUntrusted
= true;
2823 // "allow-unauthenticated" restores apts old fetching behaviour
2824 // that means that e.g. unauthenticated file:// uris are higher
2825 // priority than authenticated http:// uris
2826 if (allowUnauth
== true && seenUntrusted
== true)
2830 if (QueueNext() == false && _error
->PendingError() == false)
2831 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
2832 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
2835 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2836 // ---------------------------------------------------------------------
2837 /* This queues the next available file version for download. It checks if
2838 the archive is already available in the cache and stashs the MD5 for
2840 bool pkgAcqArchive::QueueNext()
2842 for (; Vf
.end() == false; ++Vf
)
2844 pkgCache::PkgFileIterator
const PkgF
= Vf
.File();
2845 // Ignore not source sources
2846 if (PkgF
.Flagged(pkgCache::Flag::NotSource
))
2849 // Try to cross match against the source list
2850 pkgIndexFile
*Index
;
2851 if (Sources
->FindIndex(PkgF
, Index
) == false)
2853 LocalSource
= PkgF
.Flagged(pkgCache::Flag::LocalSource
);
2855 // only try to get a trusted package from another source if that source
2857 if(Trusted
&& !Index
->IsTrusted())
2860 // Grab the text package record
2861 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2862 if (_error
->PendingError() == true)
2865 string PkgFile
= Parse
.FileName();
2866 ExpectedHashes
= Parse
.Hashes();
2868 if (PkgFile
.empty() == true)
2869 return _error
->Error(_("The package index files are corrupted. No Filename: "
2870 "field for package %s."),
2871 Version
.ParentPkg().Name());
2873 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
2874 Desc
.Description
= Index
->ArchiveInfo(Version
);
2876 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
2878 // See if we already have the file. (Legacy filenames)
2879 FileSize
= Version
->Size
;
2880 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
2882 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2884 // Make sure the size matches
2885 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2890 StoreFilename
= DestFile
= FinalFile
;
2894 /* Hmm, we have a file and its size does not match, this means it is
2895 an old style mismatched arch */
2896 RemoveFile("pkgAcqArchive::QueueNext", FinalFile
);
2899 // Check it again using the new style output filenames
2900 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
2901 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2903 // Make sure the size matches
2904 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2909 StoreFilename
= DestFile
= FinalFile
;
2913 /* Hmm, we have a file and its size does not match, this shouldn't
2915 RemoveFile("pkgAcqArchive::QueueNext", FinalFile
);
2918 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
2920 // Check the destination file
2921 if (stat(DestFile
.c_str(),&Buf
) == 0)
2923 // Hmm, the partial file is too big, erase it
2924 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
2925 RemoveFile("pkgAcqArchive::QueueNext", DestFile
);
2927 PartialSize
= Buf
.st_size
;
2930 // Disables download of archives - useful if no real installation follows,
2931 // e.g. if we are just interested in proposed installation order
2932 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2937 StoreFilename
= DestFile
= FinalFile
;
2951 // AcqArchive::Done - Finished fetching /*{{{*/
2952 // ---------------------------------------------------------------------
2954 void pkgAcqArchive::Done(string
const &Message
, HashStringList
const &Hashes
,
2955 pkgAcquire::MethodConfig
const * const Cfg
)
2957 Item::Done(Message
, Hashes
, Cfg
);
2959 // Grab the output filename
2960 std::string
const FileName
= LookupTag(Message
,"Filename");
2961 if (DestFile
!= FileName
&& RealFileExists(DestFile
) == false)
2963 StoreFilename
= DestFile
= FileName
;
2969 // Done, move it into position
2970 string
const FinalFile
= GetFinalFilename();
2971 Rename(DestFile
,FinalFile
);
2972 StoreFilename
= DestFile
= FinalFile
;
2976 // AcqArchive::Failed - Failure handler /*{{{*/
2977 // ---------------------------------------------------------------------
2978 /* Here we try other sources */
2979 void pkgAcqArchive::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
2981 Item::Failed(Message
,Cnf
);
2983 /* We don't really want to retry on failed media swaps, this prevents
2984 that. An interesting observation is that permanent failures are not
2986 if (Cnf
->Removable
== true &&
2987 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2989 // Vf = Version.FileList();
2990 while (Vf
.end() == false) ++Vf
;
2991 StoreFilename
= string();
2996 if (QueueNext() == false)
2998 // This is the retry counter
3000 Cnf
->LocalOnly
== false &&
3001 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3004 Vf
= Version
.FileList();
3005 if (QueueNext() == true)
3009 StoreFilename
= string();
3014 APT_PURE
bool pkgAcqArchive::IsTrusted() const /*{{{*/
3019 void pkgAcqArchive::Finished() /*{{{*/
3021 if (Status
== pkgAcquire::Item::StatDone
&&
3024 StoreFilename
= string();
3027 std::string
pkgAcqArchive::DescURI() const /*{{{*/
3032 std::string
pkgAcqArchive::ShortDesc() const /*{{{*/
3034 return Desc
.ShortDesc
;
3037 pkgAcqArchive::~pkgAcqArchive() {}
3039 // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
3040 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::VerIterator
const &Ver
,
3041 std::string
const &DestDir
, std::string
const &DestFilename
) :
3042 pkgAcquire::Item(Owner
), d(NULL
), SrcName(Ver
.SourcePkgName()), SrcVersion(Ver
.SourceVerStr())
3044 Desc
.URI
= URI(Ver
);
3045 Init(DestDir
, DestFilename
);
3047 // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
3048 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::RlsFileIterator
const &RlsFile
,
3049 char const * const Component
, char const * const SrcName
, char const * const SrcVersion
,
3050 const string
&DestDir
, const string
&DestFilename
) :
3051 pkgAcquire::Item(Owner
), d(NULL
), SrcName(SrcName
), SrcVersion(SrcVersion
)
3053 Desc
.URI
= URI(RlsFile
, Component
, SrcName
, SrcVersion
);
3054 Init(DestDir
, DestFilename
);
3056 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
,
3057 std::string
const &URI
, char const * const SrcName
, char const * const SrcVersion
,
3058 const string
&DestDir
, const string
&DestFilename
) :
3059 pkgAcquire::Item(Owner
), d(NULL
), SrcName(SrcName
), SrcVersion(SrcVersion
)
3062 Init(DestDir
, DestFilename
);
3064 void pkgAcqChangelog::Init(std::string
const &DestDir
, std::string
const &DestFilename
)
3066 if (Desc
.URI
.empty())
3069 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3070 strprintf(ErrorText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3071 // Let the error message print something sensible rather than "Failed to fetch /"
3072 if (DestFilename
.empty())
3073 DestFile
= SrcName
+ ".changelog";
3075 DestFile
= DestFilename
;
3076 Desc
.URI
= "changelog:/" + DestFile
;
3080 if (DestDir
.empty())
3082 std::string
const SandboxUser
= _config
->Find("APT::Sandbox::User");
3083 std::string
const systemTemp
= GetTempDir(SandboxUser
);
3085 snprintf(tmpname
, sizeof(tmpname
), "%s/apt-changelog-XXXXXX", systemTemp
.c_str());
3086 if (NULL
== mkdtemp(tmpname
))
3088 _error
->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName
.c_str(), SrcVersion
.c_str());
3092 DestFile
= TemporaryDirectory
= tmpname
;
3094 ChangeOwnerAndPermissionOfFile("Item::QueueURI", DestFile
.c_str(),
3095 SandboxUser
.c_str(), "root", 0700);
3100 if (DestFilename
.empty())
3101 DestFile
= flCombine(DestFile
, SrcName
+ ".changelog");
3103 DestFile
= flCombine(DestFile
, DestFilename
);
3105 Desc
.ShortDesc
= "Changelog";
3106 strprintf(Desc
.Description
, "%s %s %s Changelog", URI::SiteOnly(Desc
.URI
).c_str(), SrcName
.c_str(), SrcVersion
.c_str());
3111 std::string
pkgAcqChangelog::URI(pkgCache::VerIterator
const &Ver
) /*{{{*/
3113 char const * const SrcName
= Ver
.SourcePkgName();
3114 char const * const SrcVersion
= Ver
.SourceVerStr();
3115 pkgCache::PkgFileIterator PkgFile
;
3116 // find the first source for this version which promises a changelog
3117 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
3119 pkgCache::PkgFileIterator
const PF
= VF
.File();
3120 if (PF
.Flagged(pkgCache::Flag::NotSource
) || PF
->Release
== 0)
3123 pkgCache::RlsFileIterator
const RF
= PF
.ReleaseFile();
3124 std::string
const uri
= URI(RF
, PF
.Component(), SrcName
, SrcVersion
);
3131 std::string
pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator
const &Rls
)
3133 if (Rls
.end() == true || (Rls
->Label
== 0 && Rls
->Origin
== 0))
3135 std::string
const serverConfig
= "Acquire::Changelogs::URI";
3137 #define APT_EMPTY_SERVER \
3138 if (server.empty() == false) \
3140 if (server != "no") \
3144 #define APT_CHECK_SERVER(X, Y) \
3147 std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
3148 server = _config->Find(specialServerConfig); \
3151 // this way e.g. Debian-Security can fallback to Debian
3152 APT_CHECK_SERVER(Label
, "Override::")
3153 APT_CHECK_SERVER(Origin
, "Override::")
3155 if (RealFileExists(Rls
.FileName()))
3157 _error
->PushToStack();
3159 /* This can be costly. A caller wanting to get millions of URIs might
3160 want to do this on its own once and use Override settings.
3161 We don't do this here as Origin/Label are not as unique as they
3162 should be so this could produce request order-dependent anomalies */
3163 if (OpenMaybeClearSignedFile(Rls
.FileName(), rf
) == true)
3165 pkgTagFile
TagFile(&rf
, rf
.Size());
3166 pkgTagSection Section
;
3167 if (TagFile
.Step(Section
) == true)
3168 server
= Section
.FindS("Changelogs");
3170 _error
->RevertToStack();
3174 APT_CHECK_SERVER(Label
, "")
3175 APT_CHECK_SERVER(Origin
, "")
3176 #undef APT_CHECK_SERVER
3177 #undef APT_EMPTY_SERVER
3180 std::string
pkgAcqChangelog::URI(pkgCache::RlsFileIterator
const &Rls
,
3181 char const * const Component
, char const * const SrcName
,
3182 char const * const SrcVersion
)
3184 return URI(URITemplate(Rls
), Component
, SrcName
, SrcVersion
);
3186 std::string
pkgAcqChangelog::URI(std::string
const &Template
,
3187 char const * const Component
, char const * const SrcName
,
3188 char const * const SrcVersion
)
3190 if (Template
.find("CHANGEPATH") == std::string::npos
)
3193 // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
3194 std::string Src
= SrcName
;
3195 std::string path
= APT::String::Startswith(SrcName
, "lib") ? Src
.substr(0, 4) : Src
.substr(0,1);
3196 path
.append("/").append(Src
).append("/");
3197 path
.append(Src
).append("_").append(StripEpoch(SrcVersion
));
3198 // we omit component for releases without one (= flat-style repositories)
3199 if (Component
!= NULL
&& strlen(Component
) != 0)
3200 path
= std::string(Component
) + "/" + path
;
3202 return SubstVar(Template
, "CHANGEPATH", path
);
3205 // AcqChangelog::Failed - Failure handler /*{{{*/
3206 void pkgAcqChangelog::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3208 Item::Failed(Message
,Cnf
);
3210 std::string errText
;
3211 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3212 strprintf(errText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3214 // Error is probably something techy like 404 Not Found
3215 if (ErrorText
.empty())
3216 ErrorText
= errText
;
3218 ErrorText
= errText
+ " (" + ErrorText
+ ")";
3222 // AcqChangelog::Done - Item downloaded OK /*{{{*/
3223 void pkgAcqChangelog::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3224 pkgAcquire::MethodConfig
const * const Cnf
)
3226 Item::Done(Message
,CalcHashes
,Cnf
);
3231 pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
3233 if (TemporaryDirectory
.empty() == false)
3235 RemoveFile("~pkgAcqChangelog", DestFile
);
3236 rmdir(TemporaryDirectory
.c_str());
3241 // AcqFile::pkgAcqFile - Constructor /*{{{*/
3242 pkgAcqFile::pkgAcqFile(pkgAcquire
* const Owner
,string
const &URI
, HashStringList
const &Hashes
,
3243 unsigned long long const Size
,string
const &Dsc
,string
const &ShortDesc
,
3244 const string
&DestDir
, const string
&DestFilename
,
3245 bool const IsIndexFile
) :
3246 Item(Owner
), d(NULL
), IsIndexFile(IsIndexFile
), ExpectedHashes(Hashes
)
3248 Retries
= _config
->FindI("Acquire::Retries",0);
3250 if(!DestFilename
.empty())
3251 DestFile
= DestFilename
;
3252 else if(!DestDir
.empty())
3253 DestFile
= DestDir
+ "/" + flNotDir(URI
);
3255 DestFile
= flNotDir(URI
);
3259 Desc
.Description
= Dsc
;
3262 // Set the short description to the archive component
3263 Desc
.ShortDesc
= ShortDesc
;
3265 // Get the transfer sizes
3268 if (stat(DestFile
.c_str(),&Buf
) == 0)
3270 // Hmm, the partial file is too big, erase it
3271 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
3272 RemoveFile("pkgAcqFile", DestFile
);
3274 PartialSize
= Buf
.st_size
;
3280 // AcqFile::Done - Item downloaded OK /*{{{*/
3281 void pkgAcqFile::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3282 pkgAcquire::MethodConfig
const * const Cnf
)
3284 Item::Done(Message
,CalcHashes
,Cnf
);
3286 std::string
const FileName
= LookupTag(Message
,"Filename");
3289 // The files timestamp matches
3290 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
3293 // We have to copy it into place
3294 if (RealFileExists(DestFile
.c_str()) == false)
3297 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
3298 Cnf
->Removable
== true)
3300 Desc
.URI
= "copy:" + FileName
;
3305 // Erase the file if it is a symlink so we can overwrite it
3307 if (lstat(DestFile
.c_str(),&St
) == 0)
3309 if (S_ISLNK(St
.st_mode
) != 0)
3310 RemoveFile("pkgAcqFile::Done", DestFile
);
3314 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
3316 _error
->PushToStack();
3317 _error
->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile
.c_str());
3318 std::stringstream msg
;
3319 _error
->DumpErrors(msg
, GlobalError::DEBUG
, false);
3320 _error
->RevertToStack();
3321 ErrorText
= msg
.str();
3328 // AcqFile::Failed - Failure handler /*{{{*/
3329 // ---------------------------------------------------------------------
3330 /* Here we try other sources */
3331 void pkgAcqFile::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3333 Item::Failed(Message
,Cnf
);
3335 // This is the retry counter
3337 Cnf
->LocalOnly
== false &&
3338 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3348 string
pkgAcqFile::Custom600Headers() const /*{{{*/
3351 return "\nIndex-File: true";
3355 pkgAcqFile::~pkgAcqFile() {}