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
))
218 ChangeOwnerAndPermissionOfFile("GetPartialFileName", DestFile
.c_str(), "_apt", "root", 0600);
219 Owner
->Enqueue(Item
);
221 void pkgAcquire::Item::Dequeue()
223 Owner
->Dequeue(this);
226 bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState
const error
)/*{{{*/
228 if(FileExists(DestFile
))
229 Rename(DestFile
, DestFile
+ ".FAILED");
233 case HashSumMismatch
:
234 ErrorText
= _("Hash Sum mismatch");
235 Status
= StatAuthError
;
236 ReportMirrorFailure("HashChecksumFailure");
239 ErrorText
= _("Size mismatch");
240 Status
= StatAuthError
;
241 ReportMirrorFailure("SizeFailure");
244 ErrorText
= _("Invalid file format");
246 // do not report as usually its not the mirrors fault, but Portal/Proxy
249 ErrorText
= _("Signature error");
253 ErrorText
= _("Does not start with a cleartext signature");
260 void pkgAcquire::Item::SetActiveSubprocess(const std::string
&subprocess
)/*{{{*/
262 ActiveSubprocess
= subprocess
;
264 #pragma GCC diagnostic push
265 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
267 Mode
= ActiveSubprocess
.c_str();
269 #pragma GCC diagnostic pop
273 // Acquire::Item::ReportMirrorFailure /*{{{*/
274 // ---------------------------------------------------------------------
275 void pkgAcquire::Item::ReportMirrorFailure(string FailCode
)
277 // we only act if a mirror was used at all
278 if(UsedMirror
.empty())
281 std::cerr
<< "\nReportMirrorFailure: "
283 << " Uri: " << DescURI()
285 << FailCode
<< std::endl
;
287 const char *Args
[40];
289 string report
= _config
->Find("Methods::Mirror::ProblemReporting",
290 "/usr/lib/apt/apt-report-mirror-failure");
291 if(!FileExists(report
))
293 Args
[i
++] = report
.c_str();
294 Args
[i
++] = UsedMirror
.c_str();
295 Args
[i
++] = DescURI().c_str();
296 Args
[i
++] = FailCode
.c_str();
298 pid_t pid
= ExecFork();
301 _error
->Error("ReportMirrorFailure Fork failed");
306 execvp(Args
[0], (char**)Args
);
307 std::cerr
<< "Could not exec " << Args
[0] << std::endl
;
310 if(!ExecWait(pid
, "report-mirror-failure"))
312 _error
->Warning("Couldn't report problem to '%s'",
313 _config
->Find("Methods::Mirror::ProblemReporting").c_str());
317 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
318 // ---------------------------------------------------------------------
319 /* Get the DiffIndex file first and see if there are patches available
320 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
321 * patches. If anything goes wrong in that process, it will fall back to
322 * the original packages file
324 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire
*Owner
,
325 pkgAcqMetaBase
*TransactionManager
,
326 IndexTarget
const * const Target
,
327 HashStringList
const &ExpectedHashes
,
328 indexRecords
*MetaIndexParser
)
329 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
,
330 MetaIndexParser
), PackagesFileReadyInPartial(false)
333 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
335 RealURI
= Target
->URI
;
337 Desc
.Description
= Target
->Description
+ ".diff/Index";
338 Desc
.ShortDesc
= Target
->ShortDesc
;
339 Desc
.URI
= Target
->URI
+ ".diff/Index";
341 DestFile
= GetPartialFileNameFromURI(Desc
.URI
);
344 std::clog
<< "pkgAcqDiffIndex: " << Desc
.URI
<< std::endl
;
346 // look for the current package file
347 CurrentPackagesFile
= _config
->FindDir("Dir::State::lists");
348 CurrentPackagesFile
+= URItoFileName(RealURI
);
350 // FIXME: this file:/ check is a hack to prevent fetching
351 // from local sources. this is really silly, and
352 // should be fixed cleanly as soon as possible
353 if(!FileExists(CurrentPackagesFile
) ||
354 Desc
.URI
.substr(0,strlen("file:/")) == "file:/")
356 // we don't have a pkg file or we don't want to queue
357 Failed("No index file, local or canceld by user", NULL
);
362 std::clog
<< "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
363 << CurrentPackagesFile
<< std::endl
;
369 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
370 // ---------------------------------------------------------------------
371 /* The only header we use is the last-modified header. */
372 string
pkgAcqDiffIndex::Custom600Headers() const
374 string Final
= _config
->FindDir("Dir::State::lists");
375 Final
+= URItoFileName(Desc
.URI
);
378 std::clog
<< "Custom600Header-IMS: " << Final
<< std::endl
;
381 if (stat(Final
.c_str(),&Buf
) != 0)
382 return "\nIndex-File: true";
384 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
387 bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile
) /*{{{*/
389 // failing here is fine: our caller will take care of trying to
390 // get the complete file if patching fails
392 std::clog
<< "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
395 FileFd
Fd(IndexDiffFile
,FileFd::ReadOnly
);
397 if (_error
->PendingError() == true)
401 if(unlikely(TF
.Step(Tags
) == false))
404 HashStringList ServerHashes
;
405 unsigned long long ServerSize
= 0;
407 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
409 std::string tagname
= *type
;
410 tagname
.append("-Current");
411 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
412 if (tmp
.empty() == true)
416 unsigned long long size
;
417 std::stringstream
ss(tmp
);
419 if (unlikely(hash
.empty() == true))
421 if (unlikely(ServerSize
!= 0 && ServerSize
!= size
))
423 ServerHashes
.push_back(HashString(*type
, hash
));
427 if (ServerHashes
.usable() == false)
430 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Did not find a good hashsum in the index" << std::endl
;
434 if (ServerHashes
!= HashSums())
438 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl
;
439 printHashSumComparision(CurrentPackagesFile
, ServerHashes
, HashSums());
444 if (ServerHashes
.VerifyFile(CurrentPackagesFile
) == true)
446 // we have the same sha1 as the server so we are done here
448 std::clog
<< "pkgAcqDiffIndex: Package file " << CurrentPackagesFile
<< " is up-to-date" << std::endl
;
450 // list cleanup needs to know that this file as well as the already
451 // present index is ours, so we create an empty diff to save it for us
452 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
453 ExpectedHashes
, MetaIndexParser
);
457 FileFd
fd(CurrentPackagesFile
, FileFd::ReadOnly
);
458 Hashes LocalHashesCalc
;
459 LocalHashesCalc
.AddFD(fd
);
460 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
463 std::clog
<< "Server-Current: " << ServerHashes
.find(NULL
)->toStr() << " and we start at "
464 << fd
.Name() << " " << fd
.FileSize() << " " << LocalHashes
.find(NULL
)->toStr() << std::endl
;
466 // parse all of (provided) history
467 vector
<DiffInfo
> available_patches
;
468 bool firstAcceptedHashes
= true;
469 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
471 if (LocalHashes
.find(*type
) == NULL
)
474 std::string tagname
= *type
;
475 tagname
.append("-History");
476 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
477 if (tmp
.empty() == true)
480 string hash
, filename
;
481 unsigned long long size
;
482 std::stringstream
ss(tmp
);
484 while (ss
>> hash
>> size
>> filename
)
486 if (unlikely(hash
.empty() == true || filename
.empty() == true))
489 // see if we have a record for this file already
490 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
491 for (; cur
!= available_patches
.end(); ++cur
)
493 if (cur
->file
!= filename
|| unlikely(cur
->result_size
!= size
))
495 cur
->result_hashes
.push_back(HashString(*type
, hash
));
498 if (cur
!= available_patches
.end())
500 if (firstAcceptedHashes
== true)
503 next
.file
= filename
;
504 next
.result_hashes
.push_back(HashString(*type
, hash
));
505 next
.result_size
= size
;
507 available_patches
.push_back(next
);
512 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
513 << " wasn't in the list for the first parsed hash! (history)" << std::endl
;
517 firstAcceptedHashes
= false;
520 if (unlikely(available_patches
.empty() == true))
523 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
524 << "Couldn't find any patches for the patch series." << std::endl
;
528 for (char const * const * type
= HashString::SupportedHashes(); *type
!= NULL
; ++type
)
530 if (LocalHashes
.find(*type
) == NULL
)
533 std::string tagname
= *type
;
534 tagname
.append("-Patches");
535 std::string
const tmp
= Tags
.FindS(tagname
.c_str());
536 if (tmp
.empty() == true)
539 string hash
, filename
;
540 unsigned long long size
;
541 std::stringstream
ss(tmp
);
543 while (ss
>> hash
>> size
>> filename
)
545 if (unlikely(hash
.empty() == true || filename
.empty() == true))
548 // see if we have a record for this file already
549 std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
550 for (; cur
!= available_patches
.end(); ++cur
)
552 if (cur
->file
!= filename
)
554 if (unlikely(cur
->patch_size
!= 0 && cur
->patch_size
!= size
))
556 cur
->patch_hashes
.push_back(HashString(*type
, hash
));
557 cur
->patch_size
= size
;
560 if (cur
!= available_patches
.end())
563 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": File " << filename
564 << " wasn't in the list for the first parsed hash! (patches)" << std::endl
;
569 bool foundStart
= false;
570 for (std::vector
<DiffInfo
>::iterator cur
= available_patches
.begin();
571 cur
!= available_patches
.end(); ++cur
)
573 if (LocalHashes
!= cur
->result_hashes
)
576 available_patches
.erase(available_patches
.begin(), cur
);
581 if (foundStart
== false || unlikely(available_patches
.empty() == true))
584 std::clog
<< "pkgAcqDiffIndex: " << IndexDiffFile
<< ": "
585 << "Couldn't find the start of the patch series." << std::endl
;
589 // patching with too many files is rather slow compared to a fast download
590 unsigned long const fileLimit
= _config
->FindI("Acquire::PDiffs::FileLimit", 0);
591 if (fileLimit
!= 0 && fileLimit
< available_patches
.size())
594 std::clog
<< "Need " << available_patches
.size() << " diffs (Limit is " << fileLimit
595 << ") so fallback to complete download" << std::endl
;
599 // calculate the size of all patches we have to get
600 // note that all sizes are uncompressed, while we download compressed files
601 unsigned long long patchesSize
= 0;
602 for (std::vector
<DiffInfo
>::const_iterator cur
= available_patches
.begin();
603 cur
!= available_patches
.end(); ++cur
)
604 patchesSize
+= cur
->patch_size
;
605 unsigned long long const sizeLimit
= ServerSize
* _config
->FindI("Acquire::PDiffs::SizeLimit", 100);
606 if (false && sizeLimit
> 0 && (sizeLimit
/100) < patchesSize
)
609 std::clog
<< "Need " << patchesSize
<< " bytes (Limit is " << sizeLimit
/100
610 << ") so fallback to complete download" << std::endl
;
614 // FIXME: make this use the method
615 PackagesFileReadyInPartial
= true;
616 std::string
const Partial
= GetPartialFileNameFromURI(RealURI
);
618 FileFd
From(CurrentPackagesFile
, FileFd::ReadOnly
);
619 FileFd
To(Partial
, FileFd::WriteEmpty
);
620 if(CopyFile(From
, To
) == false)
621 return _error
->Errno("CopyFile", "failed to copy");
624 std::cerr
<< "Done copying " << CurrentPackagesFile
628 // we have something, queue the diffs
629 string::size_type
const last_space
= Description
.rfind(" ");
630 if(last_space
!= string::npos
)
631 Description
.erase(last_space
, Description
.size()-last_space
);
633 /* decide if we should download patches one by one or in one go:
634 The first is good if the server merges patches, but many don't so client
635 based merging can be attempt in which case the second is better.
636 "bad things" will happen if patches are merged on the server,
637 but client side merging is attempt as well */
638 bool pdiff_merge
= _config
->FindB("Acquire::PDiffs::Merge", true);
639 if (pdiff_merge
== true)
641 // reprepro adds this flag if it has merged patches on the server
642 std::string
const precedence
= Tags
.FindS("X-Patch-Precedence");
643 pdiff_merge
= (precedence
!= "merged");
646 if (pdiff_merge
== false)
648 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
, ExpectedHashes
,
649 MetaIndexParser
, available_patches
);
653 std::vector
<pkgAcqIndexMergeDiffs
*> *diffs
= new std::vector
<pkgAcqIndexMergeDiffs
*>(available_patches
.size());
654 for(size_t i
= 0; i
< available_patches
.size(); ++i
)
655 (*diffs
)[i
] = new pkgAcqIndexMergeDiffs(Owner
, TransactionManager
,
659 available_patches
[i
],
669 void pkgAcqDiffIndex::Failed(string Message
,pkgAcquire::MethodConfig
* Cnf
)/*{{{*/
672 std::clog
<< "pkgAcqDiffIndex failed: " << Desc
.URI
<< " with " << Message
<< std::endl
673 << "Falling back to normal index file acquire" << std::endl
;
675 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
677 Item::Failed(Message
,Cnf
);
681 void pkgAcqDiffIndex::Done(string Message
,unsigned long long Size
,HashStringList
const &Hashes
, /*{{{*/
682 pkgAcquire::MethodConfig
*Cnf
)
685 std::clog
<< "pkgAcqDiffIndex::Done(): " << Desc
.URI
<< std::endl
;
687 Item::Done(Message
, Size
, Hashes
, Cnf
);
689 // verify the index target
690 if(Target
&& Target
->MetaKey
!= "" && MetaIndexParser
&& Hashes
.usable())
692 std::string IndexMetaKey
= Target
->MetaKey
+ ".diff/Index";
693 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(IndexMetaKey
);
694 if(Record
&& Record
->Hashes
.usable() && Hashes
!= Record
->Hashes
)
696 RenameOnError(HashSumMismatch
);
697 printHashSumComparision(RealURI
, Record
->Hashes
, Hashes
);
698 Failed(Message
, Cnf
);
705 FinalFile
= _config
->FindDir("Dir::State::lists");
706 FinalFile
+= URItoFileName(Desc
.URI
);
708 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false))
709 DestFile
= FinalFile
;
711 if(!ParseDiffIndex(DestFile
))
712 return Failed("Message: Couldn't parse pdiff index", Cnf
);
714 // queue for final move
715 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
723 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
724 // ---------------------------------------------------------------------
725 /* The package diff is added to the queue. one object is constructed
726 * for each diff and the index
728 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire
*Owner
,
729 pkgAcqMetaBase
*TransactionManager
,
730 struct IndexTarget
const * const Target
,
731 HashStringList
const &ExpectedHashes
,
732 indexRecords
*MetaIndexParser
,
733 vector
<DiffInfo
> diffs
)
734 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
),
735 available_patches(diffs
)
737 DestFile
= GetPartialFileNameFromURI(Target
->URI
);
739 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
741 RealURI
= Target
->URI
;
743 Description
= Target
->Description
;
744 Desc
.ShortDesc
= Target
->ShortDesc
;
746 if(available_patches
.empty() == true)
748 // we are done (yeah!), check hashes against the final file
749 DestFile
= _config
->FindDir("Dir::State::lists");
750 DestFile
+= URItoFileName(Target
->URI
);
756 State
= StateFetchDiff
;
761 void pkgAcqIndexDiffs::Failed(string Message
,pkgAcquire::MethodConfig
* /*Cnf*/)/*{{{*/
764 std::clog
<< "pkgAcqIndexDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
765 << "Falling back to normal index file acquire" << std::endl
;
766 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
770 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
771 void pkgAcqIndexDiffs::Finish(bool allDone
)
774 std::clog
<< "pkgAcqIndexDiffs::Finish(): "
776 << Desc
.URI
<< std::endl
;
778 // we restore the original name, this is required, otherwise
779 // the file will be cleaned
782 if(HashSums().usable() && !HashSums().VerifyFile(DestFile
))
784 RenameOnError(HashSumMismatch
);
790 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
791 FinalFile
+= URItoFileName(RealURI
);
792 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
794 // this is for the "real" finish
799 std::clog
<< "\n\nallDone: " << DestFile
<< "\n" << std::endl
;
804 std::clog
<< "Finishing: " << Desc
.URI
<< std::endl
;
811 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
813 // calc sha1 of the just patched file
814 std::string
const FinalFile
= GetPartialFileNameFromURI(RealURI
);
816 if(!FileExists(FinalFile
))
818 Failed("Message: No FinalFile " + FinalFile
+ " available", NULL
);
822 FileFd
fd(FinalFile
, FileFd::ReadOnly
);
823 Hashes LocalHashesCalc
;
824 LocalHashesCalc
.AddFD(fd
);
825 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
828 std::clog
<< "QueueNextDiff: " << FinalFile
<< " (" << LocalHashes
.find(NULL
)->toStr() << ")" << std::endl
;
830 if (unlikely(LocalHashes
.usable() == false || ExpectedHashes
.usable() == false))
832 Failed("Local/Expected hashes are not usable", NULL
);
837 // final file reached before all patches are applied
838 if(LocalHashes
== ExpectedHashes
)
844 // remove all patches until the next matching patch is found
845 // this requires the Index file to be ordered
846 for(vector
<DiffInfo
>::iterator I
= available_patches
.begin();
847 available_patches
.empty() == false &&
848 I
!= available_patches
.end() &&
849 I
->result_hashes
!= LocalHashes
;
852 available_patches
.erase(I
);
855 // error checking and falling back if no patch was found
856 if(available_patches
.empty() == true)
858 Failed("No patches left to reach target", NULL
);
862 // queue the right diff
863 Desc
.URI
= RealURI
+ ".diff/" + available_patches
[0].file
+ ".gz";
864 Desc
.Description
= Description
+ " " + available_patches
[0].file
+ string(".pdiff");
865 DestFile
= GetPartialFileNameFromURI(RealURI
+ ".diff/" + available_patches
[0].file
);
868 std::clog
<< "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc
.URI
<< std::endl
;
875 void pkgAcqIndexDiffs::Done(string Message
,unsigned long long Size
, HashStringList
const &Hashes
, /*{{{*/
876 pkgAcquire::MethodConfig
*Cnf
)
879 std::clog
<< "pkgAcqIndexDiffs::Done(): " << Desc
.URI
<< std::endl
;
881 Item::Done(Message
, Size
, Hashes
, Cnf
);
883 // FIXME: verify this download too before feeding it to rred
884 std::string
const FinalFile
= GetPartialFileNameFromURI(RealURI
);
886 // success in downloading a diff, enter ApplyDiff state
887 if(State
== StateFetchDiff
)
889 FileFd
fd(DestFile
, FileFd::ReadOnly
, FileFd::Gzip
);
890 class Hashes LocalHashesCalc
;
891 LocalHashesCalc
.AddFD(fd
);
892 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
894 if (fd
.Size() != available_patches
[0].patch_size
||
895 available_patches
[0].patch_hashes
!= LocalHashes
)
897 Failed("Patch has Size/Hashsum mismatch", NULL
);
901 // rred excepts the patch as $FinalFile.ed
902 Rename(DestFile
,FinalFile
+".ed");
905 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
907 State
= StateApplyDiff
;
909 Desc
.URI
= "rred:" + FinalFile
;
911 SetActiveSubprocess("rred");
916 // success in download/apply a diff, queue next (if needed)
917 if(State
== StateApplyDiff
)
919 // remove the just applied patch
920 available_patches
.erase(available_patches
.begin());
921 unlink((FinalFile
+ ".ed").c_str());
926 std::clog
<< "Moving patched file in place: " << std::endl
927 << DestFile
<< " -> " << FinalFile
<< std::endl
;
929 Rename(DestFile
,FinalFile
);
930 chmod(FinalFile
.c_str(),0644);
932 // see if there is more to download
933 if(available_patches
.empty() == false) {
934 new pkgAcqIndexDiffs(Owner
, TransactionManager
, Target
,
935 ExpectedHashes
, MetaIndexParser
,
940 DestFile
= FinalFile
;
945 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
946 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire
*Owner
,
947 pkgAcqMetaBase
*TransactionManager
,
948 struct IndexTarget
const * const Target
,
949 HashStringList
const &ExpectedHashes
,
950 indexRecords
*MetaIndexParser
,
951 DiffInfo
const &patch
,
952 std::vector
<pkgAcqIndexMergeDiffs
*> const * const allPatches
)
953 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
),
954 patch(patch
), allPatches(allPatches
), State(StateFetchDiff
)
956 Debug
= _config
->FindB("Debug::pkgAcquire::Diffs",false);
958 RealURI
= Target
->URI
;
960 Description
= Target
->Description
;
961 Desc
.ShortDesc
= Target
->ShortDesc
;
963 Desc
.URI
= RealURI
+ ".diff/" + patch
.file
+ ".gz";
964 Desc
.Description
= Description
+ " " + patch
.file
+ string(".pdiff");
966 DestFile
= GetPartialFileNameFromURI(RealURI
+ ".diff/" + patch
.file
);
969 std::clog
<< "pkgAcqIndexMergeDiffs: " << Desc
.URI
<< std::endl
;
974 void pkgAcqIndexMergeDiffs::Failed(string Message
,pkgAcquire::MethodConfig
* Cnf
)/*{{{*/
977 std::clog
<< "pkgAcqIndexMergeDiffs failed: " << Desc
.URI
<< " with " << Message
<< std::endl
;
979 Item::Failed(Message
,Cnf
);
982 // check if we are the first to fail, otherwise we are done here
983 State
= StateDoneDiff
;
984 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
985 I
!= allPatches
->end(); ++I
)
986 if ((*I
)->State
== StateErrorDiff
)
989 // first failure means we should fallback
990 State
= StateErrorDiff
;
991 std::clog
<< "Falling back to normal index file acquire" << std::endl
;
992 new pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
);
995 void pkgAcqIndexMergeDiffs::Done(string Message
,unsigned long long Size
,HashStringList
const &Hashes
, /*{{{*/
996 pkgAcquire::MethodConfig
*Cnf
)
999 std::clog
<< "pkgAcqIndexMergeDiffs::Done(): " << Desc
.URI
<< std::endl
;
1001 Item::Done(Message
,Size
,Hashes
,Cnf
);
1003 // FIXME: verify download before feeding it to rred
1004 string
const FinalFile
= GetPartialFileNameFromURI(RealURI
);
1006 if (State
== StateFetchDiff
)
1008 FileFd
fd(DestFile
, FileFd::ReadOnly
, FileFd::Gzip
);
1009 class Hashes LocalHashesCalc
;
1010 LocalHashesCalc
.AddFD(fd
);
1011 HashStringList
const LocalHashes
= LocalHashesCalc
.GetHashStringList();
1013 if (fd
.Size() != patch
.patch_size
|| patch
.patch_hashes
!= LocalHashes
)
1015 Failed("Patch has Size/Hashsum mismatch", NULL
);
1019 // rred expects the patch as $FinalFile.ed.$patchname.gz
1020 Rename(DestFile
, FinalFile
+ ".ed." + patch
.file
+ ".gz");
1022 // check if this is the last completed diff
1023 State
= StateDoneDiff
;
1024 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
1025 I
!= allPatches
->end(); ++I
)
1026 if ((*I
)->State
!= StateDoneDiff
)
1029 std::clog
<< "Not the last done diff in the batch: " << Desc
.URI
<< std::endl
;
1033 // this is the last completed diff, so we are ready to apply now
1034 State
= StateApplyDiff
;
1037 std::clog
<< "Sending to rred method: " << FinalFile
<< std::endl
;
1040 Desc
.URI
= "rred:" + FinalFile
;
1042 SetActiveSubprocess("rred");
1045 // success in download/apply all diffs, clean up
1046 else if (State
== StateApplyDiff
)
1048 // see if we really got the expected file
1049 if(ExpectedHashes
.usable() && !ExpectedHashes
.VerifyFile(DestFile
))
1051 RenameOnError(HashSumMismatch
);
1056 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1057 FinalFile
+= URItoFileName(RealURI
);
1059 // move the result into place
1061 std::clog
<< "Queue patched file in place: " << std::endl
1062 << DestFile
<< " -> " << FinalFile
<< std::endl
;
1064 // queue for copy by the transaction manager
1065 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
1067 // ensure the ed's are gone regardless of list-cleanup
1068 for (std::vector
<pkgAcqIndexMergeDiffs
*>::const_iterator I
= allPatches
->begin();
1069 I
!= allPatches
->end(); ++I
)
1071 std::string
const PartialFile
= GetPartialFileNameFromURI(RealURI
);
1072 std::string patch
= PartialFile
+ ".ed." + (*I
)->patch
.file
+ ".gz";
1073 std::cerr
<< patch
<< std::endl
;
1074 unlink(patch
.c_str());
1080 std::clog
<< "allDone: " << DestFile
<< "\n" << std::endl
;
1084 // AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
1085 bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList
const &Hashes
)
1087 if(MetaKey
!= "" && Hashes
.usable())
1089 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1090 if(Record
&& Record
->Hashes
.usable() && Hashes
!= Record
->Hashes
)
1092 printHashSumComparision(RealURI
, Record
->Hashes
, Hashes
);
1099 // AcqIndex::AcqIndex - Constructor /*{{{*/
1100 // ---------------------------------------------------------------------
1101 /* The package file is added to the queue and a second class is
1102 instantiated to fetch the revision file */
1103 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
1104 string URI
,string URIDesc
,string ShortDesc
,
1105 HashStringList
const &ExpectedHash
)
1106 : pkgAcqBaseIndex(Owner
, 0, NULL
, ExpectedHash
, NULL
)
1110 AutoSelectCompression();
1111 Init(URI
, URIDesc
, ShortDesc
);
1113 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1114 std::clog
<< "New pkgIndex with TransactionManager "
1115 << TransactionManager
<< std::endl
;
1118 // AcqIndex::AcqIndex - Constructor /*{{{*/
1119 pkgAcqIndex::pkgAcqIndex(pkgAcquire
*Owner
,
1120 pkgAcqMetaBase
*TransactionManager
,
1121 IndexTarget
const *Target
,
1122 HashStringList
const &ExpectedHash
,
1123 indexRecords
*MetaIndexParser
)
1124 : pkgAcqBaseIndex(Owner
, TransactionManager
, Target
, ExpectedHash
,
1127 RealURI
= Target
->URI
;
1129 // autoselect the compression method
1130 AutoSelectCompression();
1131 Init(Target
->URI
, Target
->Description
, Target
->ShortDesc
);
1133 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1134 std::clog
<< "New pkgIndex with TransactionManager "
1135 << TransactionManager
<< std::endl
;
1138 // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
1139 void pkgAcqIndex::AutoSelectCompression()
1141 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
1142 CompressionExtensions
= "";
1143 if (ExpectedHashes
.usable())
1145 for (std::vector
<std::string
>::const_iterator t
= types
.begin();
1146 t
!= types
.end(); ++t
)
1148 std::string CompressedMetaKey
= string(Target
->MetaKey
).append(".").append(*t
);
1149 if (*t
== "uncompressed" ||
1150 MetaIndexParser
->Exists(CompressedMetaKey
) == true)
1151 CompressionExtensions
.append(*t
).append(" ");
1156 for (std::vector
<std::string
>::const_iterator t
= types
.begin(); t
!= types
.end(); ++t
)
1157 CompressionExtensions
.append(*t
).append(" ");
1159 if (CompressionExtensions
.empty() == false)
1160 CompressionExtensions
.erase(CompressionExtensions
.end()-1);
1163 // AcqIndex::Init - defered Constructor /*{{{*/
1164 void pkgAcqIndex::Init(string
const &URI
, string
const &URIDesc
,
1165 string
const &ShortDesc
)
1167 Stage
= STAGE_DOWNLOAD
;
1169 DestFile
= GetPartialFileNameFromURI(URI
);
1171 CurrentCompressionExtension
= CompressionExtensions
.substr(0, CompressionExtensions
.find(' '));
1172 if (CurrentCompressionExtension
== "uncompressed")
1176 MetaKey
= string(Target
->MetaKey
);
1180 Desc
.URI
= URI
+ '.' + CurrentCompressionExtension
;
1181 DestFile
= DestFile
+ '.' + CurrentCompressionExtension
;
1183 MetaKey
= string(Target
->MetaKey
) + '.' + CurrentCompressionExtension
;
1186 // load the filesize
1189 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1191 FileSize
= Record
->Size
;
1193 InitByHashIfNeeded(MetaKey
);
1196 Desc
.Description
= URIDesc
;
1198 Desc
.ShortDesc
= ShortDesc
;
1203 // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
1204 void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey
)
1207 // - (maybe?) add support for by-hash into the sources.list as flag
1208 // - make apt-ftparchive generate the hashes (and expire?)
1209 std::string HostKnob
= "APT::Acquire::" + ::URI(Desc
.URI
).Host
+ "::By-Hash";
1210 if(_config
->FindB("APT::Acquire::By-Hash", false) == true ||
1211 _config
->FindB(HostKnob
, false) == true ||
1212 MetaIndexParser
->GetSupportsAcquireByHash())
1214 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(MetaKey
);
1217 // FIXME: should we really use the best hash here? or a fixed one?
1218 const HashString
*TargetHash
= Record
->Hashes
.find("");
1219 std::string ByHash
= "/by-hash/" + TargetHash
->HashType() + "/" + TargetHash
->HashValue();
1220 size_t trailing_slash
= Desc
.URI
.find_last_of("/");
1221 Desc
.URI
= Desc
.URI
.replace(
1223 Desc
.URI
.substr(trailing_slash
+1).size()+1,
1227 "Fetching ByHash requested but can not find record for %s",
1233 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1234 // ---------------------------------------------------------------------
1235 /* The only header we use is the last-modified header. */
1236 string
pkgAcqIndex::Custom600Headers() const
1238 string Final
= GetFinalFilename();
1240 string msg
= "\nIndex-File: true";
1242 if (stat(Final
.c_str(),&Buf
) == 0)
1243 msg
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1248 // pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
1249 void pkgAcqIndex::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1251 size_t const nextExt
= CompressionExtensions
.find(' ');
1252 if (nextExt
!= std::string::npos
)
1254 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
1255 Init(RealURI
, Desc
.Description
, Desc
.ShortDesc
);
1259 // on decompression failure, remove bad versions in partial/
1260 if (Stage
== STAGE_DECOMPRESS_AND_VERIFY
)
1262 unlink(EraseFileName
.c_str());
1265 Item::Failed(Message
,Cnf
);
1267 /// cancel the entire transaction
1268 TransactionManager
->AbortTransaction();
1271 // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
1272 std::string
pkgAcqIndex::GetFinalFilename() const
1274 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1275 FinalFile
+= URItoFileName(RealURI
);
1276 if (_config
->FindB("Acquire::GzipIndexes",false) == true)
1277 FinalFile
+= '.' + CurrentCompressionExtension
;
1281 // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
1282 void pkgAcqIndex::ReverifyAfterIMS()
1284 // update destfile to *not* include the compression extension when doing
1285 // a reverify (as its uncompressed on disk already)
1286 DestFile
= GetPartialFileNameFromURI(RealURI
);
1288 // adjust DestFile if its compressed on disk
1289 if (_config
->FindB("Acquire::GzipIndexes",false) == true)
1290 DestFile
+= '.' + CurrentCompressionExtension
;
1292 // copy FinalFile into partial/ so that we check the hash again
1293 string FinalFile
= GetFinalFilename();
1294 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1295 Desc
.URI
= "copy:" + FinalFile
;
1299 // AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
1300 bool pkgAcqIndex::ValidateFile(const std::string
&FileName
)
1302 // FIXME: this can go away once we only ever download stuff that
1303 // has a valid hash and we never do GET based probing
1304 // FIXME2: this also leaks debian-isms into the code and should go therefore
1306 /* Always validate the index file for correctness (all indexes must
1307 * have a Package field) (LP: #346386) (Closes: #627642)
1309 FileFd
fd(FileName
, FileFd::ReadOnly
, FileFd::Extension
);
1310 // Only test for correctness if the content of the file is not empty
1315 pkgTagFile
tag(&fd
);
1317 // all our current indexes have a field 'Package' in each section
1318 if (_error
->PendingError() == true ||
1319 tag
.Step(sec
) == false ||
1320 sec
.Exists("Package") == false)
1326 // AcqIndex::Done - Finished a fetch /*{{{*/
1327 // ---------------------------------------------------------------------
1328 /* This goes through a number of states.. On the initial fetch the
1329 method could possibly return an alternate filename which points
1330 to the uncompressed version of the file. If this is so the file
1331 is copied into the partial directory. In all other cases the file
1332 is decompressed with a compressed uri. */
1333 void pkgAcqIndex::Done(string Message
,
1334 unsigned long long Size
,
1335 HashStringList
const &Hashes
,
1336 pkgAcquire::MethodConfig
*Cfg
)
1338 Item::Done(Message
,Size
,Hashes
,Cfg
);
1342 case STAGE_DOWNLOAD
:
1343 StageDownloadDone(Message
, Hashes
, Cfg
);
1345 case STAGE_DECOMPRESS_AND_VERIFY
:
1346 StageDecompressDone(Message
, Hashes
, Cfg
);
1351 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
1352 void pkgAcqIndex::StageDownloadDone(string Message
,
1353 HashStringList
const &Hashes
,
1354 pkgAcquire::MethodConfig
*Cfg
)
1356 // First check if the calculcated Hash of the (compressed) downloaded
1357 // file matches the hash we have in the MetaIndexRecords for this file
1358 if(VerifyHashByMetaKey(Hashes
) == false)
1360 RenameOnError(HashSumMismatch
);
1361 Failed(Message
, Cfg
);
1367 // Handle the unzipd case
1368 string FileName
= LookupTag(Message
,"Alt-Filename");
1369 if (FileName
.empty() == false)
1371 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1373 DestFile
+= ".decomp";
1374 Desc
.URI
= "copy:" + FileName
;
1376 SetActiveSubprocess("copy");
1380 FileName
= LookupTag(Message
,"Filename");
1381 if (FileName
.empty() == true)
1384 ErrorText
= "Method gave a blank filename";
1387 // Methods like e.g. "file:" will give us a (compressed) FileName that is
1388 // not the "DestFile" we set, in this case we uncompress from the local file
1389 if (FileName
!= DestFile
)
1392 EraseFileName
= FileName
;
1394 // we need to verify the file against the current Release file again
1395 // on if-modfied-since hit to avoid a stale attack against us
1396 if(StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
1398 // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
1399 // file when its doing the indexcopy
1400 if (RealURI
.substr(0,6) == "cdrom:")
1403 // The files timestamp matches, reverify by copy into partial/
1409 // If we have compressed indexes enabled, queue for hash verification
1410 if (_config
->FindB("Acquire::GzipIndexes",false))
1412 DestFile
= GetPartialFileNameFromURI(RealURI
+ '.' + CurrentCompressionExtension
);
1414 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1415 Desc
.URI
= "copy:" + FileName
;
1417 SetActiveSubprocess("copy");
1421 // get the binary name for your used compression type
1423 if(CurrentCompressionExtension
== "uncompressed")
1424 decompProg
= "copy";
1426 decompProg
= _config
->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension
),"");
1427 if(decompProg
.empty() == true)
1429 _error
->Error("Unsupported extension: %s", CurrentCompressionExtension
.c_str());
1433 // queue uri for the next stage
1434 Stage
= STAGE_DECOMPRESS_AND_VERIFY
;
1435 DestFile
+= ".decomp";
1436 Desc
.URI
= decompProg
+ ":" + FileName
;
1438 SetActiveSubprocess(decompProg
);
1441 // pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
1442 void pkgAcqIndex::StageDecompressDone(string Message
,
1443 HashStringList
const &Hashes
,
1444 pkgAcquire::MethodConfig
*Cfg
)
1446 if (ExpectedHashes
.usable() && ExpectedHashes
!= Hashes
)
1449 RenameOnError(HashSumMismatch
);
1450 printHashSumComparision(RealURI
, ExpectedHashes
, Hashes
);
1451 Failed(Message
, Cfg
);
1455 if(!ValidateFile(DestFile
))
1457 RenameOnError(InvalidFormat
);
1458 Failed(Message
, Cfg
);
1462 // remove the compressed version of the file
1463 unlink(EraseFileName
.c_str());
1465 // Done, queue for rename on transaction finished
1466 TransactionManager
->TransactionStageCopy(this, DestFile
, GetFinalFilename());
1471 // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
1472 // ---------------------------------------------------------------------
1473 /* The Translation file is added to the queue */
1474 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
1475 string URI
,string URIDesc
,string ShortDesc
)
1476 : pkgAcqIndex(Owner
, URI
, URIDesc
, ShortDesc
, HashStringList())
1479 pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire
*Owner
,
1480 pkgAcqMetaBase
*TransactionManager
,
1481 IndexTarget
const * const Target
,
1482 HashStringList
const &ExpectedHashes
,
1483 indexRecords
*MetaIndexParser
)
1484 : pkgAcqIndex(Owner
, TransactionManager
, Target
, ExpectedHashes
, MetaIndexParser
)
1486 // load the filesize
1487 indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup(string(Target
->MetaKey
));
1489 FileSize
= Record
->Size
;
1492 // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
1493 string
pkgAcqIndexTrans::Custom600Headers() const
1495 string Final
= GetFinalFilename();
1498 if (stat(Final
.c_str(),&Buf
) != 0)
1499 return "\nFail-Ignore: true\nIndex-File: true";
1500 return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1503 // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
1504 void pkgAcqIndexTrans::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
1506 size_t const nextExt
= CompressionExtensions
.find(' ');
1507 if (nextExt
!= std::string::npos
)
1509 CompressionExtensions
= CompressionExtensions
.substr(nextExt
+1);
1510 Init(RealURI
, Desc
.Description
, Desc
.ShortDesc
);
1515 Item::Failed(Message
,Cnf
);
1517 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1518 if (Cnf
->LocalOnly
== true ||
1519 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1526 // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
1527 void pkgAcqMetaBase::Add(Item
*I
)
1529 Transaction
.push_back(I
);
1532 // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
1533 void pkgAcqMetaBase::AbortTransaction()
1535 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1536 std::clog
<< "AbortTransaction: " << TransactionManager
<< std::endl
;
1538 // ensure the toplevel is in error state too
1539 for (std::vector
<Item
*>::iterator I
= Transaction
.begin();
1540 I
!= Transaction
.end(); ++I
)
1542 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1543 std::clog
<< " Cancel: " << (*I
)->DestFile
<< std::endl
;
1544 // the transaction will abort, so stop anything that is idle
1545 if ((*I
)->Status
== pkgAcquire::Item::StatIdle
)
1546 (*I
)->Status
= pkgAcquire::Item::StatDone
;
1548 // kill failed files in partial
1549 if ((*I
)->Status
== pkgAcquire::Item::StatError
)
1551 std::string
const PartialFile
= GetPartialFileName(flNotDir((*I
)->DestFile
));
1552 if(FileExists(PartialFile
))
1553 Rename(PartialFile
, PartialFile
+ ".FAILED");
1558 // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
1559 bool pkgAcqMetaBase::TransactionHasError()
1561 for (pkgAcquire::ItemIterator I
= Transaction
.begin();
1562 I
!= Transaction
.end(); ++I
)
1563 if((*I
)->Status
!= pkgAcquire::Item::StatDone
&&
1564 (*I
)->Status
!= pkgAcquire::Item::StatIdle
)
1570 // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
1571 void pkgAcqMetaBase::CommitTransaction()
1573 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1574 std::clog
<< "CommitTransaction: " << this << std::endl
;
1576 // move new files into place *and* remove files that are not
1577 // part of the transaction but are still on disk
1578 for (std::vector
<Item
*>::iterator I
= Transaction
.begin();
1579 I
!= Transaction
.end(); ++I
)
1581 if((*I
)->PartialFile
!= "")
1583 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1584 std::clog
<< "mv " << (*I
)->PartialFile
<< " -> "<< (*I
)->DestFile
<< " "
1585 << (*I
)->DescURI() << std::endl
;
1587 Rename((*I
)->PartialFile
, (*I
)->DestFile
);
1588 ChangeOwnerAndPermissionOfFile("CommitTransaction", (*I
)->DestFile
.c_str(), "root", "root", 0644);
1591 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1597 unlink((*I
)->DestFile
.c_str());
1599 // mark that this transaction is finished
1600 (*I
)->TransactionManager
= 0;
1604 // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
1605 void pkgAcqMetaBase::TransactionStageCopy(Item
*I
,
1606 const std::string
&From
,
1607 const std::string
&To
)
1609 I
->PartialFile
= From
;
1613 // AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
1614 void pkgAcqMetaBase::TransactionStageRemoval(Item
*I
,
1615 const std::string
&FinalFile
)
1617 I
->PartialFile
= "";
1618 I
->DestFile
= FinalFile
;
1621 // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
1622 bool pkgAcqMetaBase::CheckStopAuthentication(const std::string
&RealURI
,
1623 const std::string
&Message
)
1625 // FIXME: this entire function can do now that we disallow going to
1626 // a unauthenticated state and can cleanly rollback
1628 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
1630 if(FileExists(Final
))
1632 Status
= StatTransientNetworkError
;
1633 _error
->Warning(_("An error occurred during the signature "
1634 "verification. The repository is not updated "
1635 "and the previous index files will be used. "
1636 "GPG error: %s: %s\n"),
1637 Desc
.Description
.c_str(),
1638 LookupTag(Message
,"Message").c_str());
1639 RunScripts("APT::Update::Auth-Failure");
1641 } else if (LookupTag(Message
,"Message").find("NODATA") != string::npos
) {
1642 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
1643 _error
->Error(_("GPG error: %s: %s"),
1644 Desc
.Description
.c_str(),
1645 LookupTag(Message
,"Message").c_str());
1649 _error
->Warning(_("GPG error: %s: %s"),
1650 Desc
.Description
.c_str(),
1651 LookupTag(Message
,"Message").c_str());
1653 // gpgv method failed
1654 ReportMirrorFailure("GPGFailure");
1658 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1659 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire
*Owner
,
1660 pkgAcqMetaBase
*TransactionManager
,
1661 string URI
,string URIDesc
,string ShortDesc
,
1662 string MetaIndexFile
,
1663 const vector
<IndexTarget
*>* IndexTargets
,
1664 indexRecords
* MetaIndexParser
) :
1665 pkgAcqMetaBase(Owner
, IndexTargets
, MetaIndexParser
,
1666 HashStringList(), TransactionManager
),
1667 RealURI(URI
), MetaIndexFile(MetaIndexFile
), URIDesc(URIDesc
),
1668 ShortDesc(ShortDesc
)
1670 DestFile
= _config
->FindDir("Dir::State::lists") + "partial/";
1671 DestFile
+= URItoFileName(RealURI
);
1673 // remove any partial downloaded sig-file in partial/.
1674 // it may confuse proxies and is too small to warrant a
1675 // partial download anyway
1676 unlink(DestFile
.c_str());
1678 // set the TransactionManager
1679 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1680 std::clog
<< "New pkgAcqMetaSig with TransactionManager "
1681 << TransactionManager
<< std::endl
;
1684 Desc
.Description
= URIDesc
;
1686 Desc
.ShortDesc
= ShortDesc
;
1692 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1696 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1697 // ---------------------------------------------------------------------
1698 string
pkgAcqMetaSig::Custom600Headers() const
1700 std::string Header
= GetCustom600Headers(RealURI
);
1704 // pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1705 // ---------------------------------------------------------------------
1706 /* The only header we use is the last-modified header. */
1707 void pkgAcqMetaSig::Done(string Message
,unsigned long long Size
,
1708 HashStringList
const &Hashes
,
1709 pkgAcquire::MethodConfig
*Cfg
)
1711 Item::Done(Message
, Size
, Hashes
, Cfg
);
1713 if(AuthPass
== false)
1715 if(CheckDownloadDone(Message
, RealURI
) == true)
1717 // destfile will be modified to point to MetaIndexFile for the
1718 // gpgv method, so we need to save it here
1719 MetaIndexFileSignature
= DestFile
;
1720 QueueForSignatureVerify(MetaIndexFile
, MetaIndexFileSignature
);
1726 if(CheckAuthDone(Message
, RealURI
) == true)
1728 std::string FinalFile
= _config
->FindDir("Dir::State::lists");
1729 FinalFile
+= URItoFileName(RealURI
);
1730 TransactionManager
->TransactionStageCopy(this, MetaIndexFileSignature
, FinalFile
);
1735 void pkgAcqMetaSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)/*{{{*/
1737 string Final
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
1739 // check if we need to fail at this point
1740 if (AuthPass
== true && CheckStopAuthentication(RealURI
, Message
))
1743 // FIXME: meh, this is not really elegant
1744 string InReleaseURI
= RealURI
.replace(RealURI
.rfind("Release.gpg"), 12,
1746 string FinalInRelease
= _config
->FindDir("Dir::State::lists") + URItoFileName(InReleaseURI
);
1748 if (RealFileExists(Final
) || RealFileExists(FinalInRelease
))
1750 std::string downgrade_msg
;
1751 strprintf(downgrade_msg
, _("The repository '%s' is no longer signed."),
1753 if(_config
->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1755 // meh, the users wants to take risks (we still mark the packages
1756 // from this repository as unauthenticated)
1757 _error
->Warning("%s", downgrade_msg
.c_str());
1758 _error
->Warning(_("This is normally not allowed, but the option "
1759 "Acquire::AllowDowngradeToInsecureRepositories was "
1760 "given to override it."));
1763 _error
->Error("%s", downgrade_msg
.c_str());
1764 Rename(MetaIndexFile
, MetaIndexFile
+".FAILED");
1765 Item::Failed("Message: " + downgrade_msg
, Cnf
);
1766 TransactionManager
->AbortTransaction();
1771 // this ensures that any file in the lists/ dir is removed by the
1773 DestFile
= GetPartialFileNameFromURI(RealURI
);
1774 TransactionManager
->TransactionStageRemoval(this, DestFile
);
1776 // only allow going further if the users explicitely wants it
1777 if(_config
->FindB("Acquire::AllowInsecureRepositories") == true)
1779 // we parse the indexes here because at this point the user wanted
1780 // a repository that may potentially harm him
1781 MetaIndexParser
->Load(MetaIndexFile
);
1786 _error
->Warning("Use --allow-insecure-repositories to force the update");
1789 Item::Failed(Message
,Cnf
);
1791 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1792 if (Cnf
->LocalOnly
== true ||
1793 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == false)
1800 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire
*Owner
, /*{{{*/
1801 pkgAcqMetaBase
*TransactionManager
,
1802 string URI
,string URIDesc
,string ShortDesc
,
1803 string MetaIndexSigURI
,string MetaIndexSigURIDesc
, string MetaIndexSigShortDesc
,
1804 const vector
<IndexTarget
*>* IndexTargets
,
1805 indexRecords
* MetaIndexParser
) :
1806 pkgAcqMetaBase(Owner
, IndexTargets
, MetaIndexParser
, HashStringList(),
1807 TransactionManager
),
1808 RealURI(URI
), URIDesc(URIDesc
), ShortDesc(ShortDesc
),
1809 MetaIndexSigURI(MetaIndexSigURI
), MetaIndexSigURIDesc(MetaIndexSigURIDesc
),
1810 MetaIndexSigShortDesc(MetaIndexSigShortDesc
)
1812 if(TransactionManager
== NULL
)
1814 this->TransactionManager
= this;
1815 this->TransactionManager
->Add(this);
1818 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
1819 std::clog
<< "New pkgAcqMetaIndex with TransactionManager "
1820 << this->TransactionManager
<< std::endl
;
1823 Init(URIDesc
, ShortDesc
);
1826 // pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
1827 void pkgAcqMetaIndex::Init(std::string URIDesc
, std::string ShortDesc
)
1829 DestFile
= GetPartialFileNameFromURI(RealURI
);
1832 Desc
.Description
= URIDesc
;
1834 Desc
.ShortDesc
= ShortDesc
;
1837 // we expect more item
1838 ExpectedAdditionalItems
= IndexTargets
->size();
1842 // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
1843 // ---------------------------------------------------------------------
1844 string
pkgAcqMetaIndex::Custom600Headers() const
1846 return GetCustom600Headers(RealURI
);
1849 void pkgAcqMetaIndex::Done(string Message
,unsigned long long Size
, /*{{{*/
1850 HashStringList
const &Hashes
,
1851 pkgAcquire::MethodConfig
*Cfg
)
1853 Item::Done(Message
,Size
,Hashes
,Cfg
);
1855 if(CheckDownloadDone(Message
, RealURI
))
1857 // we have a Release file, now download the Signature, all further
1858 // verify/queue for additional downloads will be done in the
1859 // pkgAcqMetaSig::Done() code
1860 std::string MetaIndexFile
= DestFile
;
1861 new pkgAcqMetaSig(Owner
, TransactionManager
,
1862 MetaIndexSigURI
, MetaIndexSigURIDesc
,
1863 MetaIndexSigShortDesc
, MetaIndexFile
, IndexTargets
,
1866 string FinalFile
= _config
->FindDir("Dir::State::lists");
1867 FinalFile
+= URItoFileName(RealURI
);
1868 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
1872 bool pkgAcqMetaBase::CheckAuthDone(string Message
, const string
&RealURI
) /*{{{*/
1874 // At this point, the gpgv method has succeeded, so there is a
1875 // valid signature from a key in the trusted keyring. We
1876 // perform additional verification of its contents, and use them
1877 // to verify the indexes we are about to download
1879 if (!MetaIndexParser
->Load(DestFile
))
1881 Status
= StatAuthError
;
1882 ErrorText
= MetaIndexParser
->ErrorText
;
1886 if (!VerifyVendor(Message
, RealURI
))
1891 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
1892 std::cerr
<< "Signature verification succeeded: "
1893 << DestFile
<< std::endl
;
1895 // Download further indexes with verification
1897 // it would be really nice if we could simply do
1898 // if (IMSHit == false) QueueIndexes(true)
1899 // and skip the download if the Release file has not changed
1900 // - but right now the list cleaner will needs to be tricked
1901 // to not delete all our packages/source indexes in this case
1907 // pkgAcqMetaBase::GetCustom600Headers - Get header for AcqMetaBase /*{{{*/
1908 // ---------------------------------------------------------------------
1909 string
pkgAcqMetaBase::GetCustom600Headers(const string
&RealURI
) const
1911 std::string Header
= "\nIndex-File: true";
1912 std::string MaximumSize
;
1913 strprintf(MaximumSize
, "\nMaximum-Size: %i",
1914 _config
->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
1915 Header
+= MaximumSize
;
1917 string FinalFile
= _config
->FindDir("Dir::State::lists");
1918 FinalFile
+= URItoFileName(RealURI
);
1921 if (stat(FinalFile
.c_str(),&Buf
) == 0)
1922 Header
+= "\nLast-Modified: " + TimeRFC1123(Buf
.st_mtime
);
1927 // pkgAcqMetaBase::QueueForSignatureVerify /*{{{*/
1928 void pkgAcqMetaBase::QueueForSignatureVerify(const std::string
&MetaIndexFile
,
1929 const std::string
&MetaIndexFileSignature
)
1932 Desc
.URI
= "gpgv:" + MetaIndexFileSignature
;
1933 DestFile
= MetaIndexFile
;
1935 SetActiveSubprocess("gpgv");
1938 // pkgAcqMetaBase::CheckDownloadDone /*{{{*/
1939 bool pkgAcqMetaBase::CheckDownloadDone(const std::string
&Message
,
1940 const std::string
&RealURI
)
1942 // We have just finished downloading a Release file (it is not
1945 string FileName
= LookupTag(Message
,"Filename");
1946 if (FileName
.empty() == true)
1949 ErrorText
= "Method gave a blank filename";
1953 if (FileName
!= DestFile
)
1956 Desc
.URI
= "copy:" + FileName
;
1961 // make sure to verify against the right file on I-M-S hit
1962 IMSHit
= StringToBool(LookupTag(Message
,"IMS-Hit"),false);
1965 string FinalFile
= _config
->FindDir("Dir::State::lists");
1966 FinalFile
+= URItoFileName(RealURI
);
1967 DestFile
= FinalFile
;
1970 // set Item to complete as the remaining work is all local (verify etc)
1976 void pkgAcqMetaBase::QueueIndexes(bool verify
) /*{{{*/
1978 bool transInRelease
= false;
1980 std::vector
<std::string
> const keys
= MetaIndexParser
->MetaKeys();
1981 for (std::vector
<std::string
>::const_iterator k
= keys
.begin(); k
!= keys
.end(); ++k
)
1982 // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
1983 if (k
->find("Translation-") != std::string::npos
)
1985 transInRelease
= true;
1990 // at this point the real Items are loaded in the fetcher
1991 ExpectedAdditionalItems
= 0;
1992 for (vector
<IndexTarget
*>::const_iterator Target
= IndexTargets
->begin();
1993 Target
!= IndexTargets
->end();
1996 HashStringList ExpectedIndexHashes
;
1997 const indexRecords::checkSum
*Record
= MetaIndexParser
->Lookup((*Target
)->MetaKey
);
1998 bool compressedAvailable
= false;
2001 if ((*Target
)->IsOptional() == true)
2003 std::vector
<std::string
> types
= APT::Configuration::getCompressionTypes();
2004 for (std::vector
<std::string
>::const_iterator t
= types
.begin(); t
!= types
.end(); ++t
)
2005 if (MetaIndexParser
->Exists((*Target
)->MetaKey
+ "." + *t
) == true)
2007 compressedAvailable
= true;
2011 else if (verify
== true)
2013 Status
= StatAuthError
;
2014 strprintf(ErrorText
, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target
)->MetaKey
.c_str());
2020 ExpectedIndexHashes
= Record
->Hashes
;
2021 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
2023 std::cerr
<< "Queueing: " << (*Target
)->URI
<< std::endl
2024 << "Expected Hash:" << std::endl
;
2025 for (HashStringList::const_iterator hs
= ExpectedIndexHashes
.begin(); hs
!= ExpectedIndexHashes
.end(); ++hs
)
2026 std::cerr
<< "\t- " << hs
->toStr() << std::endl
;
2027 std::cerr
<< "For: " << Record
->MetaKeyFilename
<< std::endl
;
2029 if (verify
== true && ExpectedIndexHashes
.empty() == true && (*Target
)->IsOptional() == false)
2031 Status
= StatAuthError
;
2032 strprintf(ErrorText
, _("Unable to find hash sum for '%s' in Release file"), (*Target
)->MetaKey
.c_str());
2037 if ((*Target
)->IsOptional() == true)
2039 if (transInRelease
== false || Record
!= NULL
|| compressedAvailable
== true)
2041 if (_config
->FindB("Acquire::PDiffs",true) == true && transInRelease
== true &&
2042 MetaIndexParser
->Exists((*Target
)->MetaKey
+ ".diff/Index") == true)
2043 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2045 new pkgAcqIndexTrans(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2050 /* Queue Packages file (either diff or full packages files, depending
2051 on the users option) - we also check if the PDiff Index file is listed
2052 in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
2053 instead, but passing the required info to it is to much hassle */
2054 if(_config
->FindB("Acquire::PDiffs",true) == true && (verify
== false ||
2055 MetaIndexParser
->Exists((*Target
)->MetaKey
+ ".diff/Index") == true))
2056 new pkgAcqDiffIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2058 new pkgAcqIndex(Owner
, TransactionManager
, *Target
, ExpectedIndexHashes
, MetaIndexParser
);
2062 bool pkgAcqMetaBase::VerifyVendor(string Message
, const string
&RealURI
)/*{{{*/
2064 string::size_type pos
;
2066 // check for missing sigs (that where not fatal because otherwise we had
2069 string msg
= _("There is no public key available for the "
2070 "following key IDs:\n");
2071 pos
= Message
.find("NO_PUBKEY ");
2072 if (pos
!= std::string::npos
)
2074 string::size_type start
= pos
+strlen("NO_PUBKEY ");
2075 string Fingerprint
= Message
.substr(start
, Message
.find("\n")-start
);
2076 missingkeys
+= (Fingerprint
);
2078 if(!missingkeys
.empty())
2079 _error
->Warning("%s", (msg
+ missingkeys
).c_str());
2081 string Transformed
= MetaIndexParser
->GetExpectedDist();
2083 if (Transformed
== "../project/experimental")
2085 Transformed
= "experimental";
2088 pos
= Transformed
.rfind('/');
2089 if (pos
!= string::npos
)
2091 Transformed
= Transformed
.substr(0, pos
);
2094 if (Transformed
== ".")
2099 if (_config
->FindB("Acquire::Check-Valid-Until", true) == true &&
2100 MetaIndexParser
->GetValidUntil() > 0) {
2101 time_t const invalid_since
= time(NULL
) - MetaIndexParser
->GetValidUntil();
2102 if (invalid_since
> 0)
2103 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
2104 // the time since then the file is invalid - formated in the same way as in
2105 // the download progress display (e.g. 7d 3h 42min 1s)
2106 return _error
->Error(
2107 _("Release file for %s is expired (invalid since %s). "
2108 "Updates for this repository will not be applied."),
2109 RealURI
.c_str(), TimeToStr(invalid_since
).c_str());
2112 if (_config
->FindB("Debug::pkgAcquire::Auth", false))
2114 std::cerr
<< "Got Codename: " << MetaIndexParser
->GetDist() << std::endl
;
2115 std::cerr
<< "Expecting Dist: " << MetaIndexParser
->GetExpectedDist() << std::endl
;
2116 std::cerr
<< "Transformed Dist: " << Transformed
<< std::endl
;
2119 if (MetaIndexParser
->CheckDist(Transformed
) == false)
2121 // This might become fatal one day
2122 // Status = StatAuthError;
2123 // ErrorText = "Conflicting distribution; expected "
2124 // + MetaIndexParser->GetExpectedDist() + " but got "
2125 // + MetaIndexParser->GetDist();
2127 if (!Transformed
.empty())
2129 _error
->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
2130 Desc
.Description
.c_str(),
2131 Transformed
.c_str(),
2132 MetaIndexParser
->GetDist().c_str());
2139 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
2140 void pkgAcqMetaIndex::Failed(string Message
,
2141 pkgAcquire::MethodConfig
* Cnf
)
2143 pkgAcquire::Item::Failed(Message
, Cnf
);
2146 string FinalFile
= _config
->FindDir("Dir::State::lists") + URItoFileName(RealURI
);
2148 _error
->Warning(_("The repository '%s' does not have a Release file. "
2149 "This is deprecated, please contact the owner of the "
2150 "repository."), URIDesc
.c_str());
2152 // No Release file was present so fall
2153 // back to queueing Packages files without verification
2154 // only allow going further if the users explicitely wants it
2155 if(_config
->FindB("Acquire::AllowInsecureRepositories") == true)
2157 // Done, queue for rename on transaction finished
2158 if (FileExists(DestFile
))
2159 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2161 // queue without any kind of hashsum support
2162 QueueIndexes(false);
2164 // warn if the repository is unsinged
2165 _error
->Warning("Use --allow-insecure-repositories to force the update");
2166 TransactionManager
->AbortTransaction();
2172 void pkgAcqMetaIndex::Finished() /*{{{*/
2174 if(_config
->FindB("Debug::Acquire::Transaction", false) == true)
2175 std::clog
<< "Finished: " << DestFile
<<std::endl
;
2176 if(TransactionManager
!= NULL
&&
2177 TransactionManager
->TransactionHasError() == false)
2178 TransactionManager
->CommitTransaction();
2181 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire
*Owner
, /*{{{*/
2182 string
const &URI
, string
const &URIDesc
, string
const &ShortDesc
,
2183 string
const &MetaIndexURI
, string
const &MetaIndexURIDesc
, string
const &MetaIndexShortDesc
,
2184 string
const &MetaSigURI
, string
const &MetaSigURIDesc
, string
const &MetaSigShortDesc
,
2185 const vector
<IndexTarget
*>* IndexTargets
,
2186 indexRecords
* MetaIndexParser
) :
2187 pkgAcqMetaIndex(Owner
, NULL
, URI
, URIDesc
, ShortDesc
, MetaSigURI
, MetaSigURIDesc
,MetaSigShortDesc
, IndexTargets
, MetaIndexParser
),
2188 MetaIndexURI(MetaIndexURI
), MetaIndexURIDesc(MetaIndexURIDesc
), MetaIndexShortDesc(MetaIndexShortDesc
),
2189 MetaSigURI(MetaSigURI
), MetaSigURIDesc(MetaSigURIDesc
), MetaSigShortDesc(MetaSigShortDesc
)
2191 // index targets + (worst case:) Release/Release.gpg
2192 ExpectedAdditionalItems
= IndexTargets
->size() + 2;
2196 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
2200 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
2201 // ---------------------------------------------------------------------
2202 string
pkgAcqMetaClearSig::Custom600Headers() const
2204 string Header
= GetCustom600Headers(RealURI
);
2205 Header
+= "\nFail-Ignore: true";
2209 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
2210 // ---------------------------------------------------------------------
2211 void pkgAcqMetaClearSig::Done(std::string Message
,unsigned long long /*Size*/,
2212 HashStringList
const &/*Hashes*/,
2213 pkgAcquire::MethodConfig
*Cnf
)
2215 // if we expect a ClearTextSignature (InRelase), ensure that
2216 // this is what we get and if not fail to queue a
2217 // Release/Release.gpg, see #346386
2218 if (FileExists(DestFile
) && !StartsWithGPGClearTextSignature(DestFile
))
2220 pkgAcquire::Item::Failed(Message
, Cnf
);
2221 RenameOnError(NotClearsigned
);
2222 TransactionManager
->AbortTransaction();
2226 if(AuthPass
== false)
2228 if(CheckDownloadDone(Message
, RealURI
) == true)
2229 QueueForSignatureVerify(DestFile
, DestFile
);
2234 if(CheckAuthDone(Message
, RealURI
) == true)
2236 string FinalFile
= _config
->FindDir("Dir::State::lists");
2237 FinalFile
+= URItoFileName(RealURI
);
2239 // queue for copy in place
2240 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2245 void pkgAcqMetaClearSig::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
) /*{{{*/
2247 Item::Failed(Message
, Cnf
);
2249 // we failed, we will not get additional items from this method
2250 ExpectedAdditionalItems
= 0;
2252 if (AuthPass
== false)
2254 // Queue the 'old' InRelease file for removal if we try Release.gpg
2255 // as otherwise the file will stay around and gives a false-auth
2256 // impression (CVE-2012-0214)
2257 string FinalFile
= _config
->FindDir("Dir::State::lists");
2258 FinalFile
.append(URItoFileName(RealURI
));
2259 TransactionManager
->TransactionStageRemoval(this, FinalFile
);
2262 new pkgAcqMetaIndex(Owner
, TransactionManager
,
2263 MetaIndexURI
, MetaIndexURIDesc
, MetaIndexShortDesc
,
2264 MetaSigURI
, MetaSigURIDesc
, MetaSigShortDesc
,
2265 IndexTargets
, MetaIndexParser
);
2269 if(CheckStopAuthentication(RealURI
, Message
))
2272 _error
->Warning(_("The data from '%s' is not signed. Packages "
2273 "from that repository can not be authenticated."),
2276 // No Release file was present, or verification failed, so fall
2277 // back to queueing Packages files without verification
2278 // only allow going further if the users explicitely wants it
2279 if(_config
->FindB("Acquire::AllowInsecureRepositories") == true)
2283 /* Always move the meta index, even if gpgv failed. This ensures
2284 * that PackageFile objects are correctly filled in */
2285 if (FileExists(DestFile
))
2287 string FinalFile
= _config
->FindDir("Dir::State::lists");
2288 FinalFile
+= URItoFileName(RealURI
);
2289 /* InRelease files become Release files, otherwise
2290 * they would be considered as trusted later on */
2291 RealURI
= RealURI
.replace(RealURI
.rfind("InRelease"), 9,
2293 FinalFile
= FinalFile
.replace(FinalFile
.rfind("InRelease"), 9,
2296 // Done, queue for rename on transaction finished
2297 TransactionManager
->TransactionStageCopy(this, DestFile
, FinalFile
);
2299 QueueIndexes(false);
2301 // warn if the repository is unsigned
2302 _error
->Warning("Use --allow-insecure-repositories to force the update");
2303 TransactionManager
->AbortTransaction();
2309 // AcqArchive::AcqArchive - Constructor /*{{{*/
2310 // ---------------------------------------------------------------------
2311 /* This just sets up the initial fetch environment and queues the first
2313 pkgAcqArchive::pkgAcqArchive(pkgAcquire
*Owner
,pkgSourceList
*Sources
,
2314 pkgRecords
*Recs
,pkgCache::VerIterator
const &Version
,
2315 string
&StoreFilename
) :
2316 Item(Owner
, HashStringList()), Version(Version
), Sources(Sources
), Recs(Recs
),
2317 StoreFilename(StoreFilename
), Vf(Version
.FileList()),
2320 Retries
= _config
->FindI("Acquire::Retries",0);
2322 if (Version
.Arch() == 0)
2324 _error
->Error(_("I wasn't able to locate a file for the %s package. "
2325 "This might mean you need to manually fix this package. "
2326 "(due to missing arch)"),
2327 Version
.ParentPkg().FullName().c_str());
2331 /* We need to find a filename to determine the extension. We make the
2332 assumption here that all the available sources for this version share
2333 the same extension.. */
2334 // Skip not source sources, they do not have file fields.
2335 for (; Vf
.end() == false; ++Vf
)
2337 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
2342 // Does not really matter here.. we are going to fail out below
2343 if (Vf
.end() != true)
2345 // If this fails to get a file name we will bomb out below.
2346 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2347 if (_error
->PendingError() == true)
2350 // Generate the final file name as: package_version_arch.foo
2351 StoreFilename
= QuoteString(Version
.ParentPkg().Name(),"_:") + '_' +
2352 QuoteString(Version
.VerStr(),"_:") + '_' +
2353 QuoteString(Version
.Arch(),"_:.") +
2354 "." + flExtension(Parse
.FileName());
2357 // check if we have one trusted source for the package. if so, switch
2358 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2359 bool const allowUnauth
= _config
->FindB("APT::Get::AllowUnauthenticated", false);
2360 bool const debugAuth
= _config
->FindB("Debug::pkgAcquire::Auth", false);
2361 bool seenUntrusted
= false;
2362 for (pkgCache::VerFileIterator i
= Version
.FileList(); i
.end() == false; ++i
)
2364 pkgIndexFile
*Index
;
2365 if (Sources
->FindIndex(i
.File(),Index
) == false)
2368 if (debugAuth
== true)
2369 std::cerr
<< "Checking index: " << Index
->Describe()
2370 << "(Trusted=" << Index
->IsTrusted() << ")" << std::endl
;
2372 if (Index
->IsTrusted() == true)
2375 if (allowUnauth
== false)
2379 seenUntrusted
= true;
2382 // "allow-unauthenticated" restores apts old fetching behaviour
2383 // that means that e.g. unauthenticated file:// uris are higher
2384 // priority than authenticated http:// uris
2385 if (allowUnauth
== true && seenUntrusted
== true)
2389 if (QueueNext() == false && _error
->PendingError() == false)
2390 _error
->Error(_("Can't find a source to download version '%s' of '%s'"),
2391 Version
.VerStr(), Version
.ParentPkg().FullName(false).c_str());
2394 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2395 // ---------------------------------------------------------------------
2396 /* This queues the next available file version for download. It checks if
2397 the archive is already available in the cache and stashs the MD5 for
2399 bool pkgAcqArchive::QueueNext()
2401 for (; Vf
.end() == false; ++Vf
)
2403 // Ignore not source sources
2404 if ((Vf
.File()->Flags
& pkgCache::Flag::NotSource
) != 0)
2407 // Try to cross match against the source list
2408 pkgIndexFile
*Index
;
2409 if (Sources
->FindIndex(Vf
.File(),Index
) == false)
2412 // only try to get a trusted package from another source if that source
2414 if(Trusted
&& !Index
->IsTrusted())
2417 // Grab the text package record
2418 pkgRecords::Parser
&Parse
= Recs
->Lookup(Vf
);
2419 if (_error
->PendingError() == true)
2422 string PkgFile
= Parse
.FileName();
2423 ExpectedHashes
= Parse
.Hashes();
2425 if (PkgFile
.empty() == true)
2426 return _error
->Error(_("The package index files are corrupted. No Filename: "
2427 "field for package %s."),
2428 Version
.ParentPkg().Name());
2430 Desc
.URI
= Index
->ArchiveURI(PkgFile
);
2431 Desc
.Description
= Index
->ArchiveInfo(Version
);
2433 Desc
.ShortDesc
= Version
.ParentPkg().FullName(true);
2435 // See if we already have the file. (Legacy filenames)
2436 FileSize
= Version
->Size
;
2437 string FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile
);
2439 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2441 // Make sure the size matches
2442 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2447 StoreFilename
= DestFile
= FinalFile
;
2451 /* Hmm, we have a file and its size does not match, this means it is
2452 an old style mismatched arch */
2453 unlink(FinalFile
.c_str());
2456 // Check it again using the new style output filenames
2457 FinalFile
= _config
->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename
);
2458 if (stat(FinalFile
.c_str(),&Buf
) == 0)
2460 // Make sure the size matches
2461 if ((unsigned long long)Buf
.st_size
== Version
->Size
)
2466 StoreFilename
= DestFile
= FinalFile
;
2470 /* Hmm, we have a file and its size does not match, this shouldn't
2472 unlink(FinalFile
.c_str());
2475 DestFile
= _config
->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename
);
2477 // Check the destination file
2478 if (stat(DestFile
.c_str(),&Buf
) == 0)
2480 // Hmm, the partial file is too big, erase it
2481 if ((unsigned long long)Buf
.st_size
> Version
->Size
)
2482 unlink(DestFile
.c_str());
2485 PartialSize
= Buf
.st_size
;
2486 ChangeOwnerAndPermissionOfFile("pkgAcqArchive::QueueNext", DestFile
.c_str(), "_apt", "root", 0600);
2490 // Disables download of archives - useful if no real installation follows,
2491 // e.g. if we are just interested in proposed installation order
2492 if (_config
->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2497 StoreFilename
= DestFile
= FinalFile
;
2511 // AcqArchive::Done - Finished fetching /*{{{*/
2512 // ---------------------------------------------------------------------
2514 void pkgAcqArchive::Done(string Message
,unsigned long long Size
, HashStringList
const &CalcHashes
,
2515 pkgAcquire::MethodConfig
*Cfg
)
2517 Item::Done(Message
, Size
, CalcHashes
, Cfg
);
2520 if (Size
!= Version
->Size
)
2522 RenameOnError(SizeMismatch
);
2526 // FIXME: could this empty() check impose *any* sort of security issue?
2527 if(ExpectedHashes
.usable() && ExpectedHashes
!= CalcHashes
)
2529 RenameOnError(HashSumMismatch
);
2530 printHashSumComparision(DestFile
, ExpectedHashes
, CalcHashes
);
2534 // Grab the output filename
2535 string FileName
= LookupTag(Message
,"Filename");
2536 if (FileName
.empty() == true)
2539 ErrorText
= "Method gave a blank filename";
2543 // Reference filename
2544 if (FileName
!= DestFile
)
2546 StoreFilename
= DestFile
= FileName
;
2552 // Done, move it into position
2553 string FinalFile
= _config
->FindDir("Dir::Cache::Archives");
2554 FinalFile
+= flNotDir(StoreFilename
);
2555 Rename(DestFile
,FinalFile
);
2556 ChangeOwnerAndPermissionOfFile("pkgAcqArchive::Done", FinalFile
.c_str(), "root", "root", 0644);
2557 StoreFilename
= DestFile
= FinalFile
;
2561 // AcqArchive::Failed - Failure handler /*{{{*/
2562 // ---------------------------------------------------------------------
2563 /* Here we try other sources */
2564 void pkgAcqArchive::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
2566 ErrorText
= LookupTag(Message
,"Message");
2568 /* We don't really want to retry on failed media swaps, this prevents
2569 that. An interesting observation is that permanent failures are not
2571 if (Cnf
->Removable
== true &&
2572 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2574 // Vf = Version.FileList();
2575 while (Vf
.end() == false) ++Vf
;
2576 StoreFilename
= string();
2577 Item::Failed(Message
,Cnf
);
2581 if (QueueNext() == false)
2583 // This is the retry counter
2585 Cnf
->LocalOnly
== false &&
2586 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2589 Vf
= Version
.FileList();
2590 if (QueueNext() == true)
2594 StoreFilename
= string();
2595 Item::Failed(Message
,Cnf
);
2599 // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
2600 // ---------------------------------------------------------------------
2601 APT_PURE
bool pkgAcqArchive::IsTrusted() const
2606 // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
2607 // ---------------------------------------------------------------------
2609 void pkgAcqArchive::Finished()
2611 if (Status
== pkgAcquire::Item::StatDone
&&
2614 StoreFilename
= string();
2617 // AcqFile::pkgAcqFile - Constructor /*{{{*/
2618 // ---------------------------------------------------------------------
2619 /* The file is added to the queue */
2620 pkgAcqFile::pkgAcqFile(pkgAcquire
*Owner
,string URI
, HashStringList
const &Hashes
,
2621 unsigned long long Size
,string Dsc
,string ShortDesc
,
2622 const string
&DestDir
, const string
&DestFilename
,
2624 Item(Owner
, Hashes
), IsIndexFile(IsIndexFile
)
2626 Retries
= _config
->FindI("Acquire::Retries",0);
2628 if(!DestFilename
.empty())
2629 DestFile
= DestFilename
;
2630 else if(!DestDir
.empty())
2631 DestFile
= DestDir
+ "/" + flNotDir(URI
);
2633 DestFile
= flNotDir(URI
);
2637 Desc
.Description
= Dsc
;
2640 // Set the short description to the archive component
2641 Desc
.ShortDesc
= ShortDesc
;
2643 // Get the transfer sizes
2646 if (stat(DestFile
.c_str(),&Buf
) == 0)
2648 // Hmm, the partial file is too big, erase it
2649 if ((Size
> 0) && (unsigned long long)Buf
.st_size
> Size
)
2650 unlink(DestFile
.c_str());
2653 PartialSize
= Buf
.st_size
;
2654 ChangeOwnerAndPermissionOfFile("pkgAcqFile", DestFile
.c_str(), "_apt", "root", 0600);
2661 // AcqFile::Done - Item downloaded OK /*{{{*/
2662 // ---------------------------------------------------------------------
2664 void pkgAcqFile::Done(string Message
,unsigned long long Size
,HashStringList
const &CalcHashes
,
2665 pkgAcquire::MethodConfig
*Cnf
)
2667 Item::Done(Message
,Size
,CalcHashes
,Cnf
);
2670 if(ExpectedHashes
.usable() && ExpectedHashes
!= CalcHashes
)
2672 RenameOnError(HashSumMismatch
);
2673 printHashSumComparision(DestFile
, ExpectedHashes
, CalcHashes
);
2677 string FileName
= LookupTag(Message
,"Filename");
2678 if (FileName
.empty() == true)
2681 ErrorText
= "Method gave a blank filename";
2687 // The files timestamp matches
2688 if (StringToBool(LookupTag(Message
,"IMS-Hit"),false) == true)
2691 // We have to copy it into place
2692 if (FileName
!= DestFile
)
2695 if (_config
->FindB("Acquire::Source-Symlinks",true) == false ||
2696 Cnf
->Removable
== true)
2698 Desc
.URI
= "copy:" + FileName
;
2703 // Erase the file if it is a symlink so we can overwrite it
2705 if (lstat(DestFile
.c_str(),&St
) == 0)
2707 if (S_ISLNK(St
.st_mode
) != 0)
2708 unlink(DestFile
.c_str());
2712 if (symlink(FileName
.c_str(),DestFile
.c_str()) != 0)
2714 ErrorText
= "Link to " + DestFile
+ " failure ";
2721 // AcqFile::Failed - Failure handler /*{{{*/
2722 // ---------------------------------------------------------------------
2723 /* Here we try other sources */
2724 void pkgAcqFile::Failed(string Message
,pkgAcquire::MethodConfig
*Cnf
)
2726 ErrorText
= LookupTag(Message
,"Message");
2728 // This is the retry counter
2730 Cnf
->LocalOnly
== false &&
2731 StringToBool(LookupTag(Message
,"Transient-Failure"),false) == true)
2738 Item::Failed(Message
,Cnf
);
2741 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2742 // ---------------------------------------------------------------------
2743 /* The only header we use is the last-modified header. */
2744 string
pkgAcqFile::Custom600Headers() const
2747 return "\nIndex-File: true";