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();
151 static bool AllowInsecureRepositories(metaIndex
const * const MetaIndexParser
, pkgAcqMetaClearSig
* const TransactionManager
, pkgAcquire::Item
* const I
) /*{{{*/
153 if(MetaIndexParser
->GetTrusted() == metaIndex::TRI_YES
|| _config
->FindB("Acquire::AllowInsecureRepositories") == true)
156 _error
->Error(_("Use --allow-insecure-repositories to force the update"));
157 TransactionManager
->AbortTransaction();
158 I
->Status
= pkgAcquire::Item::StatError
;
162 static HashStringList
GetExpectedHashesFromFor(metaIndex
* const Parser
, std::string
const &MetaKey
)/*{{{*/
165 return HashStringList();
166 metaIndex::checkSum
* const R
= Parser
->Lookup(MetaKey
);
168 return HashStringList();
173 // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
174 /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
175 It is best to implement it as broadly as possible, while ::HashesRequired defaults
176 to true and should be as restrictive as possible for false cases. Note that if
177 a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
178 ::HashesRequired is called to evaluate if its okay to have no hashes. */
179 APT_CONST
bool pkgAcqTransactionItem::HashesRequired() const
181 /* signed repositories obviously have a parser and good hashes.
182 unsigned repositories, too, as even if we can't trust them for security,
183 we can at least trust them for integrity of the download itself.
184 Only repositories without a Release file can (obviously) not have
185 hashes – and they are very uncommon and strongly discouraged */
186 return TransactionManager
->MetaIndexParser
!= NULL
&&
187 TransactionManager
->MetaIndexParser
->GetLoadedSuccessfully() != metaIndex::TRI_UNSET
;
189 HashStringList
pkgAcqTransactionItem::GetExpectedHashes() const
191 return GetExpectedHashesFor(GetMetaKey());
194 APT_CONST
bool pkgAcqMetaBase::HashesRequired() const
196 // Release and co have no hashes 'by design'.
199 HashStringList
pkgAcqMetaBase::GetExpectedHashes() const
201 return HashStringList();
204 APT_CONST
bool pkgAcqIndexDiffs::HashesRequired() const
206 /* We don't always have the diff of the downloaded pdiff file.
207 What we have for sure is hashes for the uncompressed file,
208 but rred uncompresses them on the fly while parsing, so not handled here.
209 Hashes are (also) checked while searching for (next) patch to apply. */
210 if (State
== StateFetchDiff
)
211 return available_patches
[0].download_hashes
.empty() == false;
214 HashStringList
pkgAcqIndexDiffs::GetExpectedHashes() const
216 if (State
== StateFetchDiff
)
217 return available_patches
[0].download_hashes
;
218 return HashStringList();
221 APT_CONST
bool pkgAcqIndexMergeDiffs::HashesRequired() const
223 /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
224 we can check the rred result after all patches are applied as
225 we know the expected result rather than potentially apply more patches */
226 if (State
== StateFetchDiff
)
227 return patch
.download_hashes
.empty() == false;
228 return State
== StateApplyDiff
;
230 HashStringList
pkgAcqIndexMergeDiffs::GetExpectedHashes() const
232 if (State
== StateFetchDiff
)
233 return patch
.download_hashes
;
234 else if (State
== StateApplyDiff
)
235 return GetExpectedHashesFor(Target
.MetaKey
);
236 return HashStringList();
239 APT_CONST
bool pkgAcqArchive::HashesRequired() const
241 return LocalSource
== false;
243 HashStringList
pkgAcqArchive::GetExpectedHashes() const
245 // figured out while parsing the records
246 return ExpectedHashes
;
249 APT_CONST
bool pkgAcqFile::HashesRequired() const
251 // supplied as parameter at creation time, so the caller decides
252 return ExpectedHashes
.usable();
254 HashStringList
pkgAcqFile::GetExpectedHashes() const
256 return ExpectedHashes
;
259 // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
260 bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc
&Item
)
262 Owner
->Enqueue(Item
);
265 /* The idea here is that an item isn't queued if it exists on disk and the
266 transition manager was a hit as this means that the files it contains
267 the checksums for can't be updated either (or they are and we are asking
268 for a hashsum mismatch to happen which helps nobody) */
269 bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc
&Item
)
271 std::string
const FinalFile
= GetFinalFilename();
272 if (TransactionManager
!= NULL
&& TransactionManager
->IMSHit
== true &&
273 FileExists(FinalFile
) == true)
275 PartialFile
= DestFile
= FinalFile
;
279 return pkgAcquire::Item::QueueURI(Item
);
281 /* The transition manager InRelease itself (or its older sisters-in-law
282 Release & Release.gpg) is always queued as this allows us to rerun gpgv
283 on it to verify that we aren't stalled with old files */
284 bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc
&Item
)
286 return pkgAcquire::Item::QueueURI(Item
);
288 /* the Diff/Index needs to queue also the up-to-date complete index file
289 to ensure that the list cleaner isn't eating it */
290 bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc
&Item
)
292 if (pkgAcqTransactionItem::QueueURI(Item
) == true)
298 // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
299 std::string
pkgAcquire::Item::GetFinalFilename() const
301 return GetFinalFileNameFromURI(Desc
.URI
);
303 std::string
pkgAcqDiffIndex::GetFinalFilename() const
305 // the logic we inherent from pkgAcqBaseIndex isn't what we need here
306 return pkgAcquire::Item::GetFinalFilename();
308 std::string
pkgAcqIndex::GetFinalFilename() const
310 std::string
const FinalFile
= GetFinalFileNameFromURI(Target
.URI
);
311 return GetCompressedFileName(Target
, FinalFile
, CurrentCompressionExtension
);
313 std::string
pkgAcqMetaSig::GetFinalFilename() const
315 return GetFinalFileNameFromURI(Target
.URI
);
317 std::string
pkgAcqBaseIndex::GetFinalFilename() const
319 return GetFinalFileNameFromURI(Target
.URI
);
321 std::string
pkgAcqMetaBase::GetFinalFilename() const
323 return GetFinalFileNameFromURI(Target
.URI
);
325 std::string
pkgAcqArchive::GetFinalFilename() const
327 return _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
330 // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
331 std::string
pkgAcqTransactionItem::GetMetaKey() const
333 return Target
.MetaKey
;
335 std::string
pkgAcqIndex::GetMetaKey() const
337 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
|| CurrentCompressionExtension
== "uncompressed")
338 return Target
.MetaKey
;
339 return Target
.MetaKey
+ "." + CurrentCompressionExtension
;
341 std::string
pkgAcqDiffIndex::GetMetaKey() const
343 return Target
.MetaKey
+ ".diff/Index";
346 //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
347 bool pkgAcqTransactionItem::TransactionState(TransactionStates
const state
)
349 bool const Debug
= _config
->FindB("Debug::Acquire::Transaction", false);
352 case TransactionAbort
:
354 std::clog
<< " Cancel: " << DestFile
<< std::endl
;
355 if (Status
== pkgAcquire::Item::StatIdle
)
357 Status
= pkgAcquire::Item::StatDone
;
361 case TransactionCommit
:
362 if(PartialFile
!= "")
365 std::clog
<< "mv " << PartialFile
<< " -> "<< DestFile
<< " # " << DescURI() << std::endl
;
367 Rename(PartialFile
, DestFile
);
370 std::clog
<< "rm " << DestFile
<< " # " << DescURI() << std::endl
;
371 unlink(DestFile
.c_str());
377 bool pkgAcqMetaBase::TransactionState(TransactionStates
const state
)
379 // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
380 if (TransactionManager
->IMSHit
== false)
381 return pkgAcqTransactionItem::TransactionState(state
);
384 bool pkgAcqIndex::TransactionState(TransactionStates
const state
)
386 if (pkgAcqTransactionItem::TransactionState(state
) == false)
391 case TransactionAbort
:
392 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
394 // keep the compressed file, but drop the decompressed
395 EraseFileName
.clear();
396 if (PartialFile
.empty() == false && flExtension(PartialFile
) == "decomp")
397 unlink(PartialFile
.c_str());
400 case TransactionCommit
:
401 if (EraseFileName
.empty() == false)
402 unlink(EraseFileName
.c_str());
407 bool pkgAcqDiffIndex::TransactionState(TransactionStates
const state
)
409 if (pkgAcqTransactionItem::TransactionState(state
) == false)
414 case TransactionCommit
:
416 case TransactionAbort
:
417 std::string
const Partial
= GetPartialFileNameFromURI(Target
.URI
);
418 unlink(Partial
.c_str());
426 class APT_HIDDEN NoActionItem
: public pkgAcquire::Item
/*{{{*/
427 /* The sole purpose of this class is having an item which does nothing to
428 reach its done state to prevent cleanup deleting the mentioned file.
429 Handy in cases in which we know we have the file already, like IMS-Hits. */
431 IndexTarget
const Target
;
433 virtual std::string
DescURI() const APT_OVERRIDE
{return Target
.URI
;};
434 virtual HashStringList
GetExpectedHashes() const APT_OVERRIDE
{return HashStringList();};
436 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
) :
437 pkgAcquire::Item(Owner
), Target(Target
)
440 DestFile
= GetFinalFileNameFromURI(Target
.URI
);
442 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
, std::string
const &FinalFile
) :
443 pkgAcquire::Item(Owner
), Target(Target
)
446 DestFile
= FinalFile
;
451 // Acquire::Item::Item - Constructor /*{{{*/
452 APT_IGNORE_DEPRECATED_PUSH
453 pkgAcquire::Item::Item(pkgAcquire
* const owner
) :
454 FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
455 QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner
), d(NULL
)
460 APT_IGNORE_DEPRECATED_POP
462 // Acquire::Item::~Item - Destructor /*{{{*/
463 pkgAcquire::Item::~Item()
468 std::string
pkgAcquire::Item::Custom600Headers() const /*{{{*/
470 return std::string();
473 std::string
pkgAcquire::Item::ShortDesc() const /*{{{*/
478 APT_CONST
void pkgAcquire::Item::Finished() /*{{{*/
482 APT_PURE pkgAcquire
* pkgAcquire::Item::GetOwner() const /*{{{*/
487 APT_CONST
pkgAcquire::ItemDesc
&pkgAcquire::Item::GetItemDesc() /*{{{*/
492 APT_CONST
bool pkgAcquire::Item::IsTrusted() const /*{{{*/
497 // Acquire::Item::Failed - Item failed to download /*{{{*/
498 // ---------------------------------------------------------------------
499 /* We return to an idle state if there are still other queues that could
501 void pkgAcquire::Item::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
503 if(ErrorText
.empty())
504 ErrorText
= LookupTag(Message
,"Message");
505 if (QueueCounter
<= 1)
507 /* This indicates that the file is not available right now but might
508 be sometime later. If we do a retry cycle then this should be
510 if (Cnf
!= NULL
&& Cnf
->LocalOnly
== true &&
511 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
527 case StatTransientNetworkError
:
534 string
const FailReason
= LookupTag(Message
, "FailReason");
535 if (FailReason
== "MaximumSizeExceeded")
536 RenameOnError(MaximumSizeExceeded
);
537 else if (Status
== StatAuthError
)
538 RenameOnError(HashSumMismatch
);
540 // report mirror failure back to LP if we actually use a mirror
541 if (FailReason
.empty() == false)
542 ReportMirrorFailure(FailReason
);
544 ReportMirrorFailure(ErrorText
);
546 if (QueueCounter
> 1)
550 // Acquire::Item::Start - Item has begun to download /*{{{*/
551 // ---------------------------------------------------------------------
552 /* Stash status and the file size. Note that setting Complete means
553 sub-phases of the acquire process such as decompresion are operating */
554 void pkgAcquire::Item::Start(string
const &/*Message*/, unsigned long long const Size
)
556 Status
= StatFetching
;
558 if (FileSize
== 0 && Complete
== false)
562 // Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
563 /* Note that hash-verification is 'hardcoded' in acquire-worker and has
564 * already passed if this method is called. */
565 bool pkgAcquire::Item::VerifyDone(std::string
const &Message
,
566 pkgAcquire::MethodConfig
const * const /*Cnf*/)
568 std::string
const FileName
= LookupTag(Message
,"Filename");
569 if (FileName
.empty() == true)
572 ErrorText
= "Method gave a blank filename";
579 // Acquire::Item::Done - Item downloaded OK /*{{{*/
580 void pkgAcquire::Item::Done(string
const &/*Message*/, HashStringList
const &Hashes
,
581 pkgAcquire::MethodConfig
const * const /*Cnf*/)
583 // We just downloaded something..
586 unsigned long long const downloadedSize
= Hashes
.FileSize();
587 if (downloadedSize
!= 0)
589 FileSize
= downloadedSize
;
593 ErrorText
= string();
594 Owner
->Dequeue(this);
597 // Acquire::Item::Rename - Rename a file /*{{{*/
598 // ---------------------------------------------------------------------
599 /* This helper function is used by a lot of item methods as their final
601 bool pkgAcquire::Item::Rename(string
const &From
,string
const &To
)
603 if (From
== To
|| rename(From
.c_str(),To
.c_str()) == 0)
607 strprintf(S
, _("rename failed, %s (%s -> %s)."), strerror(errno
),
608 From
.c_str(),To
.c_str());
610 if (ErrorText
.empty())
613 ErrorText
= ErrorText
+ ": " + S
;
617 void pkgAcquire::Item::Dequeue() /*{{{*/
619 Owner
->Dequeue(this);
622 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
624 if (RealFileExists(DestFile
))
625 Rename(DestFile
, DestFile
+ ".FAILED");
630 case HashSumMismatch
:
631 errtext
= _("Hash Sum mismatch");
632 Status
= StatAuthError
;
633 ReportMirrorFailure("HashChecksumFailure");
636 errtext
= _("Size mismatch");
637 Status
= StatAuthError
;
638 ReportMirrorFailure("SizeFailure");
641 errtext
= _("Invalid file format");
643 // do not report as usually its not the mirrors fault, but Portal/Proxy
646 errtext
= _("Signature error");
650 strprintf(errtext
, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
651 Status
= StatAuthError
;
653 case MaximumSizeExceeded
:
654 // the method is expected to report a good error for this
658 // no handling here, done by callers
661 if (ErrorText
.empty())
666 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)/*{{{*/
668 ActiveSubprocess
= subprocess
;
669 APT_IGNORE_DEPRECATED(Mode
= ActiveSubprocess
.c_str();)
672 // Acquire::Item::ReportMirrorFailure /*{{{*/
673 void pkgAcquire::Item::ReportMirrorFailure(string
const &FailCode
)
675 // we only act if a mirror was used at all
676 if(UsedMirror
.empty())
679 std::cerr
<< "\nReportMirrorFailure: "
681 << " Uri: " << DescURI()
683 << FailCode
<< std::endl
;
685 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
686 "/usr/lib/apt/apt-report-mirror-failure");
687 if(!FileExists(report
))
690 std::vector
<char const*> Args
;
691 Args
.push_back(report
.c_str());
692 Args
.push_back(UsedMirror
.c_str());
693 Args
.push_back(DescURI().c_str());
694 Args
.push_back(FailCode
.c_str());
695 Args
.push_back(NULL
);
697 pid_t pid
= ExecFork();
700 _error
->Error("ReportMirrorFailure Fork failed");
705 execvp(Args
[0], (char**)Args
.data());
706 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
709 if(!ExecWait(pid
, "report-mirror-failure"))
711 _error
->Warning("Couldn't report problem to '%s'",
712 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
716 std::string
pkgAcquire::Item::HashSum() const /*{{{*/
718 HashStringList
const hashes
= GetExpectedHashes();
719 HashString
const * const hs
= hashes
.find(NULL
);
720 return hs
!= NULL
? hs
->toStr() : "";
724 pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire
* const Owner
, /*{{{*/
725 pkgAcqMetaClearSig
* const transactionManager
, IndexTarget
const &target
) :
726 pkgAcquire::Item(Owner
), d(NULL
), Target(target
), TransactionManager(transactionManager
)
728 if (TransactionManager
!= this)
729 TransactionManager
->Add(this);
732 pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
736 HashStringList
pkgAcqTransactionItem::GetExpectedHashesFor(std::string
const &MetaKey
) const /*{{{*/
738 return GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, MetaKey
);
742 // AcqMetaBase - Constructor /*{{{*/
743 pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire
* const Owner
,
744 pkgAcqMetaClearSig
* const TransactionManager
,
745 std::vector
<IndexTarget
> const &IndexTargets
,
746 IndexTarget
const &DataTarget
)
747 : pkgAcqTransactionItem(Owner
, TransactionManager
, DataTarget
), d(NULL
),
748 IndexTargets(IndexTargets
),
749 AuthPass(false), IMSHit(false)
753 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
754 void pkgAcqMetaBase::Add(pkgAcqTransactionItem
* const I
)
756 Transaction
.push_back(I
);
759 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
760 void pkgAcqMetaBase::AbortTransaction()
762 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
763 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
765 // ensure the toplevel is in error state too
766 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
767 I
!= Transaction
.end(); ++I
)
769 (*I
)->TransactionState(TransactionAbort
);
774 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
775 APT_PURE
bool pkgAcqMetaBase::TransactionHasError() const
777 for (std::vector
<pkgAcqTransactionItem
*>::const_iterator I
= Transaction
.begin();
778 I
!= Transaction
.end(); ++I
)
780 switch((*I
)->Status
) {
781 case StatDone
: break;
782 case StatIdle
: break;
783 case StatAuthError
: return true;
784 case StatError
: return true;
785 case StatTransientNetworkError
: return true;
786 case StatFetching
: break;
792 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
793 void pkgAcqMetaBase::CommitTransaction()
795 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
796 std::clog
<< "CommitTransaction: " << this << std::endl
;
798 // move new files into place *and* remove files that are not
799 // part of the transaction but are still on disk
800 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
801 I
!= Transaction
.end(); ++I
)
803 (*I
)->TransactionState(TransactionCommit
);
808 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
809 void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem
* const I
,
810 const std::string
&From
,
811 const std::string
&To
)
813 I
->PartialFile
= From
;
817 // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
818 void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem
* const I
,
819 const std::string
&FinalFile
)
822 I
->DestFile
= FinalFile
;
825 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
826 bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item
* const I
, const std::string
&Message
)
828 // FIXME: this entire function can do now that we disallow going to
829 // a unauthenticated state and can cleanly rollback
831 string
const Final
= I
->GetFinalFilename();
832 if(FileExists(Final
))
834 I
->Status
= StatTransientNetworkError
;
835 _error
->Warning(_("An error occurred during the signature "
836 "verification. The repository is not updated "
837 "and the previous index files will be used. "
838 "GPG error: %s: %s"),
839 Desc
.Description
.c_str(),
840 LookupTag(Message
,"Message").c_str());
841 RunScripts("APT::Update::Auth-Failure");
843 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
844 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
845 _error
->Error(_("GPG error: %s: %s"),
846 Desc
.Description
.c_str(),
847 LookupTag(Message
,"Message").c_str());
848 I
->Status
= StatAuthError
;
851 _error
->Warning(_("GPG error: %s: %s"),
852 Desc
.Description
.c_str(),
853 LookupTag(Message
,"Message").c_str());
855 // gpgv method failed
856 ReportMirrorFailure("GPGFailure");
860 // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
861 // ---------------------------------------------------------------------
862 string
pkgAcqMetaBase::Custom600Headers() const
864 std::string Header
= "\nIndex-File: true";
865 std::string MaximumSize
;
866 strprintf(MaximumSize
, "\nMaximum-Size: %i",
867 _config
->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
868 Header
+= MaximumSize
;
870 string
const FinalFile
= GetFinalFilename();
872 if (stat(FinalFile
.c_str(),&Buf
) == 0)
873 Header
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
878 // AcqMetaBase::QueueForSignatureVerify /*{{{*/
879 void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem
* const I
, std::string
const &File
, std::string
const &Signature
)
882 I
->Desc
.URI
= "gpgv:" + Signature
;
885 I
->SetActiveSubprocess("gpgv");
888 // AcqMetaBase::CheckDownloadDone /*{{{*/
889 bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem
* const I
, const std::string
&Message
, HashStringList
const &Hashes
) const
891 // We have just finished downloading a Release file (it is not
894 std::string
const FileName
= LookupTag(Message
,"Filename");
895 if (FileName
!= I
->DestFile
&& RealFileExists(I
->DestFile
) == false)
898 I
->Desc
.URI
= "copy:" + FileName
;
899 I
->QueueURI(I
->Desc
);
903 // make sure to verify against the right file on I-M-S hit
904 bool IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"), false);
905 if (IMSHit
== false && Hashes
.usable())
907 // detect IMS-Hits servers haven't detected by Hash comparison
908 std::string
const FinalFile
= I
->GetFinalFilename();
909 if (RealFileExists(FinalFile
) && Hashes
.VerifyFile(FinalFile
) == true)
912 unlink(I
->DestFile
.c_str());
918 // for simplicity, the transaction manager is always InRelease
919 // even if it doesn't exist.
920 if (TransactionManager
!= NULL
)
921 TransactionManager
->IMSHit
= true;
922 I
->PartialFile
= I
->DestFile
= I
->GetFinalFilename();
925 // set Item to complete as the remaining work is all local (verify etc)
931 bool pkgAcqMetaBase::CheckAuthDone(string
const &Message
) /*{{{*/
933 // At this point, the gpgv method has succeeded, so there is a
934 // valid signature from a key in the trusted keyring. We
935 // perform additional verification of its contents, and use them
936 // to verify the indexes we are about to download
938 if (TransactionManager
->IMSHit
== false)
940 // open the last (In)Release if we have it
941 std::string
const FinalFile
= GetFinalFilename();
942 std::string FinalRelease
;
943 std::string FinalInRelease
;
944 if (APT::String::Endswith(FinalFile
, "InRelease"))
946 FinalInRelease
= FinalFile
;
947 FinalRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("InRelease")) + "Release";
951 FinalInRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("Release")) + "InRelease";
952 FinalRelease
= FinalFile
;
954 if (RealFileExists(FinalInRelease
) || RealFileExists(FinalRelease
))
956 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
957 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
959 _error
->PushToStack();
960 if (RealFileExists(FinalInRelease
))
961 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
963 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
964 // its unlikely to happen, but if what we have is bad ignore it
965 if (_error
->PendingError())
967 delete TransactionManager
->LastMetaIndexParser
;
968 TransactionManager
->LastMetaIndexParser
= NULL
;
970 _error
->RevertToStack();
975 if (TransactionManager
->MetaIndexParser
->Load(DestFile
, &ErrorText
) == false)
977 Status
= StatAuthError
;
981 if (!VerifyVendor(Message
))
983 Status
= StatAuthError
;
987 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
988 std::cerr
<< "Signature verification succeeded: "
989 << DestFile
<< std::endl
;
991 // Download further indexes with verification
997 void pkgAcqMetaBase::QueueIndexes(bool const verify
) /*{{{*/
999 // at this point the real Items are loaded in the fetcher
1000 ExpectedAdditionalItems
= 0;
1002 bool metaBaseSupportsByHash
= false;
1003 if (TransactionManager
!= NULL
&& TransactionManager
->MetaIndexParser
!= NULL
)
1004 metaBaseSupportsByHash
= TransactionManager
->MetaIndexParser
->GetSupportsAcquireByHash();
1006 for (std::vector
<IndexTarget
>::iterator Target
= IndexTargets
.begin();
1007 Target
!= IndexTargets
.end();
1010 bool trypdiff
= Target
->OptionBool(IndexTarget::PDIFFS
);
1013 if (TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
) == false)
1015 // optional targets that we do not have in the Release file are skipped
1016 if (Target
->IsOptional
)
1019 Status
= StatAuthError
;
1020 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target
->MetaKey
.c_str());
1024 // autoselect the compression method
1025 std::vector
<std::string
> types
= VectorizeString(Target
->Option(IndexTarget::COMPRESSIONTYPES
), ' ');
1026 types
.erase(std::remove_if(types
.begin(), types
.end(), [&](std::string
const &t
) {
1027 if (t
== "uncompressed")
1028 return TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
) == false;
1029 std::string
const MetaKey
= Target
->MetaKey
+ "." + t
;
1030 return TransactionManager
->MetaIndexParser
->Exists(MetaKey
) == false;
1032 if (types
.empty() == false)
1034 std::ostringstream os
;
1035 // add the special compressiontype byhash first if supported
1036 std::string
const useByHashConf
= Target
->Option(IndexTarget::BY_HASH
);
1037 bool useByHash
= false;
1038 if(useByHashConf
== "force")
1041 useByHash
= StringToBool(useByHashConf
) == true && metaBaseSupportsByHash
;
1042 if (useByHash
== true)
1044 std::copy(types
.begin(), types
.end()-1, std::ostream_iterator
<std::string
>(os
, " "));
1045 os
<< *types
.rbegin();
1046 Target
->Options
["COMPRESSIONTYPES"] = os
.str();
1049 Target
->Options
["COMPRESSIONTYPES"].clear();
1051 std::string filename
= GetFinalFileNameFromURI(Target
->URI
);
1052 if (RealFileExists(filename
) == false)
1054 if (Target
->KeepCompressed
)
1056 filename
= GetKeepCompressedFileName(filename
, *Target
);
1057 if (RealFileExists(filename
) == false)
1064 if (filename
.empty() == false)
1066 // if the Release file is a hit and we have an index it must be the current one
1067 if (TransactionManager
->IMSHit
== true)
1069 else if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1071 // see if the file changed since the last Release file
1072 // we use the uncompressed files as we might compress differently compared to the server,
1073 // so the hashes might not match, even if they contain the same data.
1074 HashStringList
const newFile
= GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, Target
->MetaKey
);
1075 HashStringList
const oldFile
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
->MetaKey
);
1076 if (newFile
!= oldFile
)
1083 trypdiff
= false; // no file to patch
1085 if (filename
.empty() == false)
1087 new NoActionItem(Owner
, *Target
, filename
);
1091 // check if we have patches available
1092 trypdiff
&= TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
+ ".diff/Index");
1096 // if we have no file to patch, no point in trying
1097 std::string filename
= GetFinalFileNameFromURI(Target
->URI
);
1098 if (RealFileExists(filename
) == false)
1100 if (Target
->KeepCompressed
)
1102 filename
= GetKeepCompressedFileName(filename
, *Target
);
1103 if (RealFileExists(filename
) == false)
1109 trypdiff
&= (filename
.empty() == false);
1112 // no point in patching from local sources
1115 std::string
const proto
= Target
->URI
.substr(0, strlen("file:/"));
1116 if (proto
== "file:/" || proto
== "copy:/" || proto
== "cdrom:")
1120 // Queue the Index file (Packages, Sources, Translation-$foo, …)
1122 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
);
1124 new pkgAcqIndex(Owner
, TransactionManager
, *Target
);
1128 bool pkgAcqMetaBase::VerifyVendor(string
const &Message
) /*{{{*/
1130 string::size_type pos
;
1132 // check for missing sigs (that where not fatal because otherwise we had
1135 string msg
= _("There is no public key available for the "
1136 "following key IDs:\n");
1137 pos
= Message
.find("NO_PUBKEY ");
1138 if (pos
!= std::string::npos
)
1140 string::size_type start
= pos
+strlen("NO_PUBKEY ");
1141 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
1142 missingkeys
+= (Fingerprint
);
1144 if(!missingkeys
.empty())
1145 _error
->Warning("%s", (msg
+ missingkeys
).c_str());
1147 string Transformed
= TransactionManager
->MetaIndexParser
->GetExpectedDist();
1149 if (Transformed
== "../project/experimental")
1151 Transformed
= "experimental";
1154 pos
= Transformed
.rfind('/');
1155 if (pos
!= string::npos
)
1157 Transformed
= Transformed
.substr(0, pos
);
1160 if (Transformed
== ".")
1165 if (TransactionManager
->MetaIndexParser
->GetValidUntil() > 0)
1167 time_t const invalid_since
= time(NULL
) - TransactionManager
->MetaIndexParser
->GetValidUntil();
1168 if (invalid_since
> 0)
1172 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1173 // the time since then the file is invalid - formatted in the same way as in
1174 // the download progress display (e.g. 7d 3h 42min 1s)
1175 _("Release file for %s is expired (invalid since %s). "
1176 "Updates for this repository will not be applied."),
1177 Target
.URI
.c_str(), TimeToStr(invalid_since
).c_str());
1178 if (ErrorText
.empty())
1180 return _error
->Error("%s", errmsg
.c_str());
1184 /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
1185 as a prevention of downgrading us to older (still valid) files */
1186 if (TransactionManager
->IMSHit
== false && TransactionManager
->LastMetaIndexParser
!= NULL
&&
1187 TransactionManager
->LastMetaIndexParser
->GetDate() > TransactionManager
->MetaIndexParser
->GetDate())
1189 TransactionManager
->IMSHit
= true;
1190 unlink(DestFile
.c_str());
1191 PartialFile
= DestFile
= GetFinalFilename();
1192 // load the 'old' file in the 'new' one instead of flipping pointers as
1193 // the new one isn't owned by us, while the old one is so cleanup would be confused.
1194 TransactionManager
->MetaIndexParser
->swapLoad(TransactionManager
->LastMetaIndexParser
);
1195 delete TransactionManager
->LastMetaIndexParser
;
1196 TransactionManager
->LastMetaIndexParser
= NULL
;
1199 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1201 std::cerr
<< "Got Codename: " << TransactionManager
->MetaIndexParser
->GetCodename() << std::endl
;
1202 std::cerr
<< "Expecting Dist: " << TransactionManager
->MetaIndexParser
->GetExpectedDist() << std::endl
;
1203 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
1206 if (TransactionManager
->MetaIndexParser
->CheckDist(Transformed
) == false)
1208 // This might become fatal one day
1209 // Status = StatAuthError;
1210 // ErrorText = "Conflicting distribution; expected "
1211 // + MetaIndexParser->GetExpectedDist() + " but got "
1212 // + MetaIndexParser->GetCodename();
1214 if (!Transformed
.empty())
1216 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1217 Desc
.Description
.c_str(),
1218 Transformed
.c_str(),
1219 TransactionManager
->MetaIndexParser
->GetCodename().c_str());
1226 pkgAcqMetaBase::~pkgAcqMetaBase()
1230 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
* const Owner
, /*{{{*/
1231 IndexTarget
const &ClearsignedTarget
,
1232 IndexTarget
const &DetachedDataTarget
, IndexTarget
const &DetachedSigTarget
,
1233 std::vector
<IndexTarget
> const &IndexTargets
,
1234 metaIndex
* const MetaIndexParser
) :
1235 pkgAcqMetaIndex(Owner
, this, ClearsignedTarget
, DetachedSigTarget
, IndexTargets
),
1236 d(NULL
), ClearsignedTarget(ClearsignedTarget
),
1237 DetachedDataTarget(DetachedDataTarget
),
1238 MetaIndexParser(MetaIndexParser
), LastMetaIndexParser(NULL
)
1240 // index targets + (worst case:) Release/Release.gpg
1241 ExpectedAdditionalItems
= IndexTargets
.size() + 2;
1242 TransactionManager
->Add(this);
1245 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
1247 if (LastMetaIndexParser
!= NULL
)
1248 delete LastMetaIndexParser
;
1251 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1252 string
pkgAcqMetaClearSig::Custom600Headers() const
1254 string Header
= pkgAcqMetaBase::Custom600Headers();
1255 Header
+= "\nFail-Ignore: true";
1256 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1257 if (key
.empty() == false)
1258 Header
+= "\nSigned-By: " + key
;
1263 bool pkgAcqMetaClearSig::VerifyDone(std::string
const &Message
, /*{{{*/
1264 pkgAcquire::MethodConfig
const * const Cnf
)
1266 Item::VerifyDone(Message
, Cnf
);
1268 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
1269 return RenameOnError(NotClearsigned
);
1274 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
1275 void pkgAcqMetaClearSig::Done(std::string
const &Message
,
1276 HashStringList
const &Hashes
,
1277 pkgAcquire::MethodConfig
const * const Cnf
)
1279 Item::Done(Message
, Hashes
, Cnf
);
1281 if(AuthPass
== false)
1283 if(CheckDownloadDone(this, Message
, Hashes
) == true)
1284 QueueForSignatureVerify(this, DestFile
, DestFile
);
1287 else if(CheckAuthDone(Message
) == true)
1289 if (TransactionManager
->IMSHit
== false)
1290 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1291 else if (RealFileExists(GetFinalFilename()) == false)
1293 // We got an InRelease file IMSHit, but we haven't one, which means
1294 // we had a valid Release/Release.gpg combo stepping in, which we have
1295 // to 'acquire' now to ensure list cleanup isn't removing them
1296 new NoActionItem(Owner
, DetachedDataTarget
);
1297 new NoActionItem(Owner
, DetachedSigTarget
);
1302 void pkgAcqMetaClearSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
) /*{{{*/
1304 Item::Failed(Message
, Cnf
);
1306 // we failed, we will not get additional items from this method
1307 ExpectedAdditionalItems
= 0;
1309 if (AuthPass
== false)
1311 if (Status
== StatAuthError
)
1313 // if we expected a ClearTextSignature (InRelease) and got a file,
1314 // but it wasn't valid we end up here (see VerifyDone).
1315 // As these is usually called by web-portals we do not try Release/Release.gpg
1316 // as this is gonna fail anyway and instead abort our try (LP#346386)
1317 TransactionManager
->AbortTransaction();
1321 // Queue the 'old' InRelease file for removal if we try Release.gpg
1322 // as otherwise the file will stay around and gives a false-auth
1323 // impression (CVE-2012-0214)
1324 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1327 new pkgAcqMetaIndex(Owner
, TransactionManager
, DetachedDataTarget
, DetachedSigTarget
, IndexTargets
);
1331 if(CheckStopAuthentication(this, Message
))
1334 _error
->Warning(_("The data from '%s' is not signed. Packages "
1335 "from that repository can not be authenticated."),
1336 ClearsignedTarget
.Description
.c_str());
1338 // No Release file was present, or verification failed, so fall
1339 // back to queueing Packages files without verification
1340 // only allow going further if the users explicitely wants it
1341 if(AllowInsecureRepositories(TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1345 /* InRelease files become Release files, otherwise
1346 * they would be considered as trusted later on */
1347 string
const FinalRelease
= GetFinalFileNameFromURI(DetachedDataTarget
.URI
);
1348 string
const PartialRelease
= GetPartialFileNameFromURI(DetachedDataTarget
.URI
);
1349 string
const FinalReleasegpg
= GetFinalFileNameFromURI(DetachedSigTarget
.URI
);
1350 string
const FinalInRelease
= GetFinalFilename();
1351 Rename(DestFile
, PartialRelease
);
1352 TransactionManager
->TransactionStageCopy(this, PartialRelease
, FinalRelease
);
1354 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1356 // open the last Release if we have it
1357 if (TransactionManager
->IMSHit
== false)
1359 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1360 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1362 _error
->PushToStack();
1363 if (RealFileExists(FinalInRelease
))
1364 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1366 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1367 // its unlikely to happen, but if what we have is bad ignore it
1368 if (_error
->PendingError())
1370 delete TransactionManager
->LastMetaIndexParser
;
1371 TransactionManager
->LastMetaIndexParser
= NULL
;
1373 _error
->RevertToStack();
1378 // we parse the indexes here because at this point the user wanted
1379 // a repository that may potentially harm him
1380 if (TransactionManager
->MetaIndexParser
->Load(PartialRelease
, &ErrorText
) == false || VerifyVendor(Message
) == false)
1381 /* expired Release files are still a problem you need extra force for */;
1389 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
* const Owner
, /*{{{*/
1390 pkgAcqMetaClearSig
* const TransactionManager
,
1391 IndexTarget
const &DataTarget
,
1392 IndexTarget
const &DetachedSigTarget
,
1393 vector
<IndexTarget
> const &IndexTargets
) :
1394 pkgAcqMetaBase(Owner
, TransactionManager
, IndexTargets
, DataTarget
), d(NULL
),
1395 DetachedSigTarget(DetachedSigTarget
)
1397 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1398 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1399 << this->TransactionManager
<< std::endl
;
1401 DestFile
= GetPartialFileNameFromURI(DataTarget
.URI
);
1404 Desc
.Description
= DataTarget
.Description
;
1406 Desc
.ShortDesc
= DataTarget
.ShortDesc
;
1407 Desc
.URI
= DataTarget
.URI
;
1409 // we expect more item
1410 ExpectedAdditionalItems
= IndexTargets
.size();
1414 void pkgAcqMetaIndex::Done(string
const &Message
, /*{{{*/
1415 HashStringList
const &Hashes
,
1416 pkgAcquire::MethodConfig
const * const Cfg
)
1418 Item::Done(Message
,Hashes
,Cfg
);
1420 if(CheckDownloadDone(this, Message
, Hashes
))
1422 // we have a Release file, now download the Signature, all further
1423 // verify/queue for additional downloads will be done in the
1424 // pkgAcqMetaSig::Done() code
1425 new pkgAcqMetaSig(Owner
, TransactionManager
, DetachedSigTarget
, this);
1429 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
1430 void pkgAcqMetaIndex::Failed(string
const &Message
,
1431 pkgAcquire::MethodConfig
const * const Cnf
)
1433 pkgAcquire::Item::Failed(Message
, Cnf
);
1436 _error
->Warning(_("The repository '%s' does not have a Release file. "
1437 "This is deprecated, please contact the owner of the "
1438 "repository."), Target
.Description
.c_str());
1440 // No Release file was present so fall
1441 // back to queueing Packages files without verification
1442 // only allow going further if the users explicitely wants it
1443 if(AllowInsecureRepositories(TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1445 // ensure old Release files are removed
1446 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1448 // queue without any kind of hashsum support
1449 QueueIndexes(false);
1453 void pkgAcqMetaIndex::Finished() /*{{{*/
1455 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1456 std::clog
<< "Finished: " << DestFile
<<std::endl
;
1457 if(TransactionManager
!= NULL
&&
1458 TransactionManager
->TransactionHasError() == false)
1459 TransactionManager
->CommitTransaction();
1462 std::string
pkgAcqMetaIndex::DescURI() const /*{{{*/
1467 pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
1469 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1470 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
* const Owner
,
1471 pkgAcqMetaClearSig
* const TransactionManager
,
1472 IndexTarget
const &Target
,
1473 pkgAcqMetaIndex
* const MetaIndex
) :
1474 pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
), MetaIndex(MetaIndex
)
1476 DestFile
= GetPartialFileNameFromURI(Target
.URI
);
1478 // remove any partial downloaded sig-file in partial/.
1479 // it may confuse proxies and is too small to warrant a
1480 // partial download anyway
1481 unlink(DestFile
.c_str());
1483 // set the TransactionManager
1484 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1485 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1486 << TransactionManager
<< std::endl
;
1489 Desc
.Description
= Target
.Description
;
1491 Desc
.ShortDesc
= Target
.ShortDesc
;
1492 Desc
.URI
= Target
.URI
;
1494 // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
1495 // so we skip the download step and go instantly to verification
1496 if (TransactionManager
->IMSHit
== true && RealFileExists(GetFinalFilename()))
1500 PartialFile
= DestFile
= GetFinalFilename();
1501 MetaIndexFileSignature
= DestFile
;
1502 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1508 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1512 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1513 std::string
pkgAcqMetaSig::Custom600Headers() const
1515 std::string Header
= pkgAcqTransactionItem::Custom600Headers();
1516 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1517 if (key
.empty() == false)
1518 Header
+= "\nSigned-By: " + key
;
1522 // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1523 void pkgAcqMetaSig::Done(string
const &Message
, HashStringList
const &Hashes
,
1524 pkgAcquire::MethodConfig
const * const Cfg
)
1526 if (MetaIndexFileSignature
.empty() == false)
1528 DestFile
= MetaIndexFileSignature
;
1529 MetaIndexFileSignature
.clear();
1531 Item::Done(Message
, Hashes
, Cfg
);
1533 if(MetaIndex
->AuthPass
== false)
1535 if(MetaIndex
->CheckDownloadDone(this, Message
, Hashes
) == true)
1537 // destfile will be modified to point to MetaIndexFile for the
1538 // gpgv method, so we need to save it here
1539 MetaIndexFileSignature
= DestFile
;
1540 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1544 else if(MetaIndex
->CheckAuthDone(Message
) == true)
1546 if (TransactionManager
->IMSHit
== false)
1548 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1549 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, MetaIndex
->GetFinalFilename());
1554 void pkgAcqMetaSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
1556 Item::Failed(Message
,Cnf
);
1558 // check if we need to fail at this point
1559 if (MetaIndex
->AuthPass
== true && MetaIndex
->CheckStopAuthentication(this, Message
))
1562 string
const FinalRelease
= MetaIndex
->GetFinalFilename();
1563 string
const FinalReleasegpg
= GetFinalFilename();
1564 string
const FinalInRelease
= TransactionManager
->GetFinalFilename();
1566 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1568 std::string downgrade_msg
;
1569 strprintf(downgrade_msg
, _("The repository '%s' is no longer signed."),
1570 MetaIndex
->Target
.Description
.c_str());
1571 if(_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1573 // meh, the users wants to take risks (we still mark the packages
1574 // from this repository as unauthenticated)
1575 _error
->Warning("%s", downgrade_msg
.c_str());
1576 _error
->Warning(_("This is normally not allowed, but the option "
1577 "Acquire::AllowDowngradeToInsecureRepositories was "
1578 "given to override it."));
1581 _error
->Error("%s", downgrade_msg
.c_str());
1582 if (TransactionManager
->IMSHit
== false)
1583 Rename(MetaIndex
->DestFile
, MetaIndex
->DestFile
+ ".FAILED");
1584 Item::Failed("Message: " + downgrade_msg
, Cnf
);
1585 TransactionManager
->AbortTransaction();
1590 _error
->Warning(_("The data from '%s' is not signed. Packages "
1591 "from that repository can not be authenticated."),
1592 MetaIndex
->Target
.Description
.c_str());
1594 // ensures that a Release.gpg file in the lists/ is removed by the transaction
1595 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1597 // only allow going further if the users explicitely wants it
1598 if(AllowInsecureRepositories(TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1600 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1602 // open the last Release if we have it
1603 if (TransactionManager
->IMSHit
== false)
1605 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1606 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1608 _error
->PushToStack();
1609 if (RealFileExists(FinalInRelease
))
1610 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1612 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1613 // its unlikely to happen, but if what we have is bad ignore it
1614 if (_error
->PendingError())
1616 delete TransactionManager
->LastMetaIndexParser
;
1617 TransactionManager
->LastMetaIndexParser
= NULL
;
1619 _error
->RevertToStack();
1624 // we parse the indexes here because at this point the user wanted
1625 // a repository that may potentially harm him
1626 if (TransactionManager
->MetaIndexParser
->Load(MetaIndex
->DestFile
, &ErrorText
) == false || MetaIndex
->VerifyVendor(Message
) == false)
1627 /* expired Release files are still a problem you need extra force for */;
1629 MetaIndex
->QueueIndexes(true);
1631 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, MetaIndex
->GetFinalFilename());
1634 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1635 if (Cnf
->LocalOnly
== true ||
1636 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1645 // AcqBaseIndex - Constructor /*{{{*/
1646 pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire
* const Owner
,
1647 pkgAcqMetaClearSig
* const TransactionManager
,
1648 IndexTarget
const &Target
)
1649 : pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
)
1653 pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
1655 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
1656 // ---------------------------------------------------------------------
1657 /* Get the DiffIndex file first and see if there are patches available
1658 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
1659 * patches. If anything goes wrong in that process, it will fall back to
1660 * the original packages file
1662 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
* const Owner
,
1663 pkgAcqMetaClearSig
* const TransactionManager
,
1664 IndexTarget
const &Target
)
1665 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), diffs(NULL
)
1667 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
1670 Desc
.Description
= Target
.Description
+ ".diff/Index";
1671 Desc
.ShortDesc
= Target
.ShortDesc
;
1672 Desc
.URI
= Target
.URI
+ ".diff/Index";
1674 DestFile
= GetPartialFileNameFromURI(Desc
.URI
);
1677 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
1682 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1683 // ---------------------------------------------------------------------
1684 /* The only header we use is the last-modified header. */
1685 string
pkgAcqDiffIndex::Custom600Headers() const
1687 string
const Final
= GetFinalFilename();
1690 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
1693 if (stat(Final
.c_str(),&Buf
) != 0)
1694 return "\nIndex-File: true";
1696 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1699 void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
1701 // list cleanup needs to know that this file as well as the already
1702 // present index is ours, so we create an empty diff to save it for us
1703 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
);
1706 bool pkgAcqDiffIndex::ParseDiffIndex(string
const &IndexDiffFile
) /*{{{*/
1708 // failing here is fine: our caller will take care of trying to
1709 // get the complete file if patching fails
1711 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
1714 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
1716 if (Fd
.IsOpen() == false || Fd
.Failed())
1720 if(unlikely(TF
.Step(Tags
) == false))
1723 HashStringList ServerHashes
;
1724 unsigned long long ServerSize
= 0;
1726 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1728 std::string tagname
= *type
;
1729 tagname
.append("-Current");
1730 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1731 if (tmp
.empty() == true)
1735 unsigned long long size
;
1736 std::stringstream
ss(tmp
);
1738 if (unlikely(hash
.empty() == true))
1740 if (unlikely(ServerSize
!= 0 && ServerSize
!= size
))
1742 ServerHashes
.push_back(HashString(*type
, hash
));
1746 if (ServerHashes
.usable() == false)
1749 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Did not find a good hashsum in the index" << std::endl
;
1753 std::string
const CurrentPackagesFile
= GetFinalFileNameFromURI(Target
.URI
);
1754 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
1755 if (TargetFileHashes
.usable() == false || ServerHashes
!= TargetFileHashes
)
1759 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl
;
1760 printHashSumComparision(CurrentPackagesFile
, ServerHashes
, TargetFileHashes
);
1765 HashStringList LocalHashes
;
1766 // try avoiding calculating the hash here as this is costly
1767 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1768 LocalHashes
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
.MetaKey
);
1769 if (LocalHashes
.usable() == false)
1771 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
, FileFd::Auto
);
1772 Hashes
LocalHashesCalc(ServerHashes
);
1773 LocalHashesCalc
.AddFD(fd
);
1774 LocalHashes
= LocalHashesCalc
.GetHashStringList();
1777 if (ServerHashes
== LocalHashes
)
1779 // we have the same sha1 as the server so we are done here
1781 std::clog
<< "pkgAcqDiffIndex: Package file " << CurrentPackagesFile
<< " is up-to-date" << std::endl
;
1787 std::clog
<< "Server-Current: " << ServerHashes
.find(NULL
)->toStr() << " and we start at "
1788 << CurrentPackagesFile
<< " " << LocalHashes
.FileSize() << " " << LocalHashes
.find(NULL
)->toStr() << std::endl
;
1790 // parse all of (provided) history
1791 vector
<DiffInfo
> available_patches
;
1792 bool firstAcceptedHashes
= true;
1793 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1795 if (LocalHashes
.find(*type
) == NULL
)
1798 std::string tagname
= *type
;
1799 tagname
.append("-History");
1800 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1801 if (tmp
.empty() == true)
1804 string hash
, filename
;
1805 unsigned long long size
;
1806 std::stringstream
ss(tmp
);
1808 while (ss
>> hash
>> size
>> filename
)
1810 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1813 // see if we have a record for this file already
1814 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1815 for (; cur
!= available_patches
.end(); ++cur
)
1817 if (cur
->file
!= filename
)
1819 cur
->result_hashes
.push_back(HashString(*type
, hash
));
1822 if (cur
!= available_patches
.end())
1824 if (firstAcceptedHashes
== true)
1827 next
.file
= filename
;
1828 next
.result_hashes
.push_back(HashString(*type
, hash
));
1829 next
.result_hashes
.FileSize(size
);
1830 available_patches
.push_back(next
);
1835 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1836 << " wasn't in the list for the first parsed hash! (history)" << std::endl
;
1840 firstAcceptedHashes
= false;
1843 if (unlikely(available_patches
.empty() == true))
1846 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
1847 << "Couldn't find any patches for the patch series." << std::endl
;
1851 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1853 if (LocalHashes
.find(*type
) == NULL
)
1856 std::string tagname
= *type
;
1857 tagname
.append("-Patches");
1858 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1859 if (tmp
.empty() == true)
1862 string hash
, filename
;
1863 unsigned long long size
;
1864 std::stringstream
ss(tmp
);
1866 while (ss
>> hash
>> size
>> filename
)
1868 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1871 // see if we have a record for this file already
1872 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1873 for (; cur
!= available_patches
.end(); ++cur
)
1875 if (cur
->file
!= filename
)
1877 if (cur
->patch_hashes
.empty())
1878 cur
->patch_hashes
.FileSize(size
);
1879 cur
->patch_hashes
.push_back(HashString(*type
, hash
));
1882 if (cur
!= available_patches
.end())
1885 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1886 << " wasn't in the list for the first parsed hash! (patches)" << std::endl
;
1891 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1893 std::string tagname
= *type
;
1894 tagname
.append("-Download");
1895 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1896 if (tmp
.empty() == true)
1899 string hash
, filename
;
1900 unsigned long long size
;
1901 std::stringstream
ss(tmp
);
1903 // FIXME: all of pdiff supports only .gz compressed patches
1904 while (ss
>> hash
>> size
>> filename
)
1906 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1908 if (unlikely(APT::String::Endswith(filename
, ".gz") == false))
1910 filename
.erase(filename
.length() - 3);
1912 // see if we have a record for this file already
1913 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1914 for (; cur
!= available_patches
.end(); ++cur
)
1916 if (cur
->file
!= filename
)
1918 if (cur
->download_hashes
.empty())
1919 cur
->download_hashes
.FileSize(size
);
1920 cur
->download_hashes
.push_back(HashString(*type
, hash
));
1923 if (cur
!= available_patches
.end())
1926 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1927 << " wasn't in the list for the first parsed hash! (download)" << std::endl
;
1933 bool foundStart
= false;
1934 for (std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1935 cur
!= available_patches
.end(); ++cur
)
1937 if (LocalHashes
!= cur
->result_hashes
)
1940 available_patches
.erase(available_patches
.begin(), cur
);
1945 if (foundStart
== false || unlikely(available_patches
.empty() == true))
1948 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
1949 << "Couldn't find the start of the patch series." << std::endl
;
1953 // patching with too many files is rather slow compared to a fast download
1954 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
1955 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
1958 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
1959 << ") so fallback to complete download" << std::endl
;
1963 // calculate the size of all patches we have to get
1964 // note that all sizes are uncompressed, while we download compressed files
1965 unsigned long long patchesSize
= 0;
1966 for (std::vector
<DiffInfo
>::const_iterator cur
= available_patches
.begin();
1967 cur
!= available_patches
.end(); ++cur
)
1968 patchesSize
+= cur
->patch_hashes
.FileSize();
1969 unsigned long long const sizeLimit
= ServerSize
* _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
1970 if (sizeLimit
> 0 && (sizeLimit
/100) < patchesSize
)
1973 std::clog
<< "Need " << patchesSize
<< " bytes (Limit is " << sizeLimit
/100
1974 << ") so fallback to complete download" << std::endl
;
1978 // we have something, queue the diffs
1979 string::size_type
const last_space
= Description
.rfind(" ");
1980 if(last_space
!= string::npos
)
1981 Description
.erase(last_space
, Description
.size()-last_space
);
1983 /* decide if we should download patches one by one or in one go:
1984 The first is good if the server merges patches, but many don't so client
1985 based merging can be attempt in which case the second is better.
1986 "bad things" will happen if patches are merged on the server,
1987 but client side merging is attempt as well */
1988 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
1989 if (pdiff_merge
== true)
1991 // reprepro adds this flag if it has merged patches on the server
1992 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
1993 pdiff_merge
= (precedence
!= "merged");
1996 if (pdiff_merge
== false)
1997 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, available_patches
);
2000 diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
2001 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
2002 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
, TransactionManager
,
2004 available_patches
[i
],
2014 void pkgAcqDiffIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2016 Item::Failed(Message
,Cnf
);
2020 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2021 << "Falling back to normal index file acquire" << std::endl
;
2023 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2026 void pkgAcqDiffIndex::Done(string
const &Message
,HashStringList
const &Hashes
, /*{{{*/
2027 pkgAcquire::MethodConfig
const * const Cnf
)
2030 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
2032 Item::Done(Message
, Hashes
, Cnf
);
2034 string
const FinalFile
= GetFinalFilename();
2035 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false))
2036 DestFile
= FinalFile
;
2038 if(ParseDiffIndex(DestFile
) == false)
2040 Failed("Message: Couldn't parse pdiff index", Cnf
);
2041 // queue for final move - this should happen even if we fail
2042 // while parsing (e.g. on sizelimit) and download the complete file.
2043 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2047 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2056 pkgAcqDiffIndex::~pkgAcqDiffIndex()
2062 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
2063 // ---------------------------------------------------------------------
2064 /* The package diff is added to the queue. one object is constructed
2065 * for each diff and the index
2067 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
* const Owner
,
2068 pkgAcqMetaClearSig
* const TransactionManager
,
2069 IndexTarget
const &Target
,
2070 vector
<DiffInfo
> const &diffs
)
2071 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
),
2072 available_patches(diffs
)
2074 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2076 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2079 Description
= Target
.Description
;
2080 Desc
.ShortDesc
= Target
.ShortDesc
;
2082 if(available_patches
.empty() == true)
2084 // we are done (yeah!), check hashes against the final file
2085 DestFile
= GetKeepCompressedFileName(GetFinalFileNameFromURI(Target
.URI
), Target
);
2090 if (BootstrapPDiffWith(GetPartialFileNameFromURI(Target
.URI
), GetFinalFilename(), Target
) == false)
2092 Failed("Bootstrapping of " + DestFile
+ " failed", NULL
);
2096 // get the next diff
2097 State
= StateFetchDiff
;
2102 void pkgAcqIndexDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2104 Item::Failed(Message
,Cnf
);
2107 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2109 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2110 << "Falling back to normal index file acquire " << std::endl
;
2111 RenameOnError(PDiffError
);
2112 std::string
const patchname
= GetDiffsPatchFileName(DestFile
);
2113 if (RealFileExists(patchname
))
2114 rename(patchname
.c_str(), std::string(patchname
+ ".FAILED").c_str());
2115 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2119 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
2120 void pkgAcqIndexDiffs::Finish(bool allDone
)
2123 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
2125 << Desc
.URI
<< std::endl
;
2127 // we restore the original name, this is required, otherwise
2128 // the file will be cleaned
2131 std::string Final
= GetFinalFilename();
2132 if (Target
.KeepCompressed
)
2134 std::string
const ext
= flExtension(DestFile
);
2135 if (ext
.empty() == false)
2136 Final
.append(".").append(ext
);
2138 TransactionManager
->TransactionStageCopy(this, DestFile
, Final
);
2140 // this is for the "real" finish
2145 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
2152 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
2159 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
2161 // calc sha1 of the just patched file
2162 std::string
const FinalFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2163 if(!FileExists(FinalFile
))
2165 Failed("Message: No FinalFile " + FinalFile
+ " available", NULL
);
2169 FileFd
fd(FinalFile
, FileFd::ReadOnly
, FileFd::Extension
);
2170 Hashes LocalHashesCalc
;
2171 LocalHashesCalc
.AddFD(fd
);
2172 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
2175 std::clog
<< "QueueNextDiff: " << FinalFile
<< " (" << LocalHashes
.find(NULL
)->toStr() << ")" << std::endl
;
2177 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
2178 if (unlikely(LocalHashes
.usable() == false || TargetFileHashes
.usable() == false))
2180 Failed("Local/Expected hashes are not usable", NULL
);
2185 // final file reached before all patches are applied
2186 if(LocalHashes
== TargetFileHashes
)
2192 // remove all patches until the next matching patch is found
2193 // this requires the Index file to be ordered
2194 for(vector
<DiffInfo
>::iterator I
= available_patches
.begin();
2195 available_patches
.empty() == false &&
2196 I
!= available_patches
.end() &&
2197 I
->result_hashes
!= LocalHashes
;
2200 available_patches
.erase(I
);
2203 // error checking and falling back if no patch was found
2204 if(available_patches
.empty() == true)
2206 Failed("No patches left to reach target", NULL
);
2210 // queue the right diff
2211 Desc
.URI
= Target
.URI
+ ".diff/" + available_patches
[0].file
+ ".gz";
2212 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
2213 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + available_patches
[0].file
), Target
);
2216 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
2223 void pkgAcqIndexDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2224 pkgAcquire::MethodConfig
const * const Cnf
)
2227 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
2229 Item::Done(Message
, Hashes
, Cnf
);
2231 std::string
const FinalFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2232 std::string
const PatchFile
= GetDiffsPatchFileName(FinalFile
);
2234 // success in downloading a diff, enter ApplyDiff state
2235 if(State
== StateFetchDiff
)
2237 Rename(DestFile
, PatchFile
);
2240 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
2242 State
= StateApplyDiff
;
2244 Desc
.URI
= "rred:" + FinalFile
;
2246 SetActiveSubprocess("rred");
2250 // success in download/apply a diff, queue next (if needed)
2251 if(State
== StateApplyDiff
)
2253 // remove the just applied patch
2254 available_patches
.erase(available_patches
.begin());
2255 unlink(PatchFile
.c_str());
2260 std::clog
<< "Moving patched file in place: " << std::endl
2261 << DestFile
<< " -> " << FinalFile
<< std::endl
;
2263 Rename(DestFile
,FinalFile
);
2264 chmod(FinalFile
.c_str(),0644);
2266 // see if there is more to download
2267 if(available_patches
.empty() == false) {
2268 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
2273 DestFile
= FinalFile
;
2274 return Finish(true);
2278 std::string
pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
2280 if(State
!= StateApplyDiff
)
2281 return pkgAcqBaseIndex::Custom600Headers();
2282 std::ostringstream patchhashes
;
2283 HashStringList
const ExpectedHashes
= available_patches
[0].patch_hashes
;
2284 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2285 patchhashes
<< "\nPatch-0-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2286 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2287 return patchhashes
.str();
2290 pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
2292 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
2293 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
* const Owner
,
2294 pkgAcqMetaClearSig
* const TransactionManager
,
2295 IndexTarget
const &Target
,
2296 DiffInfo
const &patch
,
2297 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
2298 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
),
2299 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
2301 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2304 Description
= Target
.Description
;
2305 Desc
.ShortDesc
= Target
.ShortDesc
;
2307 Desc
.URI
= Target
.URI
+ ".diff/" + patch
.file
+ ".gz";
2308 Desc
.Description
= Description
+ " " + patch
.file
+ string(".pdiff");
2310 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + patch
.file
), Target
);
2313 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
2318 void pkgAcqIndexMergeDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2321 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
2323 Item::Failed(Message
,Cnf
);
2326 // check if we are the first to fail, otherwise we are done here
2327 State
= StateDoneDiff
;
2328 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2329 I
!= allPatches
->end(); ++I
)
2330 if ((*I
)->State
== StateErrorDiff
)
2333 // first failure means we should fallback
2334 State
= StateErrorDiff
;
2336 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
2337 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2338 RenameOnError(PDiffError
);
2339 std::string
const patchname
= GetMergeDiffsPatchFileName(DestFile
, patch
.file
);
2340 if (RealFileExists(patchname
))
2341 rename(patchname
.c_str(), std::string(patchname
+ ".FAILED").c_str());
2342 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2346 void pkgAcqIndexMergeDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2347 pkgAcquire::MethodConfig
const * const Cnf
)
2350 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
2352 Item::Done(Message
, Hashes
, Cnf
);
2354 std::string
const UncompressedFinalFile
= GetPartialFileNameFromURI(Target
.URI
);
2355 std::string
const FinalFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2356 if (State
== StateFetchDiff
)
2358 Rename(DestFile
, GetMergeDiffsPatchFileName(FinalFile
, patch
.file
));
2360 // check if this is the last completed diff
2361 State
= StateDoneDiff
;
2362 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2363 I
!= allPatches
->end(); ++I
)
2364 if ((*I
)->State
!= StateDoneDiff
)
2367 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
2371 // this is the last completed diff, so we are ready to apply now
2372 State
= StateApplyDiff
;
2374 if (BootstrapPDiffWith(UncompressedFinalFile
, GetFinalFilename(), Target
) == false)
2376 Failed("Bootstrapping of " + DestFile
+ " failed", NULL
);
2381 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
2384 Desc
.URI
= "rred:" + FinalFile
;
2386 SetActiveSubprocess("rred");
2389 // success in download/apply all diffs, clean up
2390 else if (State
== StateApplyDiff
)
2392 // move the result into place
2393 std::string
const Final
= GetKeepCompressedFileName(GetFinalFilename(), Target
);
2395 std::clog
<< "Queue patched file in place: " << std::endl
2396 << DestFile
<< " -> " << Final
<< std::endl
;
2398 // queue for copy by the transaction manager
2399 TransactionManager
->TransactionStageCopy(this, DestFile
, Final
);
2401 // ensure the ed's are gone regardless of list-cleanup
2402 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2403 I
!= allPatches
->end(); ++I
)
2405 std::string
const PartialFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2406 std::string
const patch
= GetMergeDiffsPatchFileName(PartialFile
, (*I
)->patch
.file
);
2407 unlink(patch
.c_str());
2409 unlink(FinalFile
.c_str());
2414 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
2418 std::string
pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
2420 if(State
!= StateApplyDiff
)
2421 return pkgAcqBaseIndex::Custom600Headers();
2422 std::ostringstream patchhashes
;
2423 unsigned int seen_patches
= 0;
2424 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2425 I
!= allPatches
->end(); ++I
)
2427 HashStringList
const ExpectedHashes
= (*I
)->patch
.patch_hashes
;
2428 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2429 patchhashes
<< "\nPatch-" << seen_patches
<< "-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2432 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2433 return patchhashes
.str();
2436 pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
2438 // AcqIndex::AcqIndex - Constructor /*{{{*/
2439 pkgAcqIndex::pkgAcqIndex(pkgAcquire
* const Owner
,
2440 pkgAcqMetaClearSig
* const TransactionManager
,
2441 IndexTarget
const &Target
)
2442 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), Stage(STAGE_DOWNLOAD
),
2443 CompressionExtensions(Target
.Option(IndexTarget::COMPRESSIONTYPES
))
2445 Init(Target
.URI
, Target
.Description
, Target
.ShortDesc
);
2447 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2448 std::clog
<< "New pkgIndex with TransactionManager "
2449 << TransactionManager
<< std::endl
;
2452 // AcqIndex::Init - defered Constructor /*{{{*/
2453 static void NextCompressionExtension(std::string
&CurrentCompressionExtension
, std::string
&CompressionExtensions
, bool const preview
)
2455 size_t const nextExt
= CompressionExtensions
.find(' ');
2456 if (nextExt
== std::string::npos
)
2458 CurrentCompressionExtension
= CompressionExtensions
;
2459 if (preview
== false)
2460 CompressionExtensions
.clear();
2464 CurrentCompressionExtension
= CompressionExtensions
.substr(0, nextExt
);
2465 if (preview
== false)
2466 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
2469 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
2470 string
const &ShortDesc
)
2472 Stage
= STAGE_DOWNLOAD
;
2474 DestFile
= GetPartialFileNameFromURI(URI
);
2475 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, false);
2477 if (CurrentCompressionExtension
== "uncompressed")
2481 else if (CurrentCompressionExtension
== "by-hash")
2483 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, true);
2484 if(unlikely(TransactionManager
->MetaIndexParser
== NULL
|| CurrentCompressionExtension
.empty()))
2486 if (CurrentCompressionExtension
!= "uncompressed")
2488 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2489 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2492 HashStringList
const Hashes
= GetExpectedHashes();
2493 HashString
const * const TargetHash
= Hashes
.find(NULL
);
2494 if (unlikely(TargetHash
== nullptr))
2496 std::string
const ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
2497 size_t const trailing_slash
= Desc
.URI
.find_last_of("/");
2498 if (unlikely(trailing_slash
== std::string::npos
))
2500 Desc
.URI
= Desc
.URI
.replace(
2502 Desc
.URI
.substr(trailing_slash
+1).size()+1,
2505 else if (unlikely(CurrentCompressionExtension
.empty()))
2509 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2510 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2514 Desc
.Description
= URIDesc
;
2516 Desc
.ShortDesc
= ShortDesc
;
2521 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2522 // ---------------------------------------------------------------------
2523 /* The only header we use is the last-modified header. */
2524 string
pkgAcqIndex::Custom600Headers() const
2526 string Final
= GetFinalFilename();
2528 string msg
= "\nIndex-File: true";
2530 if (stat(Final
.c_str(),&Buf
) == 0)
2531 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
2533 if(Target
.IsOptional
)
2534 msg
+= "\nFail-Ignore: true";
2539 // AcqIndex::Failed - getting the indexfile failed /*{{{*/
2540 void pkgAcqIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
2542 Item::Failed(Message
,Cnf
);
2544 // authorisation matches will not be fixed by other compression types
2545 if (Status
!= StatAuthError
)
2547 if (CompressionExtensions
.empty() == false)
2549 Init(Target
.URI
, Desc
.Description
, Desc
.ShortDesc
);
2555 if(Target
.IsOptional
&& GetExpectedHashes().empty() && Stage
== STAGE_DOWNLOAD
)
2558 TransactionManager
->AbortTransaction();
2561 // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
2562 void pkgAcqIndex::ReverifyAfterIMS()
2564 // update destfile to *not* include the compression extension when doing
2565 // a reverify (as its uncompressed on disk already)
2566 DestFile
= GetCompressedFileName(Target
, GetPartialFileNameFromURI(Target
.URI
), CurrentCompressionExtension
);
2568 // copy FinalFile into partial/ so that we check the hash again
2569 string FinalFile
= GetFinalFilename();
2570 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2571 Desc
.URI
= "copy:" + FinalFile
;
2575 // AcqIndex::Done - Finished a fetch /*{{{*/
2576 // ---------------------------------------------------------------------
2577 /* This goes through a number of states.. On the initial fetch the
2578 method could possibly return an alternate filename which points
2579 to the uncompressed version of the file. If this is so the file
2580 is copied into the partial directory. In all other cases the file
2581 is decompressed with a compressed uri. */
2582 void pkgAcqIndex::Done(string
const &Message
,
2583 HashStringList
const &Hashes
,
2584 pkgAcquire::MethodConfig
const * const Cfg
)
2586 Item::Done(Message
,Hashes
,Cfg
);
2590 case STAGE_DOWNLOAD
:
2591 StageDownloadDone(Message
, Hashes
, Cfg
);
2593 case STAGE_DECOMPRESS_AND_VERIFY
:
2594 StageDecompressDone(Message
, Hashes
, Cfg
);
2599 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
2600 void pkgAcqIndex::StageDownloadDone(string
const &Message
, HashStringList
const &,
2601 pkgAcquire::MethodConfig
const * const)
2605 // Handle the unzipd case
2606 std::string FileName
= LookupTag(Message
,"Alt-Filename");
2607 if (FileName
.empty() == false)
2609 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2611 DestFile
+= ".decomp";
2612 Desc
.URI
= "copy:" + FileName
;
2614 SetActiveSubprocess("copy");
2617 FileName
= LookupTag(Message
,"Filename");
2619 // Methods like e.g. "file:" will give us a (compressed) FileName that is
2620 // not the "DestFile" we set, in this case we uncompress from the local file
2621 if (FileName
!= DestFile
&& RealFileExists(DestFile
) == false)
2624 if (Target
.KeepCompressed
== true)
2626 // but if we don't keep the uncompress we copy the compressed file first
2627 Stage
= STAGE_DOWNLOAD
;
2628 Desc
.URI
= "copy:" + FileName
;
2630 SetActiveSubprocess("copy");
2635 EraseFileName
= FileName
;
2637 // we need to verify the file against the current Release file again
2638 // on if-modfied-since hit to avoid a stale attack against us
2639 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
2641 // The files timestamp matches, reverify by copy into partial/
2647 // get the binary name for your used compression type
2649 if(CurrentCompressionExtension
== "uncompressed")
2650 decompProg
= "copy";
2652 decompProg
= _config
->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension
),"");
2653 if(decompProg
.empty() == true)
2655 _error
->Error("Unsupported extension: %s", CurrentCompressionExtension
.c_str());
2659 if (Target
.KeepCompressed
== true)
2661 DestFile
= "/dev/null";
2662 EraseFileName
.clear();
2665 DestFile
+= ".decomp";
2667 // queue uri for the next stage
2668 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2669 Desc
.URI
= decompProg
+ ":" + FileName
;
2671 SetActiveSubprocess(decompProg
);
2674 // AcqIndex::StageDecompressDone - Final verification /*{{{*/
2675 void pkgAcqIndex::StageDecompressDone(string
const &,
2676 HashStringList
const &,
2677 pkgAcquire::MethodConfig
const * const)
2679 if (Target
.KeepCompressed
== true && DestFile
== "/dev/null")
2680 DestFile
= GetPartialFileNameFromURI(Target
.URI
+ '.' + CurrentCompressionExtension
);
2682 // Done, queue for rename on transaction finished
2683 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
2687 pkgAcqIndex::~pkgAcqIndex() {}
2690 // AcqArchive::AcqArchive - Constructor /*{{{*/
2691 // ---------------------------------------------------------------------
2692 /* This just sets up the initial fetch environment and queues the first
2694 pkgAcqArchive::pkgAcqArchive(pkgAcquire
* const Owner
,pkgSourceList
* const Sources
,
2695 pkgRecords
* const Recs
,pkgCache::VerIterator
const &Version
,
2696 string
&StoreFilename
) :
2697 Item(Owner
), d(NULL
), LocalSource(false), Version(Version
), Sources(Sources
), Recs(Recs
),
2698 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
2701 Retries
= _config
->FindI("Acquire::Retries",0);
2703 if (Version
.Arch() == 0)
2705 _error
->Error(_("I wasn't able to locate a file for the %s package. "
2706 "This might mean you need to manually fix this package. "
2707 "(due to missing arch)"),
2708 Version
.ParentPkg().FullName().c_str());
2712 /* We need to find a filename to determine the extension. We make the
2713 assumption here that all the available sources for this version share
2714 the same extension.. */
2715 // Skip not source sources, they do not have file fields.
2716 for (; Vf
.end() == false; ++Vf
)
2718 if (Vf
.File().Flagged(pkgCache::Flag::NotSource
))
2723 // Does not really matter here.. we are going to fail out below
2724 if (Vf
.end() != true)
2726 // If this fails to get a file name we will bomb out below.
2727 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2728 if (_error
->PendingError() == true)
2731 // Generate the final file name as: package_version_arch.foo
2732 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
2733 QuoteString(Version
.VerStr(),"_:") + '_' +
2734 QuoteString(Version
.Arch(),"_:.") +
2735 "." + flExtension(Parse
.FileName());
2738 // check if we have one trusted source for the package. if so, switch
2739 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2740 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
2741 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
2742 bool seenUntrusted
= false;
2743 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
2745 pkgIndexFile
*Index
;
2746 if (Sources
->FindIndex(i
.File(),Index
) == false)
2749 if (debugAuth
== true)
2750 std::cerr
<< "Checking index: " << Index
->Describe()
2751 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
2753 if (Index
->IsTrusted() == true)
2756 if (allowUnauth
== false)
2760 seenUntrusted
= true;
2763 // "allow-unauthenticated" restores apts old fetching behaviour
2764 // that means that e.g. unauthenticated file:// uris are higher
2765 // priority than authenticated http:// uris
2766 if (allowUnauth
== true && seenUntrusted
== true)
2770 if (QueueNext() == false && _error
->PendingError() == false)
2771 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
2772 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
2775 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2776 // ---------------------------------------------------------------------
2777 /* This queues the next available file version for download. It checks if
2778 the archive is already available in the cache and stashs the MD5 for
2780 bool pkgAcqArchive::QueueNext()
2782 for (; Vf
.end() == false; ++Vf
)
2784 pkgCache::PkgFileIterator
const PkgF
= Vf
.File();
2785 // Ignore not source sources
2786 if (PkgF
.Flagged(pkgCache::Flag::NotSource
))
2789 // Try to cross match against the source list
2790 pkgIndexFile
*Index
;
2791 if (Sources
->FindIndex(PkgF
, Index
) == false)
2793 LocalSource
= PkgF
.Flagged(pkgCache::Flag::LocalSource
);
2795 // only try to get a trusted package from another source if that source
2797 if(Trusted
&& !Index
->IsTrusted())
2800 // Grab the text package record
2801 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2802 if (_error
->PendingError() == true)
2805 string PkgFile
= Parse
.FileName();
2806 ExpectedHashes
= Parse
.Hashes();
2808 if (PkgFile
.empty() == true)
2809 return _error
->Error(_("The package index files are corrupted. No Filename: "
2810 "field for package %s."),
2811 Version
.ParentPkg().Name());
2813 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
2814 Desc
.Description
= Index
->ArchiveInfo(Version
);
2816 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
2818 // See if we already have the file. (Legacy filenames)
2819 FileSize
= Version
->Size
;
2820 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
2822 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2824 // Make sure the size matches
2825 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2830 StoreFilename
= DestFile
= FinalFile
;
2834 /* Hmm, we have a file and its size does not match, this means it is
2835 an old style mismatched arch */
2836 unlink(FinalFile
.c_str());
2839 // Check it again using the new style output filenames
2840 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
2841 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2843 // Make sure the size matches
2844 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2849 StoreFilename
= DestFile
= FinalFile
;
2853 /* Hmm, we have a file and its size does not match, this shouldn't
2855 unlink(FinalFile
.c_str());
2858 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
2860 // Check the destination file
2861 if (stat(DestFile
.c_str(),&Buf
) == 0)
2863 // Hmm, the partial file is too big, erase it
2864 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
2865 unlink(DestFile
.c_str());
2867 PartialSize
= Buf
.st_size
;
2870 // Disables download of archives - useful if no real installation follows,
2871 // e.g. if we are just interested in proposed installation order
2872 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2877 StoreFilename
= DestFile
= FinalFile
;
2891 // AcqArchive::Done - Finished fetching /*{{{*/
2892 // ---------------------------------------------------------------------
2894 void pkgAcqArchive::Done(string
const &Message
, HashStringList
const &Hashes
,
2895 pkgAcquire::MethodConfig
const * const Cfg
)
2897 Item::Done(Message
, Hashes
, Cfg
);
2899 // Grab the output filename
2900 std::string
const FileName
= LookupTag(Message
,"Filename");
2901 if (DestFile
!= FileName
&& RealFileExists(DestFile
) == false)
2903 StoreFilename
= DestFile
= FileName
;
2909 // Done, move it into position
2910 string
const FinalFile
= GetFinalFilename();
2911 Rename(DestFile
,FinalFile
);
2912 StoreFilename
= DestFile
= FinalFile
;
2916 // AcqArchive::Failed - Failure handler /*{{{*/
2917 // ---------------------------------------------------------------------
2918 /* Here we try other sources */
2919 void pkgAcqArchive::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
2921 Item::Failed(Message
,Cnf
);
2923 /* We don't really want to retry on failed media swaps, this prevents
2924 that. An interesting observation is that permanent failures are not
2926 if (Cnf
->Removable
== true &&
2927 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2929 // Vf = Version.FileList();
2930 while (Vf
.end() == false) ++Vf
;
2931 StoreFilename
= string();
2936 if (QueueNext() == false)
2938 // This is the retry counter
2940 Cnf
->LocalOnly
== false &&
2941 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2944 Vf
= Version
.FileList();
2945 if (QueueNext() == true)
2949 StoreFilename
= string();
2954 APT_PURE
bool pkgAcqArchive::IsTrusted() const /*{{{*/
2959 void pkgAcqArchive::Finished() /*{{{*/
2961 if (Status
== pkgAcquire::Item::StatDone
&&
2964 StoreFilename
= string();
2967 std::string
pkgAcqArchive::DescURI() const /*{{{*/
2972 std::string
pkgAcqArchive::ShortDesc() const /*{{{*/
2974 return Desc
.ShortDesc
;
2977 pkgAcqArchive::~pkgAcqArchive() {}
2979 // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
2980 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::VerIterator
const &Ver
,
2981 std::string
const &DestDir
, std::string
const &DestFilename
) :
2982 pkgAcquire::Item(Owner
), d(NULL
), SrcName(Ver
.SourcePkgName()), SrcVersion(Ver
.SourceVerStr())
2984 Desc
.URI
= URI(Ver
);
2985 Init(DestDir
, DestFilename
);
2987 // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
2988 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::RlsFileIterator
const &RlsFile
,
2989 char const * const Component
, char const * const SrcName
, char const * const SrcVersion
,
2990 const string
&DestDir
, const string
&DestFilename
) :
2991 pkgAcquire::Item(Owner
), d(NULL
), SrcName(SrcName
), SrcVersion(SrcVersion
)
2993 Desc
.URI
= URI(RlsFile
, Component
, SrcName
, SrcVersion
);
2994 Init(DestDir
, DestFilename
);
2996 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
,
2997 std::string
const &URI
, char const * const SrcName
, char const * const SrcVersion
,
2998 const string
&DestDir
, const string
&DestFilename
) :
2999 pkgAcquire::Item(Owner
), d(NULL
), SrcName(SrcName
), SrcVersion(SrcVersion
)
3002 Init(DestDir
, DestFilename
);
3004 void pkgAcqChangelog::Init(std::string
const &DestDir
, std::string
const &DestFilename
)
3006 if (Desc
.URI
.empty())
3009 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3010 strprintf(ErrorText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3011 // Let the error message print something sensible rather than "Failed to fetch /"
3012 if (DestFilename
.empty())
3013 DestFile
= SrcName
+ ".changelog";
3015 DestFile
= DestFilename
;
3016 Desc
.URI
= "changelog:/" + DestFile
;
3020 if (DestDir
.empty())
3022 std::string
const SandboxUser
= _config
->Find("APT::Sandbox::User");
3023 std::string
const systemTemp
= GetTempDir(SandboxUser
);
3025 snprintf(tmpname
, sizeof(tmpname
), "%s/apt-changelog-XXXXXX", systemTemp
.c_str());
3026 if (NULL
== mkdtemp(tmpname
))
3028 _error
->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName
.c_str(), SrcVersion
.c_str());
3032 DestFile
= TemporaryDirectory
= tmpname
;
3034 ChangeOwnerAndPermissionOfFile("Item::QueueURI", DestFile
.c_str(),
3035 SandboxUser
.c_str(), "root", 0700);
3040 if (DestFilename
.empty())
3041 DestFile
= flCombine(DestFile
, SrcName
+ ".changelog");
3043 DestFile
= flCombine(DestFile
, DestFilename
);
3045 Desc
.ShortDesc
= "Changelog";
3046 strprintf(Desc
.Description
, "%s %s %s Changelog", URI::SiteOnly(Desc
.URI
).c_str(), SrcName
.c_str(), SrcVersion
.c_str());
3051 std::string
pkgAcqChangelog::URI(pkgCache::VerIterator
const &Ver
) /*{{{*/
3053 char const * const SrcName
= Ver
.SourcePkgName();
3054 char const * const SrcVersion
= Ver
.SourceVerStr();
3055 pkgCache::PkgFileIterator PkgFile
;
3056 // find the first source for this version which promises a changelog
3057 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
3059 pkgCache::PkgFileIterator
const PF
= VF
.File();
3060 if (PF
.Flagged(pkgCache::Flag::NotSource
) || PF
->Release
== 0)
3063 pkgCache::RlsFileIterator
const RF
= PF
.ReleaseFile();
3064 std::string
const uri
= URI(RF
, PF
.Component(), SrcName
, SrcVersion
);
3071 std::string
pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator
const &Rls
)
3073 if (Rls
.end() == true || (Rls
->Label
== 0 && Rls
->Origin
== 0))
3075 std::string
const serverConfig
= "Acquire::Changelogs::URI";
3077 #define APT_EMPTY_SERVER \
3078 if (server.empty() == false) \
3080 if (server != "no") \
3084 #define APT_CHECK_SERVER(X, Y) \
3087 std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
3088 server = _config->Find(specialServerConfig); \
3091 // this way e.g. Debian-Security can fallback to Debian
3092 APT_CHECK_SERVER(Label
, "Override::")
3093 APT_CHECK_SERVER(Origin
, "Override::")
3095 if (RealFileExists(Rls
.FileName()))
3097 _error
->PushToStack();
3099 /* This can be costly. A caller wanting to get millions of URIs might
3100 want to do this on its own once and use Override settings.
3101 We don't do this here as Origin/Label are not as unique as they
3102 should be so this could produce request order-dependent anomalies */
3103 if (OpenMaybeClearSignedFile(Rls
.FileName(), rf
) == true)
3105 pkgTagFile
TagFile(&rf
, rf
.Size());
3106 pkgTagSection Section
;
3107 if (TagFile
.Step(Section
) == true)
3108 server
= Section
.FindS("Changelogs");
3110 _error
->RevertToStack();
3114 APT_CHECK_SERVER(Label
, "")
3115 APT_CHECK_SERVER(Origin
, "")
3116 #undef APT_CHECK_SERVER
3117 #undef APT_EMPTY_SERVER
3120 std::string
pkgAcqChangelog::URI(pkgCache::RlsFileIterator
const &Rls
,
3121 char const * const Component
, char const * const SrcName
,
3122 char const * const SrcVersion
)
3124 return URI(URITemplate(Rls
), Component
, SrcName
, SrcVersion
);
3126 std::string
pkgAcqChangelog::URI(std::string
const &Template
,
3127 char const * const Component
, char const * const SrcName
,
3128 char const * const SrcVersion
)
3130 if (Template
.find("CHANGEPATH") == std::string::npos
)
3133 // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
3134 std::string Src
= SrcName
;
3135 std::string path
= APT::String::Startswith(SrcName
, "lib") ? Src
.substr(0, 4) : Src
.substr(0,1);
3136 path
.append("/").append(Src
).append("/");
3137 path
.append(Src
).append("_").append(StripEpoch(SrcVersion
));
3138 // we omit component for releases without one (= flat-style repositories)
3139 if (Component
!= NULL
&& strlen(Component
) != 0)
3140 path
= std::string(Component
) + "/" + path
;
3142 return SubstVar(Template
, "CHANGEPATH", path
);
3145 // AcqChangelog::Failed - Failure handler /*{{{*/
3146 void pkgAcqChangelog::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3148 Item::Failed(Message
,Cnf
);
3150 std::string errText
;
3151 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3152 strprintf(errText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3154 // Error is probably something techy like 404 Not Found
3155 if (ErrorText
.empty())
3156 ErrorText
= errText
;
3158 ErrorText
= errText
+ " (" + ErrorText
+ ")";
3162 // AcqChangelog::Done - Item downloaded OK /*{{{*/
3163 void pkgAcqChangelog::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3164 pkgAcquire::MethodConfig
const * const Cnf
)
3166 Item::Done(Message
,CalcHashes
,Cnf
);
3171 pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
3173 if (TemporaryDirectory
.empty() == false)
3175 unlink(DestFile
.c_str());
3176 rmdir(TemporaryDirectory
.c_str());
3181 // AcqFile::pkgAcqFile - Constructor /*{{{*/
3182 pkgAcqFile::pkgAcqFile(pkgAcquire
* const Owner
,string
const &URI
, HashStringList
const &Hashes
,
3183 unsigned long long const Size
,string
const &Dsc
,string
const &ShortDesc
,
3184 const string
&DestDir
, const string
&DestFilename
,
3185 bool const IsIndexFile
) :
3186 Item(Owner
), d(NULL
), IsIndexFile(IsIndexFile
), ExpectedHashes(Hashes
)
3188 Retries
= _config
->FindI("Acquire::Retries",0);
3190 if(!DestFilename
.empty())
3191 DestFile
= DestFilename
;
3192 else if(!DestDir
.empty())
3193 DestFile
= DestDir
+ "/" + flNotDir(URI
);
3195 DestFile
= flNotDir(URI
);
3199 Desc
.Description
= Dsc
;
3202 // Set the short description to the archive component
3203 Desc
.ShortDesc
= ShortDesc
;
3205 // Get the transfer sizes
3208 if (stat(DestFile
.c_str(),&Buf
) == 0)
3210 // Hmm, the partial file is too big, erase it
3211 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
3212 unlink(DestFile
.c_str());
3214 PartialSize
= Buf
.st_size
;
3220 // AcqFile::Done - Item downloaded OK /*{{{*/
3221 void pkgAcqFile::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3222 pkgAcquire::MethodConfig
const * const Cnf
)
3224 Item::Done(Message
,CalcHashes
,Cnf
);
3226 std::string
const FileName
= LookupTag(Message
,"Filename");
3229 // The files timestamp matches
3230 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
3233 // We have to copy it into place
3234 if (RealFileExists(DestFile
.c_str()) == false)
3237 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
3238 Cnf
->Removable
== true)
3240 Desc
.URI
= "copy:" + FileName
;
3245 // Erase the file if it is a symlink so we can overwrite it
3247 if (lstat(DestFile
.c_str(),&St
) == 0)
3249 if (S_ISLNK(St
.st_mode
) != 0)
3250 unlink(DestFile
.c_str());
3254 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
3256 _error
->PushToStack();
3257 _error
->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile
.c_str());
3258 std::stringstream msg
;
3259 _error
->DumpErrors(msg
, GlobalError::DEBUG
, false);
3260 _error
->RevertToStack();
3261 ErrorText
= msg
.str();
3268 // AcqFile::Failed - Failure handler /*{{{*/
3269 // ---------------------------------------------------------------------
3270 /* Here we try other sources */
3271 void pkgAcqFile::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3273 Item::Failed(Message
,Cnf
);
3275 // This is the retry counter
3277 Cnf
->LocalOnly
== false &&
3278 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3288 string
pkgAcqFile::Custom600Headers() const /*{{{*/
3291 return "\nIndex-File: true";
3295 pkgAcqFile::~pkgAcqFile() {}