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