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>
55 static void printHashSumComparision(std::string
const &URI
, HashStringList
const &Expected
, HashStringList
const &Actual
) /*{{{*/
57 if (_config
->FindB("Debug::Acquire::HashSumMismatch", false) == false)
59 std::cerr
<< std::endl
<< URI
<< ":" << std::endl
<< " Expected Hash: " << std::endl
;
60 for (HashStringList::const_iterator hs
= Expected
.begin(); hs
!= Expected
.end(); ++hs
)
61 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
62 std::cerr
<< " Actual Hash: " << std::endl
;
63 for (HashStringList::const_iterator hs
= Actual
.begin(); hs
!= Actual
.end(); ++hs
)
64 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
67 static std::string
GetPartialFileName(std::string
const &file
) /*{{{*/
69 std::string DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
74 static std::string
GetPartialFileNameFromURI(std::string
const &uri
) /*{{{*/
76 return GetPartialFileName(URItoFileName(uri
));
79 static std::string
GetFinalFileNameFromURI(std::string
const &uri
) /*{{{*/
81 return _config
->FindDir("Dir::State::lists") + URItoFileName(uri
);
84 static std::string
GetKeepCompressedFileName(std::string file
, IndexTarget
const &Target
)/*{{{*/
86 if (Target
.KeepCompressed
== false)
89 std::string
const KeepCompressedAs
= Target
.Option(IndexTarget::KEEPCOMPRESSEDAS
);
90 if (KeepCompressedAs
.empty() == false)
92 std::string
const ext
= KeepCompressedAs
.substr(0, KeepCompressedAs
.find(' '));
93 if (ext
!= "uncompressed")
94 file
.append(".").append(ext
);
99 static std::string
GetMergeDiffsPatchFileName(std::string
const &Final
, std::string
const &Patch
)/*{{{*/
101 // rred expects the patch as $FinalFile.ed.$patchname.gz
102 return Final
+ ".ed." + Patch
+ ".gz";
105 static std::string
GetDiffsPatchFileName(std::string
const &Final
) /*{{{*/
107 // rred expects the patch as $FinalFile.ed
108 return Final
+ ".ed";
111 static std::string
GetExistingFilename(std::string
const &File
) /*{{{*/
113 if (RealFileExists(File
))
115 for (auto const &type
: APT::Configuration::getCompressorExtensions())
117 std::string
const Final
= File
+ type
;
118 if (RealFileExists(Final
))
125 static bool MessageInsecureRepository(bool const isError
, std::string
const &msg
)/*{{{*/
129 _error
->Error("%s", msg
.c_str());
130 _error
->Notice("%s", _("Updating from such a repository can't be done securely, and is therefore disabled by default."));
134 _error
->Warning("%s", msg
.c_str());
135 _error
->Notice("%s", _("Data from such a repository can't be authenticated and is therefore potentially dangerous to use."));
137 _error
->Notice("%s", _("See apt-secure(8) manpage for repository creation and user configuration details."));
140 static bool MessageInsecureRepository(bool const isError
, char const * const msg
, std::string
const &repo
)
143 strprintf(m
, msg
, repo
.c_str());
144 return MessageInsecureRepository(isError
, m
);
147 static bool AllowInsecureRepositories(char const * const msg
, std::string
const &repo
,/*{{{*/
148 metaIndex
const * const MetaIndexParser
, pkgAcqMetaClearSig
* const TransactionManager
, pkgAcquire::Item
* const I
)
150 if(MetaIndexParser
->GetTrusted() == metaIndex::TRI_YES
)
153 if (_config
->FindB("Acquire::AllowInsecureRepositories") == true)
155 MessageInsecureRepository(false, msg
, repo
);
159 MessageInsecureRepository(true, msg
, repo
);
160 TransactionManager
->AbortTransaction();
161 I
->Status
= pkgAcquire::Item::StatError
;
165 static HashStringList
GetExpectedHashesFromFor(metaIndex
* const Parser
, std::string
const &MetaKey
)/*{{{*/
168 return HashStringList();
169 metaIndex::checkSum
* const R
= Parser
->Lookup(MetaKey
);
171 return HashStringList();
176 // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
177 /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
178 It is best to implement it as broadly as possible, while ::HashesRequired defaults
179 to true and should be as restrictive as possible for false cases. Note that if
180 a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
181 ::HashesRequired is called to evaluate if its okay to have no hashes. */
182 APT_CONST
bool pkgAcqTransactionItem::HashesRequired() const
184 /* signed repositories obviously have a parser and good hashes.
185 unsigned repositories, too, as even if we can't trust them for security,
186 we can at least trust them for integrity of the download itself.
187 Only repositories without a Release file can (obviously) not have
188 hashes – and they are very uncommon and strongly discouraged */
189 return TransactionManager
->MetaIndexParser
!= NULL
&&
190 TransactionManager
->MetaIndexParser
->GetLoadedSuccessfully() == metaIndex::TRI_YES
;
192 HashStringList
pkgAcqTransactionItem::GetExpectedHashes() const
194 return GetExpectedHashesFor(GetMetaKey());
197 APT_CONST
bool pkgAcqMetaBase::HashesRequired() const
199 // Release and co have no hashes 'by design'.
202 HashStringList
pkgAcqMetaBase::GetExpectedHashes() const
204 return HashStringList();
207 APT_CONST
bool pkgAcqIndexDiffs::HashesRequired() const
209 /* We don't always have the diff of the downloaded pdiff file.
210 What we have for sure is hashes for the uncompressed file,
211 but rred uncompresses them on the fly while parsing, so not handled here.
212 Hashes are (also) checked while searching for (next) patch to apply. */
213 if (State
== StateFetchDiff
)
214 return available_patches
[0].download_hashes
.empty() == false;
217 HashStringList
pkgAcqIndexDiffs::GetExpectedHashes() const
219 if (State
== StateFetchDiff
)
220 return available_patches
[0].download_hashes
;
221 return HashStringList();
224 APT_CONST
bool pkgAcqIndexMergeDiffs::HashesRequired() const
226 /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
227 we can check the rred result after all patches are applied as
228 we know the expected result rather than potentially apply more patches */
229 if (State
== StateFetchDiff
)
230 return patch
.download_hashes
.empty() == false;
231 return State
== StateApplyDiff
;
233 HashStringList
pkgAcqIndexMergeDiffs::GetExpectedHashes() const
235 if (State
== StateFetchDiff
)
236 return patch
.download_hashes
;
237 else if (State
== StateApplyDiff
)
238 return GetExpectedHashesFor(Target
.MetaKey
);
239 return HashStringList();
242 APT_CONST
bool pkgAcqArchive::HashesRequired() const
244 return LocalSource
== false;
246 HashStringList
pkgAcqArchive::GetExpectedHashes() const
248 // figured out while parsing the records
249 return ExpectedHashes
;
252 APT_CONST
bool pkgAcqFile::HashesRequired() const
254 // supplied as parameter at creation time, so the caller decides
255 return ExpectedHashes
.usable();
257 HashStringList
pkgAcqFile::GetExpectedHashes() const
259 return ExpectedHashes
;
262 // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
263 bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc
&Item
)
265 Owner
->Enqueue(Item
);
268 /* The idea here is that an item isn't queued if it exists on disk and the
269 transition manager was a hit as this means that the files it contains
270 the checksums for can't be updated either (or they are and we are asking
271 for a hashsum mismatch to happen which helps nobody) */
272 bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc
&Item
)
274 std::string
const FinalFile
= GetFinalFilename();
275 if (TransactionManager
!= NULL
&& TransactionManager
->IMSHit
== true &&
276 FileExists(FinalFile
) == true)
278 PartialFile
= DestFile
= FinalFile
;
282 return pkgAcquire::Item::QueueURI(Item
);
284 /* The transition manager InRelease itself (or its older sisters-in-law
285 Release & Release.gpg) is always queued as this allows us to rerun gpgv
286 on it to verify that we aren't stalled with old files */
287 bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc
&Item
)
289 return pkgAcquire::Item::QueueURI(Item
);
291 /* the Diff/Index needs to queue also the up-to-date complete index file
292 to ensure that the list cleaner isn't eating it */
293 bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc
&Item
)
295 if (pkgAcqTransactionItem::QueueURI(Item
) == true)
301 // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
302 std::string
pkgAcquire::Item::GetFinalFilename() const
304 return GetFinalFileNameFromURI(Desc
.URI
);
306 std::string
pkgAcqDiffIndex::GetFinalFilename() const
308 // the logic we inherent from pkgAcqBaseIndex isn't what we need here
309 return pkgAcquire::Item::GetFinalFilename();
311 std::string
pkgAcqIndex::GetFinalFilename() const
313 std::string
const FinalFile
= GetFinalFileNameFromURI(Target
.URI
);
314 return GetKeepCompressedFileName(FinalFile
, Target
);
316 std::string
pkgAcqMetaSig::GetFinalFilename() const
318 return GetFinalFileNameFromURI(Target
.URI
);
320 std::string
pkgAcqBaseIndex::GetFinalFilename() const
322 return GetFinalFileNameFromURI(Target
.URI
);
324 std::string
pkgAcqMetaBase::GetFinalFilename() const
326 return GetFinalFileNameFromURI(Target
.URI
);
328 std::string
pkgAcqArchive::GetFinalFilename() const
330 return _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
333 // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
334 std::string
pkgAcqTransactionItem::GetMetaKey() const
336 return Target
.MetaKey
;
338 std::string
pkgAcqIndex::GetMetaKey() const
340 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
|| CurrentCompressionExtension
== "uncompressed")
341 return Target
.MetaKey
;
342 return Target
.MetaKey
+ "." + CurrentCompressionExtension
;
344 std::string
pkgAcqDiffIndex::GetMetaKey() const
346 return Target
.MetaKey
+ ".diff/Index";
349 //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
350 bool pkgAcqTransactionItem::TransactionState(TransactionStates
const state
)
352 bool const Debug
= _config
->FindB("Debug::Acquire::Transaction", false);
355 case TransactionAbort
:
357 std::clog
<< " Cancel: " << DestFile
<< std::endl
;
358 if (Status
== pkgAcquire::Item::StatIdle
)
360 Status
= pkgAcquire::Item::StatDone
;
364 case TransactionCommit
:
365 if(PartialFile
.empty() == false)
367 bool sameFile
= (PartialFile
== DestFile
);
368 // we use symlinks on IMS-Hit to avoid copies
369 if (RealFileExists(DestFile
))
372 if (lstat(PartialFile
.c_str(), &Buf
) != -1)
374 if (S_ISLNK(Buf
.st_mode
) && Buf
.st_size
> 0)
376 char partial
[Buf
.st_size
+ 1];
377 ssize_t
const sp
= readlink(PartialFile
.c_str(), partial
, Buf
.st_size
);
379 _error
->Errno("pkgAcqTransactionItem::TransactionState-sp", _("Failed to readlink %s"), PartialFile
.c_str());
383 sameFile
= (DestFile
== partial
);
388 _error
->Errno("pkgAcqTransactionItem::TransactionState-stat", _("Failed to stat %s"), PartialFile
.c_str());
390 if (sameFile
== false)
392 // ensure that even without lists-cleanup all compressions are nuked
393 std::string FinalFile
= GetFinalFileNameFromURI(Target
.URI
);
394 if (FileExists(FinalFile
))
397 std::clog
<< "rm " << FinalFile
<< " # " << DescURI() << std::endl
;
398 if (RemoveFile("TransactionStates-Cleanup", FinalFile
) == false)
401 for (auto const &ext
: APT::Configuration::getCompressorExtensions())
403 auto const Final
= FinalFile
+ ext
;
404 if (FileExists(Final
))
407 std::clog
<< "rm " << Final
<< " # " << DescURI() << std::endl
;
408 if (RemoveFile("TransactionStates-Cleanup", Final
) == false)
413 std::clog
<< "mv " << PartialFile
<< " -> "<< DestFile
<< " # " << DescURI() << std::endl
;
414 if (Rename(PartialFile
, DestFile
) == false)
417 else if(Debug
== true)
418 std::clog
<< "keep " << PartialFile
<< " # " << DescURI() << std::endl
;
422 std::clog
<< "rm " << DestFile
<< " # " << DescURI() << std::endl
;
423 if (RemoveFile("TransactionCommit", DestFile
) == false)
430 bool pkgAcqMetaBase::TransactionState(TransactionStates
const state
)
432 // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
433 if (TransactionManager
->IMSHit
== false)
434 return pkgAcqTransactionItem::TransactionState(state
);
437 bool pkgAcqIndex::TransactionState(TransactionStates
const state
)
439 if (pkgAcqTransactionItem::TransactionState(state
) == false)
444 case TransactionAbort
:
445 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
447 // keep the compressed file, but drop the decompressed
448 EraseFileName
.clear();
449 if (PartialFile
.empty() == false && flExtension(PartialFile
) != CurrentCompressionExtension
)
450 RemoveFile("TransactionAbort", PartialFile
);
453 case TransactionCommit
:
454 if (EraseFileName
.empty() == false)
455 RemoveFile("TransactionCommit", EraseFileName
);
460 bool pkgAcqDiffIndex::TransactionState(TransactionStates
const state
)
462 if (pkgAcqTransactionItem::TransactionState(state
) == false)
467 case TransactionCommit
:
469 case TransactionAbort
:
470 std::string
const Partial
= GetPartialFileNameFromURI(Target
.URI
);
471 RemoveFile("TransactionAbort", Partial
);
479 class APT_HIDDEN NoActionItem
: public pkgAcquire::Item
/*{{{*/
480 /* The sole purpose of this class is having an item which does nothing to
481 reach its done state to prevent cleanup deleting the mentioned file.
482 Handy in cases in which we know we have the file already, like IMS-Hits. */
484 IndexTarget
const Target
;
486 virtual std::string
DescURI() const APT_OVERRIDE
{return Target
.URI
;};
487 virtual HashStringList
GetExpectedHashes() const APT_OVERRIDE
{return HashStringList();};
489 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
) :
490 pkgAcquire::Item(Owner
), Target(Target
)
493 DestFile
= GetFinalFileNameFromURI(Target
.URI
);
495 NoActionItem(pkgAcquire
* const Owner
, IndexTarget
const &Target
, std::string
const &FinalFile
) :
496 pkgAcquire::Item(Owner
), Target(Target
)
499 DestFile
= FinalFile
;
504 // Acquire::Item::Item - Constructor /*{{{*/
505 APT_IGNORE_DEPRECATED_PUSH
506 pkgAcquire::Item::Item(pkgAcquire
* const owner
) :
507 FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
508 QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner
), d(NULL
)
513 APT_IGNORE_DEPRECATED_POP
515 // Acquire::Item::~Item - Destructor /*{{{*/
516 pkgAcquire::Item::~Item()
521 std::string
pkgAcquire::Item::Custom600Headers() const /*{{{*/
523 return std::string();
526 std::string
pkgAcquire::Item::ShortDesc() const /*{{{*/
531 APT_CONST
void pkgAcquire::Item::Finished() /*{{{*/
535 APT_PURE pkgAcquire
* pkgAcquire::Item::GetOwner() const /*{{{*/
540 APT_CONST
pkgAcquire::ItemDesc
&pkgAcquire::Item::GetItemDesc() /*{{{*/
545 APT_CONST
bool pkgAcquire::Item::IsTrusted() const /*{{{*/
550 // Acquire::Item::Failed - Item failed to download /*{{{*/
551 // ---------------------------------------------------------------------
552 /* We return to an idle state if there are still other queues that could
554 void pkgAcquire::Item::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
556 if(ErrorText
.empty())
557 ErrorText
= LookupTag(Message
,"Message");
558 if (QueueCounter
<= 1)
560 /* This indicates that the file is not available right now but might
561 be sometime later. If we do a retry cycle then this should be
563 if (Cnf
!= NULL
&& Cnf
->LocalOnly
== true &&
564 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
580 case StatTransientNetworkError
:
587 string
const FailReason
= LookupTag(Message
, "FailReason");
588 if (FailReason
== "MaximumSizeExceeded")
589 RenameOnError(MaximumSizeExceeded
);
590 else if (Status
== StatAuthError
)
591 RenameOnError(HashSumMismatch
);
593 // report mirror failure back to LP if we actually use a mirror
594 if (FailReason
.empty() == false)
595 ReportMirrorFailure(FailReason
);
597 ReportMirrorFailure(ErrorText
);
599 if (QueueCounter
> 1)
603 // Acquire::Item::Start - Item has begun to download /*{{{*/
604 // ---------------------------------------------------------------------
605 /* Stash status and the file size. Note that setting Complete means
606 sub-phases of the acquire process such as decompresion are operating */
607 void pkgAcquire::Item::Start(string
const &/*Message*/, unsigned long long const Size
)
609 Status
= StatFetching
;
611 if (FileSize
== 0 && Complete
== false)
615 // Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
616 /* Note that hash-verification is 'hardcoded' in acquire-worker and has
617 * already passed if this method is called. */
618 bool pkgAcquire::Item::VerifyDone(std::string
const &Message
,
619 pkgAcquire::MethodConfig
const * const /*Cnf*/)
621 std::string
const FileName
= LookupTag(Message
,"Filename");
622 if (FileName
.empty() == true)
625 ErrorText
= "Method gave a blank filename";
632 // Acquire::Item::Done - Item downloaded OK /*{{{*/
633 void pkgAcquire::Item::Done(string
const &/*Message*/, HashStringList
const &Hashes
,
634 pkgAcquire::MethodConfig
const * const /*Cnf*/)
636 // We just downloaded something..
639 unsigned long long const downloadedSize
= Hashes
.FileSize();
640 if (downloadedSize
!= 0)
642 FileSize
= downloadedSize
;
646 ErrorText
= string();
647 Owner
->Dequeue(this);
650 // Acquire::Item::Rename - Rename a file /*{{{*/
651 // ---------------------------------------------------------------------
652 /* This helper function is used by a lot of item methods as their final
654 bool pkgAcquire::Item::Rename(string
const &From
,string
const &To
)
656 if (From
== To
|| rename(From
.c_str(),To
.c_str()) == 0)
660 strprintf(S
, _("rename failed, %s (%s -> %s)."), strerror(errno
),
661 From
.c_str(),To
.c_str());
663 if (ErrorText
.empty())
666 ErrorText
= ErrorText
+ ": " + S
;
670 void pkgAcquire::Item::Dequeue() /*{{{*/
672 Owner
->Dequeue(this);
675 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
677 if (RealFileExists(DestFile
))
678 Rename(DestFile
, DestFile
+ ".FAILED");
683 case HashSumMismatch
:
684 errtext
= _("Hash Sum mismatch");
685 Status
= StatAuthError
;
686 ReportMirrorFailure("HashChecksumFailure");
689 errtext
= _("Size mismatch");
690 Status
= StatAuthError
;
691 ReportMirrorFailure("SizeFailure");
694 errtext
= _("Invalid file format");
696 // do not report as usually its not the mirrors fault, but Portal/Proxy
699 errtext
= _("Signature error");
703 strprintf(errtext
, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
704 Status
= StatAuthError
;
706 case MaximumSizeExceeded
:
707 // the method is expected to report a good error for this
711 // no handling here, done by callers
714 if (ErrorText
.empty())
719 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)/*{{{*/
721 ActiveSubprocess
= subprocess
;
722 APT_IGNORE_DEPRECATED(Mode
= ActiveSubprocess
.c_str();)
725 // Acquire::Item::ReportMirrorFailure /*{{{*/
726 void pkgAcquire::Item::ReportMirrorFailure(string
const &FailCode
)
728 // we only act if a mirror was used at all
729 if(UsedMirror
.empty())
732 std::cerr
<< "\nReportMirrorFailure: "
734 << " Uri: " << DescURI()
736 << FailCode
<< std::endl
;
738 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
739 "/usr/lib/apt/apt-report-mirror-failure");
740 if(!FileExists(report
))
743 std::vector
<char const*> Args
;
744 Args
.push_back(report
.c_str());
745 Args
.push_back(UsedMirror
.c_str());
746 Args
.push_back(DescURI().c_str());
747 Args
.push_back(FailCode
.c_str());
748 Args
.push_back(NULL
);
750 pid_t pid
= ExecFork();
753 _error
->Error("ReportMirrorFailure Fork failed");
758 execvp(Args
[0], (char**)Args
.data());
759 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
762 if(!ExecWait(pid
, "report-mirror-failure"))
764 _error
->Warning("Couldn't report problem to '%s'",
765 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
769 std::string
pkgAcquire::Item::HashSum() const /*{{{*/
771 HashStringList
const hashes
= GetExpectedHashes();
772 HashString
const * const hs
= hashes
.find(NULL
);
773 return hs
!= NULL
? hs
->toStr() : "";
777 pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire
* const Owner
, /*{{{*/
778 pkgAcqMetaClearSig
* const transactionManager
, IndexTarget
const &target
) :
779 pkgAcquire::Item(Owner
), d(NULL
), Target(target
), TransactionManager(transactionManager
)
781 if (TransactionManager
!= this)
782 TransactionManager
->Add(this);
785 pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
789 HashStringList
pkgAcqTransactionItem::GetExpectedHashesFor(std::string
const &MetaKey
) const /*{{{*/
791 return GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, MetaKey
);
795 // AcqMetaBase - Constructor /*{{{*/
796 pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire
* const Owner
,
797 pkgAcqMetaClearSig
* const TransactionManager
,
798 std::vector
<IndexTarget
> const &IndexTargets
,
799 IndexTarget
const &DataTarget
)
800 : pkgAcqTransactionItem(Owner
, TransactionManager
, DataTarget
), d(NULL
),
801 IndexTargets(IndexTargets
),
802 AuthPass(false), IMSHit(false)
806 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
807 void pkgAcqMetaBase::Add(pkgAcqTransactionItem
* const I
)
809 Transaction
.push_back(I
);
812 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
813 void pkgAcqMetaBase::AbortTransaction()
815 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
816 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
818 // ensure the toplevel is in error state too
819 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
820 I
!= Transaction
.end(); ++I
)
822 (*I
)->TransactionState(TransactionAbort
);
827 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
828 APT_PURE
bool pkgAcqMetaBase::TransactionHasError() const
830 for (std::vector
<pkgAcqTransactionItem
*>::const_iterator I
= Transaction
.begin();
831 I
!= Transaction
.end(); ++I
)
833 switch((*I
)->Status
) {
834 case StatDone
: break;
835 case StatIdle
: break;
836 case StatAuthError
: return true;
837 case StatError
: return true;
838 case StatTransientNetworkError
: return true;
839 case StatFetching
: break;
845 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
846 void pkgAcqMetaBase::CommitTransaction()
848 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
849 std::clog
<< "CommitTransaction: " << this << std::endl
;
851 // move new files into place *and* remove files that are not
852 // part of the transaction but are still on disk
853 for (std::vector
<pkgAcqTransactionItem
*>::iterator I
= Transaction
.begin();
854 I
!= Transaction
.end(); ++I
)
856 (*I
)->TransactionState(TransactionCommit
);
861 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
862 void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem
* const I
,
863 const std::string
&From
,
864 const std::string
&To
)
866 I
->PartialFile
= From
;
870 // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
871 void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem
* const I
,
872 const std::string
&FinalFile
)
875 I
->DestFile
= FinalFile
;
878 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
879 bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item
* const I
, const std::string
&Message
)
881 // FIXME: this entire function can do now that we disallow going to
882 // a unauthenticated state and can cleanly rollback
884 string
const Final
= I
->GetFinalFilename();
885 if(FileExists(Final
))
887 I
->Status
= StatTransientNetworkError
;
888 _error
->Warning(_("An error occurred during the signature "
889 "verification. The repository is not updated "
890 "and the previous index files will be used. "
891 "GPG error: %s: %s"),
892 Desc
.Description
.c_str(),
893 LookupTag(Message
,"Message").c_str());
894 RunScripts("APT::Update::Auth-Failure");
896 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
897 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
898 _error
->Error(_("GPG error: %s: %s"),
899 Desc
.Description
.c_str(),
900 LookupTag(Message
,"Message").c_str());
901 I
->Status
= StatAuthError
;
904 _error
->Warning(_("GPG error: %s: %s"),
905 Desc
.Description
.c_str(),
906 LookupTag(Message
,"Message").c_str());
908 // gpgv method failed
909 ReportMirrorFailure("GPGFailure");
913 // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
914 // ---------------------------------------------------------------------
915 string
pkgAcqMetaBase::Custom600Headers() const
917 std::string Header
= "\nIndex-File: true";
918 std::string MaximumSize
;
919 strprintf(MaximumSize
, "\nMaximum-Size: %i",
920 _config
->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
921 Header
+= MaximumSize
;
923 string
const FinalFile
= GetFinalFilename();
925 if (stat(FinalFile
.c_str(),&Buf
) == 0)
926 Header
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
931 // AcqMetaBase::QueueForSignatureVerify /*{{{*/
932 void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem
* const I
, std::string
const &File
, std::string
const &Signature
)
935 I
->Desc
.URI
= "gpgv:" + Signature
;
938 I
->SetActiveSubprocess("gpgv");
941 // AcqMetaBase::CheckDownloadDone /*{{{*/
942 bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem
* const I
, const std::string
&Message
, HashStringList
const &Hashes
) const
944 // We have just finished downloading a Release file (it is not
947 std::string
const FileName
= LookupTag(Message
,"Filename");
948 if (FileName
!= I
->DestFile
&& RealFileExists(I
->DestFile
) == false)
951 I
->Desc
.URI
= "copy:" + FileName
;
952 I
->QueueURI(I
->Desc
);
956 // make sure to verify against the right file on I-M-S hit
957 bool IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"), false);
958 if (IMSHit
== false && Hashes
.usable())
960 // detect IMS-Hits servers haven't detected by Hash comparison
961 std::string
const FinalFile
= I
->GetFinalFilename();
962 if (RealFileExists(FinalFile
) && Hashes
.VerifyFile(FinalFile
) == true)
965 RemoveFile("CheckDownloadDone", I
->DestFile
);
971 // for simplicity, the transaction manager is always InRelease
972 // even if it doesn't exist.
973 if (TransactionManager
!= NULL
)
974 TransactionManager
->IMSHit
= true;
975 I
->PartialFile
= I
->DestFile
= I
->GetFinalFilename();
978 // set Item to complete as the remaining work is all local (verify etc)
984 bool pkgAcqMetaBase::CheckAuthDone(string
const &Message
) /*{{{*/
986 // At this point, the gpgv method has succeeded, so there is a
987 // valid signature from a key in the trusted keyring. We
988 // perform additional verification of its contents, and use them
989 // to verify the indexes we are about to download
991 if (TransactionManager
->IMSHit
== false)
993 // open the last (In)Release if we have it
994 std::string
const FinalFile
= GetFinalFilename();
995 std::string FinalRelease
;
996 std::string FinalInRelease
;
997 if (APT::String::Endswith(FinalFile
, "InRelease"))
999 FinalInRelease
= FinalFile
;
1000 FinalRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("InRelease")) + "Release";
1004 FinalInRelease
= FinalFile
.substr(0, FinalFile
.length() - strlen("Release")) + "InRelease";
1005 FinalRelease
= FinalFile
;
1007 if (RealFileExists(FinalInRelease
) || RealFileExists(FinalRelease
))
1009 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1010 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1012 _error
->PushToStack();
1013 if (RealFileExists(FinalInRelease
))
1014 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1016 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1017 // its unlikely to happen, but if what we have is bad ignore it
1018 if (_error
->PendingError())
1020 delete TransactionManager
->LastMetaIndexParser
;
1021 TransactionManager
->LastMetaIndexParser
= NULL
;
1023 _error
->RevertToStack();
1028 if (TransactionManager
->MetaIndexParser
->Load(DestFile
, &ErrorText
) == false)
1030 Status
= StatAuthError
;
1034 if (!VerifyVendor(Message
))
1036 Status
= StatAuthError
;
1040 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1041 std::cerr
<< "Signature verification succeeded: "
1042 << DestFile
<< std::endl
;
1044 // Download further indexes with verification
1050 void pkgAcqMetaBase::QueueIndexes(bool const verify
) /*{{{*/
1052 // at this point the real Items are loaded in the fetcher
1053 ExpectedAdditionalItems
= 0;
1055 bool metaBaseSupportsByHash
= false;
1056 if (TransactionManager
!= NULL
&& TransactionManager
->MetaIndexParser
!= NULL
)
1057 metaBaseSupportsByHash
= TransactionManager
->MetaIndexParser
->GetSupportsAcquireByHash();
1059 for (std::vector
<IndexTarget
>::iterator Target
= IndexTargets
.begin();
1060 Target
!= IndexTargets
.end();
1063 // all is an implementation detail. Users shouldn't use this as arch
1064 // We need this support trickery here as e.g. Debian has binary-all files already,
1065 // but arch:all packages are still in the arch:any files, so we would waste precious
1066 // download time, bandwidth and diskspace for nothing, BUT Debian doesn't feature all
1067 // in the set of supported architectures, so we can filter based on this property rather
1068 // than invent an entirely new flag we would need to carry for all of eternity.
1069 if (Target
->Option(IndexTarget::ARCHITECTURE
) == "all")
1071 if (TransactionManager
->MetaIndexParser
->IsArchitectureSupported("all") == false)
1073 if (TransactionManager
->MetaIndexParser
->IsArchitectureAllSupportedFor(*Target
) == false)
1077 bool trypdiff
= Target
->OptionBool(IndexTarget::PDIFFS
);
1080 if (TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
) == false)
1082 // optional targets that we do not have in the Release file are skipped
1083 if (Target
->IsOptional
)
1086 std::string
const &arch
= Target
->Option(IndexTarget::ARCHITECTURE
);
1087 if (arch
.empty() == false)
1089 if (TransactionManager
->MetaIndexParser
->IsArchitectureSupported(arch
) == false)
1091 _error
->Notice(_("Skipping acquire of configured file '%s' as repository '%s' doesn't support architecture '%s'"),
1092 Target
->MetaKey
.c_str(), TransactionManager
->Target
.Description
.c_str(), arch
.c_str());
1095 // if the architecture is officially supported but currently no packages for it available,
1096 // ignore silently as this is pretty much the same as just shipping an empty file.
1097 // if we don't know which architectures are supported, we do NOT ignore it to notify user about this
1098 if (TransactionManager
->MetaIndexParser
->IsArchitectureSupported("*undefined*") == false)
1102 Status
= StatAuthError
;
1103 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target
->MetaKey
.c_str());
1108 auto const hashes
= GetExpectedHashesFor(Target
->MetaKey
);
1109 if (hashes
.usable() == false && hashes
.empty() == false)
1111 _error
->Warning(_("Skipping acquire of configured file '%s' as repository '%s' provides only weak security information for it"),
1112 Target
->MetaKey
.c_str(), TransactionManager
->Target
.Description
.c_str());
1117 // autoselect the compression method
1118 std::vector
<std::string
> types
= VectorizeString(Target
->Option(IndexTarget::COMPRESSIONTYPES
), ' ');
1119 types
.erase(std::remove_if(types
.begin(), types
.end(), [&](std::string
const &t
) {
1120 if (t
== "uncompressed")
1121 return TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
) == false;
1122 std::string
const MetaKey
= Target
->MetaKey
+ "." + t
;
1123 return TransactionManager
->MetaIndexParser
->Exists(MetaKey
) == false;
1125 if (types
.empty() == false)
1127 std::ostringstream os
;
1128 // add the special compressiontype byhash first if supported
1129 std::string
const useByHashConf
= Target
->Option(IndexTarget::BY_HASH
);
1130 bool useByHash
= false;
1131 if(useByHashConf
== "force")
1134 useByHash
= StringToBool(useByHashConf
) == true && metaBaseSupportsByHash
;
1135 if (useByHash
== true)
1137 std::copy(types
.begin(), types
.end()-1, std::ostream_iterator
<std::string
>(os
, " "));
1138 os
<< *types
.rbegin();
1139 Target
->Options
["COMPRESSIONTYPES"] = os
.str();
1142 Target
->Options
["COMPRESSIONTYPES"].clear();
1144 std::string filename
= GetExistingFilename(GetFinalFileNameFromURI(Target
->URI
));
1145 if (filename
.empty() == false)
1147 // if the Release file is a hit and we have an index it must be the current one
1148 if (TransactionManager
->IMSHit
== true)
1150 else if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1152 // see if the file changed since the last Release file
1153 // we use the uncompressed files as we might compress differently compared to the server,
1154 // so the hashes might not match, even if they contain the same data.
1155 HashStringList
const newFile
= GetExpectedHashesFromFor(TransactionManager
->MetaIndexParser
, Target
->MetaKey
);
1156 HashStringList
const oldFile
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
->MetaKey
);
1157 if (newFile
!= oldFile
)
1164 trypdiff
= false; // no file to patch
1166 if (filename
.empty() == false)
1168 new NoActionItem(Owner
, *Target
, filename
);
1169 std::string
const idxfilename
= GetFinalFileNameFromURI(Target
->URI
+ ".diff/Index");
1170 if (FileExists(idxfilename
))
1171 new NoActionItem(Owner
, *Target
, idxfilename
);
1175 // check if we have patches available
1176 trypdiff
&= TransactionManager
->MetaIndexParser
->Exists(Target
->MetaKey
+ ".diff/Index");
1180 // if we have no file to patch, no point in trying
1181 trypdiff
&= (GetExistingFilename(GetFinalFileNameFromURI(Target
->URI
)).empty() == false);
1184 // no point in patching from local sources
1187 std::string
const proto
= Target
->URI
.substr(0, strlen("file:/"));
1188 if (proto
== "file:/" || proto
== "copy:/" || proto
== "cdrom:")
1192 // Queue the Index file (Packages, Sources, Translation-$foo, …)
1194 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
);
1196 new pkgAcqIndex(Owner
, TransactionManager
, *Target
);
1200 bool pkgAcqMetaBase::VerifyVendor(string
const &Message
) /*{{{*/
1202 string::size_type pos
;
1204 // check for missing sigs (that where not fatal because otherwise we had
1207 string msg
= _("There is no public key available for the "
1208 "following key IDs:\n");
1209 pos
= Message
.find("NO_PUBKEY ");
1210 if (pos
!= std::string::npos
)
1212 string::size_type start
= pos
+strlen("NO_PUBKEY ");
1213 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
1214 missingkeys
+= (Fingerprint
);
1216 if(!missingkeys
.empty())
1217 _error
->Warning("%s", (msg
+ missingkeys
).c_str());
1219 string Transformed
= TransactionManager
->MetaIndexParser
->GetExpectedDist();
1221 if (Transformed
== "../project/experimental")
1223 Transformed
= "experimental";
1226 pos
= Transformed
.rfind('/');
1227 if (pos
!= string::npos
)
1229 Transformed
= Transformed
.substr(0, pos
);
1232 if (Transformed
== ".")
1237 if (TransactionManager
->MetaIndexParser
->GetValidUntil() > 0)
1239 time_t const invalid_since
= time(NULL
) - TransactionManager
->MetaIndexParser
->GetValidUntil();
1240 if (invalid_since
> 0)
1244 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1245 // the time since then the file is invalid - formatted in the same way as in
1246 // the download progress display (e.g. 7d 3h 42min 1s)
1247 _("Release file for %s is expired (invalid since %s). "
1248 "Updates for this repository will not be applied."),
1249 Target
.URI
.c_str(), TimeToStr(invalid_since
).c_str());
1250 if (ErrorText
.empty())
1252 return _error
->Error("%s", errmsg
.c_str());
1256 /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
1257 as a prevention of downgrading us to older (still valid) files */
1258 if (TransactionManager
->IMSHit
== false && TransactionManager
->LastMetaIndexParser
!= NULL
&&
1259 TransactionManager
->LastMetaIndexParser
->GetDate() > TransactionManager
->MetaIndexParser
->GetDate())
1261 TransactionManager
->IMSHit
= true;
1262 RemoveFile("VerifyVendor", DestFile
);
1263 PartialFile
= DestFile
= GetFinalFilename();
1264 // load the 'old' file in the 'new' one instead of flipping pointers as
1265 // the new one isn't owned by us, while the old one is so cleanup would be confused.
1266 TransactionManager
->MetaIndexParser
->swapLoad(TransactionManager
->LastMetaIndexParser
);
1267 delete TransactionManager
->LastMetaIndexParser
;
1268 TransactionManager
->LastMetaIndexParser
= NULL
;
1271 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1273 std::cerr
<< "Got Codename: " << TransactionManager
->MetaIndexParser
->GetCodename() << std::endl
;
1274 std::cerr
<< "Expecting Dist: " << TransactionManager
->MetaIndexParser
->GetExpectedDist() << std::endl
;
1275 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
1278 if (TransactionManager
->MetaIndexParser
->CheckDist(Transformed
) == false)
1280 // This might become fatal one day
1281 // Status = StatAuthError;
1282 // ErrorText = "Conflicting distribution; expected "
1283 // + MetaIndexParser->GetExpectedDist() + " but got "
1284 // + MetaIndexParser->GetCodename();
1286 if (!Transformed
.empty())
1288 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1289 Desc
.Description
.c_str(),
1290 Transformed
.c_str(),
1291 TransactionManager
->MetaIndexParser
->GetCodename().c_str());
1298 pkgAcqMetaBase::~pkgAcqMetaBase()
1302 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
* const Owner
, /*{{{*/
1303 IndexTarget
const &ClearsignedTarget
,
1304 IndexTarget
const &DetachedDataTarget
, IndexTarget
const &DetachedSigTarget
,
1305 std::vector
<IndexTarget
> const &IndexTargets
,
1306 metaIndex
* const MetaIndexParser
) :
1307 pkgAcqMetaIndex(Owner
, this, ClearsignedTarget
, DetachedSigTarget
, IndexTargets
),
1308 d(NULL
), ClearsignedTarget(ClearsignedTarget
),
1309 DetachedDataTarget(DetachedDataTarget
),
1310 MetaIndexParser(MetaIndexParser
), LastMetaIndexParser(NULL
)
1312 // index targets + (worst case:) Release/Release.gpg
1313 ExpectedAdditionalItems
= IndexTargets
.size() + 2;
1314 TransactionManager
->Add(this);
1317 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
1319 if (LastMetaIndexParser
!= NULL
)
1320 delete LastMetaIndexParser
;
1323 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1324 string
pkgAcqMetaClearSig::Custom600Headers() const
1326 string Header
= pkgAcqMetaBase::Custom600Headers();
1327 Header
+= "\nFail-Ignore: true";
1328 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1329 if (key
.empty() == false)
1330 Header
+= "\nSigned-By: " + key
;
1335 bool pkgAcqMetaClearSig::VerifyDone(std::string
const &Message
, /*{{{*/
1336 pkgAcquire::MethodConfig
const * const Cnf
)
1338 Item::VerifyDone(Message
, Cnf
);
1340 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
1341 return RenameOnError(NotClearsigned
);
1346 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
1347 void pkgAcqMetaClearSig::Done(std::string
const &Message
,
1348 HashStringList
const &Hashes
,
1349 pkgAcquire::MethodConfig
const * const Cnf
)
1351 Item::Done(Message
, Hashes
, Cnf
);
1353 if(AuthPass
== false)
1355 if(CheckDownloadDone(this, Message
, Hashes
) == true)
1356 QueueForSignatureVerify(this, DestFile
, DestFile
);
1359 else if(CheckAuthDone(Message
) == true)
1361 if (TransactionManager
->IMSHit
== false)
1362 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1363 else if (RealFileExists(GetFinalFilename()) == false)
1365 // We got an InRelease file IMSHit, but we haven't one, which means
1366 // we had a valid Release/Release.gpg combo stepping in, which we have
1367 // to 'acquire' now to ensure list cleanup isn't removing them
1368 new NoActionItem(Owner
, DetachedDataTarget
);
1369 new NoActionItem(Owner
, DetachedSigTarget
);
1374 void pkgAcqMetaClearSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
) /*{{{*/
1376 Item::Failed(Message
, Cnf
);
1378 // we failed, we will not get additional items from this method
1379 ExpectedAdditionalItems
= 0;
1381 if (AuthPass
== false)
1383 if (Status
== StatAuthError
|| Status
== StatTransientNetworkError
)
1385 // if we expected a ClearTextSignature (InRelease) but got a network
1386 // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
1387 // As these is usually called by web-portals we do not try Release/Release.gpg
1388 // as this is gonna fail anyway and instead abort our try (LP#346386)
1389 TransactionManager
->AbortTransaction();
1393 // Queue the 'old' InRelease file for removal if we try Release.gpg
1394 // as otherwise the file will stay around and gives a false-auth
1395 // impression (CVE-2012-0214)
1396 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1399 new pkgAcqMetaIndex(Owner
, TransactionManager
, DetachedDataTarget
, DetachedSigTarget
, IndexTargets
);
1403 if(CheckStopAuthentication(this, Message
))
1406 // No Release file was present, or verification failed, so fall
1407 // back to queueing Packages files without verification
1408 // only allow going further if the user explicitly wants it
1409 if(AllowInsecureRepositories(_("The repository '%s' is not signed."), ClearsignedTarget
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1413 /* InRelease files become Release files, otherwise
1414 * they would be considered as trusted later on */
1415 string
const FinalRelease
= GetFinalFileNameFromURI(DetachedDataTarget
.URI
);
1416 string
const PartialRelease
= GetPartialFileNameFromURI(DetachedDataTarget
.URI
);
1417 string
const FinalReleasegpg
= GetFinalFileNameFromURI(DetachedSigTarget
.URI
);
1418 string
const FinalInRelease
= GetFinalFilename();
1419 Rename(DestFile
, PartialRelease
);
1420 TransactionManager
->TransactionStageCopy(this, PartialRelease
, FinalRelease
);
1422 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1424 // open the last Release if we have it
1425 if (TransactionManager
->IMSHit
== false)
1427 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1428 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1430 _error
->PushToStack();
1431 if (RealFileExists(FinalInRelease
))
1432 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1434 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1435 // its unlikely to happen, but if what we have is bad ignore it
1436 if (_error
->PendingError())
1438 delete TransactionManager
->LastMetaIndexParser
;
1439 TransactionManager
->LastMetaIndexParser
= NULL
;
1441 _error
->RevertToStack();
1446 // we parse the indexes here because at this point the user wanted
1447 // a repository that may potentially harm him
1448 if (TransactionManager
->MetaIndexParser
->Load(PartialRelease
, &ErrorText
) == false || VerifyVendor(Message
) == false)
1449 /* expired Release files are still a problem you need extra force for */;
1457 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
* const Owner
, /*{{{*/
1458 pkgAcqMetaClearSig
* const TransactionManager
,
1459 IndexTarget
const &DataTarget
,
1460 IndexTarget
const &DetachedSigTarget
,
1461 vector
<IndexTarget
> const &IndexTargets
) :
1462 pkgAcqMetaBase(Owner
, TransactionManager
, IndexTargets
, DataTarget
), d(NULL
),
1463 DetachedSigTarget(DetachedSigTarget
)
1465 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1466 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1467 << this->TransactionManager
<< std::endl
;
1469 DestFile
= GetPartialFileNameFromURI(DataTarget
.URI
);
1472 Desc
.Description
= DataTarget
.Description
;
1474 Desc
.ShortDesc
= DataTarget
.ShortDesc
;
1475 Desc
.URI
= DataTarget
.URI
;
1477 // we expect more item
1478 ExpectedAdditionalItems
= IndexTargets
.size();
1482 void pkgAcqMetaIndex::Done(string
const &Message
, /*{{{*/
1483 HashStringList
const &Hashes
,
1484 pkgAcquire::MethodConfig
const * const Cfg
)
1486 Item::Done(Message
,Hashes
,Cfg
);
1488 if(CheckDownloadDone(this, Message
, Hashes
))
1490 // we have a Release file, now download the Signature, all further
1491 // verify/queue for additional downloads will be done in the
1492 // pkgAcqMetaSig::Done() code
1493 new pkgAcqMetaSig(Owner
, TransactionManager
, DetachedSigTarget
, this);
1497 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
1498 void pkgAcqMetaIndex::Failed(string
const &Message
,
1499 pkgAcquire::MethodConfig
const * const Cnf
)
1501 pkgAcquire::Item::Failed(Message
, Cnf
);
1504 // No Release file was present so fall
1505 // back to queueing Packages files without verification
1506 // only allow going further if the user explicitly wants it
1507 if(AllowInsecureRepositories(_("The repository '%s' does not have a Release file."), Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1509 // ensure old Release files are removed
1510 TransactionManager
->TransactionStageRemoval(this, GetFinalFilename());
1512 // queue without any kind of hashsum support
1513 QueueIndexes(false);
1517 void pkgAcqMetaIndex::Finished() /*{{{*/
1519 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1520 std::clog
<< "Finished: " << DestFile
<<std::endl
;
1521 if(TransactionManager
!= NULL
&&
1522 TransactionManager
->TransactionHasError() == false)
1523 TransactionManager
->CommitTransaction();
1526 std::string
pkgAcqMetaIndex::DescURI() const /*{{{*/
1531 pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
1533 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1534 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
* const Owner
,
1535 pkgAcqMetaClearSig
* const TransactionManager
,
1536 IndexTarget
const &Target
,
1537 pkgAcqMetaIndex
* const MetaIndex
) :
1538 pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
), MetaIndex(MetaIndex
)
1540 DestFile
= GetPartialFileNameFromURI(Target
.URI
);
1542 // remove any partial downloaded sig-file in partial/.
1543 // it may confuse proxies and is too small to warrant a
1544 // partial download anyway
1545 RemoveFile("pkgAcqMetaSig", DestFile
);
1547 // set the TransactionManager
1548 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1549 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1550 << TransactionManager
<< std::endl
;
1553 Desc
.Description
= Target
.Description
;
1555 Desc
.ShortDesc
= Target
.ShortDesc
;
1556 Desc
.URI
= Target
.URI
;
1558 // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
1559 // so we skip the download step and go instantly to verification
1560 if (TransactionManager
->IMSHit
== true && RealFileExists(GetFinalFilename()))
1564 PartialFile
= DestFile
= GetFinalFilename();
1565 MetaIndexFileSignature
= DestFile
;
1566 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1572 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1576 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1577 std::string
pkgAcqMetaSig::Custom600Headers() const
1579 std::string Header
= pkgAcqTransactionItem::Custom600Headers();
1580 std::string
const key
= TransactionManager
->MetaIndexParser
->GetSignedBy();
1581 if (key
.empty() == false)
1582 Header
+= "\nSigned-By: " + key
;
1586 // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1587 void pkgAcqMetaSig::Done(string
const &Message
, HashStringList
const &Hashes
,
1588 pkgAcquire::MethodConfig
const * const Cfg
)
1590 if (MetaIndexFileSignature
.empty() == false)
1592 DestFile
= MetaIndexFileSignature
;
1593 MetaIndexFileSignature
.clear();
1595 Item::Done(Message
, Hashes
, Cfg
);
1597 if(MetaIndex
->AuthPass
== false)
1599 if(MetaIndex
->CheckDownloadDone(this, Message
, Hashes
) == true)
1601 // destfile will be modified to point to MetaIndexFile for the
1602 // gpgv method, so we need to save it here
1603 MetaIndexFileSignature
= DestFile
;
1604 MetaIndex
->QueueForSignatureVerify(this, MetaIndex
->DestFile
, DestFile
);
1608 else if(MetaIndex
->CheckAuthDone(Message
) == true)
1610 if (TransactionManager
->IMSHit
== false)
1612 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1613 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, MetaIndex
->GetFinalFilename());
1618 void pkgAcqMetaSig::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
1620 Item::Failed(Message
,Cnf
);
1622 // check if we need to fail at this point
1623 if (MetaIndex
->AuthPass
== true && MetaIndex
->CheckStopAuthentication(this, Message
))
1626 string
const FinalRelease
= MetaIndex
->GetFinalFilename();
1627 string
const FinalReleasegpg
= GetFinalFilename();
1628 string
const FinalInRelease
= TransactionManager
->GetFinalFilename();
1630 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1632 std::string downgrade_msg
;
1633 strprintf(downgrade_msg
, _("The repository '%s' is no longer signed."),
1634 MetaIndex
->Target
.Description
.c_str());
1635 if(_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1637 // meh, the users wants to take risks (we still mark the packages
1638 // from this repository as unauthenticated)
1639 _error
->Warning("%s", downgrade_msg
.c_str());
1640 _error
->Warning(_("This is normally not allowed, but the option "
1641 "Acquire::AllowDowngradeToInsecureRepositories was "
1642 "given to override it."));
1645 MessageInsecureRepository(true, downgrade_msg
);
1646 if (TransactionManager
->IMSHit
== false)
1647 Rename(MetaIndex
->DestFile
, MetaIndex
->DestFile
+ ".FAILED");
1648 Item::Failed("Message: " + downgrade_msg
, Cnf
);
1649 TransactionManager
->AbortTransaction();
1654 // ensures that a Release.gpg file in the lists/ is removed by the transaction
1655 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1657 // only allow going further if the user explicitly wants it
1658 if (AllowInsecureRepositories(_("The repository '%s' is not signed."), MetaIndex
->Target
.Description
, TransactionManager
->MetaIndexParser
, TransactionManager
, this) == true)
1660 if (RealFileExists(FinalReleasegpg
) || RealFileExists(FinalInRelease
))
1662 // open the last Release if we have it
1663 if (TransactionManager
->IMSHit
== false)
1665 TransactionManager
->LastMetaIndexParser
= TransactionManager
->MetaIndexParser
->UnloadedClone();
1666 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1668 _error
->PushToStack();
1669 if (RealFileExists(FinalInRelease
))
1670 TransactionManager
->LastMetaIndexParser
->Load(FinalInRelease
, NULL
);
1672 TransactionManager
->LastMetaIndexParser
->Load(FinalRelease
, NULL
);
1673 // its unlikely to happen, but if what we have is bad ignore it
1674 if (_error
->PendingError())
1676 delete TransactionManager
->LastMetaIndexParser
;
1677 TransactionManager
->LastMetaIndexParser
= NULL
;
1679 _error
->RevertToStack();
1684 // we parse the indexes here because at this point the user wanted
1685 // a repository that may potentially harm him
1686 bool const GoodLoad
= TransactionManager
->MetaIndexParser
->Load(MetaIndex
->DestFile
, &ErrorText
);
1687 if (MetaIndex
->VerifyVendor(Message
) == false)
1688 /* expired Release files are still a problem you need extra force for */;
1690 MetaIndex
->QueueIndexes(GoodLoad
);
1692 TransactionManager
->TransactionStageCopy(MetaIndex
, MetaIndex
->DestFile
, MetaIndex
->GetFinalFilename());
1695 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1696 if (Cnf
->LocalOnly
== true ||
1697 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1706 // AcqBaseIndex - Constructor /*{{{*/
1707 pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire
* const Owner
,
1708 pkgAcqMetaClearSig
* const TransactionManager
,
1709 IndexTarget
const &Target
)
1710 : pkgAcqTransactionItem(Owner
, TransactionManager
, Target
), d(NULL
)
1714 pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
1716 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
1717 // ---------------------------------------------------------------------
1718 /* Get the DiffIndex file first and see if there are patches available
1719 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
1720 * patches. If anything goes wrong in that process, it will fall back to
1721 * the original packages file
1723 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
* const Owner
,
1724 pkgAcqMetaClearSig
* const TransactionManager
,
1725 IndexTarget
const &Target
)
1726 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), diffs(NULL
)
1728 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
1731 Desc
.Description
= Target
.Description
+ ".diff/Index";
1732 Desc
.ShortDesc
= Target
.ShortDesc
;
1733 Desc
.URI
= Target
.URI
+ ".diff/Index";
1735 DestFile
= GetPartialFileNameFromURI(Desc
.URI
);
1738 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
1743 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1744 // ---------------------------------------------------------------------
1745 /* The only header we use is the last-modified header. */
1746 string
pkgAcqDiffIndex::Custom600Headers() const
1748 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1749 return "\nIndex-File: true";
1751 string
const Final
= GetFinalFilename();
1754 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
1757 if (stat(Final
.c_str(),&Buf
) != 0)
1758 return "\nIndex-File: true";
1760 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1763 void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
1765 // list cleanup needs to know that this file as well as the already
1766 // present index is ours, so we create an empty diff to save it for us
1767 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
);
1770 bool pkgAcqDiffIndex::ParseDiffIndex(string
const &IndexDiffFile
) /*{{{*/
1772 // failing here is fine: our caller will take care of trying to
1773 // get the complete file if patching fails
1775 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
1778 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
1780 if (Fd
.IsOpen() == false || Fd
.Failed())
1784 if(unlikely(TF
.Step(Tags
) == false))
1787 HashStringList ServerHashes
;
1788 unsigned long long ServerSize
= 0;
1790 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1792 std::string tagname
= *type
;
1793 tagname
.append("-Current");
1794 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1795 if (tmp
.empty() == true)
1799 unsigned long long size
;
1800 std::stringstream
ss(tmp
);
1802 if (unlikely(hash
.empty() == true))
1804 if (unlikely(ServerSize
!= 0 && ServerSize
!= size
))
1806 ServerHashes
.push_back(HashString(*type
, hash
));
1810 if (ServerHashes
.usable() == false)
1813 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Did not find a good hashsum in the index" << std::endl
;
1817 std::string
const CurrentPackagesFile
= GetFinalFileNameFromURI(Target
.URI
);
1818 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
1819 if (TargetFileHashes
.usable() == false || ServerHashes
!= TargetFileHashes
)
1823 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl
;
1824 printHashSumComparision(CurrentPackagesFile
, ServerHashes
, TargetFileHashes
);
1829 HashStringList LocalHashes
;
1830 // try avoiding calculating the hash here as this is costly
1831 if (TransactionManager
->LastMetaIndexParser
!= NULL
)
1832 LocalHashes
= GetExpectedHashesFromFor(TransactionManager
->LastMetaIndexParser
, Target
.MetaKey
);
1833 if (LocalHashes
.usable() == false)
1835 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
, FileFd::Auto
);
1836 Hashes
LocalHashesCalc(ServerHashes
);
1837 LocalHashesCalc
.AddFD(fd
);
1838 LocalHashes
= LocalHashesCalc
.GetHashStringList();
1841 if (ServerHashes
== LocalHashes
)
1843 // we have the same sha1 as the server so we are done here
1845 std::clog
<< "pkgAcqDiffIndex: Package file " << CurrentPackagesFile
<< " is up-to-date" << std::endl
;
1851 std::clog
<< "Server-Current: " << ServerHashes
.find(NULL
)->toStr() << " and we start at "
1852 << CurrentPackagesFile
<< " " << LocalHashes
.FileSize() << " " << LocalHashes
.find(NULL
)->toStr() << std::endl
;
1854 // historically, older hashes have more info than newer ones, so start
1855 // collecting with older ones first to avoid implementing complicated
1856 // information merging techniques… a failure is after all always
1857 // recoverable with a complete file and hashes aren't changed that often.
1858 std::vector
<char const *> types
;
1859 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
1860 types
.push_back(*type
);
1862 // parse all of (provided) history
1863 vector
<DiffInfo
> available_patches
;
1864 bool firstAcceptedHashes
= true;
1865 for (auto type
= types
.crbegin(); type
!= types
.crend(); ++type
)
1867 if (LocalHashes
.find(*type
) == NULL
)
1870 std::string tagname
= *type
;
1871 tagname
.append("-History");
1872 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1873 if (tmp
.empty() == true)
1876 string hash
, filename
;
1877 unsigned long long size
;
1878 std::stringstream
ss(tmp
);
1880 while (ss
>> hash
>> size
>> filename
)
1882 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1885 // see if we have a record for this file already
1886 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1887 for (; cur
!= available_patches
.end(); ++cur
)
1889 if (cur
->file
!= filename
)
1891 cur
->result_hashes
.push_back(HashString(*type
, hash
));
1894 if (cur
!= available_patches
.end())
1896 if (firstAcceptedHashes
== true)
1899 next
.file
= filename
;
1900 next
.result_hashes
.push_back(HashString(*type
, hash
));
1901 next
.result_hashes
.FileSize(size
);
1902 available_patches
.push_back(next
);
1907 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1908 << " wasn't in the list for the first parsed hash! (history)" << std::endl
;
1912 firstAcceptedHashes
= false;
1915 if (unlikely(available_patches
.empty() == true))
1918 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
1919 << "Couldn't find any patches for the patch series." << std::endl
;
1923 for (auto type
= types
.crbegin(); type
!= types
.crend(); ++type
)
1925 if (LocalHashes
.find(*type
) == NULL
)
1928 std::string tagname
= *type
;
1929 tagname
.append("-Patches");
1930 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1931 if (tmp
.empty() == true)
1934 string hash
, filename
;
1935 unsigned long long size
;
1936 std::stringstream
ss(tmp
);
1938 while (ss
>> hash
>> size
>> filename
)
1940 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1943 // see if we have a record for this file already
1944 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1945 for (; cur
!= available_patches
.end(); ++cur
)
1947 if (cur
->file
!= filename
)
1949 if (cur
->patch_hashes
.empty())
1950 cur
->patch_hashes
.FileSize(size
);
1951 cur
->patch_hashes
.push_back(HashString(*type
, hash
));
1954 if (cur
!= available_patches
.end())
1957 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1958 << " wasn't in the list for the first parsed hash! (patches)" << std::endl
;
1963 for (auto type
= types
.crbegin(); type
!= types
.crend(); ++type
)
1965 std::string tagname
= *type
;
1966 tagname
.append("-Download");
1967 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
1968 if (tmp
.empty() == true)
1971 string hash
, filename
;
1972 unsigned long long size
;
1973 std::stringstream
ss(tmp
);
1975 // FIXME: all of pdiff supports only .gz compressed patches
1976 while (ss
>> hash
>> size
>> filename
)
1978 if (unlikely(hash
.empty() == true || filename
.empty() == true))
1980 if (unlikely(APT::String::Endswith(filename
, ".gz") == false))
1982 filename
.erase(filename
.length() - 3);
1984 // see if we have a record for this file already
1985 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
1986 for (; cur
!= available_patches
.end(); ++cur
)
1988 if (cur
->file
!= filename
)
1990 if (cur
->download_hashes
.empty())
1991 cur
->download_hashes
.FileSize(size
);
1992 cur
->download_hashes
.push_back(HashString(*type
, hash
));
1995 if (cur
!= available_patches
.end())
1998 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
1999 << " wasn't in the list for the first parsed hash! (download)" << std::endl
;
2005 bool foundStart
= false;
2006 for (std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
2007 cur
!= available_patches
.end(); ++cur
)
2009 if (LocalHashes
!= cur
->result_hashes
)
2012 available_patches
.erase(available_patches
.begin(), cur
);
2017 if (foundStart
== false || unlikely(available_patches
.empty() == true))
2020 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
2021 << "Couldn't find the start of the patch series." << std::endl
;
2025 // patching with too many files is rather slow compared to a fast download
2026 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
2027 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
2030 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
2031 << ") so fallback to complete download" << std::endl
;
2035 // calculate the size of all patches we have to get
2036 unsigned short const sizeLimitPercent
= _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
2037 if (sizeLimitPercent
> 0 && TransactionManager
->MetaIndexParser
!= nullptr)
2040 unsigned long long downloadSize
= std::accumulate(available_patches
.begin(),
2041 available_patches
.end(), 0llu, [](unsigned long long const T
, DiffInfo
const &I
) {
2042 return T
+ I
.download_hashes
.FileSize();
2044 if (downloadSize
!= 0)
2046 unsigned long long downloadSizeIdx
= 0;
2047 auto const types
= VectorizeString(Target
.Option(IndexTarget::COMPRESSIONTYPES
), ' ');
2048 for (auto const &t
: types
)
2050 std::string MetaKey
= Target
.MetaKey
;
2051 if (t
!= "uncompressed")
2053 HashStringList
const hsl
= GetExpectedHashesFor(MetaKey
);
2054 if (unlikely(hsl
.usable() == false))
2056 downloadSizeIdx
= hsl
.FileSize();
2059 unsigned long long const sizeLimit
= downloadSizeIdx
* sizeLimitPercent
;
2060 if ((sizeLimit
/100) < downloadSize
)
2063 std::clog
<< "Need " << downloadSize
<< " compressed bytes (Limit is " << (sizeLimit
/100) << ", "
2064 << "original is " << downloadSizeIdx
<< ") so fallback to complete download" << std::endl
;
2068 // uncompressed case
2069 downloadSize
= std::accumulate(available_patches
.begin(),
2070 available_patches
.end(), 0llu, [](unsigned long long const T
, DiffInfo
const &I
) {
2071 return T
+ I
.patch_hashes
.FileSize();
2073 if (downloadSize
!= 0)
2075 unsigned long long const downloadSizeIdx
= ServerSize
;
2076 unsigned long long const sizeLimit
= downloadSizeIdx
* sizeLimitPercent
;
2077 if ((sizeLimit
/100) < downloadSize
)
2080 std::clog
<< "Need " << downloadSize
<< " uncompressed bytes (Limit is " << (sizeLimit
/100) << ", "
2081 << "original is " << downloadSizeIdx
<< ") so fallback to complete download" << std::endl
;
2087 // we have something, queue the diffs
2088 string::size_type
const last_space
= Description
.rfind(" ");
2089 if(last_space
!= string::npos
)
2090 Description
.erase(last_space
, Description
.size()-last_space
);
2092 /* decide if we should download patches one by one or in one go:
2093 The first is good if the server merges patches, but many don't so client
2094 based merging can be attempt in which case the second is better.
2095 "bad things" will happen if patches are merged on the server,
2096 but client side merging is attempt as well */
2097 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
2098 if (pdiff_merge
== true)
2100 // reprepro adds this flag if it has merged patches on the server
2101 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
2102 pdiff_merge
= (precedence
!= "merged");
2107 std::string
const Final
= GetExistingFilename(CurrentPackagesFile
);
2108 if (unlikely(Final
.empty())) // because we wouldn't be called in such a case
2110 std::string
const PartialFile
= GetPartialFileNameFromURI(Target
.URI
);
2111 if (FileExists(PartialFile
) && RemoveFile("Bootstrap-linking", PartialFile
) == false)
2114 std::clog
<< "Bootstrap-linking for patching " << CurrentPackagesFile
2115 << " by removing stale " << PartialFile
<< " failed!" << std::endl
;
2118 for (auto const &ext
: APT::Configuration::getCompressorExtensions())
2120 std::string
const Partial
= PartialFile
+ ext
;
2121 if (FileExists(Partial
) && RemoveFile("Bootstrap-linking", Partial
) == false)
2124 std::clog
<< "Bootstrap-linking for patching " << CurrentPackagesFile
2125 << " by removing stale " << Partial
<< " failed!" << std::endl
;
2129 std::string
const Ext
= Final
.substr(CurrentPackagesFile
.length());
2130 std::string
const Partial
= PartialFile
+ Ext
;
2131 if (symlink(Final
.c_str(), Partial
.c_str()) != 0)
2134 std::clog
<< "Bootstrap-linking for patching " << CurrentPackagesFile
2135 << " by linking " << Final
<< " to " << Partial
<< " failed!" << std::endl
;
2140 if (pdiff_merge
== false)
2141 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, available_patches
);
2144 diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
2145 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
2146 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
, TransactionManager
,
2148 available_patches
[i
],
2158 void pkgAcqDiffIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2160 Item::Failed(Message
,Cnf
);
2164 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2165 << "Falling back to normal index file acquire" << std::endl
;
2167 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2170 void pkgAcqDiffIndex::Done(string
const &Message
,HashStringList
const &Hashes
, /*{{{*/
2171 pkgAcquire::MethodConfig
const * const Cnf
)
2174 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
2176 Item::Done(Message
, Hashes
, Cnf
);
2178 string
const FinalFile
= GetFinalFilename();
2179 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false))
2180 DestFile
= FinalFile
;
2182 if(ParseDiffIndex(DestFile
) == false)
2184 Failed("Message: Couldn't parse pdiff index", Cnf
);
2185 // queue for final move - this should happen even if we fail
2186 // while parsing (e.g. on sizelimit) and download the complete file.
2187 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2191 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2200 pkgAcqDiffIndex::~pkgAcqDiffIndex()
2206 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
2207 // ---------------------------------------------------------------------
2208 /* The package diff is added to the queue. one object is constructed
2209 * for each diff and the index
2211 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
* const Owner
,
2212 pkgAcqMetaClearSig
* const TransactionManager
,
2213 IndexTarget
const &Target
,
2214 vector
<DiffInfo
> const &diffs
)
2215 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
),
2216 available_patches(diffs
)
2218 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2220 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2223 Description
= Target
.Description
;
2224 Desc
.ShortDesc
= Target
.ShortDesc
;
2226 if(available_patches
.empty() == true)
2228 // we are done (yeah!), check hashes against the final file
2229 DestFile
= GetKeepCompressedFileName(GetFinalFileNameFromURI(Target
.URI
), Target
);
2234 State
= StateFetchDiff
;
2239 void pkgAcqIndexDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2241 Item::Failed(Message
,Cnf
);
2244 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2246 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
2247 << "Falling back to normal index file acquire " << std::endl
;
2248 RenameOnError(PDiffError
);
2249 std::string
const patchname
= GetDiffsPatchFileName(DestFile
);
2250 if (RealFileExists(patchname
))
2251 Rename(patchname
, patchname
+ ".FAILED");
2252 std::string
const UnpatchedFile
= GetExistingFilename(GetPartialFileNameFromURI(Target
.URI
));
2253 if (UnpatchedFile
.empty() == false && FileExists(UnpatchedFile
))
2254 Rename(UnpatchedFile
, UnpatchedFile
+ ".FAILED");
2255 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2259 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
2260 void pkgAcqIndexDiffs::Finish(bool allDone
)
2263 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
2265 << Desc
.URI
<< std::endl
;
2267 // we restore the original name, this is required, otherwise
2268 // the file will be cleaned
2271 std::string
const Final
= GetKeepCompressedFileName(GetFinalFilename(), Target
);
2272 TransactionManager
->TransactionStageCopy(this, DestFile
, Final
);
2274 // this is for the "real" finish
2279 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
2286 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
2293 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
2295 // calc sha1 of the just patched file
2296 std::string
const PartialFile
= GetExistingFilename(GetPartialFileNameFromURI(Target
.URI
));
2297 if(unlikely(PartialFile
.empty()))
2299 Failed("Message: The file " + GetPartialFileNameFromURI(Target
.URI
) + " isn't available", NULL
);
2303 FileFd
fd(PartialFile
, FileFd::ReadOnly
, FileFd::Extension
);
2304 Hashes LocalHashesCalc
;
2305 LocalHashesCalc
.AddFD(fd
);
2306 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
2309 std::clog
<< "QueueNextDiff: " << PartialFile
<< " (" << LocalHashes
.find(NULL
)->toStr() << ")" << std::endl
;
2311 HashStringList
const TargetFileHashes
= GetExpectedHashesFor(Target
.MetaKey
);
2312 if (unlikely(LocalHashes
.usable() == false || TargetFileHashes
.usable() == false))
2314 Failed("Local/Expected hashes are not usable for " + PartialFile
, NULL
);
2318 // final file reached before all patches are applied
2319 if(LocalHashes
== TargetFileHashes
)
2325 // remove all patches until the next matching patch is found
2326 // this requires the Index file to be ordered
2327 available_patches
.erase(available_patches
.begin(),
2328 std::find_if(available_patches
.begin(), available_patches
.end(), [&](DiffInfo
const &I
) {
2329 return I
.result_hashes
== LocalHashes
;
2332 // error checking and falling back if no patch was found
2333 if(available_patches
.empty() == true)
2335 Failed("No patches left to reach target for " + PartialFile
, NULL
);
2339 // queue the right diff
2340 Desc
.URI
= Target
.URI
+ ".diff/" + available_patches
[0].file
+ ".gz";
2341 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
2342 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
+ ".diff/" + available_patches
[0].file
), Target
);
2345 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
2352 void pkgAcqIndexDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2353 pkgAcquire::MethodConfig
const * const Cnf
)
2356 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
2358 Item::Done(Message
, Hashes
, Cnf
);
2360 std::string
const UncompressedUnpatchedFile
= GetPartialFileNameFromURI(Target
.URI
);
2361 std::string
const UnpatchedFile
= GetExistingFilename(UncompressedUnpatchedFile
);
2362 std::string
const PatchFile
= GetDiffsPatchFileName(UnpatchedFile
);
2363 std::string
const PatchedFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
, Target
);
2367 // success in downloading a diff, enter ApplyDiff state
2368 case StateFetchDiff
:
2369 Rename(DestFile
, PatchFile
);
2370 DestFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
+ "-patched", Target
);
2372 std::clog
<< "Sending to rred method: " << UnpatchedFile
<< std::endl
;
2373 State
= StateApplyDiff
;
2375 Desc
.URI
= "rred:" + UnpatchedFile
;
2377 SetActiveSubprocess("rred");
2379 // success in download/apply a diff, queue next (if needed)
2380 case StateApplyDiff
:
2381 // remove the just applied patch and base file
2382 available_patches
.erase(available_patches
.begin());
2383 RemoveFile("pkgAcqIndexDiffs::Done", PatchFile
);
2384 RemoveFile("pkgAcqIndexDiffs::Done", UnpatchedFile
);
2386 std::clog
<< "Moving patched file in place: " << std::endl
2387 << DestFile
<< " -> " << PatchedFile
<< std::endl
;
2388 Rename(DestFile
, PatchedFile
);
2390 // see if there is more to download
2391 if(available_patches
.empty() == false)
2393 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, available_patches
);
2396 DestFile
= PatchedFile
;
2403 std::string
pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
2405 if(State
!= StateApplyDiff
)
2406 return pkgAcqBaseIndex::Custom600Headers();
2407 std::ostringstream patchhashes
;
2408 HashStringList
const ExpectedHashes
= available_patches
[0].patch_hashes
;
2409 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2410 patchhashes
<< "\nPatch-0-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2411 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2412 return patchhashes
.str();
2415 pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
2417 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
2418 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
* const Owner
,
2419 pkgAcqMetaClearSig
* const TransactionManager
,
2420 IndexTarget
const &Target
,
2421 DiffInfo
const &patch
,
2422 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
2423 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
),
2424 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
2426 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
2429 Description
= Target
.Description
;
2430 Desc
.ShortDesc
= Target
.ShortDesc
;
2431 Desc
.URI
= Target
.URI
+ ".diff/" + patch
.file
+ ".gz";
2432 Desc
.Description
= Description
+ " " + patch
.file
+ ".pdiff";
2433 DestFile
= GetPartialFileNameFromURI(Desc
.URI
);
2436 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
2441 void pkgAcqIndexMergeDiffs::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)/*{{{*/
2444 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
2446 Item::Failed(Message
,Cnf
);
2449 // check if we are the first to fail, otherwise we are done here
2450 State
= StateDoneDiff
;
2451 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2452 I
!= allPatches
->end(); ++I
)
2453 if ((*I
)->State
== StateErrorDiff
)
2456 // first failure means we should fallback
2457 State
= StateErrorDiff
;
2459 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
2460 RenameOnError(PDiffError
);
2461 std::string
const patchname
= GetPartialFileNameFromURI(Desc
.URI
);
2462 if (RealFileExists(patchname
))
2463 Rename(patchname
, patchname
+ ".FAILED");
2464 std::string
const UnpatchedFile
= GetExistingFilename(GetPartialFileNameFromURI(Target
.URI
));
2465 if (UnpatchedFile
.empty() == false && FileExists(UnpatchedFile
))
2466 Rename(UnpatchedFile
, UnpatchedFile
+ ".FAILED");
2468 new pkgAcqIndex(Owner
, TransactionManager
, Target
);
2471 void pkgAcqIndexMergeDiffs::Done(string
const &Message
, HashStringList
const &Hashes
, /*{{{*/
2472 pkgAcquire::MethodConfig
const * const Cnf
)
2475 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
2477 Item::Done(Message
, Hashes
, Cnf
);
2479 if (std::any_of(allPatches
->begin(), allPatches
->end(),
2480 [](pkgAcqIndexMergeDiffs
const * const P
) { return P
->State
== StateErrorDiff
; }))
2483 std::clog
<< "Another patch failed already, no point in processing this one." << std::endl
;
2487 std::string
const UncompressedUnpatchedFile
= GetPartialFileNameFromURI(Target
.URI
);
2488 std::string
const UnpatchedFile
= GetExistingFilename(UncompressedUnpatchedFile
);
2489 if (UnpatchedFile
.empty())
2491 _error
->Fatal("Unpatched file %s doesn't exist (anymore)!", UnpatchedFile
.c_str());
2494 std::string
const PatchFile
= GetMergeDiffsPatchFileName(UnpatchedFile
, patch
.file
);
2495 std::string
const PatchedFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
, Target
);
2499 case StateFetchDiff
:
2500 Rename(DestFile
, PatchFile
);
2502 // check if this is the last completed diff
2503 State
= StateDoneDiff
;
2504 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2505 I
!= allPatches
->end(); ++I
)
2506 if ((*I
)->State
!= StateDoneDiff
)
2509 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
2512 // this is the last completed diff, so we are ready to apply now
2513 DestFile
= GetKeepCompressedFileName(UncompressedUnpatchedFile
+ "-patched", Target
);
2515 std::clog
<< "Sending to rred method: " << UnpatchedFile
<< std::endl
;
2516 State
= StateApplyDiff
;
2518 Desc
.URI
= "rred:" + UnpatchedFile
;
2520 SetActiveSubprocess("rred");
2522 case StateApplyDiff
:
2523 // success in download & apply all diffs, finialize and clean up
2525 std::clog
<< "Queue patched file in place: " << std::endl
2526 << DestFile
<< " -> " << PatchedFile
<< std::endl
;
2528 // queue for copy by the transaction manager
2529 TransactionManager
->TransactionStageCopy(this, DestFile
, GetKeepCompressedFileName(GetFinalFilename(), Target
));
2531 // ensure the ed's are gone regardless of list-cleanup
2532 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2533 I
!= allPatches
->end(); ++I
)
2534 RemoveFile("pkgAcqIndexMergeDiffs::Done", GetMergeDiffsPatchFileName(UnpatchedFile
, (*I
)->patch
.file
));
2535 RemoveFile("pkgAcqIndexMergeDiffs::Done", UnpatchedFile
);
2540 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
2542 case StateDoneDiff
: _error
->Fatal("Done called for %s which is in an invalid Done state", PatchFile
.c_str()); break;
2543 case StateErrorDiff
: _error
->Fatal("Done called for %s which is in an invalid Error state", PatchFile
.c_str()); break;
2547 std::string
pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
2549 if(State
!= StateApplyDiff
)
2550 return pkgAcqBaseIndex::Custom600Headers();
2551 std::ostringstream patchhashes
;
2552 unsigned int seen_patches
= 0;
2553 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
2554 I
!= allPatches
->end(); ++I
)
2556 HashStringList
const ExpectedHashes
= (*I
)->patch
.patch_hashes
;
2557 for (HashStringList::const_iterator hs
= ExpectedHashes
.begin(); hs
!= ExpectedHashes
.end(); ++hs
)
2558 patchhashes
<< "\nPatch-" << seen_patches
<< "-" << hs
->HashType() << "-Hash: " << hs
->HashValue();
2561 patchhashes
<< pkgAcqBaseIndex::Custom600Headers();
2562 return patchhashes
.str();
2565 pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
2567 // AcqIndex::AcqIndex - Constructor /*{{{*/
2568 pkgAcqIndex::pkgAcqIndex(pkgAcquire
* const Owner
,
2569 pkgAcqMetaClearSig
* const TransactionManager
,
2570 IndexTarget
const &Target
)
2571 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
), d(NULL
), Stage(STAGE_DOWNLOAD
),
2572 CompressionExtensions(Target
.Option(IndexTarget::COMPRESSIONTYPES
))
2574 Init(Target
.URI
, Target
.Description
, Target
.ShortDesc
);
2576 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2577 std::clog
<< "New pkgIndex with TransactionManager "
2578 << TransactionManager
<< std::endl
;
2581 // AcqIndex::Init - defered Constructor /*{{{*/
2582 static void NextCompressionExtension(std::string
&CurrentCompressionExtension
, std::string
&CompressionExtensions
, bool const preview
)
2584 size_t const nextExt
= CompressionExtensions
.find(' ');
2585 if (nextExt
== std::string::npos
)
2587 CurrentCompressionExtension
= CompressionExtensions
;
2588 if (preview
== false)
2589 CompressionExtensions
.clear();
2593 CurrentCompressionExtension
= CompressionExtensions
.substr(0, nextExt
);
2594 if (preview
== false)
2595 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
2598 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
2599 string
const &ShortDesc
)
2601 Stage
= STAGE_DOWNLOAD
;
2603 DestFile
= GetPartialFileNameFromURI(URI
);
2604 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, false);
2606 if (CurrentCompressionExtension
== "uncompressed")
2610 else if (CurrentCompressionExtension
== "by-hash")
2612 NextCompressionExtension(CurrentCompressionExtension
, CompressionExtensions
, true);
2613 if(unlikely(TransactionManager
->MetaIndexParser
== NULL
|| CurrentCompressionExtension
.empty()))
2615 if (CurrentCompressionExtension
!= "uncompressed")
2617 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2618 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2621 HashStringList
const Hashes
= GetExpectedHashes();
2622 HashString
const * const TargetHash
= Hashes
.find(NULL
);
2623 if (unlikely(TargetHash
== nullptr))
2625 std::string
const ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
2626 size_t const trailing_slash
= Desc
.URI
.find_last_of("/");
2627 if (unlikely(trailing_slash
== std::string::npos
))
2629 Desc
.URI
= Desc
.URI
.replace(
2631 Desc
.URI
.substr(trailing_slash
+1).size()+1,
2634 else if (unlikely(CurrentCompressionExtension
.empty()))
2638 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
2639 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
2643 Desc
.Description
= URIDesc
;
2645 Desc
.ShortDesc
= ShortDesc
;
2650 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2651 // ---------------------------------------------------------------------
2652 /* The only header we use is the last-modified header. */
2653 string
pkgAcqIndex::Custom600Headers() const
2656 string msg
= "\nIndex-File: true";
2658 if (TransactionManager
->LastMetaIndexParser
== NULL
)
2660 std::string
const Final
= GetFinalFilename();
2663 if (stat(Final
.c_str(),&Buf
) == 0)
2664 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
2667 if(Target
.IsOptional
)
2668 msg
+= "\nFail-Ignore: true";
2673 // AcqIndex::Failed - getting the indexfile failed /*{{{*/
2674 void pkgAcqIndex::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
2676 Item::Failed(Message
,Cnf
);
2678 // authorisation matches will not be fixed by other compression types
2679 if (Status
!= StatAuthError
)
2681 if (CompressionExtensions
.empty() == false)
2683 Init(Target
.URI
, Desc
.Description
, Desc
.ShortDesc
);
2689 if(Target
.IsOptional
&& GetExpectedHashes().empty() && Stage
== STAGE_DOWNLOAD
)
2692 TransactionManager
->AbortTransaction();
2695 // AcqIndex::Done - Finished a fetch /*{{{*/
2696 // ---------------------------------------------------------------------
2697 /* This goes through a number of states.. On the initial fetch the
2698 method could possibly return an alternate filename which points
2699 to the uncompressed version of the file. If this is so the file
2700 is copied into the partial directory. In all other cases the file
2701 is decompressed with a compressed uri. */
2702 void pkgAcqIndex::Done(string
const &Message
,
2703 HashStringList
const &Hashes
,
2704 pkgAcquire::MethodConfig
const * const Cfg
)
2706 Item::Done(Message
,Hashes
,Cfg
);
2710 case STAGE_DOWNLOAD
:
2711 StageDownloadDone(Message
);
2713 case STAGE_DECOMPRESS_AND_VERIFY
:
2714 StageDecompressDone();
2719 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
2720 void pkgAcqIndex::StageDownloadDone(string
const &Message
)
2725 std::string
const AltFilename
= LookupTag(Message
,"Alt-Filename");
2726 std::string Filename
= LookupTag(Message
,"Filename");
2728 // we need to verify the file against the current Release file again
2729 // on if-modfied-since hit to avoid a stale attack against us
2730 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
2732 // copy FinalFile into partial/ so that we check the hash again
2733 string
const FinalFile
= GetExistingFilename(GetFinalFileNameFromURI(Target
.URI
));
2734 if (symlink(FinalFile
.c_str(), DestFile
.c_str()) != 0)
2735 _error
->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking final file %s back to %s failed", FinalFile
.c_str(), DestFile
.c_str());
2738 EraseFileName
= DestFile
;
2739 Filename
= DestFile
;
2741 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2742 Desc
.URI
= "store:" + Filename
;
2744 SetActiveSubprocess(::URI(Desc
.URI
).Access
);
2747 // methods like file:// give us an alternative (uncompressed) file
2748 else if (Target
.KeepCompressed
== false && AltFilename
.empty() == false)
2750 if (CurrentCompressionExtension
!= "uncompressed")
2751 DestFile
.erase(DestFile
.length() - (CurrentCompressionExtension
.length() + 1));
2752 Filename
= AltFilename
;
2754 // Methods like e.g. "file:" will give us a (compressed) FileName that is
2755 // not the "DestFile" we set, in this case we uncompress from the local file
2756 else if (Filename
!= DestFile
&& RealFileExists(DestFile
) == false)
2758 // symlinking ensures that the filename can be used for compression detection
2759 // that is e.g. needed for by-hash which has no extension over file
2760 if (symlink(Filename
.c_str(),DestFile
.c_str()) != 0)
2761 _error
->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking file %s to %s failed", Filename
.c_str(), DestFile
.c_str());
2764 EraseFileName
= DestFile
;
2765 Filename
= DestFile
;
2769 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
2770 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2771 if (Filename
!= DestFile
&& flExtension(Filename
) == flExtension(DestFile
))
2772 Desc
.URI
= "copy:" + Filename
;
2774 Desc
.URI
= "store:" + Filename
;
2775 if (DestFile
== Filename
)
2777 if (CurrentCompressionExtension
== "uncompressed")
2778 return StageDecompressDone();
2779 DestFile
= "/dev/null";
2782 if (EraseFileName
.empty())
2783 EraseFileName
= Filename
;
2785 // queue uri for the next stage
2787 SetActiveSubprocess(::URI(Desc
.URI
).Access
);
2790 // AcqIndex::StageDecompressDone - Final verification /*{{{*/
2791 void pkgAcqIndex::StageDecompressDone()
2793 if (DestFile
== "/dev/null")
2794 DestFile
= GetKeepCompressedFileName(GetPartialFileNameFromURI(Target
.URI
), Target
);
2796 // Done, queue for rename on transaction finished
2797 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
2800 pkgAcqIndex::~pkgAcqIndex() {}
2803 // AcqArchive::AcqArchive - Constructor /*{{{*/
2804 // ---------------------------------------------------------------------
2805 /* This just sets up the initial fetch environment and queues the first
2807 pkgAcqArchive::pkgAcqArchive(pkgAcquire
* const Owner
,pkgSourceList
* const Sources
,
2808 pkgRecords
* const Recs
,pkgCache::VerIterator
const &Version
,
2809 string
&StoreFilename
) :
2810 Item(Owner
), d(NULL
), LocalSource(false), Version(Version
), Sources(Sources
), Recs(Recs
),
2811 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
2814 Retries
= _config
->FindI("Acquire::Retries",0);
2816 if (Version
.Arch() == 0)
2818 _error
->Error(_("I wasn't able to locate a file for the %s package. "
2819 "This might mean you need to manually fix this package. "
2820 "(due to missing arch)"),
2821 Version
.ParentPkg().FullName().c_str());
2825 /* We need to find a filename to determine the extension. We make the
2826 assumption here that all the available sources for this version share
2827 the same extension.. */
2828 // Skip not source sources, they do not have file fields.
2829 for (; Vf
.end() == false; ++Vf
)
2831 if (Vf
.File().Flagged(pkgCache::Flag::NotSource
))
2836 // Does not really matter here.. we are going to fail out below
2837 if (Vf
.end() != true)
2839 // If this fails to get a file name we will bomb out below.
2840 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2841 if (_error
->PendingError() == true)
2844 // Generate the final file name as: package_version_arch.foo
2845 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
2846 QuoteString(Version
.VerStr(),"_:") + '_' +
2847 QuoteString(Version
.Arch(),"_:.") +
2848 "." + flExtension(Parse
.FileName());
2851 // check if we have one trusted source for the package. if so, switch
2852 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2853 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
2854 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
2855 bool seenUntrusted
= false;
2856 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
2858 pkgIndexFile
*Index
;
2859 if (Sources
->FindIndex(i
.File(),Index
) == false)
2862 if (debugAuth
== true)
2863 std::cerr
<< "Checking index: " << Index
->Describe()
2864 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
2866 if (Index
->IsTrusted() == true)
2869 if (allowUnauth
== false)
2873 seenUntrusted
= true;
2876 // "allow-unauthenticated" restores apts old fetching behaviour
2877 // that means that e.g. unauthenticated file:// uris are higher
2878 // priority than authenticated http:// uris
2879 if (allowUnauth
== true && seenUntrusted
== true)
2883 if (QueueNext() == false && _error
->PendingError() == false)
2884 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
2885 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
2888 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2889 // ---------------------------------------------------------------------
2890 /* This queues the next available file version for download. It checks if
2891 the archive is already available in the cache and stashs the MD5 for
2893 bool pkgAcqArchive::QueueNext()
2895 for (; Vf
.end() == false; ++Vf
)
2897 pkgCache::PkgFileIterator
const PkgF
= Vf
.File();
2898 // Ignore not source sources
2899 if (PkgF
.Flagged(pkgCache::Flag::NotSource
))
2902 // Try to cross match against the source list
2903 pkgIndexFile
*Index
;
2904 if (Sources
->FindIndex(PkgF
, Index
) == false)
2906 LocalSource
= PkgF
.Flagged(pkgCache::Flag::LocalSource
);
2908 // only try to get a trusted package from another source if that source
2910 if(Trusted
&& !Index
->IsTrusted())
2913 // Grab the text package record
2914 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2915 if (_error
->PendingError() == true)
2918 string PkgFile
= Parse
.FileName();
2919 ExpectedHashes
= Parse
.Hashes();
2921 if (PkgFile
.empty() == true)
2922 return _error
->Error(_("The package index files are corrupted. No Filename: "
2923 "field for package %s."),
2924 Version
.ParentPkg().Name());
2926 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
2927 Desc
.Description
= Index
->ArchiveInfo(Version
);
2929 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
2931 // See if we already have the file. (Legacy filenames)
2932 FileSize
= Version
->Size
;
2933 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
2935 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2937 // Make sure the size matches
2938 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2943 StoreFilename
= DestFile
= FinalFile
;
2947 /* Hmm, we have a file and its size does not match, this means it is
2948 an old style mismatched arch */
2949 RemoveFile("pkgAcqArchive::QueueNext", FinalFile
);
2952 // Check it again using the new style output filenames
2953 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
2954 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2956 // Make sure the size matches
2957 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2962 StoreFilename
= DestFile
= FinalFile
;
2966 /* Hmm, we have a file and its size does not match, this shouldn't
2968 RemoveFile("pkgAcqArchive::QueueNext", FinalFile
);
2971 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
2973 // Check the destination file
2974 if (stat(DestFile
.c_str(),&Buf
) == 0)
2976 // Hmm, the partial file is too big, erase it
2977 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
2978 RemoveFile("pkgAcqArchive::QueueNext", DestFile
);
2980 PartialSize
= Buf
.st_size
;
2983 // Disables download of archives - useful if no real installation follows,
2984 // e.g. if we are just interested in proposed installation order
2985 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2990 StoreFilename
= DestFile
= FinalFile
;
3004 // AcqArchive::Done - Finished fetching /*{{{*/
3005 // ---------------------------------------------------------------------
3007 void pkgAcqArchive::Done(string
const &Message
, HashStringList
const &Hashes
,
3008 pkgAcquire::MethodConfig
const * const Cfg
)
3010 Item::Done(Message
, Hashes
, Cfg
);
3012 // Grab the output filename
3013 std::string
const FileName
= LookupTag(Message
,"Filename");
3014 if (DestFile
!= FileName
&& RealFileExists(DestFile
) == false)
3016 StoreFilename
= DestFile
= FileName
;
3022 // Done, move it into position
3023 string
const FinalFile
= GetFinalFilename();
3024 Rename(DestFile
,FinalFile
);
3025 StoreFilename
= DestFile
= FinalFile
;
3029 // AcqArchive::Failed - Failure handler /*{{{*/
3030 // ---------------------------------------------------------------------
3031 /* Here we try other sources */
3032 void pkgAcqArchive::Failed(string
const &Message
,pkgAcquire::MethodConfig
const * const Cnf
)
3034 Item::Failed(Message
,Cnf
);
3036 /* We don't really want to retry on failed media swaps, this prevents
3037 that. An interesting observation is that permanent failures are not
3039 if (Cnf
->Removable
== true &&
3040 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3042 // Vf = Version.FileList();
3043 while (Vf
.end() == false) ++Vf
;
3044 StoreFilename
= string();
3049 if (QueueNext() == false)
3051 // This is the retry counter
3053 Cnf
->LocalOnly
== false &&
3054 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3057 Vf
= Version
.FileList();
3058 if (QueueNext() == true)
3062 StoreFilename
= string();
3067 APT_PURE
bool pkgAcqArchive::IsTrusted() const /*{{{*/
3072 void pkgAcqArchive::Finished() /*{{{*/
3074 if (Status
== pkgAcquire::Item::StatDone
&&
3077 StoreFilename
= string();
3080 std::string
pkgAcqArchive::DescURI() const /*{{{*/
3085 std::string
pkgAcqArchive::ShortDesc() const /*{{{*/
3087 return Desc
.ShortDesc
;
3090 pkgAcqArchive::~pkgAcqArchive() {}
3092 // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
3093 class pkgAcqChangelog::Private
3096 std::string FinalFile
;
3098 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::VerIterator
const &Ver
,
3099 std::string
const &DestDir
, std::string
const &DestFilename
) :
3100 pkgAcquire::Item(Owner
), d(new pkgAcqChangelog::Private()), SrcName(Ver
.SourcePkgName()), SrcVersion(Ver
.SourceVerStr())
3102 Desc
.URI
= URI(Ver
);
3103 Init(DestDir
, DestFilename
);
3105 // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
3106 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
, pkgCache::RlsFileIterator
const &RlsFile
,
3107 char const * const Component
, char const * const SrcName
, char const * const SrcVersion
,
3108 const string
&DestDir
, const string
&DestFilename
) :
3109 pkgAcquire::Item(Owner
), d(new pkgAcqChangelog::Private()), SrcName(SrcName
), SrcVersion(SrcVersion
)
3111 Desc
.URI
= URI(RlsFile
, Component
, SrcName
, SrcVersion
);
3112 Init(DestDir
, DestFilename
);
3114 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire
* const Owner
,
3115 std::string
const &URI
, char const * const SrcName
, char const * const SrcVersion
,
3116 const string
&DestDir
, const string
&DestFilename
) :
3117 pkgAcquire::Item(Owner
), d(new pkgAcqChangelog::Private()), SrcName(SrcName
), SrcVersion(SrcVersion
)
3120 Init(DestDir
, DestFilename
);
3122 void pkgAcqChangelog::Init(std::string
const &DestDir
, std::string
const &DestFilename
)
3124 if (Desc
.URI
.empty())
3127 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3128 strprintf(ErrorText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3129 // Let the error message print something sensible rather than "Failed to fetch /"
3130 if (DestFilename
.empty())
3131 DestFile
= SrcName
+ ".changelog";
3133 DestFile
= DestFilename
;
3134 Desc
.URI
= "changelog:/" + DestFile
;
3138 std::string DestFileName
;
3139 if (DestFilename
.empty())
3140 DestFileName
= flCombine(DestFile
, SrcName
+ ".changelog");
3142 DestFileName
= flCombine(DestFile
, DestFilename
);
3144 std::string
const SandboxUser
= _config
->Find("APT::Sandbox::User");
3145 std::string
const systemTemp
= GetTempDir(SandboxUser
);
3147 snprintf(tmpname
, sizeof(tmpname
), "%s/apt-changelog-XXXXXX", systemTemp
.c_str());
3148 if (NULL
== mkdtemp(tmpname
))
3150 _error
->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName
.c_str(), SrcVersion
.c_str());
3154 TemporaryDirectory
= tmpname
;
3156 ChangeOwnerAndPermissionOfFile("Item::QueueURI", TemporaryDirectory
.c_str(),
3157 SandboxUser
.c_str(), "root", 0700);
3159 DestFile
= flCombine(TemporaryDirectory
, DestFileName
);
3160 if (DestDir
.empty() == false)
3162 d
->FinalFile
= flCombine(DestDir
, DestFileName
);
3163 if (RealFileExists(d
->FinalFile
))
3165 FileFd file1
, file2
;
3166 if (file1
.Open(DestFile
, FileFd::WriteOnly
| FileFd::Create
| FileFd::Exclusive
) &&
3167 file2
.Open(d
->FinalFile
, FileFd::ReadOnly
) && CopyFile(file2
, file1
))
3169 struct timeval times
[2];
3170 times
[0].tv_sec
= times
[1].tv_sec
= file2
.ModificationTime();
3171 times
[0].tv_usec
= times
[1].tv_usec
= 0;
3172 utimes(DestFile
.c_str(), times
);
3177 Desc
.ShortDesc
= "Changelog";
3178 strprintf(Desc
.Description
, "%s %s %s Changelog", URI::SiteOnly(Desc
.URI
).c_str(), SrcName
.c_str(), SrcVersion
.c_str());
3183 std::string
pkgAcqChangelog::URI(pkgCache::VerIterator
const &Ver
) /*{{{*/
3185 std::string
const confOnline
= "Acquire::Changelogs::AlwaysOnline";
3186 bool AlwaysOnline
= _config
->FindB(confOnline
, false);
3187 if (AlwaysOnline
== false)
3188 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
3190 pkgCache::PkgFileIterator
const PF
= VF
.File();
3191 if (PF
.Flagged(pkgCache::Flag::NotSource
) || PF
->Release
== 0)
3193 pkgCache::RlsFileIterator
const RF
= PF
.ReleaseFile();
3194 if (RF
->Origin
!= 0 && _config
->FindB(confOnline
+ "::Origin::" + RF
.Origin(), false))
3196 AlwaysOnline
= true;
3200 if (AlwaysOnline
== false)
3202 pkgCache::PkgIterator
const Pkg
= Ver
.ParentPkg();
3203 if (Pkg
->CurrentVer
!= 0 && Pkg
.CurrentVer() == Ver
)
3205 std::string
const basename
= std::string("/usr/share/doc/") + Pkg
.Name() + "/changelog";
3206 std::string
const debianname
= basename
+ ".Debian";
3207 if (FileExists(debianname
))
3208 return "copy://" + debianname
;
3209 else if (FileExists(debianname
+ ".gz"))
3210 return "gzip://" + debianname
+ ".gz";
3211 else if (FileExists(basename
))
3212 return "copy://" + basename
;
3213 else if (FileExists(basename
+ ".gz"))
3214 return "gzip://" + basename
+ ".gz";
3218 char const * const SrcName
= Ver
.SourcePkgName();
3219 char const * const SrcVersion
= Ver
.SourceVerStr();
3220 // find the first source for this version which promises a changelog
3221 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
3223 pkgCache::PkgFileIterator
const PF
= VF
.File();
3224 if (PF
.Flagged(pkgCache::Flag::NotSource
) || PF
->Release
== 0)
3226 pkgCache::RlsFileIterator
const RF
= PF
.ReleaseFile();
3227 std::string
const uri
= URI(RF
, PF
.Component(), SrcName
, SrcVersion
);
3234 std::string
pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator
const &Rls
)
3236 if (Rls
.end() == true || (Rls
->Label
== 0 && Rls
->Origin
== 0))
3238 std::string
const serverConfig
= "Acquire::Changelogs::URI";
3240 #define APT_EMPTY_SERVER \
3241 if (server.empty() == false) \
3243 if (server != "no") \
3247 #define APT_CHECK_SERVER(X, Y) \
3250 std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
3251 server = _config->Find(specialServerConfig); \
3254 // this way e.g. Debian-Security can fallback to Debian
3255 APT_CHECK_SERVER(Label
, "Override::")
3256 APT_CHECK_SERVER(Origin
, "Override::")
3258 if (RealFileExists(Rls
.FileName()))
3260 _error
->PushToStack();
3262 /* This can be costly. A caller wanting to get millions of URIs might
3263 want to do this on its own once and use Override settings.
3264 We don't do this here as Origin/Label are not as unique as they
3265 should be so this could produce request order-dependent anomalies */
3266 if (OpenMaybeClearSignedFile(Rls
.FileName(), rf
) == true)
3268 pkgTagFile
TagFile(&rf
, rf
.Size());
3269 pkgTagSection Section
;
3270 if (TagFile
.Step(Section
) == true)
3271 server
= Section
.FindS("Changelogs");
3273 _error
->RevertToStack();
3277 APT_CHECK_SERVER(Label
, "")
3278 APT_CHECK_SERVER(Origin
, "")
3279 #undef APT_CHECK_SERVER
3280 #undef APT_EMPTY_SERVER
3283 std::string
pkgAcqChangelog::URI(pkgCache::RlsFileIterator
const &Rls
,
3284 char const * const Component
, char const * const SrcName
,
3285 char const * const SrcVersion
)
3287 return URI(URITemplate(Rls
), Component
, SrcName
, SrcVersion
);
3289 std::string
pkgAcqChangelog::URI(std::string
const &Template
,
3290 char const * const Component
, char const * const SrcName
,
3291 char const * const SrcVersion
)
3293 if (Template
.find("@CHANGEPATH@") == std::string::npos
)
3296 // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
3297 std::string Src
= SrcName
;
3298 std::string path
= APT::String::Startswith(SrcName
, "lib") ? Src
.substr(0, 4) : Src
.substr(0,1);
3299 path
.append("/").append(Src
).append("/");
3300 path
.append(Src
).append("_").append(StripEpoch(SrcVersion
));
3301 // we omit component for releases without one (= flat-style repositories)
3302 if (Component
!= NULL
&& strlen(Component
) != 0)
3303 path
= std::string(Component
) + "/" + path
;
3305 return SubstVar(Template
, "@CHANGEPATH@", path
);
3308 // AcqChangelog::Failed - Failure handler /*{{{*/
3309 void pkgAcqChangelog::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3311 Item::Failed(Message
,Cnf
);
3313 std::string errText
;
3314 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3315 strprintf(errText
, _("Changelog unavailable for %s=%s"), SrcName
.c_str(), SrcVersion
.c_str());
3317 // Error is probably something techy like 404 Not Found
3318 if (ErrorText
.empty())
3319 ErrorText
= errText
;
3321 ErrorText
= errText
+ " (" + ErrorText
+ ")";
3324 // AcqChangelog::Done - Item downloaded OK /*{{{*/
3325 void pkgAcqChangelog::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3326 pkgAcquire::MethodConfig
const * const Cnf
)
3328 Item::Done(Message
,CalcHashes
,Cnf
);
3329 if (d
->FinalFile
.empty() == false)
3331 if (RemoveFile("pkgAcqChangelog::Done", d
->FinalFile
) == false ||
3332 Rename(DestFile
, d
->FinalFile
) == false)
3339 pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
3341 if (TemporaryDirectory
.empty() == false)
3343 RemoveFile("~pkgAcqChangelog", DestFile
);
3344 rmdir(TemporaryDirectory
.c_str());
3350 // AcqFile::pkgAcqFile - Constructor /*{{{*/
3351 pkgAcqFile::pkgAcqFile(pkgAcquire
* const Owner
,string
const &URI
, HashStringList
const &Hashes
,
3352 unsigned long long const Size
,string
const &Dsc
,string
const &ShortDesc
,
3353 const string
&DestDir
, const string
&DestFilename
,
3354 bool const IsIndexFile
) :
3355 Item(Owner
), d(NULL
), IsIndexFile(IsIndexFile
), ExpectedHashes(Hashes
)
3357 Retries
= _config
->FindI("Acquire::Retries",0);
3359 if(!DestFilename
.empty())
3360 DestFile
= DestFilename
;
3361 else if(!DestDir
.empty())
3362 DestFile
= DestDir
+ "/" + flNotDir(URI
);
3364 DestFile
= flNotDir(URI
);
3368 Desc
.Description
= Dsc
;
3371 // Set the short description to the archive component
3372 Desc
.ShortDesc
= ShortDesc
;
3374 // Get the transfer sizes
3377 if (stat(DestFile
.c_str(),&Buf
) == 0)
3379 // Hmm, the partial file is too big, erase it
3380 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
3381 RemoveFile("pkgAcqFile", DestFile
);
3383 PartialSize
= Buf
.st_size
;
3389 // AcqFile::Done - Item downloaded OK /*{{{*/
3390 void pkgAcqFile::Done(string
const &Message
,HashStringList
const &CalcHashes
,
3391 pkgAcquire::MethodConfig
const * const Cnf
)
3393 Item::Done(Message
,CalcHashes
,Cnf
);
3395 std::string
const FileName
= LookupTag(Message
,"Filename");
3398 // The files timestamp matches
3399 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
3402 // We have to copy it into place
3403 if (RealFileExists(DestFile
.c_str()) == false)
3406 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
3407 Cnf
->Removable
== true)
3409 Desc
.URI
= "copy:" + FileName
;
3414 // Erase the file if it is a symlink so we can overwrite it
3416 if (lstat(DestFile
.c_str(),&St
) == 0)
3418 if (S_ISLNK(St
.st_mode
) != 0)
3419 RemoveFile("pkgAcqFile::Done", DestFile
);
3423 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
3425 _error
->PushToStack();
3426 _error
->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile
.c_str());
3427 std::stringstream msg
;
3428 _error
->DumpErrors(msg
, GlobalError::DEBUG
, false);
3429 _error
->RevertToStack();
3430 ErrorText
= msg
.str();
3437 // AcqFile::Failed - Failure handler /*{{{*/
3438 // ---------------------------------------------------------------------
3439 /* Here we try other sources */
3440 void pkgAcqFile::Failed(string
const &Message
, pkgAcquire::MethodConfig
const * const Cnf
)
3442 Item::Failed(Message
,Cnf
);
3444 // This is the retry counter
3446 Cnf
->LocalOnly
== false &&
3447 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
3457 string
pkgAcqFile::Custom600Headers() const /*{{{*/
3460 return "\nIndex-File: true";
3464 pkgAcqFile::~pkgAcqFile() {}