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