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/sha1.h>
26 #include <apt-pkg/tagfile.h>
27 #include <apt-pkg/indexrecords.h>
28 #include <apt-pkg/acquire.h>
29 #include <apt-pkg/hashes.h>
30 #include <apt-pkg/indexfile.h>
31 #include <apt-pkg/pkgcache.h>
32 #include <apt-pkg/cacheiterators.h>
33 #include <apt-pkg/pkgrecords.h>
53 static void printHashSumComparision(std::string
const &URI
, HashStringList
const &Expected
, HashStringList
const &Actual
) /*{{{*/
55 if (_config
->FindB("Debug::Acquire::HashSumMismatch", false) == false)
57 std::cerr
<< std::endl
<< URI
<< ":" << std::endl
<< " Expected Hash: " << std::endl
;
58 for (HashStringList::const_iterator hs
= Expected
.begin(); hs
!= Expected
.end(); ++hs
)
59 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
60 std::cerr
<< " Actual Hash: " << std::endl
;
61 for (HashStringList::const_iterator hs
= Actual
.begin(); hs
!= Actual
.end(); ++hs
)
62 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
66 // Acquire::Item::Item - Constructor /*{{{*/
68 #pragma GCC diagnostic push
69 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
71 pkgAcquire::Item::Item(pkgAcquire
*Owner
,
72 HashStringList
const &ExpectedHashes
,
73 pkgAcqMetaBase
*TransactionManager
)
74 : Owner(Owner
), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
75 Local(false), QueueCounter(0), TransactionManager(TransactionManager
),
76 ExpectedAdditionalItems(0), ExpectedHashes(ExpectedHashes
)
80 if(TransactionManager
!= NULL
)
81 TransactionManager
->Add(this);
84 #pragma GCC diagnostic pop
87 // Acquire::Item::~Item - Destructor /*{{{*/
88 // ---------------------------------------------------------------------
90 pkgAcquire::Item::~Item()
95 // Acquire::Item::Failed - Item failed to download /*{{{*/
96 // ---------------------------------------------------------------------
97 /* We return to an idle state if there are still other queues that could
99 void pkgAcquire::Item::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
103 ErrorText
= LookupTag(Message
,"Message");
104 UsedMirror
= LookupTag(Message
,"UsedMirror");
105 if (QueueCounter
<= 1)
107 /* This indicates that the file is not available right now but might
108 be sometime later. If we do a retry cycle then this should be
110 if (Cnf
->LocalOnly
== true &&
111 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
122 // report mirror failure back to LP if we actually use a mirror
123 string FailReason
= LookupTag(Message
, "FailReason");
124 if(FailReason
.size() != 0)
125 ReportMirrorFailure(FailReason
);
127 ReportMirrorFailure(ErrorText
);
130 // Acquire::Item::Start - Item has begun to download /*{{{*/
131 // ---------------------------------------------------------------------
132 /* Stash status and the file size. Note that setting Complete means
133 sub-phases of the acquire process such as decompresion are operating */
134 void pkgAcquire::Item::Start(string
/*Message*/,unsigned long long Size
)
136 Status
= StatFetching
;
137 if (FileSize
== 0 && Complete
== false)
141 // Acquire::Item::Done - Item downloaded OK /*{{{*/
142 // ---------------------------------------------------------------------
144 void pkgAcquire::Item::Done(string Message
,unsigned long long Size
,HashStringList
const &/*Hash*/,
145 pkgAcquire::MethodConfig
* /*Cnf*/)
147 // We just downloaded something..
148 string FileName
= LookupTag(Message
,"Filename");
149 UsedMirror
= LookupTag(Message
,"UsedMirror");
150 if (Complete
== false && !Local
&& FileName
== DestFile
)
153 Owner
->Log
->Fetched(Size
,atoi(LookupTag(Message
,"Resume-Point","0").c_str()));
159 ErrorText
= string();
160 Owner
->Dequeue(this);
163 // Acquire::Item::Rename - Rename a file /*{{{*/
164 // ---------------------------------------------------------------------
165 /* This helper function is used by a lot of item methods as their final
167 bool pkgAcquire::Item::Rename(string From
,string To
)
169 if (rename(From
.c_str(),To
.c_str()) != 0)
172 snprintf(S
,sizeof(S
),_("rename failed, %s (%s -> %s)."),strerror(errno
),
173 From
.c_str(),To
.c_str());
181 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
183 if(FileExists(DestFile
))
184 Rename(DestFile
, DestFile
+ ".FAILED");
188 case HashSumMismatch
:
189 ErrorText
= _("Hash Sum mismatch");
190 Status
= StatAuthError
;
191 ReportMirrorFailure("HashChecksumFailure");
194 ErrorText
= _("Size mismatch");
195 Status
= StatAuthError
;
196 ReportMirrorFailure("SizeFailure");
199 ErrorText
= _("Invalid file format");
201 // do not report as usually its not the mirrors fault, but Portal/Proxy
204 ErrorText
= _("Signature error");
208 ErrorText
= _("Does not start with a cleartext signature");
215 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)
217 ActiveSubprocess
= subprocess
;
219 #pragma GCC diagnostic push
220 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
222 Mode
= ActiveSubprocess
.c_str();
224 #pragma GCC diagnostic pop
228 // Acquire::Item::ReportMirrorFailure /*{{{*/
229 // ---------------------------------------------------------------------
230 void pkgAcquire::Item::ReportMirrorFailure(string FailCode
)
232 // we only act if a mirror was used at all
233 if(UsedMirror
.empty())
236 std::cerr
<< "\nReportMirrorFailure: "
238 << " Uri: " << DescURI()
240 << FailCode
<< std::endl
;
242 const char *Args
[40];
244 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
245 "/usr/lib/apt/apt-report-mirror-failure");
246 if(!FileExists(report
))
248 Args
[i
++] = report
.c_str();
249 Args
[i
++] = UsedMirror
.c_str();
250 Args
[i
++] = DescURI().c_str();
251 Args
[i
++] = FailCode
.c_str();
253 pid_t pid
= ExecFork();
256 _error
->Error("ReportMirrorFailure Fork failed");
261 execvp(Args
[0], (char**)Args
);
262 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
265 if(!ExecWait(pid
, "report-mirror-failure"))
267 _error
->Warning("Couldn't report problem to '%s'",
268 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
272 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
273 // ---------------------------------------------------------------------
274 /* Get the DiffIndex file first and see if there are patches available
275 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
276 * patches. If anything goes wrong in that process, it will fall back to
277 * the original packages file
279 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
*Owner
,
280 pkgAcqMetaBase
*TransactionManager
,
281 IndexTarget
const * const Target
,
282 HashStringList
const &ExpectedHashes
,
283 indexRecords
*MetaIndexParser
)
284 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
,
285 MetaIndexParser
), PackagesFileReadyInPartial(false)
288 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
290 RealURI
= Target
->URI
;
292 Desc
.Description
= Target
->Description
+ "/DiffIndex";
293 Desc
.ShortDesc
= Target
->ShortDesc
;
294 Desc
.URI
= Target
->URI
+ ".diff/Index";
296 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
297 DestFile
+= URItoFileName(Desc
.URI
);
300 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
302 // look for the current package file
303 CurrentPackagesFile
= _config
->FindDir("Dir::State::lists");
304 CurrentPackagesFile
+= URItoFileName(RealURI
);
306 // FIXME: this file:/ check is a hack to prevent fetching
307 // from local sources. this is really silly, and
308 // should be fixed cleanly as soon as possible
309 if(!FileExists(CurrentPackagesFile
) ||
310 Desc
.URI
.substr(0,strlen("file:/")) == "file:/")
312 // we don't have a pkg file or we don't want to queue
314 std::clog
<< "No index file, local or canceld by user" << std::endl
;
320 std::clog
<< "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
321 << CurrentPackagesFile
<< std::endl
;
327 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
328 // ---------------------------------------------------------------------
329 /* The only header we use is the last-modified header. */
330 string
pkgAcqDiffIndex::Custom600Headers() const
332 string Final
= _config
->FindDir("Dir::State::lists");
333 Final
+= URItoFileName(Desc
.URI
);
336 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
339 if (stat(Final
.c_str(),&Buf
) != 0)
340 return "\nIndex-File: true";
342 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
345 bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile
) /*{{{*/
348 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
353 vector
<DiffInfo
> available_patches
;
355 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
357 if (_error
->PendingError() == true)
360 if(TF
.Step(Tags
) == true)
366 string
const tmp
= Tags
.FindS("SHA1-Current");
367 std::stringstream
ss(tmp
);
368 ss
>> ServerSha1
>> size
;
369 unsigned long const ServerSize
= atol(size
.c_str());
371 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
);
374 string
const local_sha1
= SHA1
.Result();
376 if(local_sha1
== ServerSha1
)
378 // we have the same sha1 as the server so we are done here
380 std::clog
<< "Package file is up-to-date" << std::endl
;
381 // ensure we have no leftovers from previous runs
382 std::string Partial
= _config
->FindDir("Dir::State::lists");
383 Partial
+= "partial/" + URItoFileName(RealURI
);
384 unlink(Partial
.c_str());
385 // list cleanup needs to know that this file as well as the already
386 // present index is ours, so we create an empty diff to save it for us
387 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
388 ExpectedHashes
, MetaIndexParser
,
389 ServerSha1
, available_patches
);
395 std::clog
<< "SHA1-Current: " << ServerSha1
<< " and we start at "<< fd
.Name() << " " << fd
.Size() << " " << local_sha1
<< std::endl
;
397 // check the historie and see what patches we need
398 string
const history
= Tags
.FindS("SHA1-History");
399 std::stringstream
hist(history
);
400 while(hist
>> d
.sha1
>> size
>> d
.file
)
402 // read until the first match is found
403 // from that point on, we probably need all diffs
404 if(d
.sha1
== local_sha1
)
406 else if (found
== false)
410 std::clog
<< "Need to get diff: " << d
.file
<< std::endl
;
411 available_patches
.push_back(d
);
414 if (available_patches
.empty() == false)
416 // patching with too many files is rather slow compared to a fast download
417 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
418 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
421 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
422 << ") so fallback to complete download" << std::endl
;
426 // see if the patches are too big
427 found
= false; // it was true and it will be true again at the end
428 d
= *available_patches
.begin();
429 string
const firstPatch
= d
.file
;
430 unsigned long patchesSize
= 0;
431 std::stringstream
patches(Tags
.FindS("SHA1-Patches"));
432 while(patches
>> d
.sha1
>> size
>> d
.file
)
434 if (firstPatch
== d
.file
)
436 else if (found
== false)
439 patchesSize
+= atol(size
.c_str());
441 unsigned long const sizeLimit
= ServerSize
* _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
442 if (sizeLimit
> 0 && (sizeLimit
/100) < patchesSize
)
445 std::clog
<< "Need " << patchesSize
<< " bytes (Limit is " << sizeLimit
/100
446 << ") so fallback to complete download" << std::endl
;
452 // we have something, queue the next diff
455 // FIXME: make this use the method
456 PackagesFileReadyInPartial
= true;
457 std::string Partial
= _config
->FindDir("Dir::State::lists");
458 Partial
+= "partial/" + URItoFileName(RealURI
);
460 FileFd
From(CurrentPackagesFile
, FileFd::ReadOnly
);
461 FileFd
To(Partial
, FileFd::WriteEmpty
);
462 if(CopyFile(From
, To
) == false)
463 return _error
->Errno("CopyFile", "failed to copy");
466 std::cerr
<< "Done copying " << CurrentPackagesFile
471 string::size_type
const last_space
= Description
.rfind(" ");
472 if(last_space
!= string::npos
)
473 Description
.erase(last_space
, Description
.size()-last_space
);
475 /* decide if we should download patches one by one or in one go:
476 The first is good if the server merges patches, but many don't so client
477 based merging can be attempt in which case the second is better.
478 "bad things" will happen if patches are merged on the server,
479 but client side merging is attempt as well */
480 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
481 if (pdiff_merge
== true)
483 // reprepro adds this flag if it has merged patches on the server
484 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
485 pdiff_merge
= (precedence
!= "merged");
488 if (pdiff_merge
== false)
490 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, ExpectedHashes
,
492 ServerSha1
, available_patches
);
496 std::vector
<pkgAcqIndexMergeDiffs
*> *diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
497 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
498 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
,
503 available_patches
[i
],
514 // Nothing found, report and return false
515 // Failing here is ok, if we return false later, the full
516 // IndexFile is queued
518 std::clog
<< "Can't find a patch in the index file" << std::endl
;
522 void pkgAcqDiffIndex::Failed(string Message
,pkgAcquire::MethodConfig
* /*Cnf*/)/*{{{*/
525 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
526 << "Falling back to normal index file acquire" << std::endl
;
528 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
535 void pkgAcqDiffIndex::Done(string Message
,unsigned long long Size
,HashStringList
const &Hashes
, /*{{{*/
536 pkgAcquire::MethodConfig
*Cnf
)
539 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
541 Item::Done(Message
, Size
, Hashes
, Cnf
);
543 // verify the index target
544 if(Target
&& Target
->MetaKey
!= "" && MetaIndexParser
&& Hashes
.usable())
546 std::string IndexMetaKey
= Target
->MetaKey
+ ".diff/Index";
547 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(IndexMetaKey
);
548 if(Record
&& Record
->Hashes
.usable() && Hashes
!= Record
->Hashes
)
550 RenameOnError(HashSumMismatch
);
551 printHashSumComparision(RealURI
, Record
->Hashes
, Hashes
);
552 Failed(Message
, Cnf
);
558 if(!ParseDiffIndex(DestFile
))
559 return Failed("", NULL
);
561 // queue for final move
563 FinalFile
= _config
->FindDir("Dir::State::lists")+URItoFileName(RealURI
);
564 FinalFile
+= string(".IndexDiff");
565 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
573 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
574 // ---------------------------------------------------------------------
575 /* The package diff is added to the queue. one object is constructed
576 * for each diff and the index
578 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
*Owner
,
579 pkgAcqMetaBase
*TransactionManager
,
580 struct IndexTarget
const * const Target
,
581 HashStringList
const &ExpectedHashes
,
582 indexRecords
*MetaIndexParser
,
584 vector
<DiffInfo
> diffs
)
585 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
),
586 available_patches(diffs
), ServerSha1(ServerSha1
)
589 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
590 DestFile
+= URItoFileName(Target
->URI
);
592 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
594 RealURI
= Target
->URI
;
596 Description
= Target
->Description
;
597 Desc
.ShortDesc
= Target
->ShortDesc
;
599 if(available_patches
.empty() == true)
601 // we are done (yeah!), check hashes against the final file
602 DestFile
= _config
->FindDir("Dir::State::lists");
603 DestFile
+= URItoFileName(Target
->URI
);
609 State
= StateFetchDiff
;
614 void pkgAcqIndexDiffs::Failed(string Message
,pkgAcquire::MethodConfig
* /*Cnf*/)/*{{{*/
617 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
618 << "Falling back to normal index file acquire" << std::endl
;
619 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
623 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
624 void pkgAcqIndexDiffs::Finish(bool allDone
)
627 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
629 << Desc
.URI
<< std::endl
;
631 // we restore the original name, this is required, otherwise
632 // the file will be cleaned
635 if(HashSums().usable() && !HashSums().VerifyFile(DestFile
))
637 RenameOnError(HashSumMismatch
);
643 PartialFile
= _config
->FindDir("Dir::State::lists")+"partial/"+URItoFileName(RealURI
);
645 DestFile
= _config
->FindDir("Dir::State::lists");
646 DestFile
+= URItoFileName(RealURI
);
648 // this happens if we have a up-to-date indexfile
649 if(!FileExists(PartialFile
))
650 PartialFile
= DestFile
;
652 TransactionManager
->TransactionStageCopy(this, PartialFile
, DestFile
);
654 // this is for the "real" finish
659 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
664 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
671 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
673 // calc sha1 of the just patched file
674 string FinalFile
= _config
->FindDir("Dir::State::lists");
675 FinalFile
+= "partial/" + URItoFileName(RealURI
);
677 if(!FileExists(FinalFile
))
679 Failed("No FinalFile " + FinalFile
+ " available", NULL
);
683 FileFd
fd(FinalFile
, FileFd::ReadOnly
);
686 string local_sha1
= string(SHA1
.Result());
688 std::clog
<< "QueueNextDiff: "
689 << FinalFile
<< " (" << local_sha1
<< ")"<<std::endl
;
692 // final file reached before all patches are applied
693 if(local_sha1
== ServerSha1
)
699 // remove all patches until the next matching patch is found
700 // this requires the Index file to be ordered
701 for(vector
<DiffInfo
>::iterator I
=available_patches
.begin();
702 available_patches
.empty() == false &&
703 I
!= available_patches
.end() &&
704 I
->sha1
!= local_sha1
;
707 available_patches
.erase(I
);
710 // error checking and falling back if no patch was found
711 if(available_patches
.empty() == true)
713 Failed("No patches available", NULL
);
717 // queue the right diff
718 Desc
.URI
= RealURI
+ ".diff/" + available_patches
[0].file
+ ".gz";
719 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
720 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
721 DestFile
+= URItoFileName(RealURI
+ ".diff/" + available_patches
[0].file
);
724 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
731 void pkgAcqIndexDiffs::Done(string Message
,unsigned long long Size
, HashStringList
const &Hashes
, /*{{{*/
732 pkgAcquire::MethodConfig
*Cnf
)
735 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
737 Item::Done(Message
, Size
, Hashes
, Cnf
);
739 // FIXME: verify this download too before feeding it to rred
742 FinalFile
= _config
->FindDir("Dir::State::lists")+"partial/"+URItoFileName(RealURI
);
744 // success in downloading a diff, enter ApplyDiff state
745 if(State
== StateFetchDiff
)
748 // rred excepts the patch as $FinalFile.ed
749 Rename(DestFile
,FinalFile
+".ed");
752 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
754 State
= StateApplyDiff
;
756 Desc
.URI
= "rred:" + FinalFile
;
758 SetActiveSubprocess("rred");
763 // success in download/apply a diff, queue next (if needed)
764 if(State
== StateApplyDiff
)
766 // remove the just applied patch
767 available_patches
.erase(available_patches
.begin());
768 unlink((FinalFile
+ ".ed").c_str());
773 std::clog
<< "Moving patched file in place: " << std::endl
774 << DestFile
<< " -> " << FinalFile
<< std::endl
;
776 Rename(DestFile
,FinalFile
);
777 chmod(FinalFile
.c_str(),0644);
779 // see if there is more to download
780 if(available_patches
.empty() == false) {
781 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
782 ExpectedHashes
, MetaIndexParser
,
783 ServerSha1
, available_patches
);
787 DestFile
= FinalFile
;
792 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
793 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
*Owner
,
794 pkgAcqMetaBase
*TransactionManager
,
795 struct IndexTarget
const * const Target
,
796 HashStringList
const &ExpectedHashes
,
797 indexRecords
*MetaIndexParser
,
798 DiffInfo
const &patch
,
799 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
800 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
),
801 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
804 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
805 DestFile
+= URItoFileName(Target
->URI
);
807 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
809 RealURI
= Target
->URI
;
811 Description
= Target
->Description
;
812 Desc
.ShortDesc
= Target
->ShortDesc
;
814 Desc
.URI
= RealURI
+ ".diff/" + patch
.file
+ ".gz";
815 Desc
.Description
= Description
+ " " + patch
.file
+ string(".pdiff");
816 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
817 DestFile
+= URItoFileName(RealURI
+ ".diff/" + patch
.file
);
820 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
825 void pkgAcqIndexMergeDiffs::Failed(string Message
,pkgAcquire::MethodConfig
* /*Cnf*/)/*{{{*/
828 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
833 // check if we are the first to fail, otherwise we are done here
834 State
= StateDoneDiff
;
835 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
836 I
!= allPatches
->end(); ++I
)
837 if ((*I
)->State
== StateErrorDiff
)
840 // first failure means we should fallback
841 State
= StateErrorDiff
;
842 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
843 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
846 void pkgAcqIndexMergeDiffs::Done(string Message
,unsigned long long Size
,HashStringList
const &Hashes
, /*{{{*/
847 pkgAcquire::MethodConfig
*Cnf
)
850 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
852 Item::Done(Message
,Size
,Hashes
,Cnf
);
854 // FIXME: verify download before feeding it to rred
856 string
const FinalFile
= _config
->FindDir("Dir::State::lists") + "partial/" + URItoFileName(RealURI
);
858 if (State
== StateFetchDiff
)
860 // rred expects the patch as $FinalFile.ed.$patchname.gz
861 Rename(DestFile
, FinalFile
+ ".ed." + patch
.file
+ ".gz");
863 // check if this is the last completed diff
864 State
= StateDoneDiff
;
865 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
866 I
!= allPatches
->end(); ++I
)
867 if ((*I
)->State
!= StateDoneDiff
)
870 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
874 // this is the last completed diff, so we are ready to apply now
875 State
= StateApplyDiff
;
878 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
881 Desc
.URI
= "rred:" + FinalFile
;
883 SetActiveSubprocess("rred");
886 // success in download/apply all diffs, clean up
887 else if (State
== StateApplyDiff
)
889 // see if we really got the expected file
890 if(ExpectedHashes
.usable() && !ExpectedHashes
.VerifyFile(DestFile
))
892 RenameOnError(HashSumMismatch
);
897 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
898 FinalFile
+= URItoFileName(RealURI
);
900 // move the result into place
902 std::clog
<< "Queue patched file in place: " << std::endl
903 << DestFile
<< " -> " << FinalFile
<< std::endl
;
905 // queue for copy by the transaction manager
906 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
908 // ensure the ed's are gone regardless of list-cleanup
909 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
910 I
!= allPatches
->end(); ++I
)
912 std::string PartialFile
= _config
->FindDir("Dir::State::lists");
913 PartialFile
+= "partial/" + URItoFileName(RealURI
);
914 std::string patch
= PartialFile
+ ".ed." + (*I
)->patch
.file
+ ".gz";
915 std::cerr
<< patch
<< std::endl
;
916 unlink(patch
.c_str());
922 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
927 // AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
928 bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList
const &Hashes
)
930 if(MetaKey
!= "" && Hashes
.usable())
932 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
933 if(Record
&& Record
->Hashes
.usable() && Hashes
!= Record
->Hashes
)
935 printHashSumComparision(RealURI
, Record
->Hashes
, Hashes
);
943 // AcqIndex::AcqIndex - Constructor /*{{{*/
944 // ---------------------------------------------------------------------
945 /* The package file is added to the queue and a second class is
946 instantiated to fetch the revision file */
947 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
948 string URI
,string URIDesc
,string ShortDesc
,
949 HashStringList
const &ExpectedHash
)
950 : pkgAcqBaseIndex(Owner
, 0, NULL
, ExpectedHash
, NULL
)
954 AutoSelectCompression();
955 Init(URI
, URIDesc
, ShortDesc
);
957 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
958 std::clog
<< "New pkgIndex with TransactionManager "
959 << TransactionManager
<< std::endl
;
962 // AcqIndex::AcqIndex - Constructor /*{{{*/
963 // ---------------------------------------------------------------------
964 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
965 pkgAcqMetaBase
*TransactionManager
,
966 IndexTarget
const *Target
,
967 HashStringList
const &ExpectedHash
,
968 indexRecords
*MetaIndexParser
)
969 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHash
,
972 RealURI
= Target
->URI
;
974 // autoselect the compression method
975 AutoSelectCompression();
976 Init(Target
->URI
, Target
->Description
, Target
->ShortDesc
);
978 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
979 std::clog
<< "New pkgIndex with TransactionManager "
980 << TransactionManager
<< std::endl
;
983 // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
984 // ---------------------------------------------------------------------
985 void pkgAcqIndex::AutoSelectCompression()
987 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
988 CompressionExtensions
= "";
989 if (ExpectedHashes
.usable())
991 for (std::vector
<std::string
>::const_iterator t
= types
.begin();
992 t
!= types
.end(); ++t
)
994 std::string CompressedMetaKey
= string(Target
->MetaKey
).append(".").append(*t
);
995 if (*t
== "uncompressed" ||
996 MetaIndexParser
->Exists(CompressedMetaKey
) == true)
997 CompressionExtensions
.append(*t
).append(" ");
1002 for (std::vector
<std::string
>::const_iterator t
= types
.begin(); t
!= types
.end(); ++t
)
1003 CompressionExtensions
.append(*t
).append(" ");
1005 if (CompressionExtensions
.empty() == false)
1006 CompressionExtensions
.erase(CompressionExtensions
.end()-1);
1008 // AcqIndex::Init - defered Constructor /*{{{*/
1009 // ---------------------------------------------------------------------
1010 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
1011 string
const &ShortDesc
)
1013 Stage
= STAGE_DOWNLOAD
;
1015 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1016 DestFile
+= URItoFileName(URI
);
1018 CurrentCompressionExtension
= CompressionExtensions
.substr(0, CompressionExtensions
.find(' '));
1019 if (CurrentCompressionExtension
== "uncompressed")
1023 MetaKey
= string(Target
->MetaKey
);
1027 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
1028 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
1030 MetaKey
= string(Target
->MetaKey
) + '.' + CurrentCompressionExtension
;
1033 // load the filesize
1036 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1038 FileSize
= Record
->Size
;
1040 InitByHashIfNeeded(MetaKey
);
1043 Desc
.Description
= URIDesc
;
1045 Desc
.ShortDesc
= ShortDesc
;
1050 // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
1051 // ---------------------------------------------------------------------
1053 void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey
)
1056 // - (maybe?) add support for by-hash into the sources.list as flag
1057 // - make apt-ftparchive generate the hashes (and expire?)
1058 std::string HostKnob
= "APT::Acquire::" + ::URI(Desc
.URI
).Host
+ "::By-Hash";
1059 if(_config
->FindB("APT::Acquire::By-Hash", false) == true ||
1060 _config
->FindB(HostKnob
, false) == true ||
1061 MetaIndexParser
->GetSupportsAcquireByHash())
1063 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1066 // FIXME: should we really use the best hash here? or a fixed one?
1067 const HashString
*TargetHash
= Record
->Hashes
.find("");
1068 std::string ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
1069 size_t trailing_slash
= Desc
.URI
.find_last_of("/");
1070 Desc
.URI
= Desc
.URI
.replace(
1072 Desc
.URI
.substr(trailing_slash
+1).size()+1,
1076 "Fetching ByHash requested but can not find record for %s",
1082 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1083 // ---------------------------------------------------------------------
1084 /* The only header we use is the last-modified header. */
1085 string
pkgAcqIndex::Custom600Headers() const
1087 string Final
= GetFinalFilename();
1089 string msg
= "\nIndex-File: true";
1091 if (stat(Final
.c_str(),&Buf
) == 0)
1092 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1097 // pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
1098 // ---------------------------------------------------------------------
1100 void pkgAcqIndex::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
) /*{{{*/
1102 size_t const nextExt
= CompressionExtensions
.find(' ');
1103 if (nextExt
!= std::string::npos
)
1105 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
1106 Init(RealURI
, Desc
.Description
, Desc
.ShortDesc
);
1110 // on decompression failure, remove bad versions in partial/
1111 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
1113 unlink(EraseFileName
.c_str());
1116 Item::Failed(Message
,Cnf
);
1118 /// cancel the entire transaction
1119 TransactionManager
->AbortTransaction();
1122 // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
1123 // ---------------------------------------------------------------------
1125 std::string
pkgAcqIndex::GetFinalFilename() const
1127 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1128 FinalFile
+= URItoFileName(RealURI
);
1129 if (_config
->FindB("Acquire::GzipIndexes",false) == true)
1130 FinalFile
+= '.' + CurrentCompressionExtension
;
1134 // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
1135 // ---------------------------------------------------------------------
1137 void pkgAcqIndex::ReverifyAfterIMS()
1139 // update destfile to *not* include the compression extension when doing
1140 // a reverify (as its uncompressed on disk already)
1141 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1142 DestFile
+= URItoFileName(RealURI
);
1144 // adjust DestFile if its compressed on disk
1145 if (_config
->FindB("Acquire::GzipIndexes",false) == true)
1146 DestFile
+= '.' + CurrentCompressionExtension
;
1148 // copy FinalFile into partial/ so that we check the hash again
1149 string FinalFile
= GetFinalFilename();
1150 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1151 Desc
.URI
= "copy:" + FinalFile
;
1156 // AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
1157 // --------------------------------------------------------------------------
1158 bool pkgAcqIndex::ValidateFile(const std::string
&FileName
)
1160 // FIXME: this can go away once we only ever download stuff that
1161 // has a valid hash and we never do GET based probing
1162 // FIXME2: this also leaks debian-isms into the code and should go therefore
1164 /* Always validate the index file for correctness (all indexes must
1165 * have a Package field) (LP: #346386) (Closes: #627642)
1167 FileFd
fd(FileName
, FileFd::ReadOnly
, FileFd::Extension
);
1168 // Only test for correctness if the content of the file is not empty
1173 pkgTagFile
tag(&fd
);
1175 // all our current indexes have a field 'Package' in each section
1176 if (_error
->PendingError() == true ||
1177 tag
.Step(sec
) == false ||
1178 sec
.Exists("Package") == false)
1184 // AcqIndex::Done - Finished a fetch /*{{{*/
1185 // ---------------------------------------------------------------------
1186 /* This goes through a number of states.. On the initial fetch the
1187 method could possibly return an alternate filename which points
1188 to the uncompressed version of the file. If this is so the file
1189 is copied into the partial directory. In all other cases the file
1190 is decompressed with a compressed uri. */
1191 void pkgAcqIndex::Done(string Message
,
1192 unsigned long long Size
,
1193 HashStringList
const &Hashes
,
1194 pkgAcquire::MethodConfig
*Cfg
)
1196 Item::Done(Message
,Size
,Hashes
,Cfg
);
1200 case STAGE_DOWNLOAD
:
1201 StageDownloadDone(Message
, Hashes
, Cfg
);
1203 case STAGE_DECOMPRESS_AND_VERIFY
:
1204 StageDecompressDone(Message
, Hashes
, Cfg
);
1209 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
1210 void pkgAcqIndex::StageDownloadDone(string Message
,
1211 HashStringList
const &Hashes
,
1212 pkgAcquire::MethodConfig
*Cfg
)
1214 // First check if the calculcated Hash of the (compressed) downloaded
1215 // file matches the hash we have in the MetaIndexRecords for this file
1216 if(VerifyHashByMetaKey(Hashes
) == false)
1218 RenameOnError(HashSumMismatch
);
1219 Failed(Message
, Cfg
);
1225 // Handle the unzipd case
1226 string FileName
= LookupTag(Message
,"Alt-Filename");
1227 if (FileName
.empty() == false)
1229 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1231 DestFile
+= ".decomp";
1232 Desc
.URI
= "copy:" + FileName
;
1234 SetActiveSubprocess("copy");
1238 FileName
= LookupTag(Message
,"Filename");
1239 if (FileName
.empty() == true)
1242 ErrorText
= "Method gave a blank filename";
1245 // Methods like e.g. "file:" will give us a (compressed) FileName that is
1246 // not the "DestFile" we set, in this case we uncompress from the local file
1247 if (FileName
!= DestFile
)
1250 EraseFileName
= FileName
;
1252 // we need to verify the file against the current Release file again
1253 // on if-modfied-since hit to avoid a stale attack against us
1254 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
1256 // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
1257 // file when its doing the indexcopy
1258 if (RealURI
.substr(0,6) == "cdrom:")
1261 // The files timestamp matches, reverify by copy into partial/
1267 // If we have compressed indexes enabled, queue for hash verification
1268 if (_config
->FindB("Acquire::GzipIndexes",false))
1270 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1271 DestFile
+= URItoFileName(RealURI
) + '.' + CurrentCompressionExtension
;
1273 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1274 Desc
.URI
= "copy:" + FileName
;
1280 // get the binary name for your used compression type
1282 if(CurrentCompressionExtension
== "uncompressed")
1283 decompProg
= "copy";
1285 decompProg
= _config
->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension
),"");
1286 if(decompProg
.empty() == true)
1288 _error
->Error("Unsupported extension: %s", CurrentCompressionExtension
.c_str());
1292 // queue uri for the next stage
1293 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1294 DestFile
+= ".decomp";
1295 Desc
.URI
= decompProg
+ ":" + FileName
;
1298 SetActiveSubprocess(decompProg
);
1301 // pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
1302 void pkgAcqIndex::StageDecompressDone(string Message
,
1303 HashStringList
const &Hashes
,
1304 pkgAcquire::MethodConfig
*Cfg
)
1306 if (ExpectedHashes
.usable() && ExpectedHashes
!= Hashes
)
1309 RenameOnError(HashSumMismatch
);
1310 printHashSumComparision(RealURI
, ExpectedHashes
, Hashes
);
1311 Failed(Message
, Cfg
);
1315 if(!ValidateFile(DestFile
))
1317 RenameOnError(InvalidFormat
);
1318 Failed(Message
, Cfg
);
1322 // remove the compressed version of the file
1323 unlink(EraseFileName
.c_str());
1325 // Done, queue for rename on transaction finished
1326 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1332 // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
1333 // ---------------------------------------------------------------------
1334 /* The Translation file is added to the queue */
1335 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
1336 string URI
,string URIDesc
,string ShortDesc
)
1337 : pkgAcqIndex(Owner
, URI
, URIDesc
, ShortDesc
, HashStringList())
1341 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
1342 pkgAcqMetaBase
*TransactionManager
,
1343 IndexTarget
const * const Target
,
1344 HashStringList
const &ExpectedHashes
,
1345 indexRecords
*MetaIndexParser
)
1346 : pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
)
1348 // load the filesize
1349 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(string(Target
->MetaKey
));
1351 FileSize
= Record
->Size
;
1354 // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
1355 // ---------------------------------------------------------------------
1356 string
pkgAcqIndexTrans::Custom600Headers() const
1358 string Final
= GetFinalFilename();
1361 if (stat(Final
.c_str(),&Buf
) != 0)
1362 return "\nFail-Ignore: true\nIndex-File: true";
1363 return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1366 // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
1367 // ---------------------------------------------------------------------
1369 void pkgAcqIndexTrans::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1371 size_t const nextExt
= CompressionExtensions
.find(' ');
1372 if (nextExt
!= std::string::npos
)
1374 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
1375 Init(RealURI
, Desc
.Description
, Desc
.ShortDesc
);
1380 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1381 if (Cnf
->LocalOnly
== true ||
1382 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1391 Item::Failed(Message
,Cnf
);
1394 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
1395 // ---------------------------------------------------------------------
1397 void pkgAcqMetaBase::Add(Item
*I
)
1399 Transaction
.push_back(I
);
1402 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
1403 // ---------------------------------------------------------------------
1405 void pkgAcqMetaBase::AbortTransaction()
1407 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1408 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
1410 // ensure the toplevel is in error state too
1411 for (std::vector
<Item
*>::iterator I
= Transaction
.begin();
1412 I
!= Transaction
.end(); ++I
)
1414 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1415 std::clog
<< " Cancel: " << (*I
)->DestFile
<< std::endl
;
1416 // the transaction will abort, so stop anything that is idle
1417 if ((*I
)->Status
== pkgAcquire::Item::StatIdle
)
1418 (*I
)->Status
= pkgAcquire::Item::StatDone
;
1420 // kill files in partial
1421 string PartialFile
= _config
->FindDir("Dir::State::lists");
1422 PartialFile
+= "partial/";
1423 PartialFile
+= flNotDir((*I
)->DestFile
);
1424 if(FileExists(PartialFile
))
1425 Rename(PartialFile
, PartialFile
+ ".FAILED");
1429 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
1430 // ---------------------------------------------------------------------
1432 bool pkgAcqMetaBase::TransactionHasError()
1434 for (pkgAcquire::ItemIterator I
= Transaction
.begin();
1435 I
!= Transaction
.end(); ++I
)
1436 if((*I
)->Status
!= pkgAcquire::Item::StatDone
&&
1437 (*I
)->Status
!= pkgAcquire::Item::StatIdle
)
1443 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
1444 // ---------------------------------------------------------------------
1446 void pkgAcqMetaBase::CommitTransaction()
1448 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1449 std::clog
<< "CommitTransaction: " << this << std::endl
;
1451 // move new files into place *and* remove files that are not
1452 // part of the transaction but are still on disk
1453 for (std::vector
<Item
*>::iterator I
= Transaction
.begin();
1454 I
!= Transaction
.end(); ++I
)
1456 if((*I
)->PartialFile
!= "")
1458 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1460 << (*I
)->PartialFile
<< " -> "
1461 << (*I
)->DestFile
<< " "
1464 Rename((*I
)->PartialFile
, (*I
)->DestFile
);
1465 chmod((*I
)->DestFile
.c_str(),0644);
1467 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1473 unlink((*I
)->DestFile
.c_str());
1475 // mark that this transaction is finished
1476 (*I
)->TransactionManager
= 0;
1480 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
1481 // ---------------------------------------------------------------------
1483 void pkgAcqMetaBase::TransactionStageCopy(Item
*I
,
1484 const std::string
&From
,
1485 const std::string
&To
)
1487 I
->PartialFile
= From
;
1491 // AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
1492 // ---------------------------------------------------------------------
1494 void pkgAcqMetaBase::TransactionStageRemoval(Item
*I
,
1495 const std::string
&FinalFile
)
1497 I
->PartialFile
= "";
1498 I
->DestFile
= FinalFile
;
1502 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
1503 // ---------------------------------------------------------------------
1505 bool pkgAcqMetaBase::GenerateAuthWarning(const std::string
&RealURI
,
1506 const std::string
&Message
)
1508 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
1510 if(FileExists(Final
))
1512 Status
= StatTransientNetworkError
;
1513 _error
->Warning(_("An error occurred during the signature "
1514 "verification. The repository is not updated "
1515 "and the previous index files will be used. "
1516 "GPG error: %s: %s\n"),
1517 Desc
.Description
.c_str(),
1518 LookupTag(Message
,"Message").c_str());
1519 RunScripts("APT::Update::Auth-Failure");
1521 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
1522 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
1523 _error
->Error(_("GPG error: %s: %s"),
1524 Desc
.Description
.c_str(),
1525 LookupTag(Message
,"Message").c_str());
1529 _error
->Warning(_("GPG error: %s: %s"),
1530 Desc
.Description
.c_str(),
1531 LookupTag(Message
,"Message").c_str());
1533 // gpgv method failed
1534 ReportMirrorFailure("GPGFailure");
1538 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1539 // ---------------------------------------------------------------------
1541 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
*Owner
,
1542 pkgAcqMetaBase
*TransactionManager
,
1543 string URI
,string URIDesc
,string ShortDesc
,
1544 string MetaIndexFile
,
1545 const vector
<IndexTarget
*>* IndexTargets
,
1546 indexRecords
* MetaIndexParser
) :
1547 pkgAcqMetaBase(Owner
, IndexTargets
, MetaIndexParser
,
1548 HashStringList(), TransactionManager
),
1549 RealURI(URI
), MetaIndexFile(MetaIndexFile
), URIDesc(URIDesc
),
1550 ShortDesc(ShortDesc
)
1552 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1553 DestFile
+= URItoFileName(RealURI
);
1555 // remove any partial downloaded sig-file in partial/.
1556 // it may confuse proxies and is too small to warrant a
1557 // partial download anyway
1558 unlink(DestFile
.c_str());
1560 // set the TransactionManager
1561 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1562 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1563 << TransactionManager
<< std::endl
;
1566 Desc
.Description
= URIDesc
;
1568 Desc
.ShortDesc
= ShortDesc
;
1574 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1578 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1579 // ---------------------------------------------------------------------
1580 /* The only header we use is the last-modified header. */
1581 string
pkgAcqMetaSig::Custom600Headers() const
1583 string FinalFile
= _config
->FindDir("Dir::State::lists");
1584 FinalFile
+= URItoFileName(RealURI
);
1587 if (stat(FinalFile
.c_str(),&Buf
) != 0)
1588 return "\nIndex-File: true";
1590 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1593 // pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1594 // ---------------------------------------------------------------------
1595 /* The only header we use is the last-modified header. */
1596 void pkgAcqMetaSig::Done(string Message
,unsigned long long Size
,
1597 HashStringList
const &Hashes
,
1598 pkgAcquire::MethodConfig
*Cfg
)
1600 Item::Done(Message
, Size
, Hashes
, Cfg
);
1602 if(AuthPass
== false)
1604 if(CheckDownloadDone(Message
, RealURI
) == true)
1606 // destfile will be modified to point to MetaIndexFile for the
1607 // gpgv method, so we need to save it here
1608 MetaIndexFileSignature
= DestFile
;
1609 QueueForSignatureVerify(MetaIndexFile
, MetaIndexFileSignature
);
1615 if(AuthDone(Message
, RealURI
) == true)
1617 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1618 FinalFile
+= URItoFileName(RealURI
);
1620 TransactionManager
->TransactionStageCopy(this, MetaIndexFileSignature
, FinalFile
);
1625 void pkgAcqMetaSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)/*{{{*/
1627 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
1629 // FIXME: duplicated code from pkgAcqMetaIndex
1630 if (AuthPass
== true)
1632 bool Stop
= GenerateAuthWarning(RealURI
, Message
);
1637 // FIXME: meh, this is not really elegant
1638 string InReleaseURI
= RealURI
.replace(RealURI
.rfind("Release.gpg"), 12,
1640 string FinalInRelease
= _config
->FindDir("Dir::State::lists") + URItoFileName(InReleaseURI
);
1642 if (RealFileExists(Final
) || RealFileExists(FinalInRelease
))
1644 std::string downgrade_msg
;
1645 strprintf(downgrade_msg
, _("The repository '%s' is no longer signed."),
1647 if(_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1649 // meh, the users wants to take risks (we still mark the packages
1650 // from this repository as unauthenticated)
1651 _error
->Warning("%s", downgrade_msg
.c_str());
1652 _error
->Warning(_("This is normally not allowed, but the option "
1653 "Acquire::AllowDowngradeToInsecureRepositories was "
1654 "given to override it."));
1657 _error
->Error("%s", downgrade_msg
.c_str());
1658 Rename(MetaIndexFile
, MetaIndexFile
+".FAILED");
1659 Status
= pkgAcquire::Item::StatError
;
1660 TransactionManager
->AbortTransaction();
1665 // this ensures that any file in the lists/ dir is removed by the
1667 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1668 DestFile
+= URItoFileName(RealURI
);
1669 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1671 // only allow going further if the users explicitely wants it
1672 if(_config
->FindB("Acquire::AllowInsecureRepositories") == true)
1674 // we parse the indexes here because at this point the user wanted
1675 // a repository that may potentially harm him
1676 MetaIndexParser
->Load(MetaIndexFile
);
1681 _error
->Warning("Use --allow-insecure-repositories to force the update");
1684 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1685 if (Cnf
->LocalOnly
== true ||
1686 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1694 Item::Failed(Message
,Cnf
);
1697 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
*Owner
, /*{{{*/
1698 pkgAcqMetaBase
*TransactionManager
,
1699 string URI
,string URIDesc
,string ShortDesc
,
1700 string MetaIndexSigURI
,string MetaIndexSigURIDesc
, string MetaIndexSigShortDesc
,
1701 const vector
<IndexTarget
*>* IndexTargets
,
1702 indexRecords
* MetaIndexParser
) :
1703 pkgAcqMetaBase(Owner
, IndexTargets
, MetaIndexParser
, HashStringList(),
1704 TransactionManager
),
1705 RealURI(URI
), URIDesc(URIDesc
), ShortDesc(ShortDesc
),
1706 MetaIndexSigURI(MetaIndexSigURI
), MetaIndexSigURIDesc(MetaIndexSigURIDesc
),
1707 MetaIndexSigShortDesc(MetaIndexSigShortDesc
)
1709 if(TransactionManager
== NULL
)
1711 this->TransactionManager
= this;
1712 this->TransactionManager
->Add(this);
1715 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1716 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1717 << this->TransactionManager
<< std::endl
;
1720 Init(URIDesc
, ShortDesc
);
1723 // pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
1724 void pkgAcqMetaIndex::Init(std::string URIDesc
, std::string ShortDesc
)
1726 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1727 DestFile
+= URItoFileName(RealURI
);
1730 Desc
.Description
= URIDesc
;
1732 Desc
.ShortDesc
= ShortDesc
;
1735 // we expect more item
1736 ExpectedAdditionalItems
= IndexTargets
->size();
1739 // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
1740 // ---------------------------------------------------------------------
1741 /* The only header we use is the last-modified header. */
1742 string
pkgAcqMetaIndex::Custom600Headers() const
1744 string Final
= _config
->FindDir("Dir::State::lists");
1745 Final
+= URItoFileName(RealURI
);
1748 if (stat(Final
.c_str(),&Buf
) != 0)
1749 return "\nIndex-File: true";
1751 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1754 void pkgAcqMetaIndex::Done(string Message
,unsigned long long Size
, /*{{{*/
1755 HashStringList
const &Hashes
,
1756 pkgAcquire::MethodConfig
*Cfg
)
1758 Item::Done(Message
,Size
,Hashes
,Cfg
);
1760 if(CheckDownloadDone(Message
, RealURI
))
1762 // we have a Release file, now download the Signature, all further
1763 // verify/queue for additional downloads will be done in the
1764 // pkgAcqMetaSig::Done() code
1765 std::string MetaIndexFile
= DestFile
;
1766 new pkgAcqMetaSig(Owner
, TransactionManager
,
1767 MetaIndexSigURI
, MetaIndexSigURIDesc
,
1768 MetaIndexSigShortDesc
, MetaIndexFile
, IndexTargets
,
1771 string FinalFile
= _config
->FindDir("Dir::State::lists");
1772 FinalFile
+= URItoFileName(RealURI
);
1773 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
1777 bool pkgAcqMetaBase::AuthDone(string Message
, const string
&RealURI
) /*{{{*/
1779 // At this point, the gpgv method has succeeded, so there is a
1780 // valid signature from a key in the trusted keyring. We
1781 // perform additional verification of its contents, and use them
1782 // to verify the indexes we are about to download
1784 if (!MetaIndexParser
->Load(DestFile
))
1786 Status
= StatAuthError
;
1787 ErrorText
= MetaIndexParser
->ErrorText
;
1791 if (!VerifyVendor(Message
, RealURI
))
1796 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1797 std::cerr
<< "Signature verification succeeded: "
1798 << DestFile
<< std::endl
;
1800 // Download further indexes with verification
1802 // it would be really nice if we could simply do
1803 // if (IMSHit == false) QueueIndexes(true)
1804 // and skip the download if the Release file has not changed
1805 // - but right now the list cleaner will needs to be tricked
1806 // to not delete all our packages/source indexes in this case
1813 void pkgAcqMetaBase::QueueForSignatureVerify(const std::string
&MetaIndexFile
,
1814 const std::string
&MetaIndexFileSignature
)
1817 Desc
.URI
= "gpgv:" + MetaIndexFileSignature
;
1818 DestFile
= MetaIndexFile
;
1820 SetActiveSubprocess("gpgv");
1824 bool pkgAcqMetaBase::CheckDownloadDone(const std::string
&Message
,
1825 const std::string
&RealURI
)
1827 // We have just finished downloading a Release file (it is not
1830 string FileName
= LookupTag(Message
,"Filename");
1831 if (FileName
.empty() == true)
1834 ErrorText
= "Method gave a blank filename";
1838 if (FileName
!= DestFile
)
1841 Desc
.URI
= "copy:" + FileName
;
1846 // make sure to verify against the right file on I-M-S hit
1847 IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"),false);
1850 string FinalFile
= _config
->FindDir("Dir::State::lists");
1851 FinalFile
+= URItoFileName(RealURI
);
1852 DestFile
= FinalFile
;
1855 // set Item to complete as the remaining work is all local (verify etc)
1861 void pkgAcqMetaBase::QueueIndexes(bool verify
) /*{{{*/
1863 bool transInRelease
= false;
1865 std::vector
<std::string
> const keys
= MetaIndexParser
->MetaKeys();
1866 for (std::vector
<std::string
>::const_iterator k
= keys
.begin(); k
!= keys
.end(); ++k
)
1867 // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
1868 if (k
->find("Translation-") != std::string::npos
)
1870 transInRelease
= true;
1875 // at this point the real Items are loaded in the fetcher
1876 ExpectedAdditionalItems
= 0;
1877 for (vector
<IndexTarget
*>::const_iterator Target
= IndexTargets
->begin();
1878 Target
!= IndexTargets
->end();
1881 HashStringList ExpectedIndexHashes
;
1882 const indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup((*Target
)->MetaKey
);
1883 bool compressedAvailable
= false;
1886 if ((*Target
)->IsOptional() == true)
1888 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
1889 for (std::vector
<std::string
>::const_iterator t
= types
.begin(); t
!= types
.end(); ++t
)
1890 if (MetaIndexParser
->Exists((*Target
)->MetaKey
+ "." + *t
) == true)
1892 compressedAvailable
= true;
1896 else if (verify
== true)
1898 Status
= StatAuthError
;
1899 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target
)->MetaKey
.c_str());
1905 ExpectedIndexHashes
= Record
->Hashes
;
1906 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1908 std::cerr
<< "Queueing: " << (*Target
)->URI
<< std::endl
1909 << "Expected Hash:" << std::endl
;
1910 for (HashStringList::const_iterator hs
= ExpectedIndexHashes
.begin(); hs
!= ExpectedIndexHashes
.end(); ++hs
)
1911 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
1912 std::cerr
<< "For: " << Record
->MetaKeyFilename
<< std::endl
;
1914 if (verify
== true && ExpectedIndexHashes
.empty() == true && (*Target
)->IsOptional() == false)
1916 Status
= StatAuthError
;
1917 strprintf(ErrorText
, _("Unable to find hash sum for '%s' in Release file"), (*Target
)->MetaKey
.c_str());
1922 if ((*Target
)->IsOptional() == true)
1924 if (transInRelease
== false || Record
!= NULL
|| compressedAvailable
== true)
1926 if (_config
->FindB("Acquire::PDiffs",true) == true && transInRelease
== true &&
1927 MetaIndexParser
->Exists((*Target
)->MetaKey
+ ".diff/Index") == true)
1928 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
1930 new pkgAcqIndexTrans(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
1935 /* Queue Packages file (either diff or full packages files, depending
1936 on the users option) - we also check if the PDiff Index file is listed
1937 in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
1938 instead, but passing the required info to it is to much hassle */
1939 if(_config
->FindB("Acquire::PDiffs",true) == true && (verify
== false ||
1940 MetaIndexParser
->Exists((*Target
)->MetaKey
+ ".diff/Index") == true))
1941 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
1943 new pkgAcqIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
1947 bool pkgAcqMetaBase::VerifyVendor(string Message
, const string
&RealURI
)/*{{{*/
1949 string::size_type pos
;
1951 // check for missing sigs (that where not fatal because otherwise we had
1954 string msg
= _("There is no public key available for the "
1955 "following key IDs:\n");
1956 pos
= Message
.find("NO_PUBKEY ");
1957 if (pos
!= std::string::npos
)
1959 string::size_type start
= pos
+strlen("NO_PUBKEY ");
1960 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
1961 missingkeys
+= (Fingerprint
);
1963 if(!missingkeys
.empty())
1964 _error
->Warning("%s", (msg
+ missingkeys
).c_str());
1966 string Transformed
= MetaIndexParser
->GetExpectedDist();
1968 if (Transformed
== "../project/experimental")
1970 Transformed
= "experimental";
1973 pos
= Transformed
.rfind('/');
1974 if (pos
!= string::npos
)
1976 Transformed
= Transformed
.substr(0, pos
);
1979 if (Transformed
== ".")
1984 if (_config
->FindB("Acquire::Check-Valid-Until", true) == true &&
1985 MetaIndexParser
->GetValidUntil() > 0) {
1986 time_t const invalid_since
= time(NULL
) - MetaIndexParser
->GetValidUntil();
1987 if (invalid_since
> 0)
1988 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1989 // the time since then the file is invalid - formated in the same way as in
1990 // the download progress display (e.g. 7d 3h 42min 1s)
1991 return _error
->Error(
1992 _("Release file for %s is expired (invalid since %s). "
1993 "Updates for this repository will not be applied."),
1994 RealURI
.c_str(), TimeToStr(invalid_since
).c_str());
1997 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1999 std::cerr
<< "Got Codename: " << MetaIndexParser
->GetDist() << std::endl
;
2000 std::cerr
<< "Expecting Dist: " << MetaIndexParser
->GetExpectedDist() << std::endl
;
2001 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
2004 if (MetaIndexParser
->CheckDist(Transformed
) == false)
2006 // This might become fatal one day
2007 // Status = StatAuthError;
2008 // ErrorText = "Conflicting distribution; expected "
2009 // + MetaIndexParser->GetExpectedDist() + " but got "
2010 // + MetaIndexParser->GetDist();
2012 if (!Transformed
.empty())
2014 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
2015 Desc
.Description
.c_str(),
2016 Transformed
.c_str(),
2017 MetaIndexParser
->GetDist().c_str());
2024 // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
2025 // ---------------------------------------------------------------------
2027 void pkgAcqMetaIndex::Failed(string Message
,
2028 pkgAcquire::MethodConfig
* /*Cnf*/)
2030 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
2032 if (AuthPass
== true)
2034 bool Stop
= GenerateAuthWarning(RealURI
, Message
);
2039 _error
->Warning(_("The data from '%s' is not signed. Packages "
2040 "from that repository can not be authenticated."),
2043 // No Release file was present, or verification failed, so fall
2044 // back to queueing Packages files without verification
2045 // only allow going further if the users explicitely wants it
2046 if(_config
->FindB("Acquire::AllowInsecureRepositories") == true)
2048 /* Always move the meta index, even if gpgv failed. This ensures
2049 * that PackageFile objects are correctly filled in */
2050 if (FileExists(DestFile
))
2052 string FinalFile
= _config
->FindDir("Dir::State::lists");
2053 FinalFile
+= URItoFileName(RealURI
);
2054 /* InRelease files become Release files, otherwise
2055 * they would be considered as trusted later on */
2056 if (SigFile
== DestFile
) {
2057 RealURI
= RealURI
.replace(RealURI
.rfind("InRelease"), 9,
2059 FinalFile
= FinalFile
.replace(FinalFile
.rfind("InRelease"), 9,
2061 SigFile
= FinalFile
;
2064 // Done, queue for rename on transaction finished
2065 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2068 QueueIndexes(false);
2070 // warn if the repository is unsinged
2071 _error
->Warning("Use --allow-insecure-repositories to force the update");
2072 TransactionManager
->AbortTransaction();
2080 void pkgAcqMetaIndex::Finished()
2082 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2083 std::clog
<< "Finished: " << DestFile
<<std::endl
;
2084 if(TransactionManager
!= NULL
&&
2085 TransactionManager
->TransactionHasError() == false)
2086 TransactionManager
->CommitTransaction();
2090 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
*Owner
, /*{{{*/
2091 string
const &URI
, string
const &URIDesc
, string
const &ShortDesc
,
2092 string
const &MetaIndexURI
, string
const &MetaIndexURIDesc
, string
const &MetaIndexShortDesc
,
2093 string
const &MetaSigURI
, string
const &MetaSigURIDesc
, string
const &MetaSigShortDesc
,
2094 const vector
<IndexTarget
*>* IndexTargets
,
2095 indexRecords
* MetaIndexParser
) :
2096 pkgAcqMetaIndex(Owner
, NULL
, URI
, URIDesc
, ShortDesc
, MetaSigURI
, MetaSigURIDesc
,MetaSigShortDesc
, IndexTargets
, MetaIndexParser
),
2097 MetaIndexURI(MetaIndexURI
), MetaIndexURIDesc(MetaIndexURIDesc
), MetaIndexShortDesc(MetaIndexShortDesc
),
2098 MetaSigURI(MetaSigURI
), MetaSigURIDesc(MetaSigURIDesc
), MetaSigShortDesc(MetaSigShortDesc
)
2102 // index targets + (worst case:) Release/Release.gpg
2103 ExpectedAdditionalItems
= IndexTargets
->size() + 2;
2106 // keep the old InRelease around in case of transistent network errors
2107 string
const Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
2108 if (RealFileExists(Final
) == true)
2110 string
const LastGoodSig
= DestFile
+ ".reverify";
2111 Rename(Final
,LastGoodSig
);
2116 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
2119 // if the file was never queued undo file-changes done in the constructor
2120 if (QueueCounter
== 1 && Status
== StatIdle
&& FileSize
== 0 && Complete
== false)
2122 string
const Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
2123 string
const LastGoodSig
= DestFile
+ ".reverify";
2124 if (RealFileExists(Final
) == false && RealFileExists(LastGoodSig
) == true)
2125 Rename(LastGoodSig
, Final
);
2130 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
2131 // ---------------------------------------------------------------------
2132 // FIXME: this can go away once the InRelease file is used widely
2133 string
pkgAcqMetaClearSig::Custom600Headers() const
2135 string Final
= _config
->FindDir("Dir::State::lists");
2136 Final
+= URItoFileName(RealURI
);
2139 if (stat(Final
.c_str(),&Buf
) != 0)
2141 if (stat(Final
.c_str(),&Buf
) != 0)
2142 return "\nIndex-File: true\nFail-Ignore: true\n";
2145 return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
2148 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
2149 // ---------------------------------------------------------------------
2150 void pkgAcqMetaClearSig::Done(std::string Message
,unsigned long long Size
,
2151 HashStringList
const &Hashes
,
2152 pkgAcquire::MethodConfig
*Cnf
)
2154 // if we expect a ClearTextSignature (InRelase), ensure that
2155 // this is what we get and if not fail to queue a
2156 // Release/Release.gpg, see #346386
2157 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
2159 pkgAcquire::Item::Failed(Message
, Cnf
);
2160 RenameOnError(NotClearsigned
);
2161 TransactionManager
->AbortTransaction();
2165 if(AuthPass
== false)
2167 if(CheckDownloadDone(Message
, RealURI
) == true)
2168 QueueForSignatureVerify(DestFile
, DestFile
);
2173 if(AuthDone(Message
, RealURI
) == true)
2175 string FinalFile
= _config
->FindDir("Dir::State::lists");
2176 FinalFile
+= URItoFileName(RealURI
);
2178 // queue for copy in place
2179 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2184 void pkgAcqMetaClearSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
) /*{{{*/
2186 // we failed, we will not get additional items from this method
2187 ExpectedAdditionalItems
= 0;
2189 if (AuthPass
== false)
2191 // Queue the 'old' InRelease file for removal if we try Release.gpg
2192 // as otherwise the file will stay around and gives a false-auth
2193 // impression (CVE-2012-0214)
2194 string FinalFile
= _config
->FindDir("Dir::State::lists");
2195 FinalFile
.append(URItoFileName(RealURI
));
2196 TransactionManager
->TransactionStageRemoval(this, FinalFile
);
2198 new pkgAcqMetaIndex(Owner
, TransactionManager
,
2199 MetaIndexURI
, MetaIndexURIDesc
, MetaIndexShortDesc
,
2200 MetaSigURI
, MetaSigURIDesc
, MetaSigShortDesc
,
2201 IndexTargets
, MetaIndexParser
);
2202 if (Cnf
->LocalOnly
== true ||
2203 StringToBool(LookupTag(Message
, "Transient-Failure"), false) == false)
2207 pkgAcqMetaIndex::Failed(Message
, Cnf
);
2210 // AcqArchive::AcqArchive - Constructor /*{{{*/
2211 // ---------------------------------------------------------------------
2212 /* This just sets up the initial fetch environment and queues the first
2214 pkgAcqArchive::pkgAcqArchive(pkgAcquire
*Owner
,pkgSourceList
*Sources
,
2215 pkgRecords
*Recs
,pkgCache::VerIterator
const &Version
,
2216 string
&StoreFilename
) :
2217 Item(Owner
, HashStringList()), Version(Version
), Sources(Sources
), Recs(Recs
),
2218 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
2221 Retries
= _config
->FindI("Acquire::Retries",0);
2223 if (Version
.Arch() == 0)
2225 _error
->Error(_("I wasn't able to locate a file for the %s package. "
2226 "This might mean you need to manually fix this package. "
2227 "(due to missing arch)"),
2228 Version
.ParentPkg().FullName().c_str());
2232 /* We need to find a filename to determine the extension. We make the
2233 assumption here that all the available sources for this version share
2234 the same extension.. */
2235 // Skip not source sources, they do not have file fields.
2236 for (; Vf
.end() == false; ++Vf
)
2238 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
2243 // Does not really matter here.. we are going to fail out below
2244 if (Vf
.end() != true)
2246 // If this fails to get a file name we will bomb out below.
2247 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2248 if (_error
->PendingError() == true)
2251 // Generate the final file name as: package_version_arch.foo
2252 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
2253 QuoteString(Version
.VerStr(),"_:") + '_' +
2254 QuoteString(Version
.Arch(),"_:.") +
2255 "." + flExtension(Parse
.FileName());
2258 // check if we have one trusted source for the package. if so, switch
2259 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2260 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
2261 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
2262 bool seenUntrusted
= false;
2263 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
2265 pkgIndexFile
*Index
;
2266 if (Sources
->FindIndex(i
.File(),Index
) == false)
2269 if (debugAuth
== true)
2270 std::cerr
<< "Checking index: " << Index
->Describe()
2271 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
2273 if (Index
->IsTrusted() == true)
2276 if (allowUnauth
== false)
2280 seenUntrusted
= true;
2283 // "allow-unauthenticated" restores apts old fetching behaviour
2284 // that means that e.g. unauthenticated file:// uris are higher
2285 // priority than authenticated http:// uris
2286 if (allowUnauth
== true && seenUntrusted
== true)
2290 if (QueueNext() == false && _error
->PendingError() == false)
2291 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
2292 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
2295 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2296 // ---------------------------------------------------------------------
2297 /* This queues the next available file version for download. It checks if
2298 the archive is already available in the cache and stashs the MD5 for
2300 bool pkgAcqArchive::QueueNext()
2302 for (; Vf
.end() == false; ++Vf
)
2304 // Ignore not source sources
2305 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
2308 // Try to cross match against the source list
2309 pkgIndexFile
*Index
;
2310 if (Sources
->FindIndex(Vf
.File(),Index
) == false)
2313 // only try to get a trusted package from another source if that source
2315 if(Trusted
&& !Index
->IsTrusted())
2318 // Grab the text package record
2319 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2320 if (_error
->PendingError() == true)
2323 string PkgFile
= Parse
.FileName();
2324 ExpectedHashes
= Parse
.Hashes();
2326 if (PkgFile
.empty() == true)
2327 return _error
->Error(_("The package index files are corrupted. No Filename: "
2328 "field for package %s."),
2329 Version
.ParentPkg().Name());
2331 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
2332 Desc
.Description
= Index
->ArchiveInfo(Version
);
2334 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
2336 // See if we already have the file. (Legacy filenames)
2337 FileSize
= Version
->Size
;
2338 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
2340 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2342 // Make sure the size matches
2343 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2348 StoreFilename
= DestFile
= FinalFile
;
2352 /* Hmm, we have a file and its size does not match, this means it is
2353 an old style mismatched arch */
2354 unlink(FinalFile
.c_str());
2357 // Check it again using the new style output filenames
2358 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
2359 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2361 // Make sure the size matches
2362 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2367 StoreFilename
= DestFile
= FinalFile
;
2371 /* Hmm, we have a file and its size does not match, this shouldn't
2373 unlink(FinalFile
.c_str());
2376 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
2378 // Check the destination file
2379 if (stat(DestFile
.c_str(),&Buf
) == 0)
2381 // Hmm, the partial file is too big, erase it
2382 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
2383 unlink(DestFile
.c_str());
2385 PartialSize
= Buf
.st_size
;
2388 // Disables download of archives - useful if no real installation follows,
2389 // e.g. if we are just interested in proposed installation order
2390 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2395 StoreFilename
= DestFile
= FinalFile
;
2409 // AcqArchive::Done - Finished fetching /*{{{*/
2410 // ---------------------------------------------------------------------
2412 void pkgAcqArchive::Done(string Message
,unsigned long long Size
, HashStringList
const &CalcHashes
,
2413 pkgAcquire::MethodConfig
*Cfg
)
2415 Item::Done(Message
, Size
, CalcHashes
, Cfg
);
2418 if (Size
!= Version
->Size
)
2420 RenameOnError(SizeMismatch
);
2424 // FIXME: could this empty() check impose *any* sort of security issue?
2425 if(ExpectedHashes
.usable() && ExpectedHashes
!= CalcHashes
)
2427 RenameOnError(HashSumMismatch
);
2428 printHashSumComparision(DestFile
, ExpectedHashes
, CalcHashes
);
2432 // Grab the output filename
2433 string FileName
= LookupTag(Message
,"Filename");
2434 if (FileName
.empty() == true)
2437 ErrorText
= "Method gave a blank filename";
2443 // Reference filename
2444 if (FileName
!= DestFile
)
2446 StoreFilename
= DestFile
= FileName
;
2451 // Done, move it into position
2452 string FinalFile
= _config
->FindDir("Dir::Cache::Archives");
2453 FinalFile
+= flNotDir(StoreFilename
);
2454 Rename(DestFile
,FinalFile
);
2456 StoreFilename
= DestFile
= FinalFile
;
2460 // AcqArchive::Failed - Failure handler /*{{{*/
2461 // ---------------------------------------------------------------------
2462 /* Here we try other sources */
2463 void pkgAcqArchive::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
2465 ErrorText
= LookupTag(Message
,"Message");
2467 /* We don't really want to retry on failed media swaps, this prevents
2468 that. An interesting observation is that permanent failures are not
2470 if (Cnf
->Removable
== true &&
2471 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2473 // Vf = Version.FileList();
2474 while (Vf
.end() == false) ++Vf
;
2475 StoreFilename
= string();
2476 Item::Failed(Message
,Cnf
);
2480 if (QueueNext() == false)
2482 // This is the retry counter
2484 Cnf
->LocalOnly
== false &&
2485 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2488 Vf
= Version
.FileList();
2489 if (QueueNext() == true)
2493 StoreFilename
= string();
2494 Item::Failed(Message
,Cnf
);
2498 // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
2499 // ---------------------------------------------------------------------
2500 APT_PURE
bool pkgAcqArchive::IsTrusted() const
2505 // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
2506 // ---------------------------------------------------------------------
2508 void pkgAcqArchive::Finished()
2510 if (Status
== pkgAcquire::Item::StatDone
&&
2513 StoreFilename
= string();
2516 // AcqFile::pkgAcqFile - Constructor /*{{{*/
2517 // ---------------------------------------------------------------------
2518 /* The file is added to the queue */
2519 pkgAcqFile::pkgAcqFile(pkgAcquire
*Owner
,string URI
, HashStringList
const &Hashes
,
2520 unsigned long long Size
,string Dsc
,string ShortDesc
,
2521 const string
&DestDir
, const string
&DestFilename
,
2523 Item(Owner
, Hashes
), IsIndexFile(IsIndexFile
)
2525 Retries
= _config
->FindI("Acquire::Retries",0);
2527 if(!DestFilename
.empty())
2528 DestFile
= DestFilename
;
2529 else if(!DestDir
.empty())
2530 DestFile
= DestDir
+ "/" + flNotDir(URI
);
2532 DestFile
= flNotDir(URI
);
2536 Desc
.Description
= Dsc
;
2539 // Set the short description to the archive component
2540 Desc
.ShortDesc
= ShortDesc
;
2542 // Get the transfer sizes
2545 if (stat(DestFile
.c_str(),&Buf
) == 0)
2547 // Hmm, the partial file is too big, erase it
2548 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
2549 unlink(DestFile
.c_str());
2551 PartialSize
= Buf
.st_size
;
2557 // AcqFile::Done - Item downloaded OK /*{{{*/
2558 // ---------------------------------------------------------------------
2560 void pkgAcqFile::Done(string Message
,unsigned long long Size
,HashStringList
const &CalcHashes
,
2561 pkgAcquire::MethodConfig
*Cnf
)
2563 Item::Done(Message
,Size
,CalcHashes
,Cnf
);
2566 if(ExpectedHashes
.usable() && ExpectedHashes
!= CalcHashes
)
2568 RenameOnError(HashSumMismatch
);
2569 printHashSumComparision(DestFile
, ExpectedHashes
, CalcHashes
);
2573 string FileName
= LookupTag(Message
,"Filename");
2574 if (FileName
.empty() == true)
2577 ErrorText
= "Method gave a blank filename";
2583 // The files timestamp matches
2584 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
2587 // We have to copy it into place
2588 if (FileName
!= DestFile
)
2591 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
2592 Cnf
->Removable
== true)
2594 Desc
.URI
= "copy:" + FileName
;
2599 // Erase the file if it is a symlink so we can overwrite it
2601 if (lstat(DestFile
.c_str(),&St
) == 0)
2603 if (S_ISLNK(St
.st_mode
) != 0)
2604 unlink(DestFile
.c_str());
2608 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
2610 ErrorText
= "Link to " + DestFile
+ " failure ";
2617 // AcqFile::Failed - Failure handler /*{{{*/
2618 // ---------------------------------------------------------------------
2619 /* Here we try other sources */
2620 void pkgAcqFile::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
2622 ErrorText
= LookupTag(Message
,"Message");
2624 // This is the retry counter
2626 Cnf
->LocalOnly
== false &&
2627 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2634 Item::Failed(Message
,Cnf
);
2637 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2638 // ---------------------------------------------------------------------
2639 /* The only header we use is the last-modified header. */
2640 string
pkgAcqFile::Custom600Headers() const
2643 return "\nIndex-File: true";