]> git.saurik.com Git - apt.git/blame - apt-pkg/acquire-item.cc
support arch:all data e.g. in separate Packages file
[apt.git] / apt-pkg / acquire-item.cc
CommitLineData
0118833a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
b3d44315 3// $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
0118833a
AL
4/* ######################################################################
5
6 Acquire Item - Item to acquire
7
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.
b185acc2 12
0118833a
AL
13 ##################################################################### */
14 /*}}}*/
15// Include Files /*{{{*/
ea542140
DK
16#include <config.h>
17
0118833a
AL
18#include <apt-pkg/acquire-item.h>
19#include <apt-pkg/configuration.h>
e878aedb 20#include <apt-pkg/aptconfiguration.h>
b2e465d6 21#include <apt-pkg/sourcelist.h>
03e39e59 22#include <apt-pkg/error.h>
cdcc6d34 23#include <apt-pkg/strutl.h>
36375005 24#include <apt-pkg/fileutl.h>
ac5b205a 25#include <apt-pkg/tagfile.h>
5ad0096a 26#include <apt-pkg/metaindex.h>
453b82a3
DK
27#include <apt-pkg/acquire.h>
28#include <apt-pkg/hashes.h>
29#include <apt-pkg/indexfile.h>
30#include <apt-pkg/pkgcache.h>
31#include <apt-pkg/cacheiterators.h>
32#include <apt-pkg/pkgrecords.h>
d56e2917 33#include <apt-pkg/gpgv.h>
453b82a3 34
d7a51997 35#include <algorithm>
453b82a3
DK
36#include <stddef.h>
37#include <stdlib.h>
38#include <string.h>
39#include <iostream>
40#include <vector>
0a8a80e5
AL
41#include <sys/stat.h>
42#include <unistd.h>
c88edf1d 43#include <errno.h>
5819a761 44#include <string>
c88edf1d 45#include <stdio.h>
1ddb8596 46#include <ctime>
ac7f8f79 47#include <sstream>
ea542140
DK
48
49#include <apti18n.h>
0118833a
AL
50 /*}}}*/
51
b3d44315 52using namespace std;
5819a761 53
b3501edb
DK
54static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
55{
56 if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
57 return;
58 std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
59 for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
60 std::cerr << "\t- " << hs->toStr() << std::endl;
61 std::cerr << " Actual Hash: " << std::endl;
62 for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
63 std::cerr << "\t- " << hs->toStr() << std::endl;
64}
65 /*}}}*/
70b63c57 66static std::string GetPartialFileName(std::string const &file) /*{{{*/
5684f71f
DK
67{
68 std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
69 DestFile += file;
70 return DestFile;
71}
70b63c57
DK
72 /*}}}*/
73static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
5684f71f 74{
ea7682a0 75 return GetPartialFileName(URItoFileName(uri));
5684f71f 76}
70b63c57 77 /*}}}*/
295d848b
DK
78static std::string GetFinalFileNameFromURI(std::string const &uri) /*{{{*/
79{
80 return _config->FindDir("Dir::State::lists") + URItoFileName(uri);
81}
82 /*}}}*/
d7a51997
DK
83static std::string GetKeepCompressedFileName(std::string file, IndexTarget const &Target)/*{{{*/
84{
85 if (Target.KeepCompressed == false)
86 return file;
87
88 std::string const CompressionTypes = Target.Option(IndexTarget::COMPRESSIONTYPES);
89 if (CompressionTypes.empty() == false)
90 {
91 std::string const ext = CompressionTypes.substr(0, CompressionTypes.find(' '));
92 if (ext != "uncompressed")
93 file.append(".").append(ext);
94 }
95 return file;
96}
97 /*}}}*/
653ef26c 98static std::string GetCompressedFileName(IndexTarget const &Target, std::string const &Name, std::string const &Ext) /*{{{*/
70b63c57
DK
99{
100 if (Ext.empty() || Ext == "uncompressed")
101 return Name;
102
103 // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
104 // file when its doing the indexcopy
653ef26c 105 if (Target.URI.substr(0,6) == "cdrom:")
70b63c57 106 return Name;
5684f71f 107
70b63c57 108 // adjust DestFile if its compressed on disk
653ef26c 109 if (Target.KeepCompressed == true)
70b63c57
DK
110 return Name + '.' + Ext;
111 return Name;
112}
113 /*}}}*/
36795154
DK
114static std::string GetMergeDiffsPatchFileName(std::string const &Final, std::string const &Patch)/*{{{*/
115{
116 // rred expects the patch as $FinalFile.ed.$patchname.gz
117 return Final + ".ed." + Patch + ".gz";
118}
119 /*}}}*/
120static std::string GetDiffsPatchFileName(std::string const &Final) /*{{{*/
121{
122 // rred expects the patch as $FinalFile.ed
123 return Final + ".ed";
124}
125 /*}}}*/
d7a51997
DK
126static bool BootstrapPDiffWith(std::string const &PartialFile, std::string const &FinalFile, IndexTarget const &Target)/*{{{*/
127{
128 // patching needs to be bootstrapped with the 'old' version
129 std::vector<std::string> types = VectorizeString(Target.Option(IndexTarget::COMPRESSIONTYPES), ' ');
130 auto typeItr = types.cbegin();
131 for (; typeItr != types.cend(); ++typeItr)
132 {
133 std::string Final = FinalFile;
134 if (*typeItr != "uncompressed")
135 Final.append(".").append(*typeItr);
136 if (RealFileExists(Final) == false)
137 continue;
138 std::string Partial = PartialFile;
139 if (*typeItr != "uncompressed")
140 Partial.append(".").append(*typeItr);
141 if (FileExists(Partial.c_str()) == true)
142 return true;
143 if (symlink(Final.c_str(), Partial.c_str()) != 0)
144 return false;
145 break;
146 }
147 return typeItr != types.cend();
148}
149 /*}}}*/
51818f26
DK
150static bool RemoveFile(char const * const Function, std::string const &FileName)/*{{{*/
151{
152 if (FileName == "/dev/null")
153 return true;
154 errno = 0;
155 if (unlink(FileName.c_str()) != 0)
156 {
157 if (errno == ENOENT)
158 return true;
159 return _error->WarningE(Function, "Removal of file %s failed", FileName.c_str());
160 }
161 return true;
162}
163 /*}}}*/
36795154 164
f18f2338 165static bool MessageInsecureRepository(bool const isError, std::string const &msg)/*{{{*/
32532943 166{
f18f2338
DK
167 if (isError)
168 {
169 _error->Error("%s", msg.c_str());
170 _error->Notice("%s", _("Updating such a repository securily is impossible and therefore disabled by default."));
171 }
172 else
173 {
174 _error->Warning("%s", msg.c_str());
175 _error->Notice("%s", _("Data from such a repository can not be authenticated and is therefore potentially dangerous to use."));
176 }
002b1bc4 177 _error->Notice("%s", _("See apt-secure(8) manpage for repository creation and user configuration details."));
f18f2338
DK
178 return false;
179}
180static bool MessageInsecureRepository(bool const isError, char const * const msg, std::string const &repo)
181{
182 std::string m;
183 strprintf(m, msg, repo.c_str());
184 return MessageInsecureRepository(isError, m);
185}
186 /*}}}*/
187static bool AllowInsecureRepositories(char const * const msg, std::string const &repo,/*{{{*/
188 metaIndex const * const MetaIndexParser, pkgAcqMetaClearSig * const TransactionManager, pkgAcquire::Item * const I)
189{
190 if(MetaIndexParser->GetTrusted() == metaIndex::TRI_YES)
32532943
DK
191 return true;
192
f18f2338
DK
193 if (_config->FindB("Acquire::AllowInsecureRepositories") == true)
194 {
195 MessageInsecureRepository(false, msg, repo);
196 return true;
197 }
198
199 MessageInsecureRepository(true, msg, repo);
32532943
DK
200 TransactionManager->AbortTransaction();
201 I->Status = pkgAcquire::Item::StatError;
202 return false;
203}
204 /*}}}*/
5ad0096a 205static HashStringList GetExpectedHashesFromFor(metaIndex * const Parser, std::string const &MetaKey)/*{{{*/
8d041b4f
DK
206{
207 if (Parser == NULL)
208 return HashStringList();
5ad0096a 209 metaIndex::checkSum * const R = Parser->Lookup(MetaKey);
8d041b4f
DK
210 if (R == NULL)
211 return HashStringList();
212 return R->Hashes;
213}
214 /*}}}*/
32532943 215
448c38bd
DK
216// all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
217/* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
218 It is best to implement it as broadly as possible, while ::HashesRequired defaults
219 to true and should be as restrictive as possible for false cases. Note that if
220 a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
221 ::HashesRequired is called to evaluate if its okay to have no hashes. */
222APT_CONST bool pkgAcqTransactionItem::HashesRequired() const
223{
224 /* signed repositories obviously have a parser and good hashes.
225 unsigned repositories, too, as even if we can't trust them for security,
226 we can at least trust them for integrity of the download itself.
227 Only repositories without a Release file can (obviously) not have
228 hashes – and they are very uncommon and strongly discouraged */
5ad0096a
DK
229 return TransactionManager->MetaIndexParser != NULL &&
230 TransactionManager->MetaIndexParser->GetLoadedSuccessfully() != metaIndex::TRI_UNSET;
448c38bd
DK
231}
232HashStringList pkgAcqTransactionItem::GetExpectedHashes() const
233{
234 return GetExpectedHashesFor(GetMetaKey());
235}
236
237APT_CONST bool pkgAcqMetaBase::HashesRequired() const
238{
239 // Release and co have no hashes 'by design'.
240 return false;
241}
242HashStringList pkgAcqMetaBase::GetExpectedHashes() const
243{
244 return HashStringList();
245}
246
247APT_CONST bool pkgAcqIndexDiffs::HashesRequired() const
248{
4f51fd86
DK
249 /* We don't always have the diff of the downloaded pdiff file.
250 What we have for sure is hashes for the uncompressed file,
251 but rred uncompresses them on the fly while parsing, so not handled here.
252 Hashes are (also) checked while searching for (next) patch to apply. */
253 if (State == StateFetchDiff)
254 return available_patches[0].download_hashes.empty() == false;
448c38bd
DK
255 return false;
256}
257HashStringList pkgAcqIndexDiffs::GetExpectedHashes() const
258{
4f51fd86
DK
259 if (State == StateFetchDiff)
260 return available_patches[0].download_hashes;
448c38bd
DK
261 return HashStringList();
262}
263
264APT_CONST bool pkgAcqIndexMergeDiffs::HashesRequired() const
265{
266 /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
267 we can check the rred result after all patches are applied as
268 we know the expected result rather than potentially apply more patches */
4f51fd86
DK
269 if (State == StateFetchDiff)
270 return patch.download_hashes.empty() == false;
448c38bd
DK
271 return State == StateApplyDiff;
272}
273HashStringList pkgAcqIndexMergeDiffs::GetExpectedHashes() const
274{
4f51fd86
DK
275 if (State == StateFetchDiff)
276 return patch.download_hashes;
277 else if (State == StateApplyDiff)
dcbbb14d 278 return GetExpectedHashesFor(Target.MetaKey);
448c38bd
DK
279 return HashStringList();
280}
281
282APT_CONST bool pkgAcqArchive::HashesRequired() const
283{
284 return LocalSource == false;
285}
286HashStringList pkgAcqArchive::GetExpectedHashes() const
287{
288 // figured out while parsing the records
289 return ExpectedHashes;
290}
291
292APT_CONST bool pkgAcqFile::HashesRequired() const
293{
294 // supplied as parameter at creation time, so the caller decides
295 return ExpectedHashes.usable();
296}
297HashStringList pkgAcqFile::GetExpectedHashes() const
298{
299 return ExpectedHashes;
300}
301 /*}}}*/
302// Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
303bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc &Item)
304{
305 Owner->Enqueue(Item);
306 return true;
307}
308/* The idea here is that an item isn't queued if it exists on disk and the
309 transition manager was a hit as this means that the files it contains
310 the checksums for can't be updated either (or they are and we are asking
311 for a hashsum mismatch to happen which helps nobody) */
312bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc &Item)
313{
314 std::string const FinalFile = GetFinalFilename();
315 if (TransactionManager != NULL && TransactionManager->IMSHit == true &&
316 FileExists(FinalFile) == true)
317 {
318 PartialFile = DestFile = FinalFile;
319 Status = StatDone;
320 return false;
321 }
322 return pkgAcquire::Item::QueueURI(Item);
323}
324/* The transition manager InRelease itself (or its older sisters-in-law
325 Release & Release.gpg) is always queued as this allows us to rerun gpgv
326 on it to verify that we aren't stalled with old files */
327bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc &Item)
328{
329 return pkgAcquire::Item::QueueURI(Item);
330}
331/* the Diff/Index needs to queue also the up-to-date complete index file
332 to ensure that the list cleaner isn't eating it */
333bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc &Item)
334{
335 if (pkgAcqTransactionItem::QueueURI(Item) == true)
336 return true;
337 QueueOnIMSHit();
338 return false;
339}
340 /*}}}*/
341// Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
342std::string pkgAcquire::Item::GetFinalFilename() const
343{
344 return GetFinalFileNameFromURI(Desc.URI);
345}
346std::string pkgAcqDiffIndex::GetFinalFilename() const
347{
348 // the logic we inherent from pkgAcqBaseIndex isn't what we need here
349 return pkgAcquire::Item::GetFinalFilename();
350}
351std::string pkgAcqIndex::GetFinalFilename() const
352{
dcbbb14d 353 std::string const FinalFile = GetFinalFileNameFromURI(Target.URI);
653ef26c 354 return GetCompressedFileName(Target, FinalFile, CurrentCompressionExtension);
448c38bd
DK
355}
356std::string pkgAcqMetaSig::GetFinalFilename() const
357{
dcbbb14d 358 return GetFinalFileNameFromURI(Target.URI);
448c38bd
DK
359}
360std::string pkgAcqBaseIndex::GetFinalFilename() const
361{
dcbbb14d 362 return GetFinalFileNameFromURI(Target.URI);
448c38bd
DK
363}
364std::string pkgAcqMetaBase::GetFinalFilename() const
365{
dcbbb14d 366 return GetFinalFileNameFromURI(Target.URI);
448c38bd
DK
367}
368std::string pkgAcqArchive::GetFinalFilename() const
369{
370 return _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
371}
372 /*}}}*/
373// pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
374std::string pkgAcqTransactionItem::GetMetaKey() const
375{
dcbbb14d 376 return Target.MetaKey;
448c38bd
DK
377}
378std::string pkgAcqIndex::GetMetaKey() const
379{
380 if (Stage == STAGE_DECOMPRESS_AND_VERIFY || CurrentCompressionExtension == "uncompressed")
dcbbb14d
DK
381 return Target.MetaKey;
382 return Target.MetaKey + "." + CurrentCompressionExtension;
448c38bd
DK
383}
384std::string pkgAcqDiffIndex::GetMetaKey() const
385{
dcbbb14d 386 return Target.MetaKey + ".diff/Index";
448c38bd
DK
387}
388 /*}}}*/
389//pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
390bool pkgAcqTransactionItem::TransactionState(TransactionStates const state)
391{
392 bool const Debug = _config->FindB("Debug::Acquire::Transaction", false);
393 switch(state)
394 {
395 case TransactionAbort:
396 if(Debug == true)
397 std::clog << " Cancel: " << DestFile << std::endl;
398 if (Status == pkgAcquire::Item::StatIdle)
399 {
400 Status = pkgAcquire::Item::StatDone;
401 Dequeue();
402 }
403 break;
404 case TransactionCommit:
405 if(PartialFile != "")
406 {
407 if(Debug == true)
408 std::clog << "mv " << PartialFile << " -> "<< DestFile << " # " << DescURI() << std::endl;
409
410 Rename(PartialFile, DestFile);
411 } else {
412 if(Debug == true)
413 std::clog << "rm " << DestFile << " # " << DescURI() << std::endl;
51818f26 414 RemoveFile("TransactionCommit", DestFile);
448c38bd
DK
415 }
416 break;
417 }
418 return true;
419}
420bool pkgAcqMetaBase::TransactionState(TransactionStates const state)
421{
422 // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
423 if (TransactionManager->IMSHit == false)
424 return pkgAcqTransactionItem::TransactionState(state);
425 return true;
426}
427bool pkgAcqIndex::TransactionState(TransactionStates const state)
428{
429 if (pkgAcqTransactionItem::TransactionState(state) == false)
430 return false;
431
432 switch (state)
433 {
434 case TransactionAbort:
435 if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
436 {
437 // keep the compressed file, but drop the decompressed
438 EraseFileName.clear();
439 if (PartialFile.empty() == false && flExtension(PartialFile) == "decomp")
51818f26 440 RemoveFile("TransactionAbort", PartialFile);
448c38bd
DK
441 }
442 break;
443 case TransactionCommit:
444 if (EraseFileName.empty() == false)
51818f26 445 RemoveFile("TransactionCommit", EraseFileName);
448c38bd
DK
446 break;
447 }
448 return true;
449}
450bool pkgAcqDiffIndex::TransactionState(TransactionStates const state)
451{
452 if (pkgAcqTransactionItem::TransactionState(state) == false)
453 return false;
454
455 switch (state)
456 {
457 case TransactionCommit:
458 break;
459 case TransactionAbort:
dcbbb14d 460 std::string const Partial = GetPartialFileNameFromURI(Target.URI);
51818f26 461 RemoveFile("TransactionAbort", Partial);
448c38bd
DK
462 break;
463 }
464
465 return true;
466}
467 /*}}}*/
b3501edb 468
8d041b4f
DK
469class APT_HIDDEN NoActionItem : public pkgAcquire::Item /*{{{*/
470/* The sole purpose of this class is having an item which does nothing to
471 reach its done state to prevent cleanup deleting the mentioned file.
472 Handy in cases in which we know we have the file already, like IMS-Hits. */
473{
dcbbb14d 474 IndexTarget const Target;
8d041b4f 475 public:
3b302846
DK
476 virtual std::string DescURI() const APT_OVERRIDE {return Target.URI;};
477 virtual HashStringList GetExpectedHashes() const APT_OVERRIDE {return HashStringList();};
8d041b4f 478
e8afd168 479 NoActionItem(pkgAcquire * const Owner, IndexTarget const &Target) :
8d041b4f
DK
480 pkgAcquire::Item(Owner), Target(Target)
481 {
482 Status = StatDone;
dcbbb14d 483 DestFile = GetFinalFileNameFromURI(Target.URI);
8d041b4f 484 }
d7a51997
DK
485 NoActionItem(pkgAcquire * const Owner, IndexTarget const &Target, std::string const &FinalFile) :
486 pkgAcquire::Item(Owner), Target(Target)
487 {
488 Status = StatDone;
489 DestFile = FinalFile;
490 }
8d041b4f
DK
491};
492 /*}}}*/
493
0118833a 494// Acquire::Item::Item - Constructor /*{{{*/
586d8704 495APT_IGNORE_DEPRECATED_PUSH
e8afd168 496pkgAcquire::Item::Item(pkgAcquire * const owner) :
1eb1836f 497 FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
6c55f07a 498 QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner), d(NULL)
0118833a
AL
499{
500 Owner->Add(this);
c88edf1d 501 Status = StatIdle;
0118833a 502}
586d8704 503APT_IGNORE_DEPRECATED_POP
0118833a
AL
504 /*}}}*/
505// Acquire::Item::~Item - Destructor /*{{{*/
0118833a
AL
506pkgAcquire::Item::~Item()
507{
508 Owner->Remove(this);
509}
510 /*}}}*/
448c38bd
DK
511std::string pkgAcquire::Item::Custom600Headers() const /*{{{*/
512{
513 return std::string();
514}
515 /*}}}*/
516std::string pkgAcquire::Item::ShortDesc() const /*{{{*/
517{
518 return DescURI();
519}
520 /*}}}*/
521APT_CONST void pkgAcquire::Item::Finished() /*{{{*/
522{
523}
524 /*}}}*/
525APT_PURE pkgAcquire * pkgAcquire::Item::GetOwner() const /*{{{*/
526{
527 return Owner;
528}
529 /*}}}*/
c8a4ce6c 530APT_CONST pkgAcquire::ItemDesc &pkgAcquire::Item::GetItemDesc() /*{{{*/
08ea7806
DK
531{
532 return Desc;
533}
534 /*}}}*/
448c38bd
DK
535APT_CONST bool pkgAcquire::Item::IsTrusted() const /*{{{*/
536{
537 return false;
538}
539 /*}}}*/
c88edf1d
AL
540// Acquire::Item::Failed - Item failed to download /*{{{*/
541// ---------------------------------------------------------------------
93bf083d
AL
542/* We return to an idle state if there are still other queues that could
543 fetch this object */
448c38bd 544void pkgAcquire::Item::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
c88edf1d 545{
03aa0847 546 if(ErrorText.empty())
2737f28a 547 ErrorText = LookupTag(Message,"Message");
c88edf1d 548 if (QueueCounter <= 1)
93bf083d 549 {
a72ace20 550 /* This indicates that the file is not available right now but might
7d8afa39 551 be sometime later. If we do a retry cycle then this should be
17caf1b1 552 retried [CDROMs] */
4dbfe436 553 if (Cnf != NULL && Cnf->LocalOnly == true &&
7d8afa39 554 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
a72ace20
AL
555 {
556 Status = StatIdle;
681d76d0 557 Dequeue();
a72ace20
AL
558 return;
559 }
7e5f33eb 560
58702f85
DK
561 switch (Status)
562 {
563 case StatIdle:
564 case StatFetching:
565 case StatDone:
566 Status = StatError;
567 break;
568 case StatAuthError:
569 case StatError:
570 case StatTransientNetworkError:
571 break;
572 }
4dbfe436 573 Complete = false;
681d76d0 574 Dequeue();
4dbfe436 575 }
23c5897c 576
03aa0847 577 string const FailReason = LookupTag(Message, "FailReason");
448c38bd 578 if (FailReason == "MaximumSizeExceeded")
03aa0847 579 RenameOnError(MaximumSizeExceeded);
448c38bd
DK
580 else if (Status == StatAuthError)
581 RenameOnError(HashSumMismatch);
ee279506
MV
582
583 // report mirror failure back to LP if we actually use a mirror
448c38bd 584 if (FailReason.empty() == false)
f0b509cd
MV
585 ReportMirrorFailure(FailReason);
586 else
587 ReportMirrorFailure(ErrorText);
146f7715 588
448c38bd
DK
589 if (QueueCounter > 1)
590 Status = StatIdle;
146f7715
DK
591}
592 /*}}}*/
8267fe24
AL
593// Acquire::Item::Start - Item has begun to download /*{{{*/
594// ---------------------------------------------------------------------
448c38bd 595/* Stash status and the file size. Note that setting Complete means
17caf1b1 596 sub-phases of the acquire process such as decompresion are operating */
448c38bd 597void pkgAcquire::Item::Start(string const &/*Message*/, unsigned long long const Size)
8267fe24
AL
598{
599 Status = StatFetching;
03aa0847 600 ErrorText.clear();
8267fe24
AL
601 if (FileSize == 0 && Complete == false)
602 FileSize = Size;
603}
604 /*}}}*/
dd676dc7
DK
605// Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
606/* Note that hash-verification is 'hardcoded' in acquire-worker and has
607 * already passed if this method is called. */
608bool pkgAcquire::Item::VerifyDone(std::string const &Message,
609 pkgAcquire::MethodConfig const * const /*Cnf*/)
610{
611 std::string const FileName = LookupTag(Message,"Filename");
612 if (FileName.empty() == true)
613 {
614 Status = StatError;
615 ErrorText = "Method gave a blank filename";
616 return false;
617 }
618
619 return true;
620}
621 /*}}}*/
c88edf1d 622// Acquire::Item::Done - Item downloaded OK /*{{{*/
a4b8112b 623void pkgAcquire::Item::Done(string const &/*Message*/, HashStringList const &Hashes,
448c38bd 624 pkgAcquire::MethodConfig const * const /*Cnf*/)
c88edf1d 625{
b98f2859 626 // We just downloaded something..
ff86d7df 627 if (FileSize == 0)
b98f2859 628 {
ff86d7df
DK
629 unsigned long long const downloadedSize = Hashes.FileSize();
630 if (downloadedSize != 0)
448c38bd 631 {
ff86d7df 632 FileSize = downloadedSize;
448c38bd 633 }
448c38bd 634 }
c88edf1d
AL
635 Status = StatDone;
636 ErrorText = string();
637 Owner->Dequeue(this);
638}
639 /*}}}*/
8b89e57f
AL
640// Acquire::Item::Rename - Rename a file /*{{{*/
641// ---------------------------------------------------------------------
1e3f4083 642/* This helper function is used by a lot of item methods as their final
8b89e57f 643 step */
448c38bd 644bool pkgAcquire::Item::Rename(string const &From,string const &To)
8b89e57f 645{
ba6b79bd 646 if (From == To || rename(From.c_str(),To.c_str()) == 0)
cecc5532
DK
647 return true;
648
649 std::string S;
650 strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
651 From.c_str(),To.c_str());
652 Status = StatError;
8eafc759
DK
653 if (ErrorText.empty())
654 ErrorText = S;
655 else
656 ErrorText = ErrorText + ": " + S;
cecc5532 657 return false;
8b89e57f
AL
658}
659 /*}}}*/
448c38bd 660void pkgAcquire::Item::Dequeue() /*{{{*/
5684f71f 661{
448c38bd 662 Owner->Dequeue(this);
ba6b79bd 663}
448c38bd
DK
664 /*}}}*/
665bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
3c8030a4 666{
03aa0847 667 if (RealFileExists(DestFile))
3c8030a4
DK
668 Rename(DestFile, DestFile + ".FAILED");
669
448c38bd 670 std::string errtext;
3c8030a4
DK
671 switch (error)
672 {
673 case HashSumMismatch:
448c38bd 674 errtext = _("Hash Sum mismatch");
3c8030a4
DK
675 Status = StatAuthError;
676 ReportMirrorFailure("HashChecksumFailure");
677 break;
678 case SizeMismatch:
448c38bd 679 errtext = _("Size mismatch");
3c8030a4
DK
680 Status = StatAuthError;
681 ReportMirrorFailure("SizeFailure");
682 break;
683 case InvalidFormat:
448c38bd 684 errtext = _("Invalid file format");
3c8030a4
DK
685 Status = StatError;
686 // do not report as usually its not the mirrors fault, but Portal/Proxy
687 break;
631a7dc7 688 case SignatureError:
448c38bd 689 errtext = _("Signature error");
631a7dc7
MV
690 Status = StatError;
691 break;
692 case NotClearsigned:
dd676dc7
DK
693 strprintf(errtext, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
694 Status = StatAuthError;
03aa0847
DK
695 break;
696 case MaximumSizeExceeded:
697 // the method is expected to report a good error for this
631a7dc7
MV
698 Status = StatError;
699 break;
146f7715
DK
700 case PDiffError:
701 // no handling here, done by callers
702 break;
3c8030a4 703 }
448c38bd
DK
704 if (ErrorText.empty())
705 ErrorText = errtext;
3c8030a4
DK
706 return false;
707}
708 /*}}}*/
8267fbd9 709void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
eeac6897
MV
710{
711 ActiveSubprocess = subprocess;
586d8704 712 APT_IGNORE_DEPRECATED(Mode = ActiveSubprocess.c_str();)
eeac6897 713}
8267fbd9 714 /*}}}*/
c91d9a63 715// Acquire::Item::ReportMirrorFailure /*{{{*/
448c38bd 716void pkgAcquire::Item::ReportMirrorFailure(string const &FailCode)
36280399 717{
59271f62
MV
718 // we only act if a mirror was used at all
719 if(UsedMirror.empty())
720 return;
36280399
MV
721#if 0
722 std::cerr << "\nReportMirrorFailure: "
723 << UsedMirror
59271f62 724 << " Uri: " << DescURI()
36280399
MV
725 << " FailCode: "
726 << FailCode << std::endl;
727#endif
36280399 728 string report = _config->Find("Methods::Mirror::ProblemReporting",
3f599bb7 729 "/usr/lib/apt/apt-report-mirror-failure");
36280399
MV
730 if(!FileExists(report))
731 return;
cecc5532
DK
732
733 std::vector<char const*> Args;
734 Args.push_back(report.c_str());
735 Args.push_back(UsedMirror.c_str());
736 Args.push_back(DescURI().c_str());
737 Args.push_back(FailCode.c_str());
738 Args.push_back(NULL);
739
36280399 740 pid_t pid = ExecFork();
cecc5532 741 if(pid < 0)
36280399
MV
742 {
743 _error->Error("ReportMirrorFailure Fork failed");
744 return;
745 }
cecc5532 746 else if(pid == 0)
36280399 747 {
cecc5532 748 execvp(Args[0], (char**)Args.data());
361593e9
MV
749 std::cerr << "Could not exec " << Args[0] << std::endl;
750 _exit(100);
36280399 751 }
cecc5532 752 if(!ExecWait(pid, "report-mirror-failure"))
36280399
MV
753 {
754 _error->Warning("Couldn't report problem to '%s'",
361593e9 755 _config->Find("Methods::Mirror::ProblemReporting").c_str());
36280399
MV
756 }
757}
c91d9a63 758 /*}}}*/
448c38bd 759std::string pkgAcquire::Item::HashSum() const /*{{{*/
ac5b205a 760{
448c38bd
DK
761 HashStringList const hashes = GetExpectedHashes();
762 HashString const * const hs = hashes.find(NULL);
763 return hs != NULL ? hs->toStr() : "";
764}
765 /*}}}*/
2237bd01 766
448c38bd 767pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire * const Owner, /*{{{*/
3d8232bf 768 pkgAcqMetaClearSig * const transactionManager, IndexTarget const &target) :
6c55f07a 769 pkgAcquire::Item(Owner), d(NULL), Target(target), TransactionManager(transactionManager)
448c38bd
DK
770{
771 if (TransactionManager != this)
772 TransactionManager->Add(this);
773}
774 /*}}}*/
775pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
776{
777}
778 /*}}}*/
e8afd168 779HashStringList pkgAcqTransactionItem::GetExpectedHashesFor(std::string const &MetaKey) const /*{{{*/
448c38bd 780{
8d041b4f 781 return GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, MetaKey);
448c38bd
DK
782}
783 /*}}}*/
ac5b205a 784
448c38bd
DK
785// AcqMetaBase - Constructor /*{{{*/
786pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire * const Owner,
3d8232bf 787 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 788 std::vector<IndexTarget> const &IndexTargets,
3d8232bf 789 IndexTarget const &DataTarget)
6c55f07a 790: pkgAcqTransactionItem(Owner, TransactionManager, DataTarget), d(NULL),
3d8232bf 791 IndexTargets(IndexTargets),
448c38bd
DK
792 AuthPass(false), IMSHit(false)
793{
794}
795 /*}}}*/
796// AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
797void pkgAcqMetaBase::Add(pkgAcqTransactionItem * const I)
798{
799 Transaction.push_back(I);
800}
801 /*}}}*/
802// AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
803void pkgAcqMetaBase::AbortTransaction()
804{
805 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
806 std::clog << "AbortTransaction: " << TransactionManager << std::endl;
ac5b205a 807
448c38bd
DK
808 // ensure the toplevel is in error state too
809 for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
810 I != Transaction.end(); ++I)
2ac3eeb6 811 {
448c38bd 812 (*I)->TransactionState(TransactionAbort);
ac5b205a 813 }
448c38bd
DK
814 Transaction.clear();
815}
816 /*}}}*/
817// AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
818APT_PURE bool pkgAcqMetaBase::TransactionHasError() const
819{
820 for (std::vector<pkgAcqTransactionItem*>::const_iterator I = Transaction.begin();
821 I != Transaction.end(); ++I)
822 {
823 switch((*I)->Status) {
824 case StatDone: break;
825 case StatIdle: break;
826 case StatAuthError: return true;
827 case StatError: return true;
828 case StatTransientNetworkError: return true;
829 case StatFetching: break;
830 }
831 }
832 return false;
833}
834 /*}}}*/
835// AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
836void pkgAcqMetaBase::CommitTransaction()
837{
838 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
839 std::clog << "CommitTransaction: " << this << std::endl;
ac5b205a 840
448c38bd
DK
841 // move new files into place *and* remove files that are not
842 // part of the transaction but are still on disk
843 for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
844 I != Transaction.end(); ++I)
845 {
846 (*I)->TransactionState(TransactionCommit);
847 }
848 Transaction.clear();
295d848b
DK
849}
850 /*}}}*/
448c38bd
DK
851// AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
852void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem * const I,
853 const std::string &From,
854 const std::string &To)
295d848b 855{
448c38bd
DK
856 I->PartialFile = From;
857 I->DestFile = To;
ac5b205a 858}
92fcbfc1 859 /*}}}*/
448c38bd
DK
860// AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
861void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem * const I,
862 const std::string &FinalFile)
863{
864 I->PartialFile = "";
865 I->DestFile = FinalFile;
866}
867 /*}}}*/
868// AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
869bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item * const I, const std::string &Message)
870{
871 // FIXME: this entire function can do now that we disallow going to
872 // a unauthenticated state and can cleanly rollback
873
874 string const Final = I->GetFinalFilename();
875 if(FileExists(Final))
876 {
877 I->Status = StatTransientNetworkError;
878 _error->Warning(_("An error occurred during the signature "
879 "verification. The repository is not updated "
880 "and the previous index files will be used. "
0efb29eb 881 "GPG error: %s: %s"),
448c38bd
DK
882 Desc.Description.c_str(),
883 LookupTag(Message,"Message").c_str());
884 RunScripts("APT::Update::Auth-Failure");
885 return true;
886 } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
887 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
888 _error->Error(_("GPG error: %s: %s"),
889 Desc.Description.c_str(),
890 LookupTag(Message,"Message").c_str());
dd676dc7 891 I->Status = StatAuthError;
448c38bd
DK
892 return true;
893 } else {
894 _error->Warning(_("GPG error: %s: %s"),
895 Desc.Description.c_str(),
896 LookupTag(Message,"Message").c_str());
897 }
898 // gpgv method failed
899 ReportMirrorFailure("GPGFailure");
900 return false;
901}
902 /*}}}*/
903// AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
6cb30d01 904// ---------------------------------------------------------------------
448c38bd 905string pkgAcqMetaBase::Custom600Headers() const
6cb30d01 906{
448c38bd
DK
907 std::string Header = "\nIndex-File: true";
908 std::string MaximumSize;
909 strprintf(MaximumSize, "\nMaximum-Size: %i",
910 _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
911 Header += MaximumSize;
4d0818cc 912
448c38bd 913 string const FinalFile = GetFinalFilename();
6cb30d01 914 struct stat Buf;
448c38bd
DK
915 if (stat(FinalFile.c_str(),&Buf) == 0)
916 Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
917
918 return Header;
6cb30d01 919}
92fcbfc1 920 /*}}}*/
448c38bd
DK
921// AcqMetaBase::QueueForSignatureVerify /*{{{*/
922void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem * const I, std::string const &File, std::string const &Signature)
ba6b79bd 923{
448c38bd
DK
924 AuthPass = true;
925 I->Desc.URI = "gpgv:" + Signature;
926 I->DestFile = File;
927 QueueURI(I->Desc);
928 I->SetActiveSubprocess("gpgv");
ba6b79bd
DK
929}
930 /*}}}*/
448c38bd
DK
931// AcqMetaBase::CheckDownloadDone /*{{{*/
932bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem * const I, const std::string &Message, HashStringList const &Hashes) const
2237bd01 933{
448c38bd
DK
934 // We have just finished downloading a Release file (it is not
935 // verified yet)
f6d4ab9a 936
dd676dc7 937 std::string const FileName = LookupTag(Message,"Filename");
08ea7806 938 if (FileName != I->DestFile && RealFileExists(I->DestFile) == false)
f6d4ab9a 939 {
448c38bd
DK
940 I->Local = true;
941 I->Desc.URI = "copy:" + FileName;
942 I->QueueURI(I->Desc);
f6d4ab9a
DK
943 return false;
944 }
2237bd01 945
448c38bd
DK
946 // make sure to verify against the right file on I-M-S hit
947 bool IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"), false);
948 if (IMSHit == false && Hashes.usable())
f6d4ab9a 949 {
448c38bd
DK
950 // detect IMS-Hits servers haven't detected by Hash comparison
951 std::string const FinalFile = I->GetFinalFilename();
952 if (RealFileExists(FinalFile) && Hashes.VerifyFile(FinalFile) == true)
2ac3eeb6 953 {
448c38bd 954 IMSHit = true;
51818f26 955 RemoveFile("CheckDownloadDone", I->DestFile);
5e1ed088 956 }
f6d4ab9a
DK
957 }
958
448c38bd 959 if(IMSHit == true)
f6d4ab9a 960 {
448c38bd
DK
961 // for simplicity, the transaction manager is always InRelease
962 // even if it doesn't exist.
963 if (TransactionManager != NULL)
964 TransactionManager->IMSHit = true;
965 I->PartialFile = I->DestFile = I->GetFinalFilename();
f6d4ab9a
DK
966 }
967
448c38bd
DK
968 // set Item to complete as the remaining work is all local (verify etc)
969 I->Complete = true;
f6d4ab9a 970
448c38bd
DK
971 return true;
972}
973 /*}}}*/
974bool pkgAcqMetaBase::CheckAuthDone(string const &Message) /*{{{*/
975{
976 // At this point, the gpgv method has succeeded, so there is a
977 // valid signature from a key in the trusted keyring. We
978 // perform additional verification of its contents, and use them
979 // to verify the indexes we are about to download
f6d4ab9a 980
448c38bd 981 if (TransactionManager->IMSHit == false)
f6d4ab9a 982 {
448c38bd
DK
983 // open the last (In)Release if we have it
984 std::string const FinalFile = GetFinalFilename();
985 std::string FinalRelease;
986 std::string FinalInRelease;
987 if (APT::String::Endswith(FinalFile, "InRelease"))
2ac3eeb6 988 {
448c38bd
DK
989 FinalInRelease = FinalFile;
990 FinalRelease = FinalFile.substr(0, FinalFile.length() - strlen("InRelease")) + "Release";
991 }
992 else
993 {
994 FinalInRelease = FinalFile.substr(0, FinalFile.length() - strlen("Release")) + "InRelease";
995 FinalRelease = FinalFile;
996 }
997 if (RealFileExists(FinalInRelease) || RealFileExists(FinalRelease))
998 {
5ad0096a
DK
999 TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
1000 if (TransactionManager->LastMetaIndexParser != NULL)
02dceb31 1001 {
5ad0096a
DK
1002 _error->PushToStack();
1003 if (RealFileExists(FinalInRelease))
1004 TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
1005 else
1006 TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
1007 // its unlikely to happen, but if what we have is bad ignore it
1008 if (_error->PendingError())
1009 {
1010 delete TransactionManager->LastMetaIndexParser;
1011 TransactionManager->LastMetaIndexParser = NULL;
1012 }
1013 _error->RevertToStack();
2237bd01
MV
1014 }
1015 }
f6d4ab9a
DK
1016 }
1017
5ad0096a 1018 if (TransactionManager->MetaIndexParser->Load(DestFile, &ErrorText) == false)
f6d4ab9a 1019 {
448c38bd 1020 Status = StatAuthError;
f6d4ab9a
DK
1021 return false;
1022 }
1023
448c38bd 1024 if (!VerifyVendor(Message))
f6d4ab9a 1025 {
448c38bd
DK
1026 Status = StatAuthError;
1027 return false;
1028 }
f6d4ab9a 1029
448c38bd
DK
1030 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1031 std::cerr << "Signature verification succeeded: "
1032 << DestFile << std::endl;
2237bd01 1033
448c38bd
DK
1034 // Download further indexes with verification
1035 QueueIndexes(true);
2237bd01 1036
448c38bd
DK
1037 return true;
1038}
1039 /*}}}*/
1040void pkgAcqMetaBase::QueueIndexes(bool const verify) /*{{{*/
1041{
1042 // at this point the real Items are loaded in the fetcher
1043 ExpectedAdditionalItems = 0;
1044
af81ab90
DK
1045 bool metaBaseSupportsByHash = false;
1046 if (TransactionManager != NULL && TransactionManager->MetaIndexParser != NULL)
1047 metaBaseSupportsByHash = TransactionManager->MetaIndexParser->GetSupportsAcquireByHash();
1048
d7a51997 1049 for (std::vector <IndexTarget>::iterator Target = IndexTargets.begin();
dcbbb14d 1050 Target != IndexTargets.end();
448c38bd
DK
1051 ++Target)
1052 {
1dd20368
DK
1053 // all is an implementation detail. Users shouldn't use this as arch
1054 // We need this support trickery here as e.g. Debian has binary-all files already,
1055 // but arch:all packages are still in the arch:any files, so we would waste precious
1056 // download time, bandwidth and diskspace for nothing, BUT Debian doesn't feature all
1057 // in the set of supported architectures, so we can filter based on this property rather
1058 // than invent an entirely new flag we would need to carry for all of eternity.
1059 if (Target->Option(IndexTarget::ARCHITECTURE) == "all" &&
1060 TransactionManager->MetaIndexParser->IsArchitectureSupported("all") == false)
1061 continue;
1062
1a3a14ac 1063 bool trypdiff = Target->OptionBool(IndexTarget::PDIFFS);
9b8c28f4 1064 if (verify == true)
2ac3eeb6 1065 {
dcbbb14d 1066 if (TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false)
9b8c28f4
DK
1067 {
1068 // optional targets that we do not have in the Release file are skipped
dcbbb14d 1069 if (Target->IsOptional)
9b8c28f4 1070 continue;
47d2bc78 1071
1dd20368
DK
1072 std::string const &arch = Target->Option(IndexTarget::ARCHITECTURE);
1073 if (arch.empty() == false)
1074 {
1075 if (TransactionManager->MetaIndexParser->IsArchitectureSupported(arch) == false)
1076 {
1077 _error->Notice(_("Skipping acquire of configured file '%s' as repository '%s' doesn't support architecture '%s'"),
1078 Target->MetaKey.c_str(), TransactionManager->Target.Description.c_str(), arch.c_str());
1079 continue;
1080 }
1081 // if the architecture is officially supported but currently no packages for it available,
1082 // ignore silently as this is pretty much the same as just shipping an empty file.
1083 // if we don't know which architectures are supported, we do NOT ignore it to notify user about this
1084 if (TransactionManager->MetaIndexParser->IsArchitectureSupported("*undefined*") == false)
1085 continue;
1086 }
1087
9b8c28f4 1088 Status = StatAuthError;
dcbbb14d 1089 strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target->MetaKey.c_str());
9b8c28f4
DK
1090 return;
1091 }
1092
d7a51997
DK
1093 // autoselect the compression method
1094 std::vector<std::string> types = VectorizeString(Target->Option(IndexTarget::COMPRESSIONTYPES), ' ');
1095 types.erase(std::remove_if(types.begin(), types.end(), [&](std::string const &t) {
1096 if (t == "uncompressed")
1097 return TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false;
1098 std::string const MetaKey = Target->MetaKey + "." + t;
1099 return TransactionManager->MetaIndexParser->Exists(MetaKey) == false;
1100 }), types.end());
1101 if (types.empty() == false)
8d041b4f 1102 {
d7a51997 1103 std::ostringstream os;
af81ab90
DK
1104 // add the special compressiontype byhash first if supported
1105 std::string const useByHashConf = Target->Option(IndexTarget::BY_HASH);
1106 bool useByHash = false;
1107 if(useByHashConf == "force")
1108 useByHash = true;
1109 else
1110 useByHash = StringToBool(useByHashConf) == true && metaBaseSupportsByHash;
1111 if (useByHash == true)
1112 os << "by-hash ";
d7a51997
DK
1113 std::copy(types.begin(), types.end()-1, std::ostream_iterator<std::string>(os, " "));
1114 os << *types.rbegin();
1115 Target->Options["COMPRESSIONTYPES"] = os.str();
1116 }
1117 else
1118 Target->Options["COMPRESSIONTYPES"].clear();
1119
1120 std::string filename = GetFinalFileNameFromURI(Target->URI);
1121 if (RealFileExists(filename) == false)
1122 {
1123 if (Target->KeepCompressed)
8d041b4f 1124 {
d7a51997
DK
1125 filename = GetKeepCompressedFileName(filename, *Target);
1126 if (RealFileExists(filename) == false)
1127 filename.clear();
8d041b4f 1128 }
d7a51997
DK
1129 else
1130 filename.clear();
1131 }
1132
1133 if (filename.empty() == false)
1134 {
1135 // if the Release file is a hit and we have an index it must be the current one
1136 if (TransactionManager->IMSHit == true)
1137 ;
1138 else if (TransactionManager->LastMetaIndexParser != NULL)
1196da2e 1139 {
d7a51997
DK
1140 // see if the file changed since the last Release file
1141 // we use the uncompressed files as we might compress differently compared to the server,
1142 // so the hashes might not match, even if they contain the same data.
1143 HashStringList const newFile = GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, Target->MetaKey);
1144 HashStringList const oldFile = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target->MetaKey);
1145 if (newFile != oldFile)
1146 filename.clear();
1196da2e 1147 }
d7a51997
DK
1148 else
1149 filename.clear();
8d041b4f
DK
1150 }
1151 else
1152 trypdiff = false; // no file to patch
1153
d7a51997
DK
1154 if (filename.empty() == false)
1155 {
1156 new NoActionItem(Owner, *Target, filename);
3d1e34b0
DK
1157 std::string const idxfilename = GetFinalFileNameFromURI(Target->URI + ".diff/Index");
1158 if (FileExists(idxfilename))
1159 new NoActionItem(Owner, *Target, idxfilename);
d7a51997
DK
1160 continue;
1161 }
1162
9b8c28f4 1163 // check if we have patches available
dcbbb14d 1164 trypdiff &= TransactionManager->MetaIndexParser->Exists(Target->MetaKey + ".diff/Index");
2237bd01 1165 }
d7a51997
DK
1166 else
1167 {
1168 // if we have no file to patch, no point in trying
1169 std::string filename = GetFinalFileNameFromURI(Target->URI);
1170 if (RealFileExists(filename) == false)
1171 {
1172 if (Target->KeepCompressed)
1173 {
1174 filename = GetKeepCompressedFileName(filename, *Target);
1175 if (RealFileExists(filename) == false)
1176 filename.clear();
1177 }
1178 else
1179 filename.clear();
1180 }
1181 trypdiff &= (filename.empty() == false);
1182 }
448c38bd 1183
9b8c28f4
DK
1184 // no point in patching from local sources
1185 if (trypdiff)
1186 {
dcbbb14d 1187 std::string const proto = Target->URI.substr(0, strlen("file:/"));
9b8c28f4
DK
1188 if (proto == "file:/" || proto == "copy:/" || proto == "cdrom:")
1189 trypdiff = false;
1190 }
1191
1192 // Queue the Index file (Packages, Sources, Translation-$foo, …)
1193 if (trypdiff)
448c38bd
DK
1194 new pkgAcqDiffIndex(Owner, TransactionManager, *Target);
1195 else
1196 new pkgAcqIndex(Owner, TransactionManager, *Target);
2237bd01 1197 }
448c38bd
DK
1198}
1199 /*}}}*/
1200bool pkgAcqMetaBase::VerifyVendor(string const &Message) /*{{{*/
1201{
1202 string::size_type pos;
f6d4ab9a 1203
448c38bd
DK
1204 // check for missing sigs (that where not fatal because otherwise we had
1205 // bombed earlier)
1206 string missingkeys;
1207 string msg = _("There is no public key available for the "
1208 "following key IDs:\n");
1209 pos = Message.find("NO_PUBKEY ");
1210 if (pos != std::string::npos)
f6d4ab9a 1211 {
448c38bd
DK
1212 string::size_type start = pos+strlen("NO_PUBKEY ");
1213 string Fingerprint = Message.substr(start, Message.find("\n")-start);
1214 missingkeys += (Fingerprint);
f6d4ab9a 1215 }
448c38bd
DK
1216 if(!missingkeys.empty())
1217 _error->Warning("%s", (msg + missingkeys).c_str());
f6d4ab9a 1218
448c38bd
DK
1219 string Transformed = TransactionManager->MetaIndexParser->GetExpectedDist();
1220
1221 if (Transformed == "../project/experimental")
f6d4ab9a 1222 {
448c38bd 1223 Transformed = "experimental";
f6d4ab9a
DK
1224 }
1225
448c38bd
DK
1226 pos = Transformed.rfind('/');
1227 if (pos != string::npos)
f6d4ab9a 1228 {
448c38bd 1229 Transformed = Transformed.substr(0, pos);
f6d4ab9a
DK
1230 }
1231
448c38bd 1232 if (Transformed == ".")
f6d4ab9a 1233 {
448c38bd 1234 Transformed = "";
f6d4ab9a
DK
1235 }
1236
0741daeb
DK
1237 if (TransactionManager->MetaIndexParser->GetValidUntil() > 0)
1238 {
448c38bd
DK
1239 time_t const invalid_since = time(NULL) - TransactionManager->MetaIndexParser->GetValidUntil();
1240 if (invalid_since > 0)
1241 {
1242 std::string errmsg;
1243 strprintf(errmsg,
1244 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
3d8232bf 1245 // the time since then the file is invalid - formatted in the same way as in
448c38bd
DK
1246 // the download progress display (e.g. 7d 3h 42min 1s)
1247 _("Release file for %s is expired (invalid since %s). "
1248 "Updates for this repository will not be applied."),
dcbbb14d 1249 Target.URI.c_str(), TimeToStr(invalid_since).c_str());
448c38bd
DK
1250 if (ErrorText.empty())
1251 ErrorText = errmsg;
1252 return _error->Error("%s", errmsg.c_str());
1253 }
1254 }
f6d4ab9a 1255
448c38bd
DK
1256 /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
1257 as a prevention of downgrading us to older (still valid) files */
1258 if (TransactionManager->IMSHit == false && TransactionManager->LastMetaIndexParser != NULL &&
1259 TransactionManager->LastMetaIndexParser->GetDate() > TransactionManager->MetaIndexParser->GetDate())
f6d4ab9a 1260 {
448c38bd 1261 TransactionManager->IMSHit = true;
51818f26 1262 RemoveFile("VerifyVendor", DestFile);
448c38bd 1263 PartialFile = DestFile = GetFinalFilename();
5ad0096a
DK
1264 // load the 'old' file in the 'new' one instead of flipping pointers as
1265 // the new one isn't owned by us, while the old one is so cleanup would be confused.
1266 TransactionManager->MetaIndexParser->swapLoad(TransactionManager->LastMetaIndexParser);
1267 delete TransactionManager->LastMetaIndexParser;
448c38bd 1268 TransactionManager->LastMetaIndexParser = NULL;
f6d4ab9a
DK
1269 }
1270
448c38bd 1271 if (_config->FindB("Debug::pkgAcquire::Auth", false))
f6d4ab9a 1272 {
5ad0096a 1273 std::cerr << "Got Codename: " << TransactionManager->MetaIndexParser->GetCodename() << std::endl;
448c38bd
DK
1274 std::cerr << "Expecting Dist: " << TransactionManager->MetaIndexParser->GetExpectedDist() << std::endl;
1275 std::cerr << "Transformed Dist: " << Transformed << std::endl;
f6d4ab9a 1276 }
448c38bd
DK
1277
1278 if (TransactionManager->MetaIndexParser->CheckDist(Transformed) == false)
f6d4ab9a 1279 {
448c38bd
DK
1280 // This might become fatal one day
1281// Status = StatAuthError;
1282// ErrorText = "Conflicting distribution; expected "
1283// + MetaIndexParser->GetExpectedDist() + " but got "
5ad0096a 1284// + MetaIndexParser->GetCodename();
448c38bd
DK
1285// return false;
1286 if (!Transformed.empty())
1287 {
1288 _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1289 Desc.Description.c_str(),
1290 Transformed.c_str(),
5ad0096a 1291 TransactionManager->MetaIndexParser->GetCodename().c_str());
448c38bd 1292 }
f6d4ab9a
DK
1293 }
1294
f6d4ab9a 1295 return true;
2237bd01 1296}
92fcbfc1 1297 /*}}}*/
3d8232bf
DK
1298pkgAcqMetaBase::~pkgAcqMetaBase()
1299{
1300}
2237bd01 1301
448c38bd
DK
1302pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire * const Owner, /*{{{*/
1303 IndexTarget const &ClearsignedTarget,
1304 IndexTarget const &DetachedDataTarget, IndexTarget const &DetachedSigTarget,
e8afd168 1305 std::vector<IndexTarget> const &IndexTargets,
5ad0096a 1306 metaIndex * const MetaIndexParser) :
3d8232bf 1307 pkgAcqMetaIndex(Owner, this, ClearsignedTarget, DetachedSigTarget, IndexTargets),
6c55f07a 1308 d(NULL), ClearsignedTarget(ClearsignedTarget),
3d8232bf
DK
1309 DetachedDataTarget(DetachedDataTarget),
1310 MetaIndexParser(MetaIndexParser), LastMetaIndexParser(NULL)
448c38bd
DK
1311{
1312 // index targets + (worst case:) Release/Release.gpg
dcbbb14d 1313 ExpectedAdditionalItems = IndexTargets.size() + 2;
448c38bd 1314 TransactionManager->Add(this);
2237bd01 1315}
92fcbfc1 1316 /*}}}*/
448c38bd 1317pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
146f7715 1318{
3d8232bf
DK
1319 if (LastMetaIndexParser != NULL)
1320 delete LastMetaIndexParser;
146f7715
DK
1321}
1322 /*}}}*/
448c38bd
DK
1323// pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1324string pkgAcqMetaClearSig::Custom600Headers() const
2237bd01 1325{
448c38bd
DK
1326 string Header = pkgAcqMetaBase::Custom600Headers();
1327 Header += "\nFail-Ignore: true";
b0d40854
DK
1328 std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
1329 if (key.empty() == false)
1330 Header += "\nSigned-By: " + key;
1331
448c38bd
DK
1332 return Header;
1333}
1334 /*}}}*/
24e8f24e 1335bool pkgAcqMetaClearSig::VerifyDone(std::string const &Message, /*{{{*/
dd676dc7
DK
1336 pkgAcquire::MethodConfig const * const Cnf)
1337{
1338 Item::VerifyDone(Message, Cnf);
1339
1340 if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
1341 return RenameOnError(NotClearsigned);
1342
1343 return true;
1344}
24e8f24e 1345 /*}}}*/
448c38bd 1346// pkgAcqMetaClearSig::Done - We got a file /*{{{*/
448c38bd
DK
1347void pkgAcqMetaClearSig::Done(std::string const &Message,
1348 HashStringList const &Hashes,
1349 pkgAcquire::MethodConfig const * const Cnf)
1350{
1351 Item::Done(Message, Hashes, Cnf);
8d266656 1352
448c38bd
DK
1353 if(AuthPass == false)
1354 {
1355 if(CheckDownloadDone(this, Message, Hashes) == true)
1356 QueueForSignatureVerify(this, DestFile, DestFile);
1357 return;
1358 }
1359 else if(CheckAuthDone(Message) == true)
1360 {
1361 if (TransactionManager->IMSHit == false)
1362 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
1363 else if (RealFileExists(GetFinalFilename()) == false)
1364 {
1365 // We got an InRelease file IMSHit, but we haven't one, which means
1366 // we had a valid Release/Release.gpg combo stepping in, which we have
1367 // to 'acquire' now to ensure list cleanup isn't removing them
dcbbb14d
DK
1368 new NoActionItem(Owner, DetachedDataTarget);
1369 new NoActionItem(Owner, DetachedSigTarget);
448c38bd
DK
1370 }
1371 }
2237bd01 1372}
92fcbfc1 1373 /*}}}*/
448c38bd 1374void pkgAcqMetaClearSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf) /*{{{*/
2237bd01 1375{
448c38bd 1376 Item::Failed(Message, Cnf);
2237bd01 1377
448c38bd
DK
1378 // we failed, we will not get additional items from this method
1379 ExpectedAdditionalItems = 0;
2237bd01 1380
448c38bd 1381 if (AuthPass == false)
2ac3eeb6 1382 {
f18f2338 1383 if (Status == StatAuthError || Status == StatTransientNetworkError)
dd676dc7 1384 {
f18f2338
DK
1385 // if we expected a ClearTextSignature (InRelease) but got a network
1386 // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
dd676dc7
DK
1387 // As these is usually called by web-portals we do not try Release/Release.gpg
1388 // as this is gonna fail anyway and instead abort our try (LP#346386)
1389 TransactionManager->AbortTransaction();
1390 return;
1391 }
1392
448c38bd
DK
1393 // Queue the 'old' InRelease file for removal if we try Release.gpg
1394 // as otherwise the file will stay around and gives a false-auth
1395 // impression (CVE-2012-0214)
1396 TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
1397 Status = StatDone;
1398
3d8232bf 1399 new pkgAcqMetaIndex(Owner, TransactionManager, DetachedDataTarget, DetachedSigTarget, IndexTargets);
2ac3eeb6
MV
1400 }
1401 else
1402 {
448c38bd
DK
1403 if(CheckStopAuthentication(this, Message))
1404 return;
1405
448c38bd
DK
1406 // No Release file was present, or verification failed, so fall
1407 // back to queueing Packages files without verification
1408 // only allow going further if the users explicitely wants it
f18f2338 1409 if(AllowInsecureRepositories(_("The repository '%s' is not signed."), ClearsignedTarget.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
146f7715 1410 {
448c38bd
DK
1411 Status = StatDone;
1412
1413 /* InRelease files become Release files, otherwise
1414 * they would be considered as trusted later on */
1415 string const FinalRelease = GetFinalFileNameFromURI(DetachedDataTarget.URI);
1416 string const PartialRelease = GetPartialFileNameFromURI(DetachedDataTarget.URI);
1417 string const FinalReleasegpg = GetFinalFileNameFromURI(DetachedSigTarget.URI);
1418 string const FinalInRelease = GetFinalFilename();
1419 Rename(DestFile, PartialRelease);
1420 TransactionManager->TransactionStageCopy(this, PartialRelease, FinalRelease);
1421
1422 if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
146f7715 1423 {
448c38bd
DK
1424 // open the last Release if we have it
1425 if (TransactionManager->IMSHit == false)
1426 {
5ad0096a
DK
1427 TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
1428 if (TransactionManager->LastMetaIndexParser != NULL)
448c38bd 1429 {
5ad0096a
DK
1430 _error->PushToStack();
1431 if (RealFileExists(FinalInRelease))
1432 TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
1433 else
1434 TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
1435 // its unlikely to happen, but if what we have is bad ignore it
1436 if (_error->PendingError())
1437 {
1438 delete TransactionManager->LastMetaIndexParser;
1439 TransactionManager->LastMetaIndexParser = NULL;
1440 }
1441 _error->RevertToStack();
448c38bd 1442 }
448c38bd 1443 }
146f7715 1444 }
146f7715 1445
448c38bd
DK
1446 // we parse the indexes here because at this point the user wanted
1447 // a repository that may potentially harm him
5ad0096a 1448 if (TransactionManager->MetaIndexParser->Load(PartialRelease, &ErrorText) == false || VerifyVendor(Message) == false)
448c38bd
DK
1449 /* expired Release files are still a problem you need extra force for */;
1450 else
1451 QueueIndexes(true);
1452 }
2237bd01
MV
1453 }
1454}
92fcbfc1 1455 /*}}}*/
03aa0847 1456
448c38bd 1457pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire * const Owner, /*{{{*/
3d8232bf 1458 pkgAcqMetaClearSig * const TransactionManager,
448c38bd
DK
1459 IndexTarget const &DataTarget,
1460 IndexTarget const &DetachedSigTarget,
3d8232bf
DK
1461 vector<IndexTarget> const &IndexTargets) :
1462 pkgAcqMetaBase(Owner, TransactionManager, IndexTargets, DataTarget), d(NULL),
448c38bd 1463 DetachedSigTarget(DetachedSigTarget)
ac5b205a 1464{
448c38bd
DK
1465 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1466 std::clog << "New pkgAcqMetaIndex with TransactionManager "
1467 << this->TransactionManager << std::endl;
2d4722e2 1468
448c38bd 1469 DestFile = GetPartialFileNameFromURI(DataTarget.URI);
fa3a96a1 1470
448c38bd
DK
1471 // Create the item
1472 Desc.Description = DataTarget.Description;
1473 Desc.Owner = this;
1474 Desc.ShortDesc = DataTarget.ShortDesc;
1475 Desc.URI = DataTarget.URI;
ac5b205a 1476
448c38bd 1477 // we expect more item
dcbbb14d 1478 ExpectedAdditionalItems = IndexTargets.size();
448c38bd 1479 QueueURI(Desc);
ac5b205a 1480}
92fcbfc1 1481 /*}}}*/
448c38bd
DK
1482void pkgAcqMetaIndex::Done(string const &Message, /*{{{*/
1483 HashStringList const &Hashes,
1484 pkgAcquire::MethodConfig const * const Cfg)
ac5b205a 1485{
448c38bd 1486 Item::Done(Message,Hashes,Cfg);
03bfbc96 1487
448c38bd 1488 if(CheckDownloadDone(this, Message, Hashes))
03bfbc96 1489 {
448c38bd
DK
1490 // we have a Release file, now download the Signature, all further
1491 // verify/queue for additional downloads will be done in the
1492 // pkgAcqMetaSig::Done() code
dcbbb14d 1493 new pkgAcqMetaSig(Owner, TransactionManager, DetachedSigTarget, this);
03bfbc96 1494 }
448c38bd
DK
1495}
1496 /*}}}*/
1497// pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
1498void pkgAcqMetaIndex::Failed(string const &Message,
1499 pkgAcquire::MethodConfig const * const Cnf)
1500{
1501 pkgAcquire::Item::Failed(Message, Cnf);
1502 Status = StatDone;
94dc9d7d 1503
448c38bd
DK
1504 // No Release file was present so fall
1505 // back to queueing Packages files without verification
1506 // only allow going further if the users explicitely wants it
f18f2338 1507 if(AllowInsecureRepositories(_("The repository '%s' does not have a Release file."), Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
f6d4ab9a 1508 {
448c38bd
DK
1509 // ensure old Release files are removed
1510 TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
03bfbc96 1511
448c38bd
DK
1512 // queue without any kind of hashsum support
1513 QueueIndexes(false);
59a704f0 1514 }
448c38bd
DK
1515}
1516 /*}}}*/
1517void pkgAcqMetaIndex::Finished() /*{{{*/
1518{
1519 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1520 std::clog << "Finished: " << DestFile <<std::endl;
1521 if(TransactionManager != NULL &&
1522 TransactionManager->TransactionHasError() == false)
1523 TransactionManager->CommitTransaction();
1524}
1525 /*}}}*/
1526std::string pkgAcqMetaIndex::DescURI() const /*{{{*/
1527{
dcbbb14d 1528 return Target.URI;
448c38bd
DK
1529}
1530 /*}}}*/
c8a4ce6c 1531pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
94dc9d7d 1532
448c38bd
DK
1533// AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1534pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire * const Owner,
3d8232bf 1535 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 1536 IndexTarget const &Target,
448c38bd 1537 pkgAcqMetaIndex * const MetaIndex) :
6c55f07a 1538 pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL), MetaIndex(MetaIndex)
448c38bd 1539{
dcbbb14d 1540 DestFile = GetPartialFileNameFromURI(Target.URI);
6cb30d01 1541
448c38bd
DK
1542 // remove any partial downloaded sig-file in partial/.
1543 // it may confuse proxies and is too small to warrant a
1544 // partial download anyway
51818f26 1545 RemoveFile("pkgAcqMetaSig", DestFile);
ac5b205a 1546
448c38bd
DK
1547 // set the TransactionManager
1548 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1549 std::clog << "New pkgAcqMetaSig with TransactionManager "
1550 << TransactionManager << std::endl;
f6d4ab9a 1551
448c38bd 1552 // Create the item
dcbbb14d 1553 Desc.Description = Target.Description;
448c38bd 1554 Desc.Owner = this;
dcbbb14d
DK
1555 Desc.ShortDesc = Target.ShortDesc;
1556 Desc.URI = Target.URI;
ac5b205a 1557
448c38bd
DK
1558 // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
1559 // so we skip the download step and go instantly to verification
1560 if (TransactionManager->IMSHit == true && RealFileExists(GetFinalFilename()))
1561 {
1562 Complete = true;
1563 Status = StatDone;
1564 PartialFile = DestFile = GetFinalFilename();
1565 MetaIndexFileSignature = DestFile;
1566 MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
1567 }
1568 else
1569 QueueURI(Desc);
ac5b205a 1570}
92fcbfc1 1571 /*}}}*/
448c38bd 1572pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
ac5b205a 1573{
b0d40854
DK
1574}
1575 /*}}}*/
1576// pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1577std::string pkgAcqMetaSig::Custom600Headers() const
1578{
1579 std::string Header = pkgAcqTransactionItem::Custom600Headers();
1580 std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
1581 if (key.empty() == false)
1582 Header += "\nSigned-By: " + key;
1583 return Header;
448c38bd
DK
1584}
1585 /*}}}*/
1586// AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1587void pkgAcqMetaSig::Done(string const &Message, HashStringList const &Hashes,
1588 pkgAcquire::MethodConfig const * const Cfg)
1589{
1590 if (MetaIndexFileSignature.empty() == false)
4a0a786f 1591 {
448c38bd
DK
1592 DestFile = MetaIndexFileSignature;
1593 MetaIndexFileSignature.clear();
1594 }
1595 Item::Done(Message, Hashes, Cfg);
f6d4ab9a 1596
448c38bd
DK
1597 if(MetaIndex->AuthPass == false)
1598 {
1599 if(MetaIndex->CheckDownloadDone(this, Message, Hashes) == true)
f6d4ab9a 1600 {
448c38bd
DK
1601 // destfile will be modified to point to MetaIndexFile for the
1602 // gpgv method, so we need to save it here
1603 MetaIndexFileSignature = DestFile;
1604 MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
1605 }
1606 return;
1607 }
1608 else if(MetaIndex->CheckAuthDone(Message) == true)
1609 {
1610 if (TransactionManager->IMSHit == false)
1611 {
1612 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
1613 TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
f6d4ab9a 1614 }
448c38bd
DK
1615 }
1616}
1617 /*}}}*/
1618void pkgAcqMetaSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
1619{
1620 Item::Failed(Message,Cnf);
4a0a786f 1621
448c38bd
DK
1622 // check if we need to fail at this point
1623 if (MetaIndex->AuthPass == true && MetaIndex->CheckStopAuthentication(this, Message))
1624 return;
4a0a786f 1625
448c38bd
DK
1626 string const FinalRelease = MetaIndex->GetFinalFilename();
1627 string const FinalReleasegpg = GetFinalFilename();
1628 string const FinalInRelease = TransactionManager->GetFinalFilename();
4a0a786f 1629
448c38bd
DK
1630 if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
1631 {
1632 std::string downgrade_msg;
1633 strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
dcbbb14d 1634 MetaIndex->Target.Description.c_str());
448c38bd
DK
1635 if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1636 {
1637 // meh, the users wants to take risks (we still mark the packages
1638 // from this repository as unauthenticated)
1639 _error->Warning("%s", downgrade_msg.c_str());
1640 _error->Warning(_("This is normally not allowed, but the option "
1641 "Acquire::AllowDowngradeToInsecureRepositories was "
1642 "given to override it."));
1643 Status = StatDone;
1644 } else {
f18f2338 1645 MessageInsecureRepository(true, downgrade_msg);
448c38bd
DK
1646 if (TransactionManager->IMSHit == false)
1647 Rename(MetaIndex->DestFile, MetaIndex->DestFile + ".FAILED");
1648 Item::Failed("Message: " + downgrade_msg, Cnf);
1649 TransactionManager->AbortTransaction();
1650 return;
1651 }
1652 }
4a0a786f 1653
448c38bd
DK
1654 // ensures that a Release.gpg file in the lists/ is removed by the transaction
1655 TransactionManager->TransactionStageRemoval(this, DestFile);
4a0a786f 1656
448c38bd 1657 // only allow going further if the users explicitely wants it
f18f2338 1658 if (AllowInsecureRepositories(_("The repository '%s' is not signed."), MetaIndex->Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
4a0a786f 1659 {
448c38bd 1660 if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
59a704f0 1661 {
448c38bd
DK
1662 // open the last Release if we have it
1663 if (TransactionManager->IMSHit == false)
1664 {
5ad0096a
DK
1665 TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
1666 if (TransactionManager->LastMetaIndexParser != NULL)
448c38bd 1667 {
5ad0096a
DK
1668 _error->PushToStack();
1669 if (RealFileExists(FinalInRelease))
1670 TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
1671 else
1672 TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
1673 // its unlikely to happen, but if what we have is bad ignore it
1674 if (_error->PendingError())
1675 {
1676 delete TransactionManager->LastMetaIndexParser;
1677 TransactionManager->LastMetaIndexParser = NULL;
1678 }
1679 _error->RevertToStack();
448c38bd 1680 }
448c38bd 1681 }
59a704f0 1682 }
4a0a786f 1683
448c38bd
DK
1684 // we parse the indexes here because at this point the user wanted
1685 // a repository that may potentially harm him
5ad0096a 1686 if (TransactionManager->MetaIndexParser->Load(MetaIndex->DestFile, &ErrorText) == false || MetaIndex->VerifyVendor(Message) == false)
448c38bd
DK
1687 /* expired Release files are still a problem you need extra force for */;
1688 else
1689 MetaIndex->QueueIndexes(true);
1690
1691 TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
1692 }
1693
1694 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1695 if (Cnf->LocalOnly == true ||
1696 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
1697 {
1698 // Ignore this
1699 Status = StatDone;
ac5b205a 1700 }
ac5b205a 1701}
92fcbfc1 1702 /*}}}*/
448c38bd
DK
1703
1704
1705// AcqBaseIndex - Constructor /*{{{*/
1706pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire * const Owner,
3d8232bf 1707 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 1708 IndexTarget const &Target)
6c55f07a 1709: pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL)
448c38bd
DK
1710{
1711}
1712 /*}}}*/
c8a4ce6c 1713pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
448c38bd
DK
1714
1715// AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
1716// ---------------------------------------------------------------------
1717/* Get the DiffIndex file first and see if there are patches available
1718 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
1719 * patches. If anything goes wrong in that process, it will fall back to
1720 * the original packages file
1721 */
1722pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire * const Owner,
3d8232bf 1723 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 1724 IndexTarget const &Target)
3d8232bf 1725 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), diffs(NULL)
47d2bc78 1726{
47d2bc78
DK
1727 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
1728
47d2bc78 1729 Desc.Owner = this;
dcbbb14d
DK
1730 Desc.Description = Target.Description + ".diff/Index";
1731 Desc.ShortDesc = Target.ShortDesc;
1732 Desc.URI = Target.URI + ".diff/Index";
47d2bc78 1733
448c38bd
DK
1734 DestFile = GetPartialFileNameFromURI(Desc.URI);
1735
1736 if(Debug)
1737 std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
5684f71f 1738
47d2bc78
DK
1739 QueueURI(Desc);
1740}
1741 /*}}}*/
448c38bd
DK
1742// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1743// ---------------------------------------------------------------------
1744/* The only header we use is the last-modified header. */
1745string pkgAcqDiffIndex::Custom600Headers() const
47d2bc78 1746{
448c38bd 1747 string const Final = GetFinalFilename();
47d2bc78 1748
448c38bd
DK
1749 if(Debug)
1750 std::clog << "Custom600Header-IMS: " << Final << std::endl;
47d2bc78 1751
448c38bd
DK
1752 struct stat Buf;
1753 if (stat(Final.c_str(),&Buf) != 0)
1754 return "\nIndex-File: true";
1755
1756 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1757}
1758 /*}}}*/
1759void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
1760{
1761 // list cleanup needs to know that this file as well as the already
1762 // present index is ours, so we create an empty diff to save it for us
1763 new pkgAcqIndexDiffs(Owner, TransactionManager, Target);
47d2bc78
DK
1764}
1765 /*}}}*/
448c38bd 1766bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/
47d2bc78 1767{
448c38bd
DK
1768 // failing here is fine: our caller will take care of trying to
1769 // get the complete file if patching fails
47d2bc78 1770 if(Debug)
448c38bd
DK
1771 std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
1772 << std::endl;
f6d4ab9a 1773
448c38bd
DK
1774 FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
1775 pkgTagFile TF(&Fd);
95278287 1776 if (Fd.IsOpen() == false || Fd.Failed())
448c38bd 1777 return false;
47d2bc78 1778
448c38bd
DK
1779 pkgTagSection Tags;
1780 if(unlikely(TF.Step(Tags) == false))
1781 return false;
47d2bc78 1782
448c38bd
DK
1783 HashStringList ServerHashes;
1784 unsigned long long ServerSize = 0;
47d2bc78 1785
448c38bd
DK
1786 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
1787 {
1788 std::string tagname = *type;
1789 tagname.append("-Current");
1790 std::string const tmp = Tags.FindS(tagname.c_str());
1791 if (tmp.empty() == true)
1792 continue;
146f7715 1793
448c38bd
DK
1794 string hash;
1795 unsigned long long size;
1796 std::stringstream ss(tmp);
1797 ss >> hash >> size;
1798 if (unlikely(hash.empty() == true))
1799 continue;
1800 if (unlikely(ServerSize != 0 && ServerSize != size))
1801 continue;
1802 ServerHashes.push_back(HashString(*type, hash));
1803 ServerSize = size;
1804 }
47d2bc78 1805
448c38bd
DK
1806 if (ServerHashes.usable() == false)
1807 {
1808 if (Debug == true)
1809 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
1810 return false;
47d2bc78 1811 }
448c38bd 1812
dcbbb14d
DK
1813 std::string const CurrentPackagesFile = GetFinalFileNameFromURI(Target.URI);
1814 HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
448c38bd 1815 if (TargetFileHashes.usable() == false || ServerHashes != TargetFileHashes)
47d2bc78 1816 {
448c38bd 1817 if (Debug == true)
47d2bc78 1818 {
448c38bd
DK
1819 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
1820 printHashSumComparision(CurrentPackagesFile, ServerHashes, TargetFileHashes);
47d2bc78 1821 }
448c38bd
DK
1822 return false;
1823 }
47d2bc78 1824
9b8c28f4
DK
1825 HashStringList LocalHashes;
1826 // try avoiding calculating the hash here as this is costly
1827 if (TransactionManager->LastMetaIndexParser != NULL)
dcbbb14d 1828 LocalHashes = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target.MetaKey);
9b8c28f4
DK
1829 if (LocalHashes.usable() == false)
1830 {
d7a51997 1831 FileFd fd(CurrentPackagesFile, FileFd::ReadOnly, FileFd::Auto);
9b8c28f4
DK
1832 Hashes LocalHashesCalc(ServerHashes);
1833 LocalHashesCalc.AddFD(fd);
1834 LocalHashes = LocalHashesCalc.GetHashStringList();
1835 }
1836
1837 if (ServerHashes == LocalHashes)
448c38bd
DK
1838 {
1839 // we have the same sha1 as the server so we are done here
47d2bc78 1840 if(Debug)
448c38bd
DK
1841 std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
1842 QueueOnIMSHit();
1843 return true;
1844 }
47d2bc78 1845
448c38bd
DK
1846 if(Debug)
1847 std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
9b8c28f4 1848 << CurrentPackagesFile << " " << LocalHashes.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
34d6ece7 1849
448c38bd
DK
1850 // parse all of (provided) history
1851 vector<DiffInfo> available_patches;
1852 bool firstAcceptedHashes = true;
1853 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
651bddad 1854 {
448c38bd
DK
1855 if (LocalHashes.find(*type) == NULL)
1856 continue;
21638c3a 1857
448c38bd
DK
1858 std::string tagname = *type;
1859 tagname.append("-History");
1860 std::string const tmp = Tags.FindS(tagname.c_str());
1861 if (tmp.empty() == true)
1862 continue;
a64bf0eb 1863
448c38bd
DK
1864 string hash, filename;
1865 unsigned long long size;
1866 std::stringstream ss(tmp);
56472095 1867
448c38bd 1868 while (ss >> hash >> size >> filename)
651bddad 1869 {
448c38bd
DK
1870 if (unlikely(hash.empty() == true || filename.empty() == true))
1871 continue;
1872
1873 // see if we have a record for this file already
1874 std::vector<DiffInfo>::iterator cur = available_patches.begin();
1875 for (; cur != available_patches.end(); ++cur)
1876 {
4f51fd86 1877 if (cur->file != filename)
448c38bd
DK
1878 continue;
1879 cur->result_hashes.push_back(HashString(*type, hash));
1880 break;
1881 }
1882 if (cur != available_patches.end())
1883 continue;
1884 if (firstAcceptedHashes == true)
1885 {
1886 DiffInfo next;
1887 next.file = filename;
1888 next.result_hashes.push_back(HashString(*type, hash));
4f51fd86 1889 next.result_hashes.FileSize(size);
448c38bd
DK
1890 available_patches.push_back(next);
1891 }
1892 else
1893 {
1894 if (Debug == true)
1895 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
1896 << " wasn't in the list for the first parsed hash! (history)" << std::endl;
1897 break;
1898 }
651bddad 1899 }
448c38bd 1900 firstAcceptedHashes = false;
5d885723 1901 }
448c38bd
DK
1902
1903 if (unlikely(available_patches.empty() == true))
5d885723 1904 {
448c38bd
DK
1905 if (Debug)
1906 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
1907 << "Couldn't find any patches for the patch series." << std::endl;
1908 return false;
5d885723 1909 }
8267fe24 1910
448c38bd 1911 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
b11f9599 1912 {
448c38bd
DK
1913 if (LocalHashes.find(*type) == NULL)
1914 continue;
97b65b10 1915
448c38bd
DK
1916 std::string tagname = *type;
1917 tagname.append("-Patches");
1918 std::string const tmp = Tags.FindS(tagname.c_str());
1919 if (tmp.empty() == true)
1920 continue;
18593cf7 1921
448c38bd
DK
1922 string hash, filename;
1923 unsigned long long size;
1924 std::stringstream ss(tmp);
03aa0847 1925
448c38bd 1926 while (ss >> hash >> size >> filename)
58702f85 1927 {
448c38bd
DK
1928 if (unlikely(hash.empty() == true || filename.empty() == true))
1929 continue;
146f7715 1930
448c38bd
DK
1931 // see if we have a record for this file already
1932 std::vector<DiffInfo>::iterator cur = available_patches.begin();
1933 for (; cur != available_patches.end(); ++cur)
146f7715 1934 {
448c38bd
DK
1935 if (cur->file != filename)
1936 continue;
4f51fd86
DK
1937 if (cur->patch_hashes.empty())
1938 cur->patch_hashes.FileSize(size);
448c38bd 1939 cur->patch_hashes.push_back(HashString(*type, hash));
448c38bd 1940 break;
146f7715 1941 }
448c38bd
DK
1942 if (cur != available_patches.end())
1943 continue;
1944 if (Debug == true)
1945 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
1946 << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
146f7715 1947 break;
146f7715
DK
1948 }
1949 }
2d0a7bb4 1950
4f51fd86
DK
1951 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
1952 {
1953 std::string tagname = *type;
1954 tagname.append("-Download");
1955 std::string const tmp = Tags.FindS(tagname.c_str());
1956 if (tmp.empty() == true)
1957 continue;
1958
1959 string hash, filename;
1960 unsigned long long size;
1961 std::stringstream ss(tmp);
1962
1963 // FIXME: all of pdiff supports only .gz compressed patches
1964 while (ss >> hash >> size >> filename)
1965 {
1966 if (unlikely(hash.empty() == true || filename.empty() == true))
1967 continue;
1968 if (unlikely(APT::String::Endswith(filename, ".gz") == false))
1969 continue;
1970 filename.erase(filename.length() - 3);
1971
1972 // see if we have a record for this file already
1973 std::vector<DiffInfo>::iterator cur = available_patches.begin();
1974 for (; cur != available_patches.end(); ++cur)
1975 {
1976 if (cur->file != filename)
1977 continue;
1978 if (cur->download_hashes.empty())
1979 cur->download_hashes.FileSize(size);
1980 cur->download_hashes.push_back(HashString(*type, hash));
1981 break;
1982 }
1983 if (cur != available_patches.end())
1984 continue;
1985 if (Debug == true)
1986 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
1987 << " wasn't in the list for the first parsed hash! (download)" << std::endl;
1988 break;
1989 }
1990 }
1991
1992
448c38bd
DK
1993 bool foundStart = false;
1994 for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
1995 cur != available_patches.end(); ++cur)
1996 {
1997 if (LocalHashes != cur->result_hashes)
1998 continue;
1999
2000 available_patches.erase(available_patches.begin(), cur);
2001 foundStart = true;
2002 break;
e6e89390 2003 }
b3d44315 2004
448c38bd
DK
2005 if (foundStart == false || unlikely(available_patches.empty() == true))
2006 {
2007 if (Debug)
2008 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
2009 << "Couldn't find the start of the patch series." << std::endl;
2010 return false;
2011 }
f6237efd 2012
448c38bd
DK
2013 // patching with too many files is rather slow compared to a fast download
2014 unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
2015 if (fileLimit != 0 && fileLimit < available_patches.size())
2016 {
2017 if (Debug)
2018 std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
2019 << ") so fallback to complete download" << std::endl;
2020 return false;
2021 }
1f4dd8fd 2022
448c38bd
DK
2023 // calculate the size of all patches we have to get
2024 // note that all sizes are uncompressed, while we download compressed files
2025 unsigned long long patchesSize = 0;
2026 for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
2027 cur != available_patches.end(); ++cur)
4f51fd86 2028 patchesSize += cur->patch_hashes.FileSize();
448c38bd
DK
2029 unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
2030 if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
2031 {
2032 if (Debug)
2033 std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
2034 << ") so fallback to complete download" << std::endl;
2035 return false;
2036 }
2737f28a 2037
448c38bd
DK
2038 // we have something, queue the diffs
2039 string::size_type const last_space = Description.rfind(" ");
2040 if(last_space != string::npos)
2041 Description.erase(last_space, Description.size()-last_space);
2042
2043 /* decide if we should download patches one by one or in one go:
2044 The first is good if the server merges patches, but many don't so client
2045 based merging can be attempt in which case the second is better.
2046 "bad things" will happen if patches are merged on the server,
2047 but client side merging is attempt as well */
2048 bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
2049 if (pdiff_merge == true)
6bf93605 2050 {
448c38bd
DK
2051 // reprepro adds this flag if it has merged patches on the server
2052 std::string const precedence = Tags.FindS("X-Patch-Precedence");
2053 pdiff_merge = (precedence != "merged");
6bf93605 2054 }
448c38bd
DK
2055
2056 if (pdiff_merge == false)
2057 new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
6bf93605 2058 else
448c38bd 2059 {
3d8232bf 2060 diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
448c38bd
DK
2061 for(size_t i = 0; i < available_patches.size(); ++i)
2062 (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
2063 Target,
2064 available_patches[i],
2065 diffs);
2066 }
2067
2068 Complete = false;
2069 Status = StatDone;
2070 Dequeue();
2071 return true;
6bf93605
DK
2072}
2073 /*}}}*/
448c38bd 2074void pkgAcqDiffIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
6bf93605 2075{
448c38bd
DK
2076 Item::Failed(Message,Cnf);
2077 Status = StatDone;
2078
2079 if(Debug)
2080 std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
2081 << "Falling back to normal index file acquire" << std::endl;
2082
2083 new pkgAcqIndex(Owner, TransactionManager, Target);
0118833a 2084}
61aea84d 2085 /*}}}*/
448c38bd
DK
2086void pkgAcqDiffIndex::Done(string const &Message,HashStringList const &Hashes, /*{{{*/
2087 pkgAcquire::MethodConfig const * const Cnf)
c88edf1d 2088{
448c38bd
DK
2089 if(Debug)
2090 std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
c88edf1d 2091
448c38bd
DK
2092 Item::Done(Message, Hashes, Cnf);
2093
2094 string const FinalFile = GetFinalFilename();
2095 if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
2096 DestFile = FinalFile;
2097
2098 if(ParseDiffIndex(DestFile) == false)
c88edf1d 2099 {
448c38bd
DK
2100 Failed("Message: Couldn't parse pdiff index", Cnf);
2101 // queue for final move - this should happen even if we fail
2102 // while parsing (e.g. on sizelimit) and download the complete file.
2103 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
2737f28a
MV
2104 return;
2105 }
448c38bd
DK
2106
2107 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
2108
2109 Complete = true;
2110 Status = StatDone;
2111 Dequeue();
2112
2113 return;
c88edf1d
AL
2114}
2115 /*}}}*/
3d8232bf
DK
2116pkgAcqDiffIndex::~pkgAcqDiffIndex()
2117{
2118 if (diffs != NULL)
2119 delete diffs;
2120}
448c38bd
DK
2121
2122// AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
2123// ---------------------------------------------------------------------
2124/* The package diff is added to the queue. one object is constructed
2125 * for each diff and the index
2126 */
2127pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire * const Owner,
3d8232bf 2128 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 2129 IndexTarget const &Target,
448c38bd 2130 vector<DiffInfo> const &diffs)
6c55f07a 2131 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
448c38bd 2132 available_patches(diffs)
681d76d0 2133{
d7a51997 2134 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
e8b1db38 2135
448c38bd 2136 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
e8b1db38 2137
448c38bd 2138 Desc.Owner = this;
dcbbb14d
DK
2139 Description = Target.Description;
2140 Desc.ShortDesc = Target.ShortDesc;
631a7dc7 2141
448c38bd 2142 if(available_patches.empty() == true)
631a7dc7 2143 {
448c38bd 2144 // we are done (yeah!), check hashes against the final file
d7a51997 2145 DestFile = GetKeepCompressedFileName(GetFinalFileNameFromURI(Target.URI), Target);
448c38bd 2146 Finish(true);
631a7dc7 2147 }
9d653a6d 2148 else
631a7dc7 2149 {
d7a51997 2150 if (BootstrapPDiffWith(GetPartialFileNameFromURI(Target.URI), GetFinalFilename(), Target) == false)
6bf93605 2151 {
d7a51997
DK
2152 Failed("Bootstrapping of " + DestFile + " failed", NULL);
2153 return;
6bf93605
DK
2154 }
2155
448c38bd
DK
2156 // get the next diff
2157 State = StateFetchDiff;
2158 QueueNextDiff();
631a7dc7 2159 }
448c38bd
DK
2160}
2161 /*}}}*/
2162void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
2163{
2164 Item::Failed(Message,Cnf);
2165 Status = StatDone;
631a7dc7 2166
d7a51997 2167 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
448c38bd
DK
2168 if(Debug)
2169 std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
d7a51997 2170 << "Falling back to normal index file acquire " << std::endl;
448c38bd 2171 RenameOnError(PDiffError);
36795154
DK
2172 std::string const patchname = GetDiffsPatchFileName(DestFile);
2173 if (RealFileExists(patchname))
2174 rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
448c38bd
DK
2175 new pkgAcqIndex(Owner, TransactionManager, Target);
2176 Finish();
2177}
2178 /*}}}*/
2179// Finish - helper that cleans the item out of the fetcher queue /*{{{*/
2180void pkgAcqIndexDiffs::Finish(bool allDone)
2181{
2182 if(Debug)
2183 std::clog << "pkgAcqIndexDiffs::Finish(): "
2184 << allDone << " "
2185 << Desc.URI << std::endl;
2186
2187 // we restore the original name, this is required, otherwise
2188 // the file will be cleaned
2189 if(allDone)
4dbfe436 2190 {
d7a51997
DK
2191 std::string Final = GetFinalFilename();
2192 if (Target.KeepCompressed)
2193 {
2194 std::string const ext = flExtension(DestFile);
2195 if (ext.empty() == false)
2196 Final.append(".").append(ext);
2197 }
2198 TransactionManager->TransactionStageCopy(this, DestFile, Final);
448c38bd
DK
2199
2200 // this is for the "real" finish
2201 Complete = true;
e05672e8 2202 Status = StatDone;
448c38bd
DK
2203 Dequeue();
2204 if(Debug)
2205 std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
2206 return;
e05672e8 2207 }
d7a51997
DK
2208 else
2209 DestFile.clear();
448c38bd
DK
2210
2211 if(Debug)
2212 std::clog << "Finishing: " << Desc.URI << std::endl;
2213 Complete = false;
2214 Status = StatDone;
2215 Dequeue();
2216 return;
681d76d0 2217}
92fcbfc1 2218 /*}}}*/
448c38bd 2219bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
b3d44315 2220{
448c38bd 2221 // calc sha1 of the just patched file
d7a51997 2222 std::string const FinalFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
448c38bd 2223 if(!FileExists(FinalFile))
715c65de 2224 {
448c38bd
DK
2225 Failed("Message: No FinalFile " + FinalFile + " available", NULL);
2226 return false;
715c65de 2227 }
e05672e8 2228
d7a51997 2229 FileFd fd(FinalFile, FileFd::ReadOnly, FileFd::Extension);
448c38bd
DK
2230 Hashes LocalHashesCalc;
2231 LocalHashesCalc.AddFD(fd);
2232 HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
b3d44315 2233
448c38bd
DK
2234 if(Debug)
2235 std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
b3d44315 2236
dcbbb14d 2237 HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
448c38bd 2238 if (unlikely(LocalHashes.usable() == false || TargetFileHashes.usable() == false))
b3d44315 2239 {
448c38bd
DK
2240 Failed("Local/Expected hashes are not usable", NULL);
2241 return false;
b3d44315 2242 }
b3d44315 2243
448c38bd
DK
2244
2245 // final file reached before all patches are applied
2246 if(LocalHashes == TargetFileHashes)
6bf93605 2247 {
448c38bd
DK
2248 Finish(true);
2249 return true;
6bf93605
DK
2250 }
2251
448c38bd
DK
2252 // remove all patches until the next matching patch is found
2253 // this requires the Index file to be ordered
2254 for(vector<DiffInfo>::iterator I = available_patches.begin();
2255 available_patches.empty() == false &&
2256 I != available_patches.end() &&
2257 I->result_hashes != LocalHashes;
2258 ++I)
f3097647 2259 {
448c38bd 2260 available_patches.erase(I);
b3d44315 2261 }
56bc3358 2262
448c38bd
DK
2263 // error checking and falling back if no patch was found
2264 if(available_patches.empty() == true)
56bc3358 2265 {
448c38bd 2266 Failed("No patches left to reach target", NULL);
f3097647 2267 return false;
56bc3358 2268 }
f3097647 2269
448c38bd 2270 // queue the right diff
dcbbb14d 2271 Desc.URI = Target.URI + ".diff/" + available_patches[0].file + ".gz";
448c38bd 2272 Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
d7a51997 2273 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI + ".diff/" + available_patches[0].file), Target);
f3097647 2274
448c38bd
DK
2275 if(Debug)
2276 std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
2277
2278 QueueURI(Desc);
f3097647
MV
2279
2280 return true;
2281}
2282 /*}}}*/
448c38bd
DK
2283void pkgAcqIndexDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
2284 pkgAcquire::MethodConfig const * const Cnf)
27e6c17a 2285{
448c38bd
DK
2286 if(Debug)
2287 std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
27e6c17a 2288
448c38bd 2289 Item::Done(Message, Hashes, Cnf);
27e6c17a 2290
d7a51997 2291 std::string const FinalFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
36795154 2292 std::string const PatchFile = GetDiffsPatchFileName(FinalFile);
b3d44315 2293
448c38bd
DK
2294 // success in downloading a diff, enter ApplyDiff state
2295 if(State == StateFetchDiff)
b3d44315 2296 {
36795154 2297 Rename(DestFile, PatchFile);
448c38bd
DK
2298
2299 if(Debug)
2300 std::clog << "Sending to rred method: " << FinalFile << std::endl;
2301
2302 State = StateApplyDiff;
2303 Local = true;
2304 Desc.URI = "rred:" + FinalFile;
2305 QueueURI(Desc);
2306 SetActiveSubprocess("rred");
2307 return;
36795154 2308 }
448c38bd
DK
2309
2310 // success in download/apply a diff, queue next (if needed)
2311 if(State == StateApplyDiff)
8eafc759 2312 {
448c38bd
DK
2313 // remove the just applied patch
2314 available_patches.erase(available_patches.begin());
51818f26 2315 RemoveFile("pkgAcqIndexDiffs::Done", PatchFile);
448c38bd
DK
2316
2317 // move into place
36795154 2318 if(Debug)
8eafc759 2319 {
448c38bd
DK
2320 std::clog << "Moving patched file in place: " << std::endl
2321 << DestFile << " -> " << FinalFile << std::endl;
8eafc759 2322 }
448c38bd
DK
2323 Rename(DestFile,FinalFile);
2324 chmod(FinalFile.c_str(),0644);
8eafc759 2325
448c38bd
DK
2326 // see if there is more to download
2327 if(available_patches.empty() == false) {
2328 new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
2329 available_patches);
2330 return Finish();
2331 } else
2332 // update
2333 DestFile = FinalFile;
2334 return Finish(true);
ba6b79bd 2335 }
448c38bd
DK
2336}
2337 /*}}}*/
36795154
DK
2338std::string pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
2339{
2340 if(State != StateApplyDiff)
2341 return pkgAcqBaseIndex::Custom600Headers();
2342 std::ostringstream patchhashes;
2343 HashStringList const ExpectedHashes = available_patches[0].patch_hashes;
2344 for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
2345 patchhashes << "\nPatch-0-" << hs->HashType() << "-Hash: " << hs->HashValue();
2346 patchhashes << pkgAcqBaseIndex::Custom600Headers();
2347 return patchhashes.str();
2348}
2349 /*}}}*/
c8a4ce6c 2350pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
448c38bd
DK
2351
2352// AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
2353pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire * const Owner,
3d8232bf 2354 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 2355 IndexTarget const &Target,
448c38bd
DK
2356 DiffInfo const &patch,
2357 std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
6c55f07a 2358 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
448c38bd
DK
2359 patch(patch), allPatches(allPatches), State(StateFetchDiff)
2360{
2361 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
2362
2363 Desc.Owner = this;
dcbbb14d
DK
2364 Description = Target.Description;
2365 Desc.ShortDesc = Target.ShortDesc;
448c38bd 2366
dcbbb14d 2367 Desc.URI = Target.URI + ".diff/" + patch.file + ".gz";
448c38bd
DK
2368 Desc.Description = Description + " " + patch.file + string(".pdiff");
2369
d7a51997 2370 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI + ".diff/" + patch.file), Target);
448c38bd
DK
2371
2372 if(Debug)
2373 std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
2374
2375 QueueURI(Desc);
2376}
2377 /*}}}*/
2378void pkgAcqIndexMergeDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
2379{
2380 if(Debug)
2381 std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
2737f28a 2382
448c38bd
DK
2383 Item::Failed(Message,Cnf);
2384 Status = StatDone;
b3d44315 2385
448c38bd
DK
2386 // check if we are the first to fail, otherwise we are done here
2387 State = StateDoneDiff;
2388 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2389 I != allPatches->end(); ++I)
2390 if ((*I)->State == StateErrorDiff)
2391 return;
2392
2393 // first failure means we should fallback
2394 State = StateErrorDiff;
2395 if (Debug)
2396 std::clog << "Falling back to normal index file acquire" << std::endl;
d7a51997 2397 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
448c38bd 2398 RenameOnError(PDiffError);
36795154
DK
2399 std::string const patchname = GetMergeDiffsPatchFileName(DestFile, patch.file);
2400 if (RealFileExists(patchname))
2401 rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
448c38bd 2402 new pkgAcqIndex(Owner, TransactionManager, Target);
d7a51997 2403 DestFile.clear();
b3d44315 2404}
92fcbfc1 2405 /*}}}*/
448c38bd
DK
2406void pkgAcqIndexMergeDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
2407 pkgAcquire::MethodConfig const * const Cnf)
b3d44315 2408{
448c38bd
DK
2409 if(Debug)
2410 std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
18593cf7 2411
448c38bd 2412 Item::Done(Message, Hashes, Cnf);
18593cf7 2413
d7a51997
DK
2414 std::string const UncompressedFinalFile = GetPartialFileNameFromURI(Target.URI);
2415 std::string const FinalFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
448c38bd
DK
2416 if (State == StateFetchDiff)
2417 {
36795154 2418 Rename(DestFile, GetMergeDiffsPatchFileName(FinalFile, patch.file));
448c38bd
DK
2419
2420 // check if this is the last completed diff
2421 State = StateDoneDiff;
2422 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2423 I != allPatches->end(); ++I)
2424 if ((*I)->State != StateDoneDiff)
2425 {
2426 if(Debug)
2427 std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
2428 return;
2429 }
2430
2431 // this is the last completed diff, so we are ready to apply now
2432 State = StateApplyDiff;
ab53c018 2433
d7a51997 2434 if (BootstrapPDiffWith(UncompressedFinalFile, GetFinalFilename(), Target) == false)
448c38bd 2435 {
d7a51997 2436 Failed("Bootstrapping of " + DestFile + " failed", NULL);
448c38bd 2437 return;
18593cf7 2438 }
448c38bd
DK
2439
2440 if(Debug)
2441 std::clog << "Sending to rred method: " << FinalFile << std::endl;
2442
2443 Local = true;
2444 Desc.URI = "rred:" + FinalFile;
2445 QueueURI(Desc);
2446 SetActiveSubprocess("rred");
2447 return;
2448 }
2449 // success in download/apply all diffs, clean up
2450 else if (State == StateApplyDiff)
2451 {
2452 // move the result into place
d7a51997 2453 std::string const Final = GetKeepCompressedFileName(GetFinalFilename(), Target);
448c38bd
DK
2454 if(Debug)
2455 std::clog << "Queue patched file in place: " << std::endl
2456 << DestFile << " -> " << Final << std::endl;
2457
2458 // queue for copy by the transaction manager
2459 TransactionManager->TransactionStageCopy(this, DestFile, Final);
2460
2461 // ensure the ed's are gone regardless of list-cleanup
2462 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2463 I != allPatches->end(); ++I)
ab53c018 2464 {
d7a51997 2465 std::string const PartialFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
36795154 2466 std::string const patch = GetMergeDiffsPatchFileName(PartialFile, (*I)->patch.file);
51818f26 2467 RemoveFile("pkgAcqIndexMergeDiffs::Done", patch);
b3d44315 2468 }
51818f26 2469 RemoveFile("pkgAcqIndexMergeDiffs::Done", FinalFile);
e1430400 2470
448c38bd
DK
2471 // all set and done
2472 Complete = true;
2473 if(Debug)
2474 std::clog << "allDone: " << DestFile << "\n" << std::endl;
b3d44315
MV
2475 }
2476}
92fcbfc1 2477 /*}}}*/
36795154
DK
2478std::string pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
2479{
2480 if(State != StateApplyDiff)
2481 return pkgAcqBaseIndex::Custom600Headers();
2482 std::ostringstream patchhashes;
2483 unsigned int seen_patches = 0;
2484 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2485 I != allPatches->end(); ++I)
2486 {
2487 HashStringList const ExpectedHashes = (*I)->patch.patch_hashes;
2488 for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
2489 patchhashes << "\nPatch-" << seen_patches << "-" << hs->HashType() << "-Hash: " << hs->HashValue();
2490 ++seen_patches;
2491 }
2492 patchhashes << pkgAcqBaseIndex::Custom600Headers();
2493 return patchhashes.str();
2494}
2495 /*}}}*/
c8a4ce6c 2496pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
448c38bd
DK
2497
2498// AcqIndex::AcqIndex - Constructor /*{{{*/
2499pkgAcqIndex::pkgAcqIndex(pkgAcquire * const Owner,
3d8232bf 2500 pkgAcqMetaClearSig * const TransactionManager,
e8afd168 2501 IndexTarget const &Target)
d7a51997
DK
2502 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), Stage(STAGE_DOWNLOAD),
2503 CompressionExtensions(Target.Option(IndexTarget::COMPRESSIONTYPES))
b3d44315 2504{
dcbbb14d 2505 Init(Target.URI, Target.Description, Target.ShortDesc);
ce424cd4 2506
448c38bd
DK
2507 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
2508 std::clog << "New pkgIndex with TransactionManager "
2509 << TransactionManager << std::endl;
2510}
2511 /*}}}*/
448c38bd 2512// AcqIndex::Init - defered Constructor /*{{{*/
af81ab90 2513static void NextCompressionExtension(std::string &CurrentCompressionExtension, std::string &CompressionExtensions, bool const preview)
448c38bd 2514{
448c38bd
DK
2515 size_t const nextExt = CompressionExtensions.find(' ');
2516 if (nextExt == std::string::npos)
b3d44315 2517 {
448c38bd 2518 CurrentCompressionExtension = CompressionExtensions;
af81ab90
DK
2519 if (preview == false)
2520 CompressionExtensions.clear();
b3d44315 2521 }
448c38bd
DK
2522 else
2523 {
2524 CurrentCompressionExtension = CompressionExtensions.substr(0, nextExt);
af81ab90
DK
2525 if (preview == false)
2526 CompressionExtensions = CompressionExtensions.substr(nextExt+1);
1ddb8596 2527 }
af81ab90
DK
2528}
2529void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
2530 string const &ShortDesc)
2531{
2532 Stage = STAGE_DOWNLOAD;
2533
2534 DestFile = GetPartialFileNameFromURI(URI);
2535 NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, false);
1ddb8596 2536
448c38bd 2537 if (CurrentCompressionExtension == "uncompressed")
6bf93605 2538 {
448c38bd 2539 Desc.URI = URI;
6bf93605 2540 }
af81ab90
DK
2541 else if (CurrentCompressionExtension == "by-hash")
2542 {
2543 NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, true);
2544 if(unlikely(TransactionManager->MetaIndexParser == NULL || CurrentCompressionExtension.empty()))
2545 return;
2546 if (CurrentCompressionExtension != "uncompressed")
2547 {
2548 Desc.URI = URI + '.' + CurrentCompressionExtension;
2549 DestFile = DestFile + '.' + CurrentCompressionExtension;
2550 }
2551
2552 HashStringList const Hashes = GetExpectedHashes();
2553 HashString const * const TargetHash = Hashes.find(NULL);
2554 if (unlikely(TargetHash == nullptr))
2555 return;
2556 std::string const ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
2557 size_t const trailing_slash = Desc.URI.find_last_of("/");
2558 if (unlikely(trailing_slash == std::string::npos))
2559 return;
2560 Desc.URI = Desc.URI.replace(
2561 trailing_slash,
2562 Desc.URI.substr(trailing_slash+1).size()+1,
2563 ByHash);
2564 }
448c38bd
DK
2565 else if (unlikely(CurrentCompressionExtension.empty()))
2566 return;
2567 else
b3d44315 2568 {
448c38bd
DK
2569 Desc.URI = URI + '.' + CurrentCompressionExtension;
2570 DestFile = DestFile + '.' + CurrentCompressionExtension;
b3d44315
MV
2571 }
2572
448c38bd
DK
2573
2574 Desc.Description = URIDesc;
2575 Desc.Owner = this;
2576 Desc.ShortDesc = ShortDesc;
2577
2578 QueueURI(Desc);
2579}
2580 /*}}}*/
448c38bd
DK
2581// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2582// ---------------------------------------------------------------------
2583/* The only header we use is the last-modified header. */
2584string pkgAcqIndex::Custom600Headers() const
b3d44315 2585{
448c38bd 2586 string Final = GetFinalFilename();
c5fced38 2587
448c38bd
DK
2588 string msg = "\nIndex-File: true";
2589 struct stat Buf;
2590 if (stat(Final.c_str(),&Buf) == 0)
2591 msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1d970e6c 2592
dcbbb14d 2593 if(Target.IsOptional)
448c38bd
DK
2594 msg += "\nFail-Ignore: true";
2595
2596 return msg;
b3d44315 2597}
681d76d0 2598 /*}}}*/
448c38bd
DK
2599// AcqIndex::Failed - getting the indexfile failed /*{{{*/
2600void pkgAcqIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
56472095 2601{
448c38bd
DK
2602 Item::Failed(Message,Cnf);
2603
2604 // authorisation matches will not be fixed by other compression types
2605 if (Status != StatAuthError)
2606 {
2607 if (CompressionExtensions.empty() == false)
2608 {
dcbbb14d 2609 Init(Target.URI, Desc.Description, Desc.ShortDesc);
448c38bd
DK
2610 Status = StatIdle;
2611 return;
2612 }
2613 }
2614
dcbbb14d 2615 if(Target.IsOptional && GetExpectedHashes().empty() && Stage == STAGE_DOWNLOAD)
448c38bd
DK
2616 Status = StatDone;
2617 else
2618 TransactionManager->AbortTransaction();
56472095 2619}
8267fbd9 2620 /*}}}*/
448c38bd
DK
2621// AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
2622void pkgAcqIndex::ReverifyAfterIMS()
fe0f7911 2623{
448c38bd
DK
2624 // update destfile to *not* include the compression extension when doing
2625 // a reverify (as its uncompressed on disk already)
653ef26c 2626 DestFile = GetCompressedFileName(Target, GetPartialFileNameFromURI(Target.URI), CurrentCompressionExtension);
448c38bd
DK
2627
2628 // copy FinalFile into partial/ so that we check the hash again
2629 string FinalFile = GetFinalFilename();
2630 Stage = STAGE_DECOMPRESS_AND_VERIFY;
2631 Desc.URI = "copy:" + FinalFile;
2632 QueueURI(Desc);
fe0f7911
DK
2633}
2634 /*}}}*/
448c38bd
DK
2635// AcqIndex::Done - Finished a fetch /*{{{*/
2636// ---------------------------------------------------------------------
2637/* This goes through a number of states.. On the initial fetch the
2638 method could possibly return an alternate filename which points
2639 to the uncompressed version of the file. If this is so the file
2640 is copied into the partial directory. In all other cases the file
2641 is decompressed with a compressed uri. */
2642void pkgAcqIndex::Done(string const &Message,
2643 HashStringList const &Hashes,
2644 pkgAcquire::MethodConfig const * const Cfg)
8d6c5839 2645{
448c38bd
DK
2646 Item::Done(Message,Hashes,Cfg);
2647
2648 switch(Stage)
2649 {
2650 case STAGE_DOWNLOAD:
2651 StageDownloadDone(Message, Hashes, Cfg);
2652 break;
2653 case STAGE_DECOMPRESS_AND_VERIFY:
2654 StageDecompressDone(Message, Hashes, Cfg);
2655 break;
2656 }
8d6c5839
MV
2657}
2658 /*}}}*/
448c38bd
DK
2659// AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
2660void pkgAcqIndex::StageDownloadDone(string const &Message, HashStringList const &,
2661 pkgAcquire::MethodConfig const * const)
6bf93605 2662{
448c38bd 2663 Complete = true;
6bf93605 2664
448c38bd 2665 // Handle the unzipd case
dd676dc7 2666 std::string FileName = LookupTag(Message,"Alt-Filename");
448c38bd 2667 if (FileName.empty() == false)
6bf93605 2668 {
448c38bd
DK
2669 Stage = STAGE_DECOMPRESS_AND_VERIFY;
2670 Local = true;
2671 DestFile += ".decomp";
2672 Desc.URI = "copy:" + FileName;
2673 QueueURI(Desc);
2674 SetActiveSubprocess("copy");
2675 return;
6bf93605 2676 }
448c38bd 2677 FileName = LookupTag(Message,"Filename");
f3097647 2678
448c38bd
DK
2679 // Methods like e.g. "file:" will give us a (compressed) FileName that is
2680 // not the "DestFile" we set, in this case we uncompress from the local file
08ea7806 2681 if (FileName != DestFile && RealFileExists(DestFile) == false)
af9e40c9 2682 {
448c38bd 2683 Local = true;
af9e40c9
DK
2684 if (Target.KeepCompressed == true)
2685 {
2686 // but if we don't keep the uncompress we copy the compressed file first
2687 Stage = STAGE_DOWNLOAD;
2688 Desc.URI = "copy:" + FileName;
2689 QueueURI(Desc);
2690 SetActiveSubprocess("copy");
2691 return;
2692 }
2693 }
448c38bd
DK
2694 else
2695 EraseFileName = FileName;
2696
2697 // we need to verify the file against the current Release file again
2698 // on if-modfied-since hit to avoid a stale attack against us
2699 if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
f3097647 2700 {
448c38bd
DK
2701 // The files timestamp matches, reverify by copy into partial/
2702 EraseFileName = "";
2703 ReverifyAfterIMS();
f3097647
MV
2704 return;
2705 }
448c38bd 2706
448c38bd
DK
2707 // get the binary name for your used compression type
2708 string decompProg;
2709 if(CurrentCompressionExtension == "uncompressed")
2710 decompProg = "copy";
2711 else
2712 decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
2713 if(decompProg.empty() == true)
2714 {
2715 _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
2716 return;
6bf93605 2717 }
448c38bd 2718
af9e40c9
DK
2719 if (Target.KeepCompressed == true)
2720 {
2721 DestFile = "/dev/null";
2722 EraseFileName.clear();
2723 }
2724 else
2725 DestFile += ".decomp";
2726
448c38bd
DK
2727 // queue uri for the next stage
2728 Stage = STAGE_DECOMPRESS_AND_VERIFY;
448c38bd
DK
2729 Desc.URI = decompProg + ":" + FileName;
2730 QueueURI(Desc);
2731 SetActiveSubprocess(decompProg);
a9bb651a
MV
2732}
2733 /*}}}*/
448c38bd 2734// AcqIndex::StageDecompressDone - Final verification /*{{{*/
4cd86fc6 2735void pkgAcqIndex::StageDecompressDone(string const &,
448c38bd 2736 HashStringList const &,
4cd86fc6 2737 pkgAcquire::MethodConfig const * const)
a9bb651a 2738{
af9e40c9
DK
2739 if (Target.KeepCompressed == true && DestFile == "/dev/null")
2740 DestFile = GetPartialFileNameFromURI(Target.URI + '.' + CurrentCompressionExtension);
2741
448c38bd
DK
2742 // Done, queue for rename on transaction finished
2743 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
448c38bd 2744 return;
fe0f7911
DK
2745}
2746 /*}}}*/
c8a4ce6c 2747pkgAcqIndex::~pkgAcqIndex() {}
448c38bd
DK
2748
2749
03e39e59
AL
2750// AcqArchive::AcqArchive - Constructor /*{{{*/
2751// ---------------------------------------------------------------------
17caf1b1
AL
2752/* This just sets up the initial fetch environment and queues the first
2753 possibilitiy */
448c38bd
DK
2754pkgAcqArchive::pkgAcqArchive(pkgAcquire * const Owner,pkgSourceList * const Sources,
2755 pkgRecords * const Recs,pkgCache::VerIterator const &Version,
30e1eab5 2756 string &StoreFilename) :
6c55f07a 2757 Item(Owner), d(NULL), LocalSource(false), Version(Version), Sources(Sources), Recs(Recs),
448c38bd 2758 StoreFilename(StoreFilename), Vf(Version.FileList()),
b3d44315 2759 Trusted(false)
03e39e59 2760{
7d8afa39 2761 Retries = _config->FindI("Acquire::Retries",0);
813c8eea
AL
2762
2763 if (Version.Arch() == 0)
bdae53f1 2764 {
d1f1f6a8 2765 _error->Error(_("I wasn't able to locate a file for the %s package. "
7a3c2ab0
AL
2766 "This might mean you need to manually fix this package. "
2767 "(due to missing arch)"),
40f8a8ba 2768 Version.ParentPkg().FullName().c_str());
bdae53f1
AL
2769 return;
2770 }
813c8eea 2771
b2e465d6
AL
2772 /* We need to find a filename to determine the extension. We make the
2773 assumption here that all the available sources for this version share
2774 the same extension.. */
2775 // Skip not source sources, they do not have file fields.
69c2ecbd 2776 for (; Vf.end() == false; ++Vf)
b2e465d6 2777 {
b07aeb1a 2778 if (Vf.File().Flagged(pkgCache::Flag::NotSource))
b2e465d6
AL
2779 continue;
2780 break;
2781 }
2782
2783 // Does not really matter here.. we are going to fail out below
2784 if (Vf.end() != true)
2785 {
2786 // If this fails to get a file name we will bomb out below.
2787 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2788 if (_error->PendingError() == true)
2789 return;
2790
2791 // Generate the final file name as: package_version_arch.foo
2792 StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
2793 QuoteString(Version.VerStr(),"_:") + '_' +
2794 QuoteString(Version.Arch(),"_:.") +
2795 "." + flExtension(Parse.FileName());
2796 }
b3d44315
MV
2797
2798 // check if we have one trusted source for the package. if so, switch
6c34ccca
DK
2799 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2800 bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
2801 bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
2802 bool seenUntrusted = false;
f7f0d6c7 2803 for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
b3d44315
MV
2804 {
2805 pkgIndexFile *Index;
2806 if (Sources->FindIndex(i.File(),Index) == false)
2807 continue;
6c34ccca
DK
2808
2809 if (debugAuth == true)
b3d44315 2810 std::cerr << "Checking index: " << Index->Describe()
6c34ccca
DK
2811 << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
2812
2813 if (Index->IsTrusted() == true)
2814 {
b3d44315 2815 Trusted = true;
6c34ccca
DK
2816 if (allowUnauth == false)
2817 break;
b3d44315 2818 }
6c34ccca
DK
2819 else
2820 seenUntrusted = true;
b3d44315
MV
2821 }
2822
a3371852
MV
2823 // "allow-unauthenticated" restores apts old fetching behaviour
2824 // that means that e.g. unauthenticated file:// uris are higher
2825 // priority than authenticated http:// uris
6c34ccca 2826 if (allowUnauth == true && seenUntrusted == true)
a3371852
MV
2827 Trusted = false;
2828
03e39e59 2829 // Select a source
b185acc2 2830 if (QueueNext() == false && _error->PendingError() == false)
d57f6084
DK
2831 _error->Error(_("Can't find a source to download version '%s' of '%s'"),
2832 Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
b185acc2
AL
2833}
2834 /*}}}*/
2835// AcqArchive::QueueNext - Queue the next file source /*{{{*/
2836// ---------------------------------------------------------------------
17caf1b1
AL
2837/* This queues the next available file version for download. It checks if
2838 the archive is already available in the cache and stashs the MD5 for
2839 checking later. */
b185acc2 2840bool pkgAcqArchive::QueueNext()
a722b2c5 2841{
f7f0d6c7 2842 for (; Vf.end() == false; ++Vf)
03e39e59 2843 {
448c38bd 2844 pkgCache::PkgFileIterator const PkgF = Vf.File();
03e39e59 2845 // Ignore not source sources
b07aeb1a 2846 if (PkgF.Flagged(pkgCache::Flag::NotSource))
03e39e59
AL
2847 continue;
2848
2849 // Try to cross match against the source list
b2e465d6 2850 pkgIndexFile *Index;
448c38bd 2851 if (Sources->FindIndex(PkgF, Index) == false)
b2e465d6 2852 continue;
b07aeb1a 2853 LocalSource = PkgF.Flagged(pkgCache::Flag::LocalSource);
448c38bd 2854
b3d44315
MV
2855 // only try to get a trusted package from another source if that source
2856 // is also trusted
2857 if(Trusted && !Index->IsTrusted())
2858 continue;
2859
03e39e59
AL
2860 // Grab the text package record
2861 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2862 if (_error->PendingError() == true)
b185acc2 2863 return false;
b3501edb 2864
b2e465d6 2865 string PkgFile = Parse.FileName();
b3501edb
DK
2866 ExpectedHashes = Parse.Hashes();
2867
03e39e59 2868 if (PkgFile.empty() == true)
b2e465d6
AL
2869 return _error->Error(_("The package index files are corrupted. No Filename: "
2870 "field for package %s."),
2871 Version.ParentPkg().Name());
a6568219 2872
b3d44315
MV
2873 Desc.URI = Index->ArchiveURI(PkgFile);
2874 Desc.Description = Index->ArchiveInfo(Version);
2875 Desc.Owner = this;
40f8a8ba 2876 Desc.ShortDesc = Version.ParentPkg().FullName(true);
b3d44315 2877
17caf1b1 2878 // See if we already have the file. (Legacy filenames)
a6568219
AL
2879 FileSize = Version->Size;
2880 string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
2881 struct stat Buf;
2882 if (stat(FinalFile.c_str(),&Buf) == 0)
2883 {
2884 // Make sure the size matches
73da43e9 2885 if ((unsigned long long)Buf.st_size == Version->Size)
a6568219
AL
2886 {
2887 Complete = true;
2888 Local = true;
2889 Status = StatDone;
30e1eab5 2890 StoreFilename = DestFile = FinalFile;
b185acc2 2891 return true;
a6568219
AL
2892 }
2893
6b1ff003
AL
2894 /* Hmm, we have a file and its size does not match, this means it is
2895 an old style mismatched arch */
51818f26 2896 RemoveFile("pkgAcqArchive::QueueNext", FinalFile);
a6568219 2897 }
17caf1b1
AL
2898
2899 // Check it again using the new style output filenames
2900 FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
2901 if (stat(FinalFile.c_str(),&Buf) == 0)
2902 {
2903 // Make sure the size matches
73da43e9 2904 if ((unsigned long long)Buf.st_size == Version->Size)
17caf1b1
AL
2905 {
2906 Complete = true;
2907 Local = true;
2908 Status = StatDone;
2909 StoreFilename = DestFile = FinalFile;
2910 return true;
2911 }
2912
1e3f4083 2913 /* Hmm, we have a file and its size does not match, this shouldn't
17caf1b1 2914 happen.. */
51818f26 2915 RemoveFile("pkgAcqArchive::QueueNext", FinalFile);
17caf1b1
AL
2916 }
2917
2918 DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
6b1ff003
AL
2919
2920 // Check the destination file
2921 if (stat(DestFile.c_str(),&Buf) == 0)
2922 {
2923 // Hmm, the partial file is too big, erase it
73da43e9 2924 if ((unsigned long long)Buf.st_size > Version->Size)
51818f26 2925 RemoveFile("pkgAcqArchive::QueueNext", DestFile);
6b1ff003
AL
2926 else
2927 PartialSize = Buf.st_size;
2928 }
de31189f
DK
2929
2930 // Disables download of archives - useful if no real installation follows,
2931 // e.g. if we are just interested in proposed installation order
2932 if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2933 {
2934 Complete = true;
2935 Local = true;
2936 Status = StatDone;
2937 StoreFilename = DestFile = FinalFile;
2938 return true;
2939 }
2940
03e39e59 2941 // Create the item
b2e465d6 2942 Local = false;
03e39e59 2943 QueueURI(Desc);
b185acc2 2944
f7f0d6c7 2945 ++Vf;
b185acc2 2946 return true;
03e39e59 2947 }
b185acc2
AL
2948 return false;
2949}
03e39e59
AL
2950 /*}}}*/
2951// AcqArchive::Done - Finished fetching /*{{{*/
2952// ---------------------------------------------------------------------
2953/* */
448c38bd
DK
2954void pkgAcqArchive::Done(string const &Message, HashStringList const &Hashes,
2955 pkgAcquire::MethodConfig const * const Cfg)
03e39e59 2956{
448c38bd 2957 Item::Done(Message, Hashes, Cfg);
a6568219
AL
2958
2959 // Grab the output filename
dd676dc7 2960 std::string const FileName = LookupTag(Message,"Filename");
08ea7806 2961 if (DestFile != FileName && RealFileExists(DestFile) == false)
a6568219 2962 {
30e1eab5 2963 StoreFilename = DestFile = FileName;
a6568219 2964 Local = true;
5684f71f 2965 Complete = true;
a6568219
AL
2966 return;
2967 }
5684f71f 2968
a6568219 2969 // Done, move it into position
295d848b 2970 string const FinalFile = GetFinalFilename();
a6568219 2971 Rename(DestFile,FinalFile);
30e1eab5 2972 StoreFilename = DestFile = FinalFile;
03e39e59
AL
2973 Complete = true;
2974}
2975 /*}}}*/
db890fdb
AL
2976// AcqArchive::Failed - Failure handler /*{{{*/
2977// ---------------------------------------------------------------------
2978/* Here we try other sources */
448c38bd 2979void pkgAcqArchive::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
db890fdb 2980{
03aa0847
DK
2981 Item::Failed(Message,Cnf);
2982
448c38bd 2983 /* We don't really want to retry on failed media swaps, this prevents
b2e465d6
AL
2984 that. An interesting observation is that permanent failures are not
2985 recorded. */
448c38bd 2986 if (Cnf->Removable == true &&
b2e465d6
AL
2987 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2988 {
2989 // Vf = Version.FileList();
f7f0d6c7 2990 while (Vf.end() == false) ++Vf;
b2e465d6 2991 StoreFilename = string();
b2e465d6
AL
2992 return;
2993 }
03aa0847
DK
2994
2995 Status = StatIdle;
db890fdb 2996 if (QueueNext() == false)
7d8afa39
AL
2997 {
2998 // This is the retry counter
2999 if (Retries != 0 &&
3000 Cnf->LocalOnly == false &&
3001 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
3002 {
3003 Retries--;
3004 Vf = Version.FileList();
3005 if (QueueNext() == true)
3006 return;
3007 }
03aa0847 3008
9dbb421f 3009 StoreFilename = string();
03aa0847 3010 Status = StatError;
7d8afa39 3011 }
db890fdb
AL
3012}
3013 /*}}}*/
448c38bd 3014APT_PURE bool pkgAcqArchive::IsTrusted() const /*{{{*/
b3d44315
MV
3015{
3016 return Trusted;
3017}
92fcbfc1 3018 /*}}}*/
448c38bd 3019void pkgAcqArchive::Finished() /*{{{*/
ab559b35
AL
3020{
3021 if (Status == pkgAcquire::Item::StatDone &&
3022 Complete == true)
3023 return;
3024 StoreFilename = string();
3025}
3026 /*}}}*/
448c38bd
DK
3027std::string pkgAcqArchive::DescURI() const /*{{{*/
3028{
3029 return Desc.URI;
3030}
3031 /*}}}*/
3032std::string pkgAcqArchive::ShortDesc() const /*{{{*/
3033{
3034 return Desc.ShortDesc;
3035}
3036 /*}}}*/
c8a4ce6c 3037pkgAcqArchive::~pkgAcqArchive() {}
448c38bd 3038
d56e2917
DK
3039// AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
3040pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::VerIterator const &Ver,
3041 std::string const &DestDir, std::string const &DestFilename) :
3042 pkgAcquire::Item(Owner), d(NULL), SrcName(Ver.SourcePkgName()), SrcVersion(Ver.SourceVerStr())
3043{
3044 Desc.URI = URI(Ver);
3045 Init(DestDir, DestFilename);
3046}
3047// some parameters are char* here as they come likely from char* interfaces – which can also return NULL
3048pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::RlsFileIterator const &RlsFile,
3049 char const * const Component, char const * const SrcName, char const * const SrcVersion,
3050 const string &DestDir, const string &DestFilename) :
3051 pkgAcquire::Item(Owner), d(NULL), SrcName(SrcName), SrcVersion(SrcVersion)
3052{
3053 Desc.URI = URI(RlsFile, Component, SrcName, SrcVersion);
3054 Init(DestDir, DestFilename);
3055}
3056pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner,
3057 std::string const &URI, char const * const SrcName, char const * const SrcVersion,
3058 const string &DestDir, const string &DestFilename) :
3059 pkgAcquire::Item(Owner), d(NULL), SrcName(SrcName), SrcVersion(SrcVersion)
3060{
3061 Desc.URI = URI;
3062 Init(DestDir, DestFilename);
3063}
3064void pkgAcqChangelog::Init(std::string const &DestDir, std::string const &DestFilename)
3065{
3066 if (Desc.URI.empty())
3067 {
3068 Status = StatError;
3069 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3070 strprintf(ErrorText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
3071 // Let the error message print something sensible rather than "Failed to fetch /"
3072 if (DestFilename.empty())
3073 DestFile = SrcName + ".changelog";
3074 else
3075 DestFile = DestFilename;
3076 Desc.URI = "changelog:/" + DestFile;
3077 return;
3078 }
3079
3080 if (DestDir.empty())
3081 {
dd6da7d2
DK
3082 std::string const SandboxUser = _config->Find("APT::Sandbox::User");
3083 std::string const systemTemp = GetTempDir(SandboxUser);
d56e2917
DK
3084 char tmpname[100];
3085 snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX", systemTemp.c_str());
3086 if (NULL == mkdtemp(tmpname))
3087 {
3088 _error->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName.c_str(), SrcVersion.c_str());
3089 Status = StatError;
3090 return;
3091 }
3092 DestFile = TemporaryDirectory = tmpname;
d1256170 3093
d1256170
DK
3094 ChangeOwnerAndPermissionOfFile("Item::QueueURI", DestFile.c_str(),
3095 SandboxUser.c_str(), "root", 0700);
d56e2917
DK
3096 }
3097 else
3098 DestFile = DestDir;
3099
3100 if (DestFilename.empty())
3101 DestFile = flCombine(DestFile, SrcName + ".changelog");
3102 else
3103 DestFile = flCombine(DestFile, DestFilename);
3104
3105 Desc.ShortDesc = "Changelog";
3106 strprintf(Desc.Description, "%s %s %s Changelog", URI::SiteOnly(Desc.URI).c_str(), SrcName.c_str(), SrcVersion.c_str());
3107 Desc.Owner = this;
3108 QueueURI(Desc);
d56e2917
DK
3109}
3110 /*}}}*/
3111std::string pkgAcqChangelog::URI(pkgCache::VerIterator const &Ver) /*{{{*/
3112{
3113 char const * const SrcName = Ver.SourcePkgName();
3114 char const * const SrcVersion = Ver.SourceVerStr();
3115 pkgCache::PkgFileIterator PkgFile;
3116 // find the first source for this version which promises a changelog
3117 for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
3118 {
3119 pkgCache::PkgFileIterator const PF = VF.File();
3120 if (PF.Flagged(pkgCache::Flag::NotSource) || PF->Release == 0)
3121 continue;
3122 PkgFile = PF;
3123 pkgCache::RlsFileIterator const RF = PF.ReleaseFile();
3124 std::string const uri = URI(RF, PF.Component(), SrcName, SrcVersion);
3125 if (uri.empty())
3126 continue;
3127 return uri;
3128 }
3129 return "";
3130}
3131std::string pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator const &Rls)
3132{
3133 if (Rls.end() == true || (Rls->Label == 0 && Rls->Origin == 0))
3134 return "";
3135 std::string const serverConfig = "Acquire::Changelogs::URI";
3136 std::string server;
3137#define APT_EMPTY_SERVER \
3138 if (server.empty() == false) \
3139 { \
3140 if (server != "no") \
3141 return server; \
3142 return ""; \
3143 }
3144#define APT_CHECK_SERVER(X, Y) \
3145 if (Rls->X != 0) \
3146 { \
3147 std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
3148 server = _config->Find(specialServerConfig); \
3149 APT_EMPTY_SERVER \
3150 }
3151 // this way e.g. Debian-Security can fallback to Debian
3152 APT_CHECK_SERVER(Label, "Override::")
3153 APT_CHECK_SERVER(Origin, "Override::")
3154
3155 if (RealFileExists(Rls.FileName()))
3156 {
3157 _error->PushToStack();
3158 FileFd rf;
3159 /* This can be costly. A caller wanting to get millions of URIs might
3160 want to do this on its own once and use Override settings.
3161 We don't do this here as Origin/Label are not as unique as they
3162 should be so this could produce request order-dependent anomalies */
3163 if (OpenMaybeClearSignedFile(Rls.FileName(), rf) == true)
3164 {
3165 pkgTagFile TagFile(&rf, rf.Size());
3166 pkgTagSection Section;
3167 if (TagFile.Step(Section) == true)
3168 server = Section.FindS("Changelogs");
3169 }
3170 _error->RevertToStack();
3171 APT_EMPTY_SERVER
3172 }
3173
3174 APT_CHECK_SERVER(Label, "")
3175 APT_CHECK_SERVER(Origin, "")
3176#undef APT_CHECK_SERVER
3177#undef APT_EMPTY_SERVER
3178 return "";
3179}
3180std::string pkgAcqChangelog::URI(pkgCache::RlsFileIterator const &Rls,
3181 char const * const Component, char const * const SrcName,
3182 char const * const SrcVersion)
3183{
3184 return URI(URITemplate(Rls), Component, SrcName, SrcVersion);
3185}
3186std::string pkgAcqChangelog::URI(std::string const &Template,
3187 char const * const Component, char const * const SrcName,
3188 char const * const SrcVersion)
3189{
3190 if (Template.find("CHANGEPATH") == std::string::npos)
3191 return "";
3192
3193 // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
3194 std::string Src = SrcName;
3195 std::string path = APT::String::Startswith(SrcName, "lib") ? Src.substr(0, 4) : Src.substr(0,1);
3196 path.append("/").append(Src).append("/");
3197 path.append(Src).append("_").append(StripEpoch(SrcVersion));
3198 // we omit component for releases without one (= flat-style repositories)
3199 if (Component != NULL && strlen(Component) != 0)
3200 path = std::string(Component) + "/" + path;
3201
3202 return SubstVar(Template, "CHANGEPATH", path);
3203}
3204 /*}}}*/
3205// AcqChangelog::Failed - Failure handler /*{{{*/
3206void pkgAcqChangelog::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
3207{
3208 Item::Failed(Message,Cnf);
3209
3210 std::string errText;
3211 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3212 strprintf(errText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
3213
3214 // Error is probably something techy like 404 Not Found
3215 if (ErrorText.empty())
3216 ErrorText = errText;
3217 else
3218 ErrorText = errText + " (" + ErrorText + ")";
3219 return;
3220}
3221 /*}}}*/
3222// AcqChangelog::Done - Item downloaded OK /*{{{*/
3223void pkgAcqChangelog::Done(string const &Message,HashStringList const &CalcHashes,
3224 pkgAcquire::MethodConfig const * const Cnf)
3225{
3226 Item::Done(Message,CalcHashes,Cnf);
3227
3228 Complete = true;
3229}
3230 /*}}}*/
3231pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
3232{
3233 if (TemporaryDirectory.empty() == false)
3234 {
51818f26 3235 RemoveFile("~pkgAcqChangelog", DestFile);
d56e2917
DK
3236 rmdir(TemporaryDirectory.c_str());
3237 }
3238}
3239 /*}}}*/
3240
36375005 3241// AcqFile::pkgAcqFile - Constructor /*{{{*/
448c38bd
DK
3242pkgAcqFile::pkgAcqFile(pkgAcquire * const Owner,string const &URI, HashStringList const &Hashes,
3243 unsigned long long const Size,string const &Dsc,string const &ShortDesc,
77278c2b 3244 const string &DestDir, const string &DestFilename,
448c38bd 3245 bool const IsIndexFile) :
6c55f07a 3246 Item(Owner), d(NULL), IsIndexFile(IsIndexFile), ExpectedHashes(Hashes)
36375005 3247{
08cfc005 3248 Retries = _config->FindI("Acquire::Retries",0);
448c38bd 3249
46e00f9d
MV
3250 if(!DestFilename.empty())
3251 DestFile = DestFilename;
3252 else if(!DestDir.empty())
3253 DestFile = DestDir + "/" + flNotDir(URI);
3254 else
3255 DestFile = flNotDir(URI);
3256
36375005
AL
3257 // Create the item
3258 Desc.URI = URI;
3259 Desc.Description = Dsc;
3260 Desc.Owner = this;
3261
3262 // Set the short description to the archive component
3263 Desc.ShortDesc = ShortDesc;
448c38bd 3264
36375005
AL
3265 // Get the transfer sizes
3266 FileSize = Size;
3267 struct stat Buf;
3268 if (stat(DestFile.c_str(),&Buf) == 0)
3269 {
3270 // Hmm, the partial file is too big, erase it
ed9665ae 3271 if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
51818f26 3272 RemoveFile("pkgAcqFile", DestFile);
36375005
AL
3273 else
3274 PartialSize = Buf.st_size;
3275 }
092ae175 3276
36375005
AL
3277 QueueURI(Desc);
3278}
3279 /*}}}*/
3280// AcqFile::Done - Item downloaded OK /*{{{*/
448c38bd
DK
3281void pkgAcqFile::Done(string const &Message,HashStringList const &CalcHashes,
3282 pkgAcquire::MethodConfig const * const Cnf)
36375005 3283{
448c38bd 3284 Item::Done(Message,CalcHashes,Cnf);
495e5cb2 3285
dd676dc7 3286 std::string const FileName = LookupTag(Message,"Filename");
36375005 3287 Complete = true;
448c38bd 3288
36375005
AL
3289 // The files timestamp matches
3290 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
3291 return;
448c38bd 3292
36375005 3293 // We have to copy it into place
08ea7806 3294 if (RealFileExists(DestFile.c_str()) == false)
36375005
AL
3295 {
3296 Local = true;
459681d3
AL
3297 if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
3298 Cnf->Removable == true)
917ae805
AL
3299 {
3300 Desc.URI = "copy:" + FileName;
3301 QueueURI(Desc);
3302 return;
3303 }
448c38bd 3304
83ab33fc
AL
3305 // Erase the file if it is a symlink so we can overwrite it
3306 struct stat St;
3307 if (lstat(DestFile.c_str(),&St) == 0)
3308 {
3309 if (S_ISLNK(St.st_mode) != 0)
51818f26 3310 RemoveFile("pkgAcqFile::Done", DestFile);
83ab33fc 3311 }
448c38bd 3312
83ab33fc 3313 // Symlink the file
917ae805
AL
3314 if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
3315 {
03aa0847
DK
3316 _error->PushToStack();
3317 _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
3318 std::stringstream msg;
95278287 3319 _error->DumpErrors(msg, GlobalError::DEBUG, false);
03aa0847
DK
3320 _error->RevertToStack();
3321 ErrorText = msg.str();
917ae805
AL
3322 Status = StatError;
3323 Complete = false;
448c38bd 3324 }
36375005
AL
3325 }
3326}
3327 /*}}}*/
08cfc005
AL
3328// AcqFile::Failed - Failure handler /*{{{*/
3329// ---------------------------------------------------------------------
3330/* Here we try other sources */
448c38bd 3331void pkgAcqFile::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
08cfc005 3332{
03aa0847
DK
3333 Item::Failed(Message,Cnf);
3334
08cfc005
AL
3335 // This is the retry counter
3336 if (Retries != 0 &&
3337 Cnf->LocalOnly == false &&
3338 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
3339 {
03aa0847 3340 --Retries;
08cfc005 3341 QueueURI(Desc);
03aa0847 3342 Status = StatIdle;
08cfc005
AL
3343 return;
3344 }
03aa0847 3345
08cfc005
AL
3346}
3347 /*}}}*/
448c38bd 3348string pkgAcqFile::Custom600Headers() const /*{{{*/
77278c2b
MV
3349{
3350 if (IsIndexFile)
3351 return "\nIndex-File: true";
61a07c57 3352 return "";
77278c2b
MV
3353}
3354 /*}}}*/
c8a4ce6c 3355pkgAcqFile::~pkgAcqFile() {}