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