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>
47 #include <sys/types.h>
56 static void printHashSumComparision(std::string
const &URI
, HashStringList
const &Expected
, HashStringList
const &Actual
) /*{{{*/
58 if (_config
->FindB("Debug::Acquire::HashSumMismatch", false) == false)
60 std::cerr
<< std::endl
<< URI
<< ":" << std::endl
<< " Expected Hash: " << std::endl
;
61 for (HashStringList::const_iterator hs
= Expected
.begin(); hs
!= Expected
.end(); ++hs
)
62 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
63 std::cerr
<< " Actual Hash: " << std::endl
;
64 for (HashStringList::const_iterator hs
= Actual
.begin(); hs
!= Actual
.end(); ++hs
)
65 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
68 static void ChangeOwnerAndPermissionOfFile(char const * const requester
, char const * const file
, char const * const user
, char const * const group
, mode_t
const mode
)
70 // ensure the file is owned by root and has good permissions
71 struct passwd
const * const pw
= getpwnam(user
);
72 struct group
const * const gr
= getgrnam(group
);
73 if (getuid() == 0) // if we aren't root, we can't chown, so don't try it
75 if (pw
!= NULL
&& gr
!= NULL
&& chown(file
, pw
->pw_uid
, gr
->gr_gid
) != 0)
76 _error
->WarningE(requester
, "chown to %s:%s of file %s failed", user
, group
, file
);
78 if (chmod(file
, mode
) != 0)
79 _error
->WarningE(requester
, "chmod 0%o of file %s failed", mode
, file
);
81 static std::string
GetPartialFileName(std::string
const &file
)
83 std::string DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
87 static std::string
GetPartialFileNameFromURI(std::string
const &uri
)
89 return GetPartialFileName(URItoFileName(uri
));
93 // Acquire::Item::Item - Constructor /*{{{*/
95 #pragma GCC diagnostic push
96 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
98 pkgAcquire::Item::Item(pkgAcquire
*Owner
,
99 HashStringList
const &ExpectedHashes
,
100 pkgAcqMetaBase
*TransactionManager
)
101 : Owner(Owner
), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
102 Local(false), QueueCounter(0), TransactionManager(TransactionManager
),
103 ExpectedAdditionalItems(0), ExpectedHashes(ExpectedHashes
)
107 if(TransactionManager
!= NULL
)
108 TransactionManager
->Add(this);
111 #pragma GCC diagnostic pop
114 // Acquire::Item::~Item - Destructor /*{{{*/
115 // ---------------------------------------------------------------------
117 pkgAcquire::Item::~Item()
122 // Acquire::Item::Failed - Item failed to download /*{{{*/
123 // ---------------------------------------------------------------------
124 /* We return to an idle state if there are still other queues that could
126 void pkgAcquire::Item::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
129 ErrorText
= LookupTag(Message
,"Message");
130 UsedMirror
= LookupTag(Message
,"UsedMirror");
131 if (QueueCounter
<= 1)
133 /* This indicates that the file is not available right now but might
134 be sometime later. If we do a retry cycle then this should be
136 if (Cnf
!= NULL
&& Cnf
->LocalOnly
== true &&
137 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
152 string FailReason
= LookupTag(Message
, "FailReason");
153 if(FailReason
== "MaximumSizeExceeded")
154 Rename(DestFile
, DestFile
+".FAILED");
156 // report mirror failure back to LP if we actually use a mirror
157 if(FailReason
.size() != 0)
158 ReportMirrorFailure(FailReason
);
160 ReportMirrorFailure(ErrorText
);
163 // Acquire::Item::Start - Item has begun to download /*{{{*/
164 // ---------------------------------------------------------------------
165 /* Stash status and the file size. Note that setting Complete means
166 sub-phases of the acquire process such as decompresion are operating */
167 void pkgAcquire::Item::Start(string
/*Message*/,unsigned long long Size
)
169 Status
= StatFetching
;
170 if (FileSize
== 0 && Complete
== false)
174 // Acquire::Item::Done - Item downloaded OK /*{{{*/
175 // ---------------------------------------------------------------------
177 void pkgAcquire::Item::Done(string Message
,unsigned long long Size
,HashStringList
const &/*Hash*/,
178 pkgAcquire::MethodConfig
* /*Cnf*/)
180 // We just downloaded something..
181 string FileName
= LookupTag(Message
,"Filename");
182 UsedMirror
= LookupTag(Message
,"UsedMirror");
183 if (Complete
== false && !Local
&& FileName
== DestFile
)
186 Owner
->Log
->Fetched(Size
,atoi(LookupTag(Message
,"Resume-Point","0").c_str()));
192 ErrorText
= string();
193 Owner
->Dequeue(this);
196 // Acquire::Item::Rename - Rename a file /*{{{*/
197 // ---------------------------------------------------------------------
198 /* This helper function is used by a lot of item methods as their final
200 bool pkgAcquire::Item::Rename(string From
,string To
)
202 if (rename(From
.c_str(),To
.c_str()) != 0)
205 snprintf(S
,sizeof(S
),_("rename failed, %s (%s -> %s)."),strerror(errno
),
206 From
.c_str(),To
.c_str());
215 void pkgAcquire::Item::QueueURI(ItemDesc
&Item
)
217 if (RealFileExists(DestFile
))
219 std::string SandboxUser
= _config
->Find("APT::Sandbox::User");
220 ChangeOwnerAndPermissionOfFile("GetPartialFileName", DestFile
.c_str(),
221 SandboxUser
.c_str(), "root", 0600);
223 Owner
->Enqueue(Item
);
225 void pkgAcquire::Item::Dequeue()
227 Owner
->Dequeue(this);
230 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
232 if(FileExists(DestFile
))
233 Rename(DestFile
, DestFile
+ ".FAILED");
237 case HashSumMismatch
:
238 ErrorText
= _("Hash Sum mismatch");
239 Status
= StatAuthError
;
240 ReportMirrorFailure("HashChecksumFailure");
243 ErrorText
= _("Size mismatch");
244 Status
= StatAuthError
;
245 ReportMirrorFailure("SizeFailure");
248 ErrorText
= _("Invalid file format");
250 // do not report as usually its not the mirrors fault, but Portal/Proxy
253 ErrorText
= _("Signature error");
257 ErrorText
= _("Does not start with a cleartext signature");
264 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)/*{{{*/
266 ActiveSubprocess
= subprocess
;
268 #pragma GCC diagnostic push
269 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
271 Mode
= ActiveSubprocess
.c_str();
273 #pragma GCC diagnostic pop
277 // Acquire::Item::ReportMirrorFailure /*{{{*/
278 // ---------------------------------------------------------------------
279 void pkgAcquire::Item::ReportMirrorFailure(string FailCode
)
281 // we only act if a mirror was used at all
282 if(UsedMirror
.empty())
285 std::cerr
<< "\nReportMirrorFailure: "
287 << " Uri: " << DescURI()
289 << FailCode
<< std::endl
;
291 const char *Args
[40];
293 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
294 "/usr/lib/apt/apt-report-mirror-failure");
295 if(!FileExists(report
))
297 Args
[i
++] = report
.c_str();
298 Args
[i
++] = UsedMirror
.c_str();
299 Args
[i
++] = DescURI().c_str();
300 Args
[i
++] = FailCode
.c_str();
302 pid_t pid
= ExecFork();
305 _error
->Error("ReportMirrorFailure Fork failed");
310 execvp(Args
[0], (char**)Args
);
311 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
314 if(!ExecWait(pid
, "report-mirror-failure"))
316 _error
->Warning("Couldn't report problem to '%s'",
317 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
321 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
322 // ---------------------------------------------------------------------
323 /* Get the DiffIndex file first and see if there are patches available
324 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
325 * patches. If anything goes wrong in that process, it will fall back to
326 * the original packages file
328 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
*Owner
,
329 pkgAcqMetaBase
*TransactionManager
,
330 IndexTarget
const * const Target
,
331 HashStringList
const &ExpectedHashes
,
332 indexRecords
*MetaIndexParser
)
333 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
,
334 MetaIndexParser
), PackagesFileReadyInPartial(false)
337 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
339 RealURI
= Target
->URI
;
341 Desc
.Description
= Target
->Description
+ ".diff/Index";
342 Desc
.ShortDesc
= Target
->ShortDesc
;
343 Desc
.URI
= Target
->URI
+ ".diff/Index";
345 DestFile
= GetPartialFileNameFromURI(Desc
.URI
);
348 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
350 // look for the current package file
351 CurrentPackagesFile
= _config
->FindDir("Dir::State::lists");
352 CurrentPackagesFile
+= URItoFileName(RealURI
);
354 // FIXME: this file:/ check is a hack to prevent fetching
355 // from local sources. this is really silly, and
356 // should be fixed cleanly as soon as possible
357 if(!FileExists(CurrentPackagesFile
) ||
358 Desc
.URI
.substr(0,strlen("file:/")) == "file:/")
360 // we don't have a pkg file or we don't want to queue
361 Failed("No index file, local or canceld by user", NULL
);
366 std::clog
<< "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
367 << CurrentPackagesFile
<< std::endl
;
373 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
374 // ---------------------------------------------------------------------
375 /* The only header we use is the last-modified header. */
376 string
pkgAcqDiffIndex::Custom600Headers() const
378 string Final
= _config
->FindDir("Dir::State::lists");
379 Final
+= URItoFileName(Desc
.URI
);
382 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
385 if (stat(Final
.c_str(),&Buf
) != 0)
386 return "\nIndex-File: true";
388 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
391 bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile
) /*{{{*/
393 // failing here is fine: our caller will take care of trying to
394 // get the complete file if patching fails
396 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
399 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
401 if (_error
->PendingError() == true)
405 if(unlikely(TF
.Step(Tags
) == false))
408 HashStringList ServerHashes
;
409 unsigned long long ServerSize
= 0;
411 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
413 std::string tagname
= *type
;
414 tagname
.append("-Current");
415 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
416 if (tmp
.empty() == true)
420 unsigned long long size
;
421 std::stringstream
ss(tmp
);
423 if (unlikely(hash
.empty() == true))
425 if (unlikely(ServerSize
!= 0 && ServerSize
!= size
))
427 ServerHashes
.push_back(HashString(*type
, hash
));
431 if (ServerHashes
.usable() == false)
434 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Did not find a good hashsum in the index" << std::endl
;
438 if (ServerHashes
!= HashSums())
442 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl
;
443 printHashSumComparision(CurrentPackagesFile
, ServerHashes
, HashSums());
448 if (ServerHashes
.VerifyFile(CurrentPackagesFile
) == true)
450 // we have the same sha1 as the server so we are done here
452 std::clog
<< "pkgAcqDiffIndex: Package file " << CurrentPackagesFile
<< " is up-to-date" << std::endl
;
454 // list cleanup needs to know that this file as well as the already
455 // present index is ours, so we create an empty diff to save it for us
456 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
457 ExpectedHashes
, MetaIndexParser
);
461 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
);
462 Hashes LocalHashesCalc
;
463 LocalHashesCalc
.AddFD(fd
);
464 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
467 std::clog
<< "Server-Current: " << ServerHashes
.find(NULL
)->toStr() << " and we start at "
468 << fd
.Name() << " " << fd
.FileSize() << " " << LocalHashes
.find(NULL
)->toStr() << std::endl
;
470 // parse all of (provided) history
471 vector
<DiffInfo
> available_patches
;
472 bool firstAcceptedHashes
= true;
473 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
475 if (LocalHashes
.find(*type
) == NULL
)
478 std::string tagname
= *type
;
479 tagname
.append("-History");
480 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
481 if (tmp
.empty() == true)
484 string hash
, filename
;
485 unsigned long long size
;
486 std::stringstream
ss(tmp
);
488 while (ss
>> hash
>> size
>> filename
)
490 if (unlikely(hash
.empty() == true || filename
.empty() == true))
493 // see if we have a record for this file already
494 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
495 for (; cur
!= available_patches
.end(); ++cur
)
497 if (cur
->file
!= filename
|| unlikely(cur
->result_size
!= size
))
499 cur
->result_hashes
.push_back(HashString(*type
, hash
));
502 if (cur
!= available_patches
.end())
504 if (firstAcceptedHashes
== true)
507 next
.file
= filename
;
508 next
.result_hashes
.push_back(HashString(*type
, hash
));
509 next
.result_size
= size
;
511 available_patches
.push_back(next
);
516 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
517 << " wasn't in the list for the first parsed hash! (history)" << std::endl
;
521 firstAcceptedHashes
= false;
524 if (unlikely(available_patches
.empty() == true))
527 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
528 << "Couldn't find any patches for the patch series." << std::endl
;
532 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
534 if (LocalHashes
.find(*type
) == NULL
)
537 std::string tagname
= *type
;
538 tagname
.append("-Patches");
539 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
540 if (tmp
.empty() == true)
543 string hash
, filename
;
544 unsigned long long size
;
545 std::stringstream
ss(tmp
);
547 while (ss
>> hash
>> size
>> filename
)
549 if (unlikely(hash
.empty() == true || filename
.empty() == true))
552 // see if we have a record for this file already
553 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
554 for (; cur
!= available_patches
.end(); ++cur
)
556 if (cur
->file
!= filename
)
558 if (unlikely(cur
->patch_size
!= 0 && cur
->patch_size
!= size
))
560 cur
->patch_hashes
.push_back(HashString(*type
, hash
));
561 cur
->patch_size
= size
;
564 if (cur
!= available_patches
.end())
567 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
568 << " wasn't in the list for the first parsed hash! (patches)" << std::endl
;
573 bool foundStart
= false;
574 for (std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
575 cur
!= available_patches
.end(); ++cur
)
577 if (LocalHashes
!= cur
->result_hashes
)
580 available_patches
.erase(available_patches
.begin(), cur
);
585 if (foundStart
== false || unlikely(available_patches
.empty() == true))
588 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
589 << "Couldn't find the start of the patch series." << std::endl
;
593 // patching with too many files is rather slow compared to a fast download
594 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
595 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
598 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
599 << ") so fallback to complete download" << std::endl
;
603 // calculate the size of all patches we have to get
604 // note that all sizes are uncompressed, while we download compressed files
605 unsigned long long patchesSize
= 0;
606 for (std::vector
<DiffInfo
>::const_iterator cur
= available_patches
.begin();
607 cur
!= available_patches
.end(); ++cur
)
608 patchesSize
+= cur
->patch_size
;
609 unsigned long long const sizeLimit
= ServerSize
* _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
610 if (false && sizeLimit
> 0 && (sizeLimit
/100) < patchesSize
)
613 std::clog
<< "Need " << patchesSize
<< " bytes (Limit is " << sizeLimit
/100
614 << ") so fallback to complete download" << std::endl
;
618 // FIXME: make this use the method
619 PackagesFileReadyInPartial
= true;
620 std::string
const Partial
= GetPartialFileNameFromURI(RealURI
);
622 FileFd
From(CurrentPackagesFile
, FileFd::ReadOnly
);
623 FileFd
To(Partial
, FileFd::WriteEmpty
);
624 if(CopyFile(From
, To
) == false)
625 return _error
->Errno("CopyFile", "failed to copy");
628 std::cerr
<< "Done copying " << CurrentPackagesFile
632 // we have something, queue the diffs
633 string::size_type
const last_space
= Description
.rfind(" ");
634 if(last_space
!= string::npos
)
635 Description
.erase(last_space
, Description
.size()-last_space
);
637 /* decide if we should download patches one by one or in one go:
638 The first is good if the server merges patches, but many don't so client
639 based merging can be attempt in which case the second is better.
640 "bad things" will happen if patches are merged on the server,
641 but client side merging is attempt as well */
642 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
643 if (pdiff_merge
== true)
645 // reprepro adds this flag if it has merged patches on the server
646 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
647 pdiff_merge
= (precedence
!= "merged");
650 if (pdiff_merge
== false)
652 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, ExpectedHashes
,
653 MetaIndexParser
, available_patches
);
657 std::vector
<pkgAcqIndexMergeDiffs
*> *diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
658 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
659 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
, TransactionManager
,
663 available_patches
[i
],
673 void pkgAcqDiffIndex::Failed(string Message
,pkgAcquire::MethodConfig
* Cnf
)/*{{{*/
676 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
677 << "Falling back to normal index file acquire" << std::endl
;
679 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
681 Item::Failed(Message
,Cnf
);
685 void pkgAcqDiffIndex::Done(string Message
,unsigned long long Size
,HashStringList
const &Hashes
, /*{{{*/
686 pkgAcquire::MethodConfig
*Cnf
)
689 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
691 Item::Done(Message
, Size
, Hashes
, Cnf
);
693 // verify the index target
694 if(Target
&& Target
->MetaKey
!= "" && MetaIndexParser
&& Hashes
.usable())
696 std::string IndexMetaKey
= Target
->MetaKey
+ ".diff/Index";
697 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(IndexMetaKey
);
698 if(Record
&& Record
->Hashes
.usable() && Hashes
!= Record
->Hashes
)
700 RenameOnError(HashSumMismatch
);
701 printHashSumComparision(RealURI
, Record
->Hashes
, Hashes
);
702 Failed(Message
, Cnf
);
709 FinalFile
= _config
->FindDir("Dir::State::lists");
710 FinalFile
+= URItoFileName(Desc
.URI
);
712 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false))
713 DestFile
= FinalFile
;
715 if(!ParseDiffIndex(DestFile
))
716 return Failed("Message: Couldn't parse pdiff index", Cnf
);
718 // queue for final move
719 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
727 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
728 // ---------------------------------------------------------------------
729 /* The package diff is added to the queue. one object is constructed
730 * for each diff and the index
732 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
*Owner
,
733 pkgAcqMetaBase
*TransactionManager
,
734 struct IndexTarget
const * const Target
,
735 HashStringList
const &ExpectedHashes
,
736 indexRecords
*MetaIndexParser
,
737 vector
<DiffInfo
> diffs
)
738 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
),
739 available_patches(diffs
)
741 DestFile
= GetPartialFileNameFromURI(Target
->URI
);
743 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
745 RealURI
= Target
->URI
;
747 Description
= Target
->Description
;
748 Desc
.ShortDesc
= Target
->ShortDesc
;
750 if(available_patches
.empty() == true)
752 // we are done (yeah!), check hashes against the final file
753 DestFile
= _config
->FindDir("Dir::State::lists");
754 DestFile
+= URItoFileName(Target
->URI
);
760 State
= StateFetchDiff
;
765 void pkgAcqIndexDiffs::Failed(string Message
,pkgAcquire::MethodConfig
* /*Cnf*/)/*{{{*/
768 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
769 << "Falling back to normal index file acquire" << std::endl
;
770 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
774 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
775 void pkgAcqIndexDiffs::Finish(bool allDone
)
778 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
780 << Desc
.URI
<< std::endl
;
782 // we restore the original name, this is required, otherwise
783 // the file will be cleaned
786 if(HashSums().usable() && !HashSums().VerifyFile(DestFile
))
788 RenameOnError(HashSumMismatch
);
794 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
795 FinalFile
+= URItoFileName(RealURI
);
796 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
798 // this is for the "real" finish
803 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
808 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
815 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
817 // calc sha1 of the just patched file
818 std::string
const FinalFile
= GetPartialFileNameFromURI(RealURI
);
820 if(!FileExists(FinalFile
))
822 Failed("Message: No FinalFile " + FinalFile
+ " available", NULL
);
826 FileFd
fd(FinalFile
, FileFd::ReadOnly
);
827 Hashes LocalHashesCalc
;
828 LocalHashesCalc
.AddFD(fd
);
829 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
832 std::clog
<< "QueueNextDiff: " << FinalFile
<< " (" << LocalHashes
.find(NULL
)->toStr() << ")" << std::endl
;
834 if (unlikely(LocalHashes
.usable() == false || ExpectedHashes
.usable() == false))
836 Failed("Local/Expected hashes are not usable", NULL
);
841 // final file reached before all patches are applied
842 if(LocalHashes
== ExpectedHashes
)
848 // remove all patches until the next matching patch is found
849 // this requires the Index file to be ordered
850 for(vector
<DiffInfo
>::iterator I
= available_patches
.begin();
851 available_patches
.empty() == false &&
852 I
!= available_patches
.end() &&
853 I
->result_hashes
!= LocalHashes
;
856 available_patches
.erase(I
);
859 // error checking and falling back if no patch was found
860 if(available_patches
.empty() == true)
862 Failed("No patches left to reach target", NULL
);
866 // queue the right diff
867 Desc
.URI
= RealURI
+ ".diff/" + available_patches
[0].file
+ ".gz";
868 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
869 DestFile
= GetPartialFileNameFromURI(RealURI
+ ".diff/" + available_patches
[0].file
);
872 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
879 void pkgAcqIndexDiffs::Done(string Message
,unsigned long long Size
, HashStringList
const &Hashes
, /*{{{*/
880 pkgAcquire::MethodConfig
*Cnf
)
883 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
885 Item::Done(Message
, Size
, Hashes
, Cnf
);
887 // FIXME: verify this download too before feeding it to rred
888 std::string
const FinalFile
= GetPartialFileNameFromURI(RealURI
);
890 // success in downloading a diff, enter ApplyDiff state
891 if(State
== StateFetchDiff
)
893 FileFd
fd(DestFile
, FileFd::ReadOnly
, FileFd::Gzip
);
894 class Hashes LocalHashesCalc
;
895 LocalHashesCalc
.AddFD(fd
);
896 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
898 if (fd
.Size() != available_patches
[0].patch_size
||
899 available_patches
[0].patch_hashes
!= LocalHashes
)
901 Failed("Patch has Size/Hashsum mismatch", NULL
);
905 // rred excepts the patch as $FinalFile.ed
906 Rename(DestFile
,FinalFile
+".ed");
909 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
911 State
= StateApplyDiff
;
913 Desc
.URI
= "rred:" + FinalFile
;
915 SetActiveSubprocess("rred");
920 // success in download/apply a diff, queue next (if needed)
921 if(State
== StateApplyDiff
)
923 // remove the just applied patch
924 available_patches
.erase(available_patches
.begin());
925 unlink((FinalFile
+ ".ed").c_str());
930 std::clog
<< "Moving patched file in place: " << std::endl
931 << DestFile
<< " -> " << FinalFile
<< std::endl
;
933 Rename(DestFile
,FinalFile
);
934 chmod(FinalFile
.c_str(),0644);
936 // see if there is more to download
937 if(available_patches
.empty() == false) {
938 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
939 ExpectedHashes
, MetaIndexParser
,
944 DestFile
= FinalFile
;
949 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
950 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
*Owner
,
951 pkgAcqMetaBase
*TransactionManager
,
952 struct IndexTarget
const * const Target
,
953 HashStringList
const &ExpectedHashes
,
954 indexRecords
*MetaIndexParser
,
955 DiffInfo
const &patch
,
956 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
957 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
),
958 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
960 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
962 RealURI
= Target
->URI
;
964 Description
= Target
->Description
;
965 Desc
.ShortDesc
= Target
->ShortDesc
;
967 Desc
.URI
= RealURI
+ ".diff/" + patch
.file
+ ".gz";
968 Desc
.Description
= Description
+ " " + patch
.file
+ string(".pdiff");
970 DestFile
= GetPartialFileNameFromURI(RealURI
+ ".diff/" + patch
.file
);
973 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
978 void pkgAcqIndexMergeDiffs::Failed(string Message
,pkgAcquire::MethodConfig
* Cnf
)/*{{{*/
981 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
983 Item::Failed(Message
,Cnf
);
986 // check if we are the first to fail, otherwise we are done here
987 State
= StateDoneDiff
;
988 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
989 I
!= allPatches
->end(); ++I
)
990 if ((*I
)->State
== StateErrorDiff
)
993 // first failure means we should fallback
994 State
= StateErrorDiff
;
995 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
996 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
999 void pkgAcqIndexMergeDiffs::Done(string Message
,unsigned long long Size
,HashStringList
const &Hashes
, /*{{{*/
1000 pkgAcquire::MethodConfig
*Cnf
)
1003 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
1005 Item::Done(Message
,Size
,Hashes
,Cnf
);
1007 // FIXME: verify download before feeding it to rred
1008 string
const FinalFile
= GetPartialFileNameFromURI(RealURI
);
1010 if (State
== StateFetchDiff
)
1012 FileFd
fd(DestFile
, FileFd::ReadOnly
, FileFd::Gzip
);
1013 class Hashes LocalHashesCalc
;
1014 LocalHashesCalc
.AddFD(fd
);
1015 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
1017 if (fd
.Size() != patch
.patch_size
|| patch
.patch_hashes
!= LocalHashes
)
1019 Failed("Patch has Size/Hashsum mismatch", NULL
);
1023 // rred expects the patch as $FinalFile.ed.$patchname.gz
1024 Rename(DestFile
, FinalFile
+ ".ed." + patch
.file
+ ".gz");
1026 // check if this is the last completed diff
1027 State
= StateDoneDiff
;
1028 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
1029 I
!= allPatches
->end(); ++I
)
1030 if ((*I
)->State
!= StateDoneDiff
)
1033 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
1037 // this is the last completed diff, so we are ready to apply now
1038 State
= StateApplyDiff
;
1041 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
1044 Desc
.URI
= "rred:" + FinalFile
;
1046 SetActiveSubprocess("rred");
1049 // success in download/apply all diffs, clean up
1050 else if (State
== StateApplyDiff
)
1052 // see if we really got the expected file
1053 if(ExpectedHashes
.usable() && !ExpectedHashes
.VerifyFile(DestFile
))
1055 RenameOnError(HashSumMismatch
);
1060 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1061 FinalFile
+= URItoFileName(RealURI
);
1063 // move the result into place
1065 std::clog
<< "Queue patched file in place: " << std::endl
1066 << DestFile
<< " -> " << FinalFile
<< std::endl
;
1068 // queue for copy by the transaction manager
1069 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
1071 // ensure the ed's are gone regardless of list-cleanup
1072 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
1073 I
!= allPatches
->end(); ++I
)
1075 std::string
const PartialFile
= GetPartialFileNameFromURI(RealURI
);
1076 std::string patch
= PartialFile
+ ".ed." + (*I
)->patch
.file
+ ".gz";
1077 unlink(patch
.c_str());
1083 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
1087 // AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
1088 bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList
const &Hashes
)
1090 if(MetaKey
!= "" && Hashes
.usable())
1092 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1093 if(Record
&& Record
->Hashes
.usable() && Hashes
!= Record
->Hashes
)
1095 printHashSumComparision(RealURI
, Record
->Hashes
, Hashes
);
1102 // AcqIndex::AcqIndex - Constructor /*{{{*/
1103 // ---------------------------------------------------------------------
1104 /* The package file is added to the queue and a second class is
1105 instantiated to fetch the revision file */
1106 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
1107 string URI
,string URIDesc
,string ShortDesc
,
1108 HashStringList
const &ExpectedHash
)
1109 : pkgAcqBaseIndex(Owner
, 0, NULL
, ExpectedHash
, NULL
)
1113 AutoSelectCompression();
1114 Init(URI
, URIDesc
, ShortDesc
);
1116 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1117 std::clog
<< "New pkgIndex with TransactionManager "
1118 << TransactionManager
<< std::endl
;
1121 // AcqIndex::AcqIndex - Constructor /*{{{*/
1122 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
1123 pkgAcqMetaBase
*TransactionManager
,
1124 IndexTarget
const *Target
,
1125 HashStringList
const &ExpectedHash
,
1126 indexRecords
*MetaIndexParser
)
1127 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHash
,
1130 RealURI
= Target
->URI
;
1132 // autoselect the compression method
1133 AutoSelectCompression();
1134 Init(Target
->URI
, Target
->Description
, Target
->ShortDesc
);
1136 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1137 std::clog
<< "New pkgIndex with TransactionManager "
1138 << TransactionManager
<< std::endl
;
1141 // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
1142 void pkgAcqIndex::AutoSelectCompression()
1144 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
1145 CompressionExtensions
= "";
1146 if (ExpectedHashes
.usable())
1148 for (std::vector
<std::string
>::const_iterator t
= types
.begin();
1149 t
!= types
.end(); ++t
)
1151 std::string CompressedMetaKey
= string(Target
->MetaKey
).append(".").append(*t
);
1152 if (*t
== "uncompressed" ||
1153 MetaIndexParser
->Exists(CompressedMetaKey
) == true)
1154 CompressionExtensions
.append(*t
).append(" ");
1159 for (std::vector
<std::string
>::const_iterator t
= types
.begin(); t
!= types
.end(); ++t
)
1160 CompressionExtensions
.append(*t
).append(" ");
1162 if (CompressionExtensions
.empty() == false)
1163 CompressionExtensions
.erase(CompressionExtensions
.end()-1);
1166 // AcqIndex::Init - defered Constructor /*{{{*/
1167 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
1168 string
const &ShortDesc
)
1170 Stage
= STAGE_DOWNLOAD
;
1172 DestFile
= GetPartialFileNameFromURI(URI
);
1174 CurrentCompressionExtension
= CompressionExtensions
.substr(0, CompressionExtensions
.find(' '));
1175 if (CurrentCompressionExtension
== "uncompressed")
1179 MetaKey
= string(Target
->MetaKey
);
1183 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
1184 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
1186 MetaKey
= string(Target
->MetaKey
) + '.' + CurrentCompressionExtension
;
1189 // load the filesize
1192 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1194 FileSize
= Record
->Size
;
1196 InitByHashIfNeeded(MetaKey
);
1199 Desc
.Description
= URIDesc
;
1201 Desc
.ShortDesc
= ShortDesc
;
1206 // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
1207 void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey
)
1210 // - (maybe?) add support for by-hash into the sources.list as flag
1211 // - make apt-ftparchive generate the hashes (and expire?)
1212 std::string HostKnob
= "APT::Acquire::" + ::URI(Desc
.URI
).Host
+ "::By-Hash";
1213 if(_config
->FindB("APT::Acquire::By-Hash", false) == true ||
1214 _config
->FindB(HostKnob
, false) == true ||
1215 MetaIndexParser
->GetSupportsAcquireByHash())
1217 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1220 // FIXME: should we really use the best hash here? or a fixed one?
1221 const HashString
*TargetHash
= Record
->Hashes
.find("");
1222 std::string ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
1223 size_t trailing_slash
= Desc
.URI
.find_last_of("/");
1224 Desc
.URI
= Desc
.URI
.replace(
1226 Desc
.URI
.substr(trailing_slash
+1).size()+1,
1230 "Fetching ByHash requested but can not find record for %s",
1236 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1237 // ---------------------------------------------------------------------
1238 /* The only header we use is the last-modified header. */
1239 string
pkgAcqIndex::Custom600Headers() const
1241 string Final
= GetFinalFilename();
1243 string msg
= "\nIndex-File: true";
1245 if (stat(Final
.c_str(),&Buf
) == 0)
1246 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1251 // pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
1252 void pkgAcqIndex::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1254 size_t const nextExt
= CompressionExtensions
.find(' ');
1255 if (nextExt
!= std::string::npos
)
1257 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
1258 Init(RealURI
, Desc
.Description
, Desc
.ShortDesc
);
1262 // on decompression failure, remove bad versions in partial/
1263 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
1265 unlink(EraseFileName
.c_str());
1268 Item::Failed(Message
,Cnf
);
1270 /// cancel the entire transaction
1271 TransactionManager
->AbortTransaction();
1274 // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
1275 std::string
pkgAcqIndex::GetFinalFilename() const
1277 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1278 FinalFile
+= URItoFileName(RealURI
);
1279 if (_config
->FindB("Acquire::GzipIndexes",false) == true)
1280 FinalFile
+= '.' + CurrentCompressionExtension
;
1284 // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
1285 void pkgAcqIndex::ReverifyAfterIMS()
1287 // update destfile to *not* include the compression extension when doing
1288 // a reverify (as its uncompressed on disk already)
1289 DestFile
= GetPartialFileNameFromURI(RealURI
);
1291 // adjust DestFile if its compressed on disk
1292 if (_config
->FindB("Acquire::GzipIndexes",false) == true)
1293 DestFile
+= '.' + CurrentCompressionExtension
;
1295 // copy FinalFile into partial/ so that we check the hash again
1296 string FinalFile
= GetFinalFilename();
1297 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1298 Desc
.URI
= "copy:" + FinalFile
;
1302 // AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
1303 bool pkgAcqIndex::ValidateFile(const std::string
&FileName
)
1305 // FIXME: this can go away once we only ever download stuff that
1306 // has a valid hash and we never do GET based probing
1307 // FIXME2: this also leaks debian-isms into the code and should go therefore
1309 /* Always validate the index file for correctness (all indexes must
1310 * have a Package field) (LP: #346386) (Closes: #627642)
1312 FileFd
fd(FileName
, FileFd::ReadOnly
, FileFd::Extension
);
1313 // Only test for correctness if the content of the file is not empty
1318 pkgTagFile
tag(&fd
);
1320 // all our current indexes have a field 'Package' in each section
1321 if (_error
->PendingError() == true ||
1322 tag
.Step(sec
) == false ||
1323 sec
.Exists("Package") == false)
1329 // AcqIndex::Done - Finished a fetch /*{{{*/
1330 // ---------------------------------------------------------------------
1331 /* This goes through a number of states.. On the initial fetch the
1332 method could possibly return an alternate filename which points
1333 to the uncompressed version of the file. If this is so the file
1334 is copied into the partial directory. In all other cases the file
1335 is decompressed with a compressed uri. */
1336 void pkgAcqIndex::Done(string Message
,
1337 unsigned long long Size
,
1338 HashStringList
const &Hashes
,
1339 pkgAcquire::MethodConfig
*Cfg
)
1341 Item::Done(Message
,Size
,Hashes
,Cfg
);
1345 case STAGE_DOWNLOAD
:
1346 StageDownloadDone(Message
, Hashes
, Cfg
);
1348 case STAGE_DECOMPRESS_AND_VERIFY
:
1349 StageDecompressDone(Message
, Hashes
, Cfg
);
1354 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
1355 void pkgAcqIndex::StageDownloadDone(string Message
,
1356 HashStringList
const &Hashes
,
1357 pkgAcquire::MethodConfig
*Cfg
)
1359 // First check if the calculcated Hash of the (compressed) downloaded
1360 // file matches the hash we have in the MetaIndexRecords for this file
1361 if(VerifyHashByMetaKey(Hashes
) == false)
1363 RenameOnError(HashSumMismatch
);
1364 Failed(Message
, Cfg
);
1370 // Handle the unzipd case
1371 string FileName
= LookupTag(Message
,"Alt-Filename");
1372 if (FileName
.empty() == false)
1374 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1376 DestFile
+= ".decomp";
1377 Desc
.URI
= "copy:" + FileName
;
1379 SetActiveSubprocess("copy");
1383 FileName
= LookupTag(Message
,"Filename");
1384 if (FileName
.empty() == true)
1387 ErrorText
= "Method gave a blank filename";
1390 // Methods like e.g. "file:" will give us a (compressed) FileName that is
1391 // not the "DestFile" we set, in this case we uncompress from the local file
1392 if (FileName
!= DestFile
)
1395 EraseFileName
= FileName
;
1397 // we need to verify the file against the current Release file again
1398 // on if-modfied-since hit to avoid a stale attack against us
1399 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
1401 // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
1402 // file when its doing the indexcopy
1403 if (RealURI
.substr(0,6) == "cdrom:")
1406 // The files timestamp matches, reverify by copy into partial/
1412 // If we have compressed indexes enabled, queue for hash verification
1413 if (_config
->FindB("Acquire::GzipIndexes",false))
1415 DestFile
= GetPartialFileNameFromURI(RealURI
+ '.' + CurrentCompressionExtension
);
1417 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1418 Desc
.URI
= "copy:" + FileName
;
1420 SetActiveSubprocess("copy");
1424 // get the binary name for your used compression type
1426 if(CurrentCompressionExtension
== "uncompressed")
1427 decompProg
= "copy";
1429 decompProg
= _config
->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension
),"");
1430 if(decompProg
.empty() == true)
1432 _error
->Error("Unsupported extension: %s", CurrentCompressionExtension
.c_str());
1436 // queue uri for the next stage
1437 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1438 DestFile
+= ".decomp";
1439 Desc
.URI
= decompProg
+ ":" + FileName
;
1441 SetActiveSubprocess(decompProg
);
1444 // pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
1445 void pkgAcqIndex::StageDecompressDone(string Message
,
1446 HashStringList
const &Hashes
,
1447 pkgAcquire::MethodConfig
*Cfg
)
1449 if (ExpectedHashes
.usable() && ExpectedHashes
!= Hashes
)
1452 RenameOnError(HashSumMismatch
);
1453 printHashSumComparision(RealURI
, ExpectedHashes
, Hashes
);
1454 Failed(Message
, Cfg
);
1458 if(!ValidateFile(DestFile
))
1460 RenameOnError(InvalidFormat
);
1461 Failed(Message
, Cfg
);
1465 // remove the compressed version of the file
1466 unlink(EraseFileName
.c_str());
1468 // Done, queue for rename on transaction finished
1469 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1474 // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
1475 // ---------------------------------------------------------------------
1476 /* The Translation file is added to the queue */
1477 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
1478 string URI
,string URIDesc
,string ShortDesc
)
1479 : pkgAcqIndex(Owner
, URI
, URIDesc
, ShortDesc
, HashStringList())
1482 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
1483 pkgAcqMetaBase
*TransactionManager
,
1484 IndexTarget
const * const Target
,
1485 HashStringList
const &ExpectedHashes
,
1486 indexRecords
*MetaIndexParser
)
1487 : pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
)
1491 // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
1492 string
pkgAcqIndexTrans::Custom600Headers() const
1494 string Final
= GetFinalFilename();
1497 if (stat(Final
.c_str(),&Buf
) != 0)
1498 return "\nFail-Ignore: true\nIndex-File: true";
1499 return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1502 // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
1503 void pkgAcqIndexTrans::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1505 size_t const nextExt
= CompressionExtensions
.find(' ');
1506 if (nextExt
!= std::string::npos
)
1508 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
1509 Init(RealURI
, Desc
.Description
, Desc
.ShortDesc
);
1514 Item::Failed(Message
,Cnf
);
1516 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1517 if (Cnf
->LocalOnly
== true ||
1518 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1525 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
1526 void pkgAcqMetaBase::Add(Item
*I
)
1528 Transaction
.push_back(I
);
1531 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
1532 void pkgAcqMetaBase::AbortTransaction()
1534 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1535 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
1537 // ensure the toplevel is in error state too
1538 for (std::vector
<Item
*>::iterator I
= Transaction
.begin();
1539 I
!= Transaction
.end(); ++I
)
1541 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1542 std::clog
<< " Cancel: " << (*I
)->DestFile
<< std::endl
;
1543 // the transaction will abort, so stop anything that is idle
1544 if ((*I
)->Status
== pkgAcquire::Item::StatIdle
)
1545 (*I
)->Status
= pkgAcquire::Item::StatDone
;
1547 // kill failed files in partial
1548 if ((*I
)->Status
== pkgAcquire::Item::StatError
)
1550 std::string
const PartialFile
= GetPartialFileName(flNotDir((*I
)->DestFile
));
1551 if(FileExists(PartialFile
))
1552 Rename(PartialFile
, PartialFile
+ ".FAILED");
1557 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
1558 bool pkgAcqMetaBase::TransactionHasError()
1560 for (pkgAcquire::ItemIterator I
= Transaction
.begin();
1561 I
!= Transaction
.end(); ++I
)
1562 if((*I
)->Status
!= pkgAcquire::Item::StatDone
&&
1563 (*I
)->Status
!= pkgAcquire::Item::StatIdle
)
1569 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
1570 void pkgAcqMetaBase::CommitTransaction()
1572 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1573 std::clog
<< "CommitTransaction: " << this << std::endl
;
1575 // move new files into place *and* remove files that are not
1576 // part of the transaction but are still on disk
1577 for (std::vector
<Item
*>::iterator I
= Transaction
.begin();
1578 I
!= Transaction
.end(); ++I
)
1580 if((*I
)->PartialFile
!= "")
1582 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1583 std::clog
<< "mv " << (*I
)->PartialFile
<< " -> "<< (*I
)->DestFile
<< " "
1584 << (*I
)->DescURI() << std::endl
;
1586 Rename((*I
)->PartialFile
, (*I
)->DestFile
);
1587 ChangeOwnerAndPermissionOfFile("CommitTransaction", (*I
)->DestFile
.c_str(), "root", "root", 0644);
1590 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1596 unlink((*I
)->DestFile
.c_str());
1598 // mark that this transaction is finished
1599 (*I
)->TransactionManager
= 0;
1603 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
1604 void pkgAcqMetaBase::TransactionStageCopy(Item
*I
,
1605 const std::string
&From
,
1606 const std::string
&To
)
1608 I
->PartialFile
= From
;
1612 // AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
1613 void pkgAcqMetaBase::TransactionStageRemoval(Item
*I
,
1614 const std::string
&FinalFile
)
1616 I
->PartialFile
= "";
1617 I
->DestFile
= FinalFile
;
1620 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
1621 bool pkgAcqMetaBase::CheckStopAuthentication(const std::string
&RealURI
,
1622 const std::string
&Message
)
1624 // FIXME: this entire function can do now that we disallow going to
1625 // a unauthenticated state and can cleanly rollback
1627 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
1629 if(FileExists(Final
))
1631 Status
= StatTransientNetworkError
;
1632 _error
->Warning(_("An error occurred during the signature "
1633 "verification. The repository is not updated "
1634 "and the previous index files will be used. "
1635 "GPG error: %s: %s\n"),
1636 Desc
.Description
.c_str(),
1637 LookupTag(Message
,"Message").c_str());
1638 RunScripts("APT::Update::Auth-Failure");
1640 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
1641 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
1642 _error
->Error(_("GPG error: %s: %s"),
1643 Desc
.Description
.c_str(),
1644 LookupTag(Message
,"Message").c_str());
1648 _error
->Warning(_("GPG error: %s: %s"),
1649 Desc
.Description
.c_str(),
1650 LookupTag(Message
,"Message").c_str());
1652 // gpgv method failed
1653 ReportMirrorFailure("GPGFailure");
1657 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1658 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
*Owner
,
1659 pkgAcqMetaBase
*TransactionManager
,
1660 string URI
,string URIDesc
,string ShortDesc
,
1661 string MetaIndexFile
,
1662 const vector
<IndexTarget
*>* IndexTargets
,
1663 indexRecords
* MetaIndexParser
) :
1664 pkgAcqMetaBase(Owner
, IndexTargets
, MetaIndexParser
,
1665 HashStringList(), TransactionManager
),
1666 RealURI(URI
), MetaIndexFile(MetaIndexFile
), URIDesc(URIDesc
),
1667 ShortDesc(ShortDesc
)
1669 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1670 DestFile
+= URItoFileName(RealURI
);
1672 // remove any partial downloaded sig-file in partial/.
1673 // it may confuse proxies and is too small to warrant a
1674 // partial download anyway
1675 unlink(DestFile
.c_str());
1677 // set the TransactionManager
1678 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1679 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1680 << TransactionManager
<< std::endl
;
1683 Desc
.Description
= URIDesc
;
1685 Desc
.ShortDesc
= ShortDesc
;
1691 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1695 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1696 // ---------------------------------------------------------------------
1697 string
pkgAcqMetaSig::Custom600Headers() const
1699 std::string Header
= GetCustom600Headers(RealURI
);
1703 // pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1704 // ---------------------------------------------------------------------
1705 /* The only header we use is the last-modified header. */
1706 void pkgAcqMetaSig::Done(string Message
,unsigned long long Size
,
1707 HashStringList
const &Hashes
,
1708 pkgAcquire::MethodConfig
*Cfg
)
1710 Item::Done(Message
, Size
, Hashes
, Cfg
);
1712 if(AuthPass
== false)
1714 if(CheckDownloadDone(Message
, RealURI
) == true)
1716 // destfile will be modified to point to MetaIndexFile for the
1717 // gpgv method, so we need to save it here
1718 MetaIndexFileSignature
= DestFile
;
1719 QueueForSignatureVerify(MetaIndexFile
, MetaIndexFileSignature
);
1725 if(CheckAuthDone(Message
, RealURI
) == true)
1727 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1728 FinalFile
+= URItoFileName(RealURI
);
1729 TransactionManager
->TransactionStageCopy(this, MetaIndexFileSignature
, FinalFile
);
1734 void pkgAcqMetaSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)/*{{{*/
1736 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
1738 // check if we need to fail at this point
1739 if (AuthPass
== true && CheckStopAuthentication(RealURI
, Message
))
1742 // FIXME: meh, this is not really elegant
1743 string InReleaseURI
= RealURI
.replace(RealURI
.rfind("Release.gpg"), 12,
1745 string FinalInRelease
= _config
->FindDir("Dir::State::lists") + URItoFileName(InReleaseURI
);
1747 if (RealFileExists(Final
) || RealFileExists(FinalInRelease
))
1749 std::string downgrade_msg
;
1750 strprintf(downgrade_msg
, _("The repository '%s' is no longer signed."),
1752 if(_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1754 // meh, the users wants to take risks (we still mark the packages
1755 // from this repository as unauthenticated)
1756 _error
->Warning("%s", downgrade_msg
.c_str());
1757 _error
->Warning(_("This is normally not allowed, but the option "
1758 "Acquire::AllowDowngradeToInsecureRepositories was "
1759 "given to override it."));
1762 _error
->Error("%s", downgrade_msg
.c_str());
1763 Rename(MetaIndexFile
, MetaIndexFile
+".FAILED");
1764 Item::Failed("Message: " + downgrade_msg
, Cnf
);
1765 TransactionManager
->AbortTransaction();
1770 _error
->Warning(_("The data from '%s' is not signed. Packages "
1771 "from that repository can not be authenticated."),
1774 // this ensures that any file in the lists/ dir is removed by the
1776 DestFile
= GetPartialFileNameFromURI(RealURI
);
1777 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1779 // only allow going further if the users explicitely wants it
1780 if(MetaIndexParser
->IsAlwaysTrusted() || _config
->FindB("Acquire::AllowInsecureRepositories") == true)
1782 // we parse the indexes here because at this point the user wanted
1783 // a repository that may potentially harm him
1784 MetaIndexParser
->Load(MetaIndexFile
);
1789 _error
->Error("Use --allow-insecure-repositories to force the update");
1792 Item::Failed(Message
,Cnf
);
1794 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1795 if (Cnf
->LocalOnly
== true ||
1796 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1803 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
*Owner
, /*{{{*/
1804 pkgAcqMetaBase
*TransactionManager
,
1805 string URI
,string URIDesc
,string ShortDesc
,
1806 string MetaIndexSigURI
,string MetaIndexSigURIDesc
, string MetaIndexSigShortDesc
,
1807 const vector
<IndexTarget
*>* IndexTargets
,
1808 indexRecords
* MetaIndexParser
) :
1809 pkgAcqMetaBase(Owner
, IndexTargets
, MetaIndexParser
, HashStringList(),
1810 TransactionManager
),
1811 RealURI(URI
), URIDesc(URIDesc
), ShortDesc(ShortDesc
),
1812 MetaIndexSigURI(MetaIndexSigURI
), MetaIndexSigURIDesc(MetaIndexSigURIDesc
),
1813 MetaIndexSigShortDesc(MetaIndexSigShortDesc
)
1815 if(TransactionManager
== NULL
)
1817 this->TransactionManager
= this;
1818 this->TransactionManager
->Add(this);
1821 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1822 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1823 << this->TransactionManager
<< std::endl
;
1826 Init(URIDesc
, ShortDesc
);
1829 // pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
1830 void pkgAcqMetaIndex::Init(std::string URIDesc
, std::string ShortDesc
)
1832 DestFile
= GetPartialFileNameFromURI(RealURI
);
1835 Desc
.Description
= URIDesc
;
1837 Desc
.ShortDesc
= ShortDesc
;
1840 // we expect more item
1841 ExpectedAdditionalItems
= IndexTargets
->size();
1845 // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
1846 // ---------------------------------------------------------------------
1847 string
pkgAcqMetaIndex::Custom600Headers() const
1849 return GetCustom600Headers(RealURI
);
1852 void pkgAcqMetaIndex::Done(string Message
,unsigned long long Size
, /*{{{*/
1853 HashStringList
const &Hashes
,
1854 pkgAcquire::MethodConfig
*Cfg
)
1856 Item::Done(Message
,Size
,Hashes
,Cfg
);
1858 if(CheckDownloadDone(Message
, RealURI
))
1860 // we have a Release file, now download the Signature, all further
1861 // verify/queue for additional downloads will be done in the
1862 // pkgAcqMetaSig::Done() code
1863 std::string MetaIndexFile
= DestFile
;
1864 new pkgAcqMetaSig(Owner
, TransactionManager
,
1865 MetaIndexSigURI
, MetaIndexSigURIDesc
,
1866 MetaIndexSigShortDesc
, MetaIndexFile
, IndexTargets
,
1869 string FinalFile
= _config
->FindDir("Dir::State::lists");
1870 FinalFile
+= URItoFileName(RealURI
);
1871 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
1875 bool pkgAcqMetaBase::CheckAuthDone(string Message
, const string
&RealURI
) /*{{{*/
1877 // At this point, the gpgv method has succeeded, so there is a
1878 // valid signature from a key in the trusted keyring. We
1879 // perform additional verification of its contents, and use them
1880 // to verify the indexes we are about to download
1882 if (!MetaIndexParser
->Load(DestFile
))
1884 Status
= StatAuthError
;
1885 ErrorText
= MetaIndexParser
->ErrorText
;
1889 if (!VerifyVendor(Message
, RealURI
))
1894 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1895 std::cerr
<< "Signature verification succeeded: "
1896 << DestFile
<< std::endl
;
1898 // Download further indexes with verification
1900 // it would be really nice if we could simply do
1901 // if (IMSHit == false) QueueIndexes(true)
1902 // and skip the download if the Release file has not changed
1903 // - but right now the list cleaner will needs to be tricked
1904 // to not delete all our packages/source indexes in this case
1910 // pkgAcqMetaBase::GetCustom600Headers - Get header for AcqMetaBase /*{{{*/
1911 // ---------------------------------------------------------------------
1912 string
pkgAcqMetaBase::GetCustom600Headers(const string
&RealURI
) const
1914 std::string Header
= "\nIndex-File: true";
1915 std::string MaximumSize
;
1916 strprintf(MaximumSize
, "\nMaximum-Size: %i",
1917 _config
->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
1918 Header
+= MaximumSize
;
1920 string FinalFile
= _config
->FindDir("Dir::State::lists");
1921 FinalFile
+= URItoFileName(RealURI
);
1924 if (stat(FinalFile
.c_str(),&Buf
) == 0)
1925 Header
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1930 // pkgAcqMetaBase::QueueForSignatureVerify /*{{{*/
1931 void pkgAcqMetaBase::QueueForSignatureVerify(const std::string
&MetaIndexFile
,
1932 const std::string
&MetaIndexFileSignature
)
1935 Desc
.URI
= "gpgv:" + MetaIndexFileSignature
;
1936 DestFile
= MetaIndexFile
;
1938 SetActiveSubprocess("gpgv");
1941 // pkgAcqMetaBase::CheckDownloadDone /*{{{*/
1942 bool pkgAcqMetaBase::CheckDownloadDone(const std::string
&Message
,
1943 const std::string
&RealURI
)
1945 // We have just finished downloading a Release file (it is not
1948 string FileName
= LookupTag(Message
,"Filename");
1949 if (FileName
.empty() == true)
1952 ErrorText
= "Method gave a blank filename";
1956 if (FileName
!= DestFile
)
1959 Desc
.URI
= "copy:" + FileName
;
1964 // make sure to verify against the right file on I-M-S hit
1965 IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"),false);
1968 string FinalFile
= _config
->FindDir("Dir::State::lists");
1969 FinalFile
+= URItoFileName(RealURI
);
1970 DestFile
= FinalFile
;
1973 // set Item to complete as the remaining work is all local (verify etc)
1979 void pkgAcqMetaBase::QueueIndexes(bool verify
) /*{{{*/
1981 bool transInRelease
= false;
1983 std::vector
<std::string
> const keys
= MetaIndexParser
->MetaKeys();
1984 for (std::vector
<std::string
>::const_iterator k
= keys
.begin(); k
!= keys
.end(); ++k
)
1985 // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
1986 if (k
->find("Translation-") != std::string::npos
)
1988 transInRelease
= true;
1993 // at this point the real Items are loaded in the fetcher
1994 ExpectedAdditionalItems
= 0;
1995 for (vector
<IndexTarget
*>::const_iterator Target
= IndexTargets
->begin();
1996 Target
!= IndexTargets
->end();
1999 HashStringList ExpectedIndexHashes
;
2000 const indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup((*Target
)->MetaKey
);
2001 bool compressedAvailable
= false;
2004 if ((*Target
)->IsOptional() == true)
2006 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
2007 for (std::vector
<std::string
>::const_iterator t
= types
.begin(); t
!= types
.end(); ++t
)
2008 if (MetaIndexParser
->Exists((*Target
)->MetaKey
+ "." + *t
) == true)
2010 compressedAvailable
= true;
2014 else if (verify
== true)
2016 Status
= StatAuthError
;
2017 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target
)->MetaKey
.c_str());
2023 ExpectedIndexHashes
= Record
->Hashes
;
2024 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
2026 std::cerr
<< "Queueing: " << (*Target
)->URI
<< std::endl
2027 << "Expected Hash:" << std::endl
;
2028 for (HashStringList::const_iterator hs
= ExpectedIndexHashes
.begin(); hs
!= ExpectedIndexHashes
.end(); ++hs
)
2029 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
2030 std::cerr
<< "For: " << Record
->MetaKeyFilename
<< std::endl
;
2032 if (verify
== true && ExpectedIndexHashes
.empty() == true && (*Target
)->IsOptional() == false)
2034 Status
= StatAuthError
;
2035 strprintf(ErrorText
, _("Unable to find hash sum for '%s' in Release file"), (*Target
)->MetaKey
.c_str());
2040 if ((*Target
)->IsOptional() == true)
2042 if (transInRelease
== false || Record
!= NULL
|| compressedAvailable
== true)
2044 if (_config
->FindB("Acquire::PDiffs",true) == true && transInRelease
== true &&
2045 MetaIndexParser
->Exists((*Target
)->MetaKey
+ ".diff/Index") == true)
2046 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2048 new pkgAcqIndexTrans(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2053 /* Queue Packages file (either diff or full packages files, depending
2054 on the users option) - we also check if the PDiff Index file is listed
2055 in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
2056 instead, but passing the required info to it is to much hassle */
2057 if(_config
->FindB("Acquire::PDiffs",true) == true && (verify
== false ||
2058 MetaIndexParser
->Exists((*Target
)->MetaKey
+ ".diff/Index") == true))
2059 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2061 new pkgAcqIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2065 bool pkgAcqMetaBase::VerifyVendor(string Message
, const string
&RealURI
)/*{{{*/
2067 string::size_type pos
;
2069 // check for missing sigs (that where not fatal because otherwise we had
2072 string msg
= _("There is no public key available for the "
2073 "following key IDs:\n");
2074 pos
= Message
.find("NO_PUBKEY ");
2075 if (pos
!= std::string::npos
)
2077 string::size_type start
= pos
+strlen("NO_PUBKEY ");
2078 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
2079 missingkeys
+= (Fingerprint
);
2081 if(!missingkeys
.empty())
2082 _error
->Warning("%s", (msg
+ missingkeys
).c_str());
2084 string Transformed
= MetaIndexParser
->GetExpectedDist();
2086 if (Transformed
== "../project/experimental")
2088 Transformed
= "experimental";
2091 pos
= Transformed
.rfind('/');
2092 if (pos
!= string::npos
)
2094 Transformed
= Transformed
.substr(0, pos
);
2097 if (Transformed
== ".")
2102 if (_config
->FindB("Acquire::Check-Valid-Until", true) == true &&
2103 MetaIndexParser
->GetValidUntil() > 0) {
2104 time_t const invalid_since
= time(NULL
) - MetaIndexParser
->GetValidUntil();
2105 if (invalid_since
> 0)
2106 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
2107 // the time since then the file is invalid - formated in the same way as in
2108 // the download progress display (e.g. 7d 3h 42min 1s)
2109 return _error
->Error(
2110 _("Release file for %s is expired (invalid since %s). "
2111 "Updates for this repository will not be applied."),
2112 RealURI
.c_str(), TimeToStr(invalid_since
).c_str());
2115 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
2117 std::cerr
<< "Got Codename: " << MetaIndexParser
->GetDist() << std::endl
;
2118 std::cerr
<< "Expecting Dist: " << MetaIndexParser
->GetExpectedDist() << std::endl
;
2119 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
2122 if (MetaIndexParser
->CheckDist(Transformed
) == false)
2124 // This might become fatal one day
2125 // Status = StatAuthError;
2126 // ErrorText = "Conflicting distribution; expected "
2127 // + MetaIndexParser->GetExpectedDist() + " but got "
2128 // + MetaIndexParser->GetDist();
2130 if (!Transformed
.empty())
2132 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
2133 Desc
.Description
.c_str(),
2134 Transformed
.c_str(),
2135 MetaIndexParser
->GetDist().c_str());
2142 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
2143 void pkgAcqMetaIndex::Failed(string Message
,
2144 pkgAcquire::MethodConfig
* Cnf
)
2146 pkgAcquire::Item::Failed(Message
, Cnf
);
2149 string FinalFile
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
2151 _error
->Warning(_("The repository '%s' does not have a Release file. "
2152 "This is deprecated, please contact the owner of the "
2153 "repository."), URIDesc
.c_str());
2155 // No Release file was present so fall
2156 // back to queueing Packages files without verification
2157 // only allow going further if the users explicitely wants it
2158 if(MetaIndexParser
->IsAlwaysTrusted() || _config
->FindB("Acquire::AllowInsecureRepositories") == true)
2160 // Done, queue for rename on transaction finished
2161 if (FileExists(DestFile
))
2162 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2164 // queue without any kind of hashsum support
2165 QueueIndexes(false);
2167 // warn if the repository is unsinged
2168 _error
->Error("Use --allow-insecure-repositories to force the update");
2169 TransactionManager
->AbortTransaction();
2175 void pkgAcqMetaIndex::Finished() /*{{{*/
2177 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2178 std::clog
<< "Finished: " << DestFile
<<std::endl
;
2179 if(TransactionManager
!= NULL
&&
2180 TransactionManager
->TransactionHasError() == false)
2181 TransactionManager
->CommitTransaction();
2184 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
*Owner
, /*{{{*/
2185 string
const &URI
, string
const &URIDesc
, string
const &ShortDesc
,
2186 string
const &MetaIndexURI
, string
const &MetaIndexURIDesc
, string
const &MetaIndexShortDesc
,
2187 string
const &MetaSigURI
, string
const &MetaSigURIDesc
, string
const &MetaSigShortDesc
,
2188 const vector
<IndexTarget
*>* IndexTargets
,
2189 indexRecords
* MetaIndexParser
) :
2190 pkgAcqMetaIndex(Owner
, NULL
, URI
, URIDesc
, ShortDesc
, MetaSigURI
, MetaSigURIDesc
,MetaSigShortDesc
, IndexTargets
, MetaIndexParser
),
2191 MetaIndexURI(MetaIndexURI
), MetaIndexURIDesc(MetaIndexURIDesc
), MetaIndexShortDesc(MetaIndexShortDesc
),
2192 MetaSigURI(MetaSigURI
), MetaSigURIDesc(MetaSigURIDesc
), MetaSigShortDesc(MetaSigShortDesc
)
2194 // index targets + (worst case:) Release/Release.gpg
2195 ExpectedAdditionalItems
= IndexTargets
->size() + 2;
2199 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
2203 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
2204 // ---------------------------------------------------------------------
2205 string
pkgAcqMetaClearSig::Custom600Headers() const
2207 string Header
= GetCustom600Headers(RealURI
);
2208 Header
+= "\nFail-Ignore: true";
2212 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
2213 // ---------------------------------------------------------------------
2214 void pkgAcqMetaClearSig::Done(std::string Message
,unsigned long long /*Size*/,
2215 HashStringList
const &/*Hashes*/,
2216 pkgAcquire::MethodConfig
*Cnf
)
2218 // if we expect a ClearTextSignature (InRelase), ensure that
2219 // this is what we get and if not fail to queue a
2220 // Release/Release.gpg, see #346386
2221 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
2223 pkgAcquire::Item::Failed(Message
, Cnf
);
2224 RenameOnError(NotClearsigned
);
2225 TransactionManager
->AbortTransaction();
2229 if(AuthPass
== false)
2231 if(CheckDownloadDone(Message
, RealURI
) == true)
2232 QueueForSignatureVerify(DestFile
, DestFile
);
2237 if(CheckAuthDone(Message
, RealURI
) == true)
2239 string FinalFile
= _config
->FindDir("Dir::State::lists");
2240 FinalFile
+= URItoFileName(RealURI
);
2242 // queue for copy in place
2243 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2248 void pkgAcqMetaClearSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
) /*{{{*/
2250 Item::Failed(Message
, Cnf
);
2252 // we failed, we will not get additional items from this method
2253 ExpectedAdditionalItems
= 0;
2255 if (AuthPass
== false)
2257 // Queue the 'old' InRelease file for removal if we try Release.gpg
2258 // as otherwise the file will stay around and gives a false-auth
2259 // impression (CVE-2012-0214)
2260 string FinalFile
= _config
->FindDir("Dir::State::lists");
2261 FinalFile
.append(URItoFileName(RealURI
));
2262 TransactionManager
->TransactionStageRemoval(this, FinalFile
);
2265 new pkgAcqMetaIndex(Owner
, TransactionManager
,
2266 MetaIndexURI
, MetaIndexURIDesc
, MetaIndexShortDesc
,
2267 MetaSigURI
, MetaSigURIDesc
, MetaSigShortDesc
,
2268 IndexTargets
, MetaIndexParser
);
2272 if(CheckStopAuthentication(RealURI
, Message
))
2275 _error
->Warning(_("The data from '%s' is not signed. Packages "
2276 "from that repository can not be authenticated."),
2279 // No Release file was present, or verification failed, so fall
2280 // back to queueing Packages files without verification
2281 // only allow going further if the users explicitely wants it
2282 if(MetaIndexParser
->IsAlwaysTrusted() || _config
->FindB("Acquire::AllowInsecureRepositories") == true)
2286 /* Always move the meta index, even if gpgv failed. This ensures
2287 * that PackageFile objects are correctly filled in */
2288 if (FileExists(DestFile
))
2290 string FinalFile
= _config
->FindDir("Dir::State::lists");
2291 FinalFile
+= URItoFileName(RealURI
);
2292 /* InRelease files become Release files, otherwise
2293 * they would be considered as trusted later on */
2294 RealURI
= RealURI
.replace(RealURI
.rfind("InRelease"), 9,
2296 FinalFile
= FinalFile
.replace(FinalFile
.rfind("InRelease"), 9,
2299 // Done, queue for rename on transaction finished
2300 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2302 QueueIndexes(false);
2304 // warn if the repository is unsigned
2305 _error
->Error("Use --allow-insecure-repositories to force the update");
2306 TransactionManager
->AbortTransaction();
2312 // AcqArchive::AcqArchive - Constructor /*{{{*/
2313 // ---------------------------------------------------------------------
2314 /* This just sets up the initial fetch environment and queues the first
2316 pkgAcqArchive::pkgAcqArchive(pkgAcquire
*Owner
,pkgSourceList
*Sources
,
2317 pkgRecords
*Recs
,pkgCache::VerIterator
const &Version
,
2318 string
&StoreFilename
) :
2319 Item(Owner
, HashStringList()), Version(Version
), Sources(Sources
), Recs(Recs
),
2320 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
2323 Retries
= _config
->FindI("Acquire::Retries",0);
2325 if (Version
.Arch() == 0)
2327 _error
->Error(_("I wasn't able to locate a file for the %s package. "
2328 "This might mean you need to manually fix this package. "
2329 "(due to missing arch)"),
2330 Version
.ParentPkg().FullName().c_str());
2334 /* We need to find a filename to determine the extension. We make the
2335 assumption here that all the available sources for this version share
2336 the same extension.. */
2337 // Skip not source sources, they do not have file fields.
2338 for (; Vf
.end() == false; ++Vf
)
2340 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
2345 // Does not really matter here.. we are going to fail out below
2346 if (Vf
.end() != true)
2348 // If this fails to get a file name we will bomb out below.
2349 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2350 if (_error
->PendingError() == true)
2353 // Generate the final file name as: package_version_arch.foo
2354 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
2355 QuoteString(Version
.VerStr(),"_:") + '_' +
2356 QuoteString(Version
.Arch(),"_:.") +
2357 "." + flExtension(Parse
.FileName());
2360 // check if we have one trusted source for the package. if so, switch
2361 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2362 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
2363 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
2364 bool seenUntrusted
= false;
2365 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
2367 pkgIndexFile
*Index
;
2368 if (Sources
->FindIndex(i
.File(),Index
) == false)
2371 if (debugAuth
== true)
2372 std::cerr
<< "Checking index: " << Index
->Describe()
2373 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
2375 if (Index
->IsTrusted() == true)
2378 if (allowUnauth
== false)
2382 seenUntrusted
= true;
2385 // "allow-unauthenticated" restores apts old fetching behaviour
2386 // that means that e.g. unauthenticated file:// uris are higher
2387 // priority than authenticated http:// uris
2388 if (allowUnauth
== true && seenUntrusted
== true)
2392 if (QueueNext() == false && _error
->PendingError() == false)
2393 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
2394 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
2397 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2398 // ---------------------------------------------------------------------
2399 /* This queues the next available file version for download. It checks if
2400 the archive is already available in the cache and stashs the MD5 for
2402 bool pkgAcqArchive::QueueNext()
2404 for (; Vf
.end() == false; ++Vf
)
2406 // Ignore not source sources
2407 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
2410 // Try to cross match against the source list
2411 pkgIndexFile
*Index
;
2412 if (Sources
->FindIndex(Vf
.File(),Index
) == false)
2415 // only try to get a trusted package from another source if that source
2417 if(Trusted
&& !Index
->IsTrusted())
2420 // Grab the text package record
2421 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2422 if (_error
->PendingError() == true)
2425 string PkgFile
= Parse
.FileName();
2426 ExpectedHashes
= Parse
.Hashes();
2428 if (PkgFile
.empty() == true)
2429 return _error
->Error(_("The package index files are corrupted. No Filename: "
2430 "field for package %s."),
2431 Version
.ParentPkg().Name());
2433 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
2434 Desc
.Description
= Index
->ArchiveInfo(Version
);
2436 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
2438 // See if we already have the file. (Legacy filenames)
2439 FileSize
= Version
->Size
;
2440 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
2442 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2444 // Make sure the size matches
2445 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2450 StoreFilename
= DestFile
= FinalFile
;
2454 /* Hmm, we have a file and its size does not match, this means it is
2455 an old style mismatched arch */
2456 unlink(FinalFile
.c_str());
2459 // Check it again using the new style output filenames
2460 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
2461 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2463 // Make sure the size matches
2464 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2469 StoreFilename
= DestFile
= FinalFile
;
2473 /* Hmm, we have a file and its size does not match, this shouldn't
2475 unlink(FinalFile
.c_str());
2478 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
2480 // Check the destination file
2481 if (stat(DestFile
.c_str(),&Buf
) == 0)
2483 // Hmm, the partial file is too big, erase it
2484 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
2485 unlink(DestFile
.c_str());
2488 PartialSize
= Buf
.st_size
;
2489 std::string SandboxUser
= _config
->Find("APT::Sandbox::User");
2490 ChangeOwnerAndPermissionOfFile("pkgAcqArchive::QueueNext",DestFile
.c_str(), SandboxUser
.c_str(), "root", 0600);
2494 // Disables download of archives - useful if no real installation follows,
2495 // e.g. if we are just interested in proposed installation order
2496 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2501 StoreFilename
= DestFile
= FinalFile
;
2515 // AcqArchive::Done - Finished fetching /*{{{*/
2516 // ---------------------------------------------------------------------
2518 void pkgAcqArchive::Done(string Message
,unsigned long long Size
, HashStringList
const &CalcHashes
,
2519 pkgAcquire::MethodConfig
*Cfg
)
2521 Item::Done(Message
, Size
, CalcHashes
, Cfg
);
2524 if (Size
!= Version
->Size
)
2526 RenameOnError(SizeMismatch
);
2530 // FIXME: could this empty() check impose *any* sort of security issue?
2531 if(ExpectedHashes
.usable() && ExpectedHashes
!= CalcHashes
)
2533 RenameOnError(HashSumMismatch
);
2534 printHashSumComparision(DestFile
, ExpectedHashes
, CalcHashes
);
2538 // Grab the output filename
2539 string FileName
= LookupTag(Message
,"Filename");
2540 if (FileName
.empty() == true)
2543 ErrorText
= "Method gave a blank filename";
2547 // Reference filename
2548 if (FileName
!= DestFile
)
2550 StoreFilename
= DestFile
= FileName
;
2556 // Done, move it into position
2557 string FinalFile
= _config
->FindDir("Dir::Cache::Archives");
2558 FinalFile
+= flNotDir(StoreFilename
);
2559 Rename(DestFile
,FinalFile
);
2560 ChangeOwnerAndPermissionOfFile("pkgAcqArchive::Done", FinalFile
.c_str(), "root", "root", 0644);
2561 StoreFilename
= DestFile
= FinalFile
;
2565 // AcqArchive::Failed - Failure handler /*{{{*/
2566 // ---------------------------------------------------------------------
2567 /* Here we try other sources */
2568 void pkgAcqArchive::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
2570 ErrorText
= LookupTag(Message
,"Message");
2572 /* We don't really want to retry on failed media swaps, this prevents
2573 that. An interesting observation is that permanent failures are not
2575 if (Cnf
->Removable
== true &&
2576 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2578 // Vf = Version.FileList();
2579 while (Vf
.end() == false) ++Vf
;
2580 StoreFilename
= string();
2581 Item::Failed(Message
,Cnf
);
2585 if (QueueNext() == false)
2587 // This is the retry counter
2589 Cnf
->LocalOnly
== false &&
2590 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2593 Vf
= Version
.FileList();
2594 if (QueueNext() == true)
2598 StoreFilename
= string();
2599 Item::Failed(Message
,Cnf
);
2603 // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
2604 // ---------------------------------------------------------------------
2605 APT_PURE
bool pkgAcqArchive::IsTrusted() const
2610 // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
2611 // ---------------------------------------------------------------------
2613 void pkgAcqArchive::Finished()
2615 if (Status
== pkgAcquire::Item::StatDone
&&
2618 StoreFilename
= string();
2621 // AcqFile::pkgAcqFile - Constructor /*{{{*/
2622 // ---------------------------------------------------------------------
2623 /* The file is added to the queue */
2624 pkgAcqFile::pkgAcqFile(pkgAcquire
*Owner
,string URI
, HashStringList
const &Hashes
,
2625 unsigned long long Size
,string Dsc
,string ShortDesc
,
2626 const string
&DestDir
, const string
&DestFilename
,
2628 Item(Owner
, Hashes
), IsIndexFile(IsIndexFile
)
2630 Retries
= _config
->FindI("Acquire::Retries",0);
2632 if(!DestFilename
.empty())
2633 DestFile
= DestFilename
;
2634 else if(!DestDir
.empty())
2635 DestFile
= DestDir
+ "/" + flNotDir(URI
);
2637 DestFile
= flNotDir(URI
);
2641 Desc
.Description
= Dsc
;
2644 // Set the short description to the archive component
2645 Desc
.ShortDesc
= ShortDesc
;
2647 // Get the transfer sizes
2650 if (stat(DestFile
.c_str(),&Buf
) == 0)
2652 // Hmm, the partial file is too big, erase it
2653 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
2654 unlink(DestFile
.c_str());
2657 PartialSize
= Buf
.st_size
;
2658 std::string SandboxUser
= _config
->Find("APT::Sandbox::User");
2659 ChangeOwnerAndPermissionOfFile("pkgAcqFile", DestFile
.c_str(), SandboxUser
.c_str(), "root", 0600);
2666 // AcqFile::Done - Item downloaded OK /*{{{*/
2667 // ---------------------------------------------------------------------
2669 void pkgAcqFile::Done(string Message
,unsigned long long Size
,HashStringList
const &CalcHashes
,
2670 pkgAcquire::MethodConfig
*Cnf
)
2672 Item::Done(Message
,Size
,CalcHashes
,Cnf
);
2675 if(ExpectedHashes
.usable() && ExpectedHashes
!= CalcHashes
)
2677 RenameOnError(HashSumMismatch
);
2678 printHashSumComparision(DestFile
, ExpectedHashes
, CalcHashes
);
2682 string FileName
= LookupTag(Message
,"Filename");
2683 if (FileName
.empty() == true)
2686 ErrorText
= "Method gave a blank filename";
2692 // The files timestamp matches
2693 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
2696 // We have to copy it into place
2697 if (FileName
!= DestFile
)
2700 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
2701 Cnf
->Removable
== true)
2703 Desc
.URI
= "copy:" + FileName
;
2708 // Erase the file if it is a symlink so we can overwrite it
2710 if (lstat(DestFile
.c_str(),&St
) == 0)
2712 if (S_ISLNK(St
.st_mode
) != 0)
2713 unlink(DestFile
.c_str());
2717 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
2719 ErrorText
= "Link to " + DestFile
+ " failure ";
2726 // AcqFile::Failed - Failure handler /*{{{*/
2727 // ---------------------------------------------------------------------
2728 /* Here we try other sources */
2729 void pkgAcqFile::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
2731 ErrorText
= LookupTag(Message
,"Message");
2733 // This is the retry counter
2735 Cnf
->LocalOnly
== false &&
2736 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2743 Item::Failed(Message
,Cnf
);
2746 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2747 // ---------------------------------------------------------------------
2748 /* The only header we use is the last-modified header. */
2749 string
pkgAcqFile::Custom600Headers() const
2752 return "\nIndex-File: true";