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