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