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