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 /*{{{*/
16 #include <apt-pkg/acquire-item.h>
17 #include <apt-pkg/configuration.h>
18 #include <apt-pkg/sourcelist.h>
19 #include <apt-pkg/vendorlist.h>
20 #include <apt-pkg/error.h>
21 #include <apt-pkg/strutl.h>
22 #include <apt-pkg/fileutl.h>
23 #include <apt-pkg/md5.h>
24 #include <apt-pkg/sha1.h>
25 #include <apt-pkg/tagfile.h>
39 // Acquire::Item::Item - Constructor /*{{{*/
40 // ---------------------------------------------------------------------
42 pkgAcquire::Item::Item(pkgAcquire
*Owner
) : Owner(Owner
), FileSize(0),
43 PartialSize(0), Mode(0), ID(0), Complete(false),
44 Local(false), QueueCounter(0)
50 // Acquire::Item::~Item - Destructor /*{{{*/
51 // ---------------------------------------------------------------------
53 pkgAcquire::Item::~Item()
58 // Acquire::Item::Failed - Item failed to download /*{{{*/
59 // ---------------------------------------------------------------------
60 /* We return to an idle state if there are still other queues that could
62 void pkgAcquire::Item::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
65 ErrorText
= LookupTag(Message
,"Message");
66 UsedMirror
= LookupTag(Message
,"UsedMirror");
67 if (QueueCounter
<= 1)
69 /* This indicates that the file is not available right now but might
70 be sometime later. If we do a retry cycle then this should be
72 if (Cnf
->LocalOnly
== true &&
73 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
84 // report mirror failure back to LP if we actually use a mirror
85 string FailReason
= LookupTag(Message
, "FailReason");
86 if(FailReason
.size() != 0)
87 ReportMirrorFailure(FailReason
);
89 ReportMirrorFailure(ErrorText
);
92 // Acquire::Item::Start - Item has begun to download /*{{{*/
93 // ---------------------------------------------------------------------
94 /* Stash status and the file size. Note that setting Complete means
95 sub-phases of the acquire process such as decompresion are operating */
96 void pkgAcquire::Item::Start(string
/*Message*/,unsigned long Size
)
98 Status
= StatFetching
;
99 if (FileSize
== 0 && Complete
== false)
103 // Acquire::Item::Done - Item downloaded OK /*{{{*/
104 // ---------------------------------------------------------------------
106 void pkgAcquire::Item::Done(string Message
,unsigned long Size
,string Hash
,
107 pkgAcquire::MethodConfig
*Cnf
)
109 // We just downloaded something..
110 string FileName
= LookupTag(Message
,"Filename");
111 UsedMirror
= LookupTag(Message
,"UsedMirror");
112 if (Complete
== false && !Local
&& FileName
== DestFile
)
115 Owner
->Log
->Fetched(Size
,atoi(LookupTag(Message
,"Resume-Point","0").c_str()));
121 ErrorText
= string();
122 Owner
->Dequeue(this);
125 // Acquire::Item::Rename - Rename a file /*{{{*/
126 // ---------------------------------------------------------------------
127 /* This helper function is used by alot of item methods as thier final
129 void pkgAcquire::Item::Rename(string From
,string To
)
131 if (rename(From
.c_str(),To
.c_str()) != 0)
134 snprintf(S
,sizeof(S
),_("rename failed, %s (%s -> %s)."),strerror(errno
),
135 From
.c_str(),To
.c_str());
142 void pkgAcquire::Item::ReportMirrorFailure(string FailCode
)
144 // we only act if a mirror was used at all
145 if(UsedMirror
.empty())
148 std::cerr
<< "\nReportMirrorFailure: "
150 << " Uri: " << DescURI()
152 << FailCode
<< std::endl
;
154 const char *Args
[40];
156 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
157 "/usr/lib/apt/apt-report-mirror-failure");
158 if(!FileExists(report
))
160 Args
[i
++] = report
.c_str();
161 Args
[i
++] = UsedMirror
.c_str();
162 Args
[i
++] = DescURI().c_str();
163 Args
[i
++] = FailCode
.c_str();
165 pid_t pid
= ExecFork();
168 _error
->Error("ReportMirrorFailure Fork failed");
173 execvp(Args
[0], (char**)Args
);
174 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
177 if(!ExecWait(pid
, "report-mirror-failure"))
179 _error
->Warning("Couldn't report problem to '%s'",
180 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
186 // AcqDiffIndex::AcqDiffIndex - Constructor
187 // ---------------------------------------------------------------------
188 /* Get the DiffIndex file first and see if there are patches availabe
189 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
190 * patches. If anything goes wrong in that process, it will fall back to
191 * the original packages file
193 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
*Owner
,
194 string URI
,string URIDesc
,string ShortDesc
,
195 HashString ExpectedHash
)
196 : Item(Owner
), RealURI(URI
), ExpectedHash(ExpectedHash
),
200 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
202 Desc
.Description
= URIDesc
+ "/DiffIndex";
204 Desc
.ShortDesc
= ShortDesc
;
205 Desc
.URI
= URI
+ ".diff/Index";
207 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
208 DestFile
+= URItoFileName(URI
) + string(".DiffIndex");
211 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
213 // look for the current package file
214 CurrentPackagesFile
= _config
->FindDir("Dir::State::lists");
215 CurrentPackagesFile
+= URItoFileName(RealURI
);
217 // FIXME: this file:/ check is a hack to prevent fetching
218 // from local sources. this is really silly, and
219 // should be fixed cleanly as soon as possible
220 if(!FileExists(CurrentPackagesFile
) ||
221 Desc
.URI
.substr(0,strlen("file:/")) == "file:/")
223 // we don't have a pkg file or we don't want to queue
225 std::clog
<< "No index file, local or canceld by user" << std::endl
;
231 std::clog
<< "pkgAcqIndexDiffs::pkgAcqIndexDiffs(): "
232 << CurrentPackagesFile
<< std::endl
;
238 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
239 // ---------------------------------------------------------------------
240 /* The only header we use is the last-modified header. */
241 string
pkgAcqDiffIndex::Custom600Headers()
243 string Final
= _config
->FindDir("Dir::State::lists");
244 Final
+= URItoFileName(RealURI
) + string(".IndexDiff");
247 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
250 if (stat(Final
.c_str(),&Buf
) != 0)
251 return "\nIndex-File: true";
253 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
257 bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile
)
260 std::clog
<< "pkgAcqIndexDiffs::ParseIndexDiff() " << IndexDiffFile
265 vector
<DiffInfo
> available_patches
;
267 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
269 if (_error
->PendingError() == true)
272 if(TF
.Step(Tags
) == true)
279 string tmp
= Tags
.FindS("SHA1-Current");
280 std::stringstream
ss(tmp
);
283 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
);
285 SHA1
.AddFD(fd
.Fd(), fd
.Size());
286 local_sha1
= string(SHA1
.Result());
288 if(local_sha1
== ServerSha1
)
290 // we have the same sha1 as the server
292 std::clog
<< "Package file is up-to-date" << std::endl
;
293 // set found to true, this will queue a pkgAcqIndexDiffs with
294 // a empty availabe_patches
300 std::clog
<< "SHA1-Current: " << ServerSha1
<< std::endl
;
302 // check the historie and see what patches we need
303 string history
= Tags
.FindS("SHA1-History");
304 std::stringstream
hist(history
);
305 while(hist
>> d
.sha1
>> size
>> d
.file
)
307 d
.size
= atoi(size
.c_str());
308 // read until the first match is found
309 if(d
.sha1
== local_sha1
)
311 // from that point on, we probably need all diffs
315 std::clog
<< "Need to get diff: " << d
.file
<< std::endl
;
316 available_patches
.push_back(d
);
321 // we have something, queue the next diff
325 string::size_type last_space
= Description
.rfind(" ");
326 if(last_space
!= string::npos
)
327 Description
.erase(last_space
, Description
.size()-last_space
);
328 new pkgAcqIndexDiffs(Owner
, RealURI
, Description
, Desc
.ShortDesc
,
329 ExpectedHash
, available_patches
);
337 // Nothing found, report and return false
338 // Failing here is ok, if we return false later, the full
339 // IndexFile is queued
341 std::clog
<< "Can't find a patch in the index file" << std::endl
;
345 void pkgAcqDiffIndex::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
348 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< std::endl
349 << "Falling back to normal index file aquire" << std::endl
;
351 new pkgAcqIndex(Owner
, RealURI
, Description
, Desc
.ShortDesc
,
359 void pkgAcqDiffIndex::Done(string Message
,unsigned long Size
,string Md5Hash
,
360 pkgAcquire::MethodConfig
*Cnf
)
363 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
365 Item::Done(Message
,Size
,Md5Hash
,Cnf
);
368 FinalFile
= _config
->FindDir("Dir::State::lists")+URItoFileName(RealURI
);
370 // sucess in downloading the index
372 FinalFile
+= string(".IndexDiff");
374 std::clog
<< "Renaming: " << DestFile
<< " -> " << FinalFile
376 Rename(DestFile
,FinalFile
);
377 chmod(FinalFile
.c_str(),0644);
378 DestFile
= FinalFile
;
380 if(!ParseDiffIndex(DestFile
))
381 return Failed("", NULL
);
391 // AcqIndexDiffs::AcqIndexDiffs - Constructor
392 // ---------------------------------------------------------------------
393 /* The package diff is added to the queue. one object is constructed
394 * for each diff and the index
396 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
*Owner
,
397 string URI
,string URIDesc
,string ShortDesc
,
398 HashString ExpectedMD5
,
399 vector
<DiffInfo
> diffs
)
400 : Item(Owner
), RealURI(URI
), ExpectedHash(ExpectedHash
),
401 available_patches(diffs
)
404 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
405 DestFile
+= URItoFileName(URI
);
407 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
409 Description
= URIDesc
;
411 Desc
.ShortDesc
= ShortDesc
;
413 if(available_patches
.size() == 0)
415 // we are done (yeah!)
421 State
= StateFetchDiff
;
427 void pkgAcqIndexDiffs::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
430 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< std::endl
431 << "Falling back to normal index file aquire" << std::endl
;
432 new pkgAcqIndex(Owner
, RealURI
, Description
,Desc
.ShortDesc
,
438 // helper that cleans the item out of the fetcher queue
439 void pkgAcqIndexDiffs::Finish(bool allDone
)
441 // we restore the original name, this is required, otherwise
442 // the file will be cleaned
445 DestFile
= _config
->FindDir("Dir::State::lists");
446 DestFile
+= URItoFileName(RealURI
);
448 if(!ExpectedHash
.empty() && !ExpectedHash
.VerifyFile(DestFile
))
450 Status
= StatAuthError
;
451 ErrorText
= _("MD5Sum mismatch");
452 Rename(DestFile
,DestFile
+ ".FAILED");
457 // this is for the "real" finish
462 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
467 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
476 bool pkgAcqIndexDiffs::QueueNextDiff()
479 // calc sha1 of the just patched file
480 string FinalFile
= _config
->FindDir("Dir::State::lists");
481 FinalFile
+= URItoFileName(RealURI
);
483 FileFd
fd(FinalFile
, FileFd::ReadOnly
);
485 SHA1
.AddFD(fd
.Fd(), fd
.Size());
486 string local_sha1
= string(SHA1
.Result());
488 std::clog
<< "QueueNextDiff: "
489 << FinalFile
<< " (" << local_sha1
<< ")"<<std::endl
;
491 // remove all patches until the next matching patch is found
492 // this requires the Index file to be ordered
493 for(vector
<DiffInfo
>::iterator I
=available_patches
.begin();
494 available_patches
.size() > 0 &&
495 I
!= available_patches
.end() &&
496 (*I
).sha1
!= local_sha1
;
499 available_patches
.erase(I
);
502 // error checking and falling back if no patch was found
503 if(available_patches
.size() == 0)
509 // queue the right diff
510 Desc
.URI
= string(RealURI
) + ".diff/" + available_patches
[0].file
+ ".gz";
511 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
512 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
513 DestFile
+= URItoFileName(RealURI
+ ".diff/" + available_patches
[0].file
);
516 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
525 void pkgAcqIndexDiffs::Done(string Message
,unsigned long Size
,string Md5Hash
,
526 pkgAcquire::MethodConfig
*Cnf
)
529 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
531 Item::Done(Message
,Size
,Md5Hash
,Cnf
);
534 FinalFile
= _config
->FindDir("Dir::State::lists")+URItoFileName(RealURI
);
536 // sucess in downloading a diff, enter ApplyDiff state
537 if(State
== StateFetchDiff
)
541 std::clog
<< "Sending to gzip method: " << FinalFile
<< std::endl
;
543 string FileName
= LookupTag(Message
,"Filename");
544 State
= StateUnzipDiff
;
546 Desc
.URI
= "gzip:" + FileName
;
547 DestFile
+= ".decomp";
553 // sucess in downloading a diff, enter ApplyDiff state
554 if(State
== StateUnzipDiff
)
557 // rred excepts the patch as $FinalFile.ed
558 Rename(DestFile
,FinalFile
+".ed");
561 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
563 State
= StateApplyDiff
;
565 Desc
.URI
= "rred:" + FinalFile
;
572 // success in download/apply a diff, queue next (if needed)
573 if(State
== StateApplyDiff
)
575 // remove the just applied patch
576 available_patches
.erase(available_patches
.begin());
581 std::clog
<< "Moving patched file in place: " << std::endl
582 << DestFile
<< " -> " << FinalFile
<< std::endl
;
584 Rename(DestFile
,FinalFile
);
585 chmod(FinalFile
.c_str(),0644);
587 // see if there is more to download
588 if(available_patches
.size() > 0) {
589 new pkgAcqIndexDiffs(Owner
, RealURI
, Description
, Desc
.ShortDesc
,
590 ExpectedHash
, available_patches
);
598 // AcqIndex::AcqIndex - Constructor /*{{{*/
599 // ---------------------------------------------------------------------
600 /* The package file is added to the queue and a second class is
601 instantiated to fetch the revision file */
602 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
603 string URI
,string URIDesc
,string ShortDesc
,
604 HashString ExpectedHash
, string comprExt
)
605 : Item(Owner
), RealURI(URI
), ExpectedHash(ExpectedHash
)
607 Decompression
= false;
610 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
611 DestFile
+= URItoFileName(URI
);
615 // autoselect the compression method
616 if(FileExists("/bin/bzip2"))
617 CompressionExtension
= ".bz2";
619 CompressionExtension
= ".gz";
621 CompressionExtension
= comprExt
;
623 Desc
.URI
= URI
+ CompressionExtension
;
625 Desc
.Description
= URIDesc
;
627 Desc
.ShortDesc
= ShortDesc
;
632 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
633 // ---------------------------------------------------------------------
634 /* The only header we use is the last-modified header. */
635 string
pkgAcqIndex::Custom600Headers()
637 string Final
= _config
->FindDir("Dir::State::lists");
638 Final
+= URItoFileName(RealURI
);
641 if (stat(Final
.c_str(),&Buf
) != 0)
642 return "\nIndex-File: true";
643 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
647 void pkgAcqIndex::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
649 // no .bz2 found, retry with .gz
650 if(Desc
.URI
.substr(Desc
.URI
.size()-3) == "bz2") {
651 Desc
.URI
= Desc
.URI
.substr(0,Desc
.URI
.size()-3) + "gz";
653 // retry with a gzip one
654 new pkgAcqIndex(Owner
, RealURI
, Desc
.Description
,Desc
.ShortDesc
,
655 ExpectedHash
, string(".gz"));
662 // on decompression failure, remove bad versions in partial/
663 if(Decompression
&& Erase
) {
664 string s
= _config
->FindDir("Dir::State::lists") + "partial/";
665 s
+= URItoFileName(RealURI
);
669 Item::Failed(Message
,Cnf
);
673 // AcqIndex::Done - Finished a fetch /*{{{*/
674 // ---------------------------------------------------------------------
675 /* This goes through a number of states.. On the initial fetch the
676 method could possibly return an alternate filename which points
677 to the uncompressed version of the file. If this is so the file
678 is copied into the partial directory. In all other cases the file
679 is decompressed with a gzip uri. */
680 void pkgAcqIndex::Done(string Message
,unsigned long Size
,string Hash
,
681 pkgAcquire::MethodConfig
*Cfg
)
683 Item::Done(Message
,Size
,Hash
,Cfg
);
685 if (Decompression
== true)
687 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
689 std::cerr
<< std::endl
<< RealURI
<< ": Computed Hash: " << Hash
;
690 std::cerr
<< " Expected Hash: " << ExpectedHash
.toStr() << std::endl
;
693 if (!ExpectedHash
.empty() && ExpectedHash
.toStr() != Hash
)
695 Status
= StatAuthError
;
696 ErrorText
= _("Hash Sum mismatch");
697 Rename(DestFile
,DestFile
+ ".FAILED");
698 ReportMirrorFailure("HashChecksumFailure");
701 // Done, move it into position
702 string FinalFile
= _config
->FindDir("Dir::State::lists");
703 FinalFile
+= URItoFileName(RealURI
);
704 Rename(DestFile
,FinalFile
);
705 chmod(FinalFile
.c_str(),0644);
707 /* We restore the original name to DestFile so that the clean operation
709 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
710 DestFile
+= URItoFileName(RealURI
);
712 // Remove the compressed version.
714 unlink(DestFile
.c_str());
721 // Handle the unzipd case
722 string FileName
= LookupTag(Message
,"Alt-Filename");
723 if (FileName
.empty() == false)
725 // The files timestamp matches
726 if (StringToBool(LookupTag(Message
,"Alt-IMS-Hit"),false) == true)
728 Decompression
= true;
730 DestFile
+= ".decomp";
731 Desc
.URI
= "copy:" + FileName
;
737 FileName
= LookupTag(Message
,"Filename");
738 if (FileName
.empty() == true)
741 ErrorText
= "Method gave a blank filename";
744 // The files timestamp matches
745 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
747 unlink(FileName
.c_str());
751 if (FileName
== DestFile
)
756 string compExt
= Desc
.URI
.substr(Desc
.URI
.size()-3);
759 decompProg
= "bzip2";
760 else if(compExt
== ".gz")
763 _error
->Error("Unsupported extension: %s", compExt
.c_str());
767 Decompression
= true;
768 DestFile
+= ".decomp";
769 Desc
.URI
= string(decompProg
) + ":" + FileName
;
774 // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
775 // ---------------------------------------------------------------------
776 /* The Translation file is added to the queue */
777 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
778 string URI
,string URIDesc
,string ShortDesc
)
779 : pkgAcqIndex(Owner
, URI
, URIDesc
, ShortDesc
, HashString(), "")
784 // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
785 // ---------------------------------------------------------------------
787 void pkgAcqIndexTrans::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
789 if (Cnf
->LocalOnly
== true ||
790 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
799 Item::Failed(Message
,Cnf
);
803 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
*Owner
,
804 string URI
,string URIDesc
,string ShortDesc
,
805 string MetaIndexURI
, string MetaIndexURIDesc
,
806 string MetaIndexShortDesc
,
807 const vector
<IndexTarget
*>* IndexTargets
,
808 indexRecords
* MetaIndexParser
) :
809 Item(Owner
), RealURI(URI
), MetaIndexURI(MetaIndexURI
),
810 MetaIndexURIDesc(MetaIndexURIDesc
), MetaIndexShortDesc(MetaIndexShortDesc
),
811 MetaIndexParser(MetaIndexParser
), IndexTargets(IndexTargets
)
813 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
814 DestFile
+= URItoFileName(URI
);
816 // remove any partial downloaded sig-file in partial/.
817 // it may confuse proxies and is too small to warrant a
818 // partial download anyway
819 unlink(DestFile
.c_str());
822 Desc
.Description
= URIDesc
;
824 Desc
.ShortDesc
= ShortDesc
;
828 string Final
= _config
->FindDir("Dir::State::lists");
829 Final
+= URItoFileName(RealURI
);
831 if (stat(Final
.c_str(),&Buf
) == 0)
833 // File was already in place. It needs to be re-verified
834 // because Release might have changed, so Move it into partial
835 Rename(Final
,DestFile
);
841 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
842 // ---------------------------------------------------------------------
843 /* The only header we use is the last-modified header. */
844 string
pkgAcqMetaSig::Custom600Headers()
847 if (stat(DestFile
.c_str(),&Buf
) != 0)
848 return "\nIndex-File: true";
850 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
853 void pkgAcqMetaSig::Done(string Message
,unsigned long Size
,string MD5
,
854 pkgAcquire::MethodConfig
*Cfg
)
856 Item::Done(Message
,Size
,MD5
,Cfg
);
858 string FileName
= LookupTag(Message
,"Filename");
859 if (FileName
.empty() == true)
862 ErrorText
= "Method gave a blank filename";
866 if (FileName
!= DestFile
)
868 // We have to copy it into place
870 Desc
.URI
= "copy:" + FileName
;
877 // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
878 new pkgAcqMetaIndex(Owner
, MetaIndexURI
, MetaIndexURIDesc
, MetaIndexShortDesc
,
879 DestFile
, IndexTargets
, MetaIndexParser
);
883 void pkgAcqMetaSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
885 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
887 // if we get a network error we fail gracefully
888 if(Status
== StatTransientNetworkError
)
890 Item::Failed(Message
,Cnf
);
891 // move the sigfile back on transient network failures
892 if(FileExists(DestFile
))
893 Rename(DestFile
,Final
);
895 // set the status back to , Item::Failed likes to reset it
896 Status
= pkgAcquire::Item::StatTransientNetworkError
;
900 // Delete any existing sigfile when the acquire failed
901 unlink(Final
.c_str());
903 // queue a pkgAcqMetaIndex with no sigfile
904 new pkgAcqMetaIndex(Owner
, MetaIndexURI
, MetaIndexURIDesc
, MetaIndexShortDesc
,
905 "", IndexTargets
, MetaIndexParser
);
907 if (Cnf
->LocalOnly
== true ||
908 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
917 Item::Failed(Message
,Cnf
);
920 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
*Owner
,
921 string URI
,string URIDesc
,string ShortDesc
,
923 const vector
<struct IndexTarget
*>* IndexTargets
,
924 indexRecords
* MetaIndexParser
) :
925 Item(Owner
), RealURI(URI
), SigFile(SigFile
), IndexTargets(IndexTargets
),
926 MetaIndexParser(MetaIndexParser
), AuthPass(false), IMSHit(false)
928 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
929 DestFile
+= URItoFileName(URI
);
932 Desc
.Description
= URIDesc
;
934 Desc
.ShortDesc
= ShortDesc
;
941 // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
942 // ---------------------------------------------------------------------
943 /* The only header we use is the last-modified header. */
944 string
pkgAcqMetaIndex::Custom600Headers()
946 string Final
= _config
->FindDir("Dir::State::lists");
947 Final
+= URItoFileName(RealURI
);
950 if (stat(Final
.c_str(),&Buf
) != 0)
951 return "\nIndex-File: true";
953 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
956 void pkgAcqMetaIndex::Done(string Message
,unsigned long Size
,string Hash
,
957 pkgAcquire::MethodConfig
*Cfg
)
959 Item::Done(Message
,Size
,Hash
,Cfg
);
961 // MetaIndexes are done in two passes: one to download the
962 // metaindex with an appropriate method, and a second to verify it
963 // with the gpgv method
965 if (AuthPass
== true)
971 RetrievalDone(Message
);
973 // Still more retrieving to do
978 // There was no signature file, so we are finished. Download
979 // the indexes without verification.
984 // There was a signature file, so pass it to gpgv for
987 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
988 std::cerr
<< "Metaindex acquired, queueing gpg verification ("
989 << SigFile
<< "," << DestFile
<< ")\n";
991 Desc
.URI
= "gpgv:" + SigFile
;
998 void pkgAcqMetaIndex::RetrievalDone(string Message
)
1000 // We have just finished downloading a Release file (it is not
1003 string FileName
= LookupTag(Message
,"Filename");
1004 if (FileName
.empty() == true)
1007 ErrorText
= "Method gave a blank filename";
1011 if (FileName
!= DestFile
)
1014 Desc
.URI
= "copy:" + FileName
;
1019 // see if the download was a IMSHit
1020 IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"),false);
1023 string FinalFile
= _config
->FindDir("Dir::State::lists");
1024 FinalFile
+= URItoFileName(RealURI
);
1026 // If we get a IMS hit we can remove the empty file in partial
1027 // othersie we move the file in place
1029 unlink(DestFile
.c_str());
1031 Rename(DestFile
,FinalFile
);
1033 chmod(FinalFile
.c_str(),0644);
1034 DestFile
= FinalFile
;
1037 void pkgAcqMetaIndex::AuthDone(string Message
)
1039 // At this point, the gpgv method has succeeded, so there is a
1040 // valid signature from a key in the trusted keyring. We
1041 // perform additional verification of its contents, and use them
1042 // to verify the indexes we are about to download
1044 if (!MetaIndexParser
->Load(DestFile
))
1046 Status
= StatAuthError
;
1047 ErrorText
= MetaIndexParser
->ErrorText
;
1051 if (!VerifyVendor(Message
))
1056 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1057 std::cerr
<< "Signature verification succeeded: "
1058 << DestFile
<< std::endl
;
1060 // Download further indexes with verification
1063 // Done, move signature file into position
1065 string VerifiedSigFile
= _config
->FindDir("Dir::State::lists") +
1066 URItoFileName(RealURI
) + ".gpg";
1067 Rename(SigFile
,VerifiedSigFile
);
1068 chmod(VerifiedSigFile
.c_str(),0644);
1071 void pkgAcqMetaIndex::QueueIndexes(bool verify
)
1073 for (vector
<struct IndexTarget
*>::const_iterator Target
= IndexTargets
->begin();
1074 Target
!= IndexTargets
->end();
1077 HashString ExpectedIndexHash
;
1080 const indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup((*Target
)->MetaKey
);
1083 Status
= StatAuthError
;
1084 ErrorText
= "Unable to find expected entry "
1085 + (*Target
)->MetaKey
+ " in Meta-index file (malformed Release file?)";
1088 ExpectedIndexHash
= Record
->Hash
;
1089 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1091 std::cerr
<< "Queueing: " << (*Target
)->URI
<< std::endl
;
1092 std::cerr
<< "Expected Hash: " << ExpectedIndexHash
.toStr() << std::endl
;
1094 if (ExpectedIndexHash
.empty())
1096 Status
= StatAuthError
;
1097 ErrorText
= "Unable to find hash sum for "
1098 + (*Target
)->MetaKey
+ " in Meta-index file";
1103 // Queue Packages file (either diff or full packages files, depending
1104 // on the users option)
1105 if(_config
->FindB("Acquire::PDiffs",false) == true)
1106 new pkgAcqDiffIndex(Owner
, (*Target
)->URI
, (*Target
)->Description
,
1107 (*Target
)->ShortDesc
, ExpectedIndexHash
);
1109 new pkgAcqIndex(Owner
, (*Target
)->URI
, (*Target
)->Description
,
1110 (*Target
)->ShortDesc
, ExpectedIndexHash
);
1114 bool pkgAcqMetaIndex::VerifyVendor(string Message
)
1116 // // Maybe this should be made available from above so we don't have
1117 // // to read and parse it every time?
1118 // pkgVendorList List;
1119 // List.ReadMainList();
1121 // const Vendor* Vndr = NULL;
1122 // for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
1124 // string::size_type pos = (*I).find("VALIDSIG ");
1125 // if (_config->FindB("Debug::Vendor", false))
1126 // std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
1128 // if (pos != std::string::npos)
1130 // string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
1131 // if (_config->FindB("Debug::Vendor", false))
1132 // std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
1134 // Vndr = List.FindVendor(Fingerprint) != "";
1135 // if (Vndr != NULL);
1139 string::size_type pos
;
1141 // check for missing sigs (that where not fatal because otherwise we had
1144 string msg
= _("There is no public key available for the "
1145 "following key IDs:\n");
1146 pos
= Message
.find("NO_PUBKEY ");
1147 if (pos
!= std::string::npos
)
1149 string::size_type start
= pos
+strlen("NO_PUBKEY ");
1150 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
1151 missingkeys
+= (Fingerprint
);
1153 if(!missingkeys
.empty())
1154 _error
->Warning("%s", string(msg
+missingkeys
).c_str());
1156 string Transformed
= MetaIndexParser
->GetExpectedDist();
1158 if (Transformed
== "../project/experimental")
1160 Transformed
= "experimental";
1163 pos
= Transformed
.rfind('/');
1164 if (pos
!= string::npos
)
1166 Transformed
= Transformed
.substr(0, pos
);
1169 if (Transformed
== ".")
1174 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1176 std::cerr
<< "Got Codename: " << MetaIndexParser
->GetDist() << std::endl
;
1177 std::cerr
<< "Expecting Dist: " << MetaIndexParser
->GetExpectedDist() << std::endl
;
1178 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
1181 if (MetaIndexParser
->CheckDist(Transformed
) == false)
1183 // This might become fatal one day
1184 // Status = StatAuthError;
1185 // ErrorText = "Conflicting distribution; expected "
1186 // + MetaIndexParser->GetExpectedDist() + " but got "
1187 // + MetaIndexParser->GetDist();
1189 if (!Transformed
.empty())
1191 _error
->Warning("Conflicting distribution: %s (expected %s but got %s)",
1192 Desc
.Description
.c_str(),
1193 Transformed
.c_str(),
1194 MetaIndexParser
->GetDist().c_str());
1201 // pkgAcqMetaIndex::Failed - no Release file present or no signature
1202 // file present /*{{{*/
1203 // ---------------------------------------------------------------------
1205 void pkgAcqMetaIndex::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1207 if (AuthPass
== true)
1209 // if we fail the authentication but got the file via a IMS-Hit
1210 // this means that the file wasn't downloaded and that it might be
1211 // just stale (server problem, proxy etc). we delete what we have
1212 // queue it again without i-m-s
1213 // alternatively we could just unlink the file and let the user try again
1219 unlink(DestFile
.c_str());
1221 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1222 DestFile
+= URItoFileName(RealURI
);
1228 // gpgv method failed
1229 ReportMirrorFailure("GPGFailure");
1230 _error
->Warning("GPG error: %s: %s",
1231 Desc
.Description
.c_str(),
1232 LookupTag(Message
,"Message").c_str());
1236 // No Release file was present, or verification failed, so fall
1237 // back to queueing Packages files without verification
1238 QueueIndexes(false);
1243 // AcqArchive::AcqArchive - Constructor /*{{{*/
1244 // ---------------------------------------------------------------------
1245 /* This just sets up the initial fetch environment and queues the first
1247 pkgAcqArchive::pkgAcqArchive(pkgAcquire
*Owner
,pkgSourceList
*Sources
,
1248 pkgRecords
*Recs
,pkgCache::VerIterator
const &Version
,
1249 string
&StoreFilename
) :
1250 Item(Owner
), Version(Version
), Sources(Sources
), Recs(Recs
),
1251 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
1254 Retries
= _config
->FindI("Acquire::Retries",0);
1256 if (Version
.Arch() == 0)
1258 _error
->Error(_("I wasn't able to locate a file for the %s package. "
1259 "This might mean you need to manually fix this package. "
1260 "(due to missing arch)"),
1261 Version
.ParentPkg().Name());
1265 /* We need to find a filename to determine the extension. We make the
1266 assumption here that all the available sources for this version share
1267 the same extension.. */
1268 // Skip not source sources, they do not have file fields.
1269 for (; Vf
.end() == false; Vf
++)
1271 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
1276 // Does not really matter here.. we are going to fail out below
1277 if (Vf
.end() != true)
1279 // If this fails to get a file name we will bomb out below.
1280 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
1281 if (_error
->PendingError() == true)
1284 // Generate the final file name as: package_version_arch.foo
1285 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
1286 QuoteString(Version
.VerStr(),"_:") + '_' +
1287 QuoteString(Version
.Arch(),"_:.") +
1288 "." + flExtension(Parse
.FileName());
1291 // check if we have one trusted source for the package. if so, switch
1292 // to "TrustedOnly" mode
1293 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; i
++)
1295 pkgIndexFile
*Index
;
1296 if (Sources
->FindIndex(i
.File(),Index
) == false)
1298 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1300 std::cerr
<< "Checking index: " << Index
->Describe()
1301 << "(Trusted=" << Index
->IsTrusted() << ")\n";
1303 if (Index
->IsTrusted()) {
1309 // "allow-unauthenticated" restores apts old fetching behaviour
1310 // that means that e.g. unauthenticated file:// uris are higher
1311 // priority than authenticated http:// uris
1312 if (_config
->FindB("APT::Get::AllowUnauthenticated",false) == true)
1316 if (QueueNext() == false && _error
->PendingError() == false)
1317 _error
->Error(_("I wasn't able to locate file for the %s package. "
1318 "This might mean you need to manually fix this package."),
1319 Version
.ParentPkg().Name());
1322 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
1323 // ---------------------------------------------------------------------
1324 /* This queues the next available file version for download. It checks if
1325 the archive is already available in the cache and stashs the MD5 for
1327 bool pkgAcqArchive::QueueNext()
1329 for (; Vf
.end() == false; Vf
++)
1331 // Ignore not source sources
1332 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
1335 // Try to cross match against the source list
1336 pkgIndexFile
*Index
;
1337 if (Sources
->FindIndex(Vf
.File(),Index
) == false)
1340 // only try to get a trusted package from another source if that source
1342 if(Trusted
&& !Index
->IsTrusted())
1345 // Grab the text package record
1346 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
1347 if (_error
->PendingError() == true)
1350 string PkgFile
= Parse
.FileName();
1351 if(Parse
.SHA256Hash() != "")
1352 ExpectedHash
= HashString("SHA256", Parse
.SHA256Hash());
1353 else if (Parse
.SHA1Hash() != "")
1354 ExpectedHash
= HashString("SHA1", Parse
.SHA1Hash());
1356 ExpectedHash
= HashString("MD5Sum", Parse
.MD5Hash());
1357 if (PkgFile
.empty() == true)
1358 return _error
->Error(_("The package index files are corrupted. No Filename: "
1359 "field for package %s."),
1360 Version
.ParentPkg().Name());
1362 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
1363 Desc
.Description
= Index
->ArchiveInfo(Version
);
1365 Desc
.ShortDesc
= Version
.ParentPkg().Name();
1367 // See if we already have the file. (Legacy filenames)
1368 FileSize
= Version
->Size
;
1369 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
1371 if (stat(FinalFile
.c_str(),&Buf
) == 0)
1373 // Make sure the size matches
1374 if ((unsigned)Buf
.st_size
== Version
->Size
)
1379 StoreFilename
= DestFile
= FinalFile
;
1383 /* Hmm, we have a file and its size does not match, this means it is
1384 an old style mismatched arch */
1385 unlink(FinalFile
.c_str());
1388 // Check it again using the new style output filenames
1389 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
1390 if (stat(FinalFile
.c_str(),&Buf
) == 0)
1392 // Make sure the size matches
1393 if ((unsigned)Buf
.st_size
== Version
->Size
)
1398 StoreFilename
= DestFile
= FinalFile
;
1402 /* Hmm, we have a file and its size does not match, this shouldnt
1404 unlink(FinalFile
.c_str());
1407 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
1409 // Check the destination file
1410 if (stat(DestFile
.c_str(),&Buf
) == 0)
1412 // Hmm, the partial file is too big, erase it
1413 if ((unsigned)Buf
.st_size
> Version
->Size
)
1414 unlink(DestFile
.c_str());
1416 PartialSize
= Buf
.st_size
;
1421 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
1422 Desc
.Description
= Index
->ArchiveInfo(Version
);
1424 Desc
.ShortDesc
= Version
.ParentPkg().Name();
1433 // AcqArchive::Done - Finished fetching /*{{{*/
1434 // ---------------------------------------------------------------------
1436 void pkgAcqArchive::Done(string Message
,unsigned long Size
,string CalcHash
,
1437 pkgAcquire::MethodConfig
*Cfg
)
1439 Item::Done(Message
,Size
,CalcHash
,Cfg
);
1442 if (Size
!= Version
->Size
)
1445 ErrorText
= _("Size mismatch");
1450 if(ExpectedHash
.toStr() != CalcHash
)
1453 ErrorText
= _("Hash Sum mismatch");
1454 if(FileExists(DestFile
))
1455 Rename(DestFile
,DestFile
+ ".FAILED");
1459 // Grab the output filename
1460 string FileName
= LookupTag(Message
,"Filename");
1461 if (FileName
.empty() == true)
1464 ErrorText
= "Method gave a blank filename";
1470 // Reference filename
1471 if (FileName
!= DestFile
)
1473 StoreFilename
= DestFile
= FileName
;
1478 // Done, move it into position
1479 string FinalFile
= _config
->FindDir("Dir::Cache::Archives");
1480 FinalFile
+= flNotDir(StoreFilename
);
1481 Rename(DestFile
,FinalFile
);
1483 StoreFilename
= DestFile
= FinalFile
;
1487 // AcqArchive::Failed - Failure handler /*{{{*/
1488 // ---------------------------------------------------------------------
1489 /* Here we try other sources */
1490 void pkgAcqArchive::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1492 ErrorText
= LookupTag(Message
,"Message");
1494 /* We don't really want to retry on failed media swaps, this prevents
1495 that. An interesting observation is that permanent failures are not
1497 if (Cnf
->Removable
== true &&
1498 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
1500 // Vf = Version.FileList();
1501 while (Vf
.end() == false) Vf
++;
1502 StoreFilename
= string();
1503 Item::Failed(Message
,Cnf
);
1507 if (QueueNext() == false)
1509 // This is the retry counter
1511 Cnf
->LocalOnly
== false &&
1512 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
1515 Vf
= Version
.FileList();
1516 if (QueueNext() == true)
1520 StoreFilename
= string();
1521 Item::Failed(Message
,Cnf
);
1525 // AcqArchive::IsTrusted - Determine whether this archive comes from a
1526 // trusted source /*{{{*/
1527 // ---------------------------------------------------------------------
1528 bool pkgAcqArchive::IsTrusted()
1533 // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
1534 // ---------------------------------------------------------------------
1536 void pkgAcqArchive::Finished()
1538 if (Status
== pkgAcquire::Item::StatDone
&&
1541 StoreFilename
= string();
1545 // AcqFile::pkgAcqFile - Constructor /*{{{*/
1546 // ---------------------------------------------------------------------
1547 /* The file is added to the queue */
1548 pkgAcqFile::pkgAcqFile(pkgAcquire
*Owner
,string URI
,string Hash
,
1549 unsigned long Size
,string Dsc
,string ShortDesc
,
1550 const string
&DestDir
, const string
&DestFilename
) :
1551 Item(Owner
), ExpectedHash(Hash
)
1553 Retries
= _config
->FindI("Acquire::Retries",0);
1555 if(!DestFilename
.empty())
1556 DestFile
= DestFilename
;
1557 else if(!DestDir
.empty())
1558 DestFile
= DestDir
+ "/" + flNotDir(URI
);
1560 DestFile
= flNotDir(URI
);
1564 Desc
.Description
= Dsc
;
1567 // Set the short description to the archive component
1568 Desc
.ShortDesc
= ShortDesc
;
1570 // Get the transfer sizes
1573 if (stat(DestFile
.c_str(),&Buf
) == 0)
1575 // Hmm, the partial file is too big, erase it
1576 if ((unsigned)Buf
.st_size
> Size
)
1577 unlink(DestFile
.c_str());
1579 PartialSize
= Buf
.st_size
;
1585 // AcqFile::Done - Item downloaded OK /*{{{*/
1586 // ---------------------------------------------------------------------
1588 void pkgAcqFile::Done(string Message
,unsigned long Size
,string CalcHash
,
1589 pkgAcquire::MethodConfig
*Cnf
)
1591 Item::Done(Message
,Size
,CalcHash
,Cnf
);
1594 if(!ExpectedHash
.empty() && ExpectedHash
.toStr() != CalcHash
)
1597 ErrorText
= "Hash Sum mismatch";
1598 Rename(DestFile
,DestFile
+ ".FAILED");
1602 string FileName
= LookupTag(Message
,"Filename");
1603 if (FileName
.empty() == true)
1606 ErrorText
= "Method gave a blank filename";
1612 // The files timestamp matches
1613 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
1616 // We have to copy it into place
1617 if (FileName
!= DestFile
)
1620 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
1621 Cnf
->Removable
== true)
1623 Desc
.URI
= "copy:" + FileName
;
1628 // Erase the file if it is a symlink so we can overwrite it
1630 if (lstat(DestFile
.c_str(),&St
) == 0)
1632 if (S_ISLNK(St
.st_mode
) != 0)
1633 unlink(DestFile
.c_str());
1637 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
1639 ErrorText
= "Link to " + DestFile
+ " failure ";
1646 // AcqFile::Failed - Failure handler /*{{{*/
1647 // ---------------------------------------------------------------------
1648 /* Here we try other sources */
1649 void pkgAcqFile::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1651 ErrorText
= LookupTag(Message
,"Message");
1653 // This is the retry counter
1655 Cnf
->LocalOnly
== false &&
1656 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
1663 Item::Failed(Message
,Cnf
);