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