]> git.saurik.com Git - apt.git/blob - apt-pkg/acquire-item.cc
do not cleanup .diff/Index files on Hit
[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 unlink(DestFile.c_str());
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 unlink(PartialFile.c_str());
427 }
428 break;
429 case TransactionCommit:
430 if (EraseFileName.empty() == false)
431 unlink(EraseFileName.c_str());
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 unlink(Partial.c_str());
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 unlink(I->DestFile.c_str());
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 bool trypdiff = Target->OptionBool(IndexTarget::PDIFFS);
1040 if (verify == true)
1041 {
1042 if (TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false)
1043 {
1044 // optional targets that we do not have in the Release file are skipped
1045 if (Target->IsOptional)
1046 continue;
1047
1048 Status = StatAuthError;
1049 strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target->MetaKey.c_str());
1050 return;
1051 }
1052
1053 // autoselect the compression method
1054 std::vector<std::string> types = VectorizeString(Target->Option(IndexTarget::COMPRESSIONTYPES), ' ');
1055 types.erase(std::remove_if(types.begin(), types.end(), [&](std::string const &t) {
1056 if (t == "uncompressed")
1057 return TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false;
1058 std::string const MetaKey = Target->MetaKey + "." + t;
1059 return TransactionManager->MetaIndexParser->Exists(MetaKey) == false;
1060 }), types.end());
1061 if (types.empty() == false)
1062 {
1063 std::ostringstream os;
1064 // add the special compressiontype byhash first if supported
1065 std::string const useByHashConf = Target->Option(IndexTarget::BY_HASH);
1066 bool useByHash = false;
1067 if(useByHashConf == "force")
1068 useByHash = true;
1069 else
1070 useByHash = StringToBool(useByHashConf) == true && metaBaseSupportsByHash;
1071 if (useByHash == true)
1072 os << "by-hash ";
1073 std::copy(types.begin(), types.end()-1, std::ostream_iterator<std::string>(os, " "));
1074 os << *types.rbegin();
1075 Target->Options["COMPRESSIONTYPES"] = os.str();
1076 }
1077 else
1078 Target->Options["COMPRESSIONTYPES"].clear();
1079
1080 std::string filename = GetFinalFileNameFromURI(Target->URI);
1081 if (RealFileExists(filename) == false)
1082 {
1083 if (Target->KeepCompressed)
1084 {
1085 filename = GetKeepCompressedFileName(filename, *Target);
1086 if (RealFileExists(filename) == false)
1087 filename.clear();
1088 }
1089 else
1090 filename.clear();
1091 }
1092
1093 if (filename.empty() == false)
1094 {
1095 // if the Release file is a hit and we have an index it must be the current one
1096 if (TransactionManager->IMSHit == true)
1097 ;
1098 else if (TransactionManager->LastMetaIndexParser != NULL)
1099 {
1100 // see if the file changed since the last Release file
1101 // we use the uncompressed files as we might compress differently compared to the server,
1102 // so the hashes might not match, even if they contain the same data.
1103 HashStringList const newFile = GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, Target->MetaKey);
1104 HashStringList const oldFile = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target->MetaKey);
1105 if (newFile != oldFile)
1106 filename.clear();
1107 }
1108 else
1109 filename.clear();
1110 }
1111 else
1112 trypdiff = false; // no file to patch
1113
1114 if (filename.empty() == false)
1115 {
1116 new NoActionItem(Owner, *Target, filename);
1117 std::string const idxfilename = GetFinalFileNameFromURI(Target->URI + ".diff/Index");
1118 if (FileExists(idxfilename))
1119 new NoActionItem(Owner, *Target, idxfilename);
1120 continue;
1121 }
1122
1123 // check if we have patches available
1124 trypdiff &= TransactionManager->MetaIndexParser->Exists(Target->MetaKey + ".diff/Index");
1125 }
1126 else
1127 {
1128 // if we have no file to patch, no point in trying
1129 std::string filename = GetFinalFileNameFromURI(Target->URI);
1130 if (RealFileExists(filename) == false)
1131 {
1132 if (Target->KeepCompressed)
1133 {
1134 filename = GetKeepCompressedFileName(filename, *Target);
1135 if (RealFileExists(filename) == false)
1136 filename.clear();
1137 }
1138 else
1139 filename.clear();
1140 }
1141 trypdiff &= (filename.empty() == false);
1142 }
1143
1144 // no point in patching from local sources
1145 if (trypdiff)
1146 {
1147 std::string const proto = Target->URI.substr(0, strlen("file:/"));
1148 if (proto == "file:/" || proto == "copy:/" || proto == "cdrom:")
1149 trypdiff = false;
1150 }
1151
1152 // Queue the Index file (Packages, Sources, Translation-$foo, …)
1153 if (trypdiff)
1154 new pkgAcqDiffIndex(Owner, TransactionManager, *Target);
1155 else
1156 new pkgAcqIndex(Owner, TransactionManager, *Target);
1157 }
1158 }
1159 /*}}}*/
1160 bool pkgAcqMetaBase::VerifyVendor(string const &Message) /*{{{*/
1161 {
1162 string::size_type pos;
1163
1164 // check for missing sigs (that where not fatal because otherwise we had
1165 // bombed earlier)
1166 string missingkeys;
1167 string msg = _("There is no public key available for the "
1168 "following key IDs:\n");
1169 pos = Message.find("NO_PUBKEY ");
1170 if (pos != std::string::npos)
1171 {
1172 string::size_type start = pos+strlen("NO_PUBKEY ");
1173 string Fingerprint = Message.substr(start, Message.find("\n")-start);
1174 missingkeys += (Fingerprint);
1175 }
1176 if(!missingkeys.empty())
1177 _error->Warning("%s", (msg + missingkeys).c_str());
1178
1179 string Transformed = TransactionManager->MetaIndexParser->GetExpectedDist();
1180
1181 if (Transformed == "../project/experimental")
1182 {
1183 Transformed = "experimental";
1184 }
1185
1186 pos = Transformed.rfind('/');
1187 if (pos != string::npos)
1188 {
1189 Transformed = Transformed.substr(0, pos);
1190 }
1191
1192 if (Transformed == ".")
1193 {
1194 Transformed = "";
1195 }
1196
1197 if (TransactionManager->MetaIndexParser->GetValidUntil() > 0)
1198 {
1199 time_t const invalid_since = time(NULL) - TransactionManager->MetaIndexParser->GetValidUntil();
1200 if (invalid_since > 0)
1201 {
1202 std::string errmsg;
1203 strprintf(errmsg,
1204 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1205 // the time since then the file is invalid - formatted in the same way as in
1206 // the download progress display (e.g. 7d 3h 42min 1s)
1207 _("Release file for %s is expired (invalid since %s). "
1208 "Updates for this repository will not be applied."),
1209 Target.URI.c_str(), TimeToStr(invalid_since).c_str());
1210 if (ErrorText.empty())
1211 ErrorText = errmsg;
1212 return _error->Error("%s", errmsg.c_str());
1213 }
1214 }
1215
1216 /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
1217 as a prevention of downgrading us to older (still valid) files */
1218 if (TransactionManager->IMSHit == false && TransactionManager->LastMetaIndexParser != NULL &&
1219 TransactionManager->LastMetaIndexParser->GetDate() > TransactionManager->MetaIndexParser->GetDate())
1220 {
1221 TransactionManager->IMSHit = true;
1222 unlink(DestFile.c_str());
1223 PartialFile = DestFile = GetFinalFilename();
1224 // load the 'old' file in the 'new' one instead of flipping pointers as
1225 // the new one isn't owned by us, while the old one is so cleanup would be confused.
1226 TransactionManager->MetaIndexParser->swapLoad(TransactionManager->LastMetaIndexParser);
1227 delete TransactionManager->LastMetaIndexParser;
1228 TransactionManager->LastMetaIndexParser = NULL;
1229 }
1230
1231 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1232 {
1233 std::cerr << "Got Codename: " << TransactionManager->MetaIndexParser->GetCodename() << std::endl;
1234 std::cerr << "Expecting Dist: " << TransactionManager->MetaIndexParser->GetExpectedDist() << std::endl;
1235 std::cerr << "Transformed Dist: " << Transformed << std::endl;
1236 }
1237
1238 if (TransactionManager->MetaIndexParser->CheckDist(Transformed) == false)
1239 {
1240 // This might become fatal one day
1241 // Status = StatAuthError;
1242 // ErrorText = "Conflicting distribution; expected "
1243 // + MetaIndexParser->GetExpectedDist() + " but got "
1244 // + MetaIndexParser->GetCodename();
1245 // return false;
1246 if (!Transformed.empty())
1247 {
1248 _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1249 Desc.Description.c_str(),
1250 Transformed.c_str(),
1251 TransactionManager->MetaIndexParser->GetCodename().c_str());
1252 }
1253 }
1254
1255 return true;
1256 }
1257 /*}}}*/
1258 pkgAcqMetaBase::~pkgAcqMetaBase()
1259 {
1260 }
1261
1262 pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire * const Owner, /*{{{*/
1263 IndexTarget const &ClearsignedTarget,
1264 IndexTarget const &DetachedDataTarget, IndexTarget const &DetachedSigTarget,
1265 std::vector<IndexTarget> const &IndexTargets,
1266 metaIndex * const MetaIndexParser) :
1267 pkgAcqMetaIndex(Owner, this, ClearsignedTarget, DetachedSigTarget, IndexTargets),
1268 d(NULL), ClearsignedTarget(ClearsignedTarget),
1269 DetachedDataTarget(DetachedDataTarget),
1270 MetaIndexParser(MetaIndexParser), LastMetaIndexParser(NULL)
1271 {
1272 // index targets + (worst case:) Release/Release.gpg
1273 ExpectedAdditionalItems = IndexTargets.size() + 2;
1274 TransactionManager->Add(this);
1275 }
1276 /*}}}*/
1277 pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
1278 {
1279 if (LastMetaIndexParser != NULL)
1280 delete LastMetaIndexParser;
1281 }
1282 /*}}}*/
1283 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1284 string pkgAcqMetaClearSig::Custom600Headers() const
1285 {
1286 string Header = pkgAcqMetaBase::Custom600Headers();
1287 Header += "\nFail-Ignore: true";
1288 std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
1289 if (key.empty() == false)
1290 Header += "\nSigned-By: " + key;
1291
1292 return Header;
1293 }
1294 /*}}}*/
1295 bool pkgAcqMetaClearSig::VerifyDone(std::string const &Message, /*{{{*/
1296 pkgAcquire::MethodConfig const * const Cnf)
1297 {
1298 Item::VerifyDone(Message, Cnf);
1299
1300 if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
1301 return RenameOnError(NotClearsigned);
1302
1303 return true;
1304 }
1305 /*}}}*/
1306 // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
1307 void pkgAcqMetaClearSig::Done(std::string const &Message,
1308 HashStringList const &Hashes,
1309 pkgAcquire::MethodConfig const * const Cnf)
1310 {
1311 Item::Done(Message, Hashes, Cnf);
1312
1313 if(AuthPass == false)
1314 {
1315 if(CheckDownloadDone(this, Message, Hashes) == true)
1316 QueueForSignatureVerify(this, DestFile, DestFile);
1317 return;
1318 }
1319 else if(CheckAuthDone(Message) == true)
1320 {
1321 if (TransactionManager->IMSHit == false)
1322 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
1323 else if (RealFileExists(GetFinalFilename()) == false)
1324 {
1325 // We got an InRelease file IMSHit, but we haven't one, which means
1326 // we had a valid Release/Release.gpg combo stepping in, which we have
1327 // to 'acquire' now to ensure list cleanup isn't removing them
1328 new NoActionItem(Owner, DetachedDataTarget);
1329 new NoActionItem(Owner, DetachedSigTarget);
1330 }
1331 }
1332 }
1333 /*}}}*/
1334 void pkgAcqMetaClearSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf) /*{{{*/
1335 {
1336 Item::Failed(Message, Cnf);
1337
1338 // we failed, we will not get additional items from this method
1339 ExpectedAdditionalItems = 0;
1340
1341 if (AuthPass == false)
1342 {
1343 if (Status == StatAuthError || Status == StatTransientNetworkError)
1344 {
1345 // if we expected a ClearTextSignature (InRelease) but got a network
1346 // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
1347 // As these is usually called by web-portals we do not try Release/Release.gpg
1348 // as this is gonna fail anyway and instead abort our try (LP#346386)
1349 TransactionManager->AbortTransaction();
1350 return;
1351 }
1352
1353 // Queue the 'old' InRelease file for removal if we try Release.gpg
1354 // as otherwise the file will stay around and gives a false-auth
1355 // impression (CVE-2012-0214)
1356 TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
1357 Status = StatDone;
1358
1359 new pkgAcqMetaIndex(Owner, TransactionManager, DetachedDataTarget, DetachedSigTarget, IndexTargets);
1360 }
1361 else
1362 {
1363 if(CheckStopAuthentication(this, Message))
1364 return;
1365
1366 // No Release file was present, or verification failed, so fall
1367 // back to queueing Packages files without verification
1368 // only allow going further if the users explicitely wants it
1369 if(AllowInsecureRepositories(_("The repository '%s' is not signed."), ClearsignedTarget.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
1370 {
1371 Status = StatDone;
1372
1373 /* InRelease files become Release files, otherwise
1374 * they would be considered as trusted later on */
1375 string const FinalRelease = GetFinalFileNameFromURI(DetachedDataTarget.URI);
1376 string const PartialRelease = GetPartialFileNameFromURI(DetachedDataTarget.URI);
1377 string const FinalReleasegpg = GetFinalFileNameFromURI(DetachedSigTarget.URI);
1378 string const FinalInRelease = GetFinalFilename();
1379 Rename(DestFile, PartialRelease);
1380 TransactionManager->TransactionStageCopy(this, PartialRelease, FinalRelease);
1381
1382 if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
1383 {
1384 // open the last Release if we have it
1385 if (TransactionManager->IMSHit == false)
1386 {
1387 TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
1388 if (TransactionManager->LastMetaIndexParser != NULL)
1389 {
1390 _error->PushToStack();
1391 if (RealFileExists(FinalInRelease))
1392 TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
1393 else
1394 TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
1395 // its unlikely to happen, but if what we have is bad ignore it
1396 if (_error->PendingError())
1397 {
1398 delete TransactionManager->LastMetaIndexParser;
1399 TransactionManager->LastMetaIndexParser = NULL;
1400 }
1401 _error->RevertToStack();
1402 }
1403 }
1404 }
1405
1406 // we parse the indexes here because at this point the user wanted
1407 // a repository that may potentially harm him
1408 if (TransactionManager->MetaIndexParser->Load(PartialRelease, &ErrorText) == false || VerifyVendor(Message) == false)
1409 /* expired Release files are still a problem you need extra force for */;
1410 else
1411 QueueIndexes(true);
1412 }
1413 }
1414 }
1415 /*}}}*/
1416
1417 pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire * const Owner, /*{{{*/
1418 pkgAcqMetaClearSig * const TransactionManager,
1419 IndexTarget const &DataTarget,
1420 IndexTarget const &DetachedSigTarget,
1421 vector<IndexTarget> const &IndexTargets) :
1422 pkgAcqMetaBase(Owner, TransactionManager, IndexTargets, DataTarget), d(NULL),
1423 DetachedSigTarget(DetachedSigTarget)
1424 {
1425 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1426 std::clog << "New pkgAcqMetaIndex with TransactionManager "
1427 << this->TransactionManager << std::endl;
1428
1429 DestFile = GetPartialFileNameFromURI(DataTarget.URI);
1430
1431 // Create the item
1432 Desc.Description = DataTarget.Description;
1433 Desc.Owner = this;
1434 Desc.ShortDesc = DataTarget.ShortDesc;
1435 Desc.URI = DataTarget.URI;
1436
1437 // we expect more item
1438 ExpectedAdditionalItems = IndexTargets.size();
1439 QueueURI(Desc);
1440 }
1441 /*}}}*/
1442 void pkgAcqMetaIndex::Done(string const &Message, /*{{{*/
1443 HashStringList const &Hashes,
1444 pkgAcquire::MethodConfig const * const Cfg)
1445 {
1446 Item::Done(Message,Hashes,Cfg);
1447
1448 if(CheckDownloadDone(this, Message, Hashes))
1449 {
1450 // we have a Release file, now download the Signature, all further
1451 // verify/queue for additional downloads will be done in the
1452 // pkgAcqMetaSig::Done() code
1453 new pkgAcqMetaSig(Owner, TransactionManager, DetachedSigTarget, this);
1454 }
1455 }
1456 /*}}}*/
1457 // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
1458 void pkgAcqMetaIndex::Failed(string const &Message,
1459 pkgAcquire::MethodConfig const * const Cnf)
1460 {
1461 pkgAcquire::Item::Failed(Message, Cnf);
1462 Status = StatDone;
1463
1464 // No Release file was present so fall
1465 // back to queueing Packages files without verification
1466 // only allow going further if the users explicitely wants it
1467 if(AllowInsecureRepositories(_("The repository '%s' does not have a Release file."), Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
1468 {
1469 // ensure old Release files are removed
1470 TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
1471
1472 // queue without any kind of hashsum support
1473 QueueIndexes(false);
1474 }
1475 }
1476 /*}}}*/
1477 void pkgAcqMetaIndex::Finished() /*{{{*/
1478 {
1479 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1480 std::clog << "Finished: " << DestFile <<std::endl;
1481 if(TransactionManager != NULL &&
1482 TransactionManager->TransactionHasError() == false)
1483 TransactionManager->CommitTransaction();
1484 }
1485 /*}}}*/
1486 std::string pkgAcqMetaIndex::DescURI() const /*{{{*/
1487 {
1488 return Target.URI;
1489 }
1490 /*}}}*/
1491 pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
1492
1493 // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
1494 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire * const Owner,
1495 pkgAcqMetaClearSig * const TransactionManager,
1496 IndexTarget const &Target,
1497 pkgAcqMetaIndex * const MetaIndex) :
1498 pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL), MetaIndex(MetaIndex)
1499 {
1500 DestFile = GetPartialFileNameFromURI(Target.URI);
1501
1502 // remove any partial downloaded sig-file in partial/.
1503 // it may confuse proxies and is too small to warrant a
1504 // partial download anyway
1505 unlink(DestFile.c_str());
1506
1507 // set the TransactionManager
1508 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1509 std::clog << "New pkgAcqMetaSig with TransactionManager "
1510 << TransactionManager << std::endl;
1511
1512 // Create the item
1513 Desc.Description = Target.Description;
1514 Desc.Owner = this;
1515 Desc.ShortDesc = Target.ShortDesc;
1516 Desc.URI = Target.URI;
1517
1518 // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
1519 // so we skip the download step and go instantly to verification
1520 if (TransactionManager->IMSHit == true && RealFileExists(GetFinalFilename()))
1521 {
1522 Complete = true;
1523 Status = StatDone;
1524 PartialFile = DestFile = GetFinalFilename();
1525 MetaIndexFileSignature = DestFile;
1526 MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
1527 }
1528 else
1529 QueueURI(Desc);
1530 }
1531 /*}}}*/
1532 pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1533 {
1534 }
1535 /*}}}*/
1536 // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1537 std::string pkgAcqMetaSig::Custom600Headers() const
1538 {
1539 std::string Header = pkgAcqTransactionItem::Custom600Headers();
1540 std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
1541 if (key.empty() == false)
1542 Header += "\nSigned-By: " + key;
1543 return Header;
1544 }
1545 /*}}}*/
1546 // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
1547 void pkgAcqMetaSig::Done(string const &Message, HashStringList const &Hashes,
1548 pkgAcquire::MethodConfig const * const Cfg)
1549 {
1550 if (MetaIndexFileSignature.empty() == false)
1551 {
1552 DestFile = MetaIndexFileSignature;
1553 MetaIndexFileSignature.clear();
1554 }
1555 Item::Done(Message, Hashes, Cfg);
1556
1557 if(MetaIndex->AuthPass == false)
1558 {
1559 if(MetaIndex->CheckDownloadDone(this, Message, Hashes) == true)
1560 {
1561 // destfile will be modified to point to MetaIndexFile for the
1562 // gpgv method, so we need to save it here
1563 MetaIndexFileSignature = DestFile;
1564 MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
1565 }
1566 return;
1567 }
1568 else if(MetaIndex->CheckAuthDone(Message) == true)
1569 {
1570 if (TransactionManager->IMSHit == false)
1571 {
1572 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
1573 TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
1574 }
1575 }
1576 }
1577 /*}}}*/
1578 void pkgAcqMetaSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
1579 {
1580 Item::Failed(Message,Cnf);
1581
1582 // check if we need to fail at this point
1583 if (MetaIndex->AuthPass == true && MetaIndex->CheckStopAuthentication(this, Message))
1584 return;
1585
1586 string const FinalRelease = MetaIndex->GetFinalFilename();
1587 string const FinalReleasegpg = GetFinalFilename();
1588 string const FinalInRelease = TransactionManager->GetFinalFilename();
1589
1590 if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
1591 {
1592 std::string downgrade_msg;
1593 strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
1594 MetaIndex->Target.Description.c_str());
1595 if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1596 {
1597 // meh, the users wants to take risks (we still mark the packages
1598 // from this repository as unauthenticated)
1599 _error->Warning("%s", downgrade_msg.c_str());
1600 _error->Warning(_("This is normally not allowed, but the option "
1601 "Acquire::AllowDowngradeToInsecureRepositories was "
1602 "given to override it."));
1603 Status = StatDone;
1604 } else {
1605 MessageInsecureRepository(true, downgrade_msg);
1606 if (TransactionManager->IMSHit == false)
1607 Rename(MetaIndex->DestFile, MetaIndex->DestFile + ".FAILED");
1608 Item::Failed("Message: " + downgrade_msg, Cnf);
1609 TransactionManager->AbortTransaction();
1610 return;
1611 }
1612 }
1613
1614 // ensures that a Release.gpg file in the lists/ is removed by the transaction
1615 TransactionManager->TransactionStageRemoval(this, DestFile);
1616
1617 // only allow going further if the users explicitely wants it
1618 if (AllowInsecureRepositories(_("The repository '%s' is not signed."), MetaIndex->Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
1619 {
1620 if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
1621 {
1622 // open the last Release if we have it
1623 if (TransactionManager->IMSHit == false)
1624 {
1625 TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
1626 if (TransactionManager->LastMetaIndexParser != NULL)
1627 {
1628 _error->PushToStack();
1629 if (RealFileExists(FinalInRelease))
1630 TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
1631 else
1632 TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
1633 // its unlikely to happen, but if what we have is bad ignore it
1634 if (_error->PendingError())
1635 {
1636 delete TransactionManager->LastMetaIndexParser;
1637 TransactionManager->LastMetaIndexParser = NULL;
1638 }
1639 _error->RevertToStack();
1640 }
1641 }
1642 }
1643
1644 // we parse the indexes here because at this point the user wanted
1645 // a repository that may potentially harm him
1646 if (TransactionManager->MetaIndexParser->Load(MetaIndex->DestFile, &ErrorText) == false || MetaIndex->VerifyVendor(Message) == false)
1647 /* expired Release files are still a problem you need extra force for */;
1648 else
1649 MetaIndex->QueueIndexes(true);
1650
1651 TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
1652 }
1653
1654 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1655 if (Cnf->LocalOnly == true ||
1656 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
1657 {
1658 // Ignore this
1659 Status = StatDone;
1660 }
1661 }
1662 /*}}}*/
1663
1664
1665 // AcqBaseIndex - Constructor /*{{{*/
1666 pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire * const Owner,
1667 pkgAcqMetaClearSig * const TransactionManager,
1668 IndexTarget const &Target)
1669 : pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL)
1670 {
1671 }
1672 /*}}}*/
1673 pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
1674
1675 // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
1676 // ---------------------------------------------------------------------
1677 /* Get the DiffIndex file first and see if there are patches available
1678 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
1679 * patches. If anything goes wrong in that process, it will fall back to
1680 * the original packages file
1681 */
1682 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire * const Owner,
1683 pkgAcqMetaClearSig * const TransactionManager,
1684 IndexTarget const &Target)
1685 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), diffs(NULL)
1686 {
1687 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
1688
1689 Desc.Owner = this;
1690 Desc.Description = Target.Description + ".diff/Index";
1691 Desc.ShortDesc = Target.ShortDesc;
1692 Desc.URI = Target.URI + ".diff/Index";
1693
1694 DestFile = GetPartialFileNameFromURI(Desc.URI);
1695
1696 if(Debug)
1697 std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
1698
1699 QueueURI(Desc);
1700 }
1701 /*}}}*/
1702 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1703 // ---------------------------------------------------------------------
1704 /* The only header we use is the last-modified header. */
1705 string pkgAcqDiffIndex::Custom600Headers() const
1706 {
1707 string const Final = GetFinalFilename();
1708
1709 if(Debug)
1710 std::clog << "Custom600Header-IMS: " << Final << std::endl;
1711
1712 struct stat Buf;
1713 if (stat(Final.c_str(),&Buf) != 0)
1714 return "\nIndex-File: true";
1715
1716 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1717 }
1718 /*}}}*/
1719 void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
1720 {
1721 // list cleanup needs to know that this file as well as the already
1722 // present index is ours, so we create an empty diff to save it for us
1723 new pkgAcqIndexDiffs(Owner, TransactionManager, Target);
1724 }
1725 /*}}}*/
1726 bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/
1727 {
1728 // failing here is fine: our caller will take care of trying to
1729 // get the complete file if patching fails
1730 if(Debug)
1731 std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
1732 << std::endl;
1733
1734 FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
1735 pkgTagFile TF(&Fd);
1736 if (Fd.IsOpen() == false || Fd.Failed())
1737 return false;
1738
1739 pkgTagSection Tags;
1740 if(unlikely(TF.Step(Tags) == false))
1741 return false;
1742
1743 HashStringList ServerHashes;
1744 unsigned long long ServerSize = 0;
1745
1746 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
1747 {
1748 std::string tagname = *type;
1749 tagname.append("-Current");
1750 std::string const tmp = Tags.FindS(tagname.c_str());
1751 if (tmp.empty() == true)
1752 continue;
1753
1754 string hash;
1755 unsigned long long size;
1756 std::stringstream ss(tmp);
1757 ss >> hash >> size;
1758 if (unlikely(hash.empty() == true))
1759 continue;
1760 if (unlikely(ServerSize != 0 && ServerSize != size))
1761 continue;
1762 ServerHashes.push_back(HashString(*type, hash));
1763 ServerSize = size;
1764 }
1765
1766 if (ServerHashes.usable() == false)
1767 {
1768 if (Debug == true)
1769 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
1770 return false;
1771 }
1772
1773 std::string const CurrentPackagesFile = GetFinalFileNameFromURI(Target.URI);
1774 HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
1775 if (TargetFileHashes.usable() == false || ServerHashes != TargetFileHashes)
1776 {
1777 if (Debug == true)
1778 {
1779 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
1780 printHashSumComparision(CurrentPackagesFile, ServerHashes, TargetFileHashes);
1781 }
1782 return false;
1783 }
1784
1785 HashStringList LocalHashes;
1786 // try avoiding calculating the hash here as this is costly
1787 if (TransactionManager->LastMetaIndexParser != NULL)
1788 LocalHashes = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target.MetaKey);
1789 if (LocalHashes.usable() == false)
1790 {
1791 FileFd fd(CurrentPackagesFile, FileFd::ReadOnly, FileFd::Auto);
1792 Hashes LocalHashesCalc(ServerHashes);
1793 LocalHashesCalc.AddFD(fd);
1794 LocalHashes = LocalHashesCalc.GetHashStringList();
1795 }
1796
1797 if (ServerHashes == LocalHashes)
1798 {
1799 // we have the same sha1 as the server so we are done here
1800 if(Debug)
1801 std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
1802 QueueOnIMSHit();
1803 return true;
1804 }
1805
1806 if(Debug)
1807 std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
1808 << CurrentPackagesFile << " " << LocalHashes.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
1809
1810 // parse all of (provided) history
1811 vector<DiffInfo> available_patches;
1812 bool firstAcceptedHashes = true;
1813 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
1814 {
1815 if (LocalHashes.find(*type) == NULL)
1816 continue;
1817
1818 std::string tagname = *type;
1819 tagname.append("-History");
1820 std::string const tmp = Tags.FindS(tagname.c_str());
1821 if (tmp.empty() == true)
1822 continue;
1823
1824 string hash, filename;
1825 unsigned long long size;
1826 std::stringstream ss(tmp);
1827
1828 while (ss >> hash >> size >> filename)
1829 {
1830 if (unlikely(hash.empty() == true || filename.empty() == true))
1831 continue;
1832
1833 // see if we have a record for this file already
1834 std::vector<DiffInfo>::iterator cur = available_patches.begin();
1835 for (; cur != available_patches.end(); ++cur)
1836 {
1837 if (cur->file != filename)
1838 continue;
1839 cur->result_hashes.push_back(HashString(*type, hash));
1840 break;
1841 }
1842 if (cur != available_patches.end())
1843 continue;
1844 if (firstAcceptedHashes == true)
1845 {
1846 DiffInfo next;
1847 next.file = filename;
1848 next.result_hashes.push_back(HashString(*type, hash));
1849 next.result_hashes.FileSize(size);
1850 available_patches.push_back(next);
1851 }
1852 else
1853 {
1854 if (Debug == true)
1855 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
1856 << " wasn't in the list for the first parsed hash! (history)" << std::endl;
1857 break;
1858 }
1859 }
1860 firstAcceptedHashes = false;
1861 }
1862
1863 if (unlikely(available_patches.empty() == true))
1864 {
1865 if (Debug)
1866 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
1867 << "Couldn't find any patches for the patch series." << std::endl;
1868 return false;
1869 }
1870
1871 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
1872 {
1873 if (LocalHashes.find(*type) == NULL)
1874 continue;
1875
1876 std::string tagname = *type;
1877 tagname.append("-Patches");
1878 std::string const tmp = Tags.FindS(tagname.c_str());
1879 if (tmp.empty() == true)
1880 continue;
1881
1882 string hash, filename;
1883 unsigned long long size;
1884 std::stringstream ss(tmp);
1885
1886 while (ss >> hash >> size >> filename)
1887 {
1888 if (unlikely(hash.empty() == true || filename.empty() == true))
1889 continue;
1890
1891 // see if we have a record for this file already
1892 std::vector<DiffInfo>::iterator cur = available_patches.begin();
1893 for (; cur != available_patches.end(); ++cur)
1894 {
1895 if (cur->file != filename)
1896 continue;
1897 if (cur->patch_hashes.empty())
1898 cur->patch_hashes.FileSize(size);
1899 cur->patch_hashes.push_back(HashString(*type, hash));
1900 break;
1901 }
1902 if (cur != available_patches.end())
1903 continue;
1904 if (Debug == true)
1905 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
1906 << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
1907 break;
1908 }
1909 }
1910
1911 for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
1912 {
1913 std::string tagname = *type;
1914 tagname.append("-Download");
1915 std::string const tmp = Tags.FindS(tagname.c_str());
1916 if (tmp.empty() == true)
1917 continue;
1918
1919 string hash, filename;
1920 unsigned long long size;
1921 std::stringstream ss(tmp);
1922
1923 // FIXME: all of pdiff supports only .gz compressed patches
1924 while (ss >> hash >> size >> filename)
1925 {
1926 if (unlikely(hash.empty() == true || filename.empty() == true))
1927 continue;
1928 if (unlikely(APT::String::Endswith(filename, ".gz") == false))
1929 continue;
1930 filename.erase(filename.length() - 3);
1931
1932 // see if we have a record for this file already
1933 std::vector<DiffInfo>::iterator cur = available_patches.begin();
1934 for (; cur != available_patches.end(); ++cur)
1935 {
1936 if (cur->file != filename)
1937 continue;
1938 if (cur->download_hashes.empty())
1939 cur->download_hashes.FileSize(size);
1940 cur->download_hashes.push_back(HashString(*type, hash));
1941 break;
1942 }
1943 if (cur != available_patches.end())
1944 continue;
1945 if (Debug == true)
1946 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
1947 << " wasn't in the list for the first parsed hash! (download)" << std::endl;
1948 break;
1949 }
1950 }
1951
1952
1953 bool foundStart = false;
1954 for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
1955 cur != available_patches.end(); ++cur)
1956 {
1957 if (LocalHashes != cur->result_hashes)
1958 continue;
1959
1960 available_patches.erase(available_patches.begin(), cur);
1961 foundStart = true;
1962 break;
1963 }
1964
1965 if (foundStart == false || unlikely(available_patches.empty() == true))
1966 {
1967 if (Debug)
1968 std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
1969 << "Couldn't find the start of the patch series." << std::endl;
1970 return false;
1971 }
1972
1973 // patching with too many files is rather slow compared to a fast download
1974 unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
1975 if (fileLimit != 0 && fileLimit < available_patches.size())
1976 {
1977 if (Debug)
1978 std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
1979 << ") so fallback to complete download" << std::endl;
1980 return false;
1981 }
1982
1983 // calculate the size of all patches we have to get
1984 // note that all sizes are uncompressed, while we download compressed files
1985 unsigned long long patchesSize = 0;
1986 for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
1987 cur != available_patches.end(); ++cur)
1988 patchesSize += cur->patch_hashes.FileSize();
1989 unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
1990 if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
1991 {
1992 if (Debug)
1993 std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
1994 << ") so fallback to complete download" << std::endl;
1995 return false;
1996 }
1997
1998 // we have something, queue the diffs
1999 string::size_type const last_space = Description.rfind(" ");
2000 if(last_space != string::npos)
2001 Description.erase(last_space, Description.size()-last_space);
2002
2003 /* decide if we should download patches one by one or in one go:
2004 The first is good if the server merges patches, but many don't so client
2005 based merging can be attempt in which case the second is better.
2006 "bad things" will happen if patches are merged on the server,
2007 but client side merging is attempt as well */
2008 bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
2009 if (pdiff_merge == true)
2010 {
2011 // reprepro adds this flag if it has merged patches on the server
2012 std::string const precedence = Tags.FindS("X-Patch-Precedence");
2013 pdiff_merge = (precedence != "merged");
2014 }
2015
2016 if (pdiff_merge == false)
2017 new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
2018 else
2019 {
2020 diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
2021 for(size_t i = 0; i < available_patches.size(); ++i)
2022 (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
2023 Target,
2024 available_patches[i],
2025 diffs);
2026 }
2027
2028 Complete = false;
2029 Status = StatDone;
2030 Dequeue();
2031 return true;
2032 }
2033 /*}}}*/
2034 void pkgAcqDiffIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
2035 {
2036 Item::Failed(Message,Cnf);
2037 Status = StatDone;
2038
2039 if(Debug)
2040 std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
2041 << "Falling back to normal index file acquire" << std::endl;
2042
2043 new pkgAcqIndex(Owner, TransactionManager, Target);
2044 }
2045 /*}}}*/
2046 void pkgAcqDiffIndex::Done(string const &Message,HashStringList const &Hashes, /*{{{*/
2047 pkgAcquire::MethodConfig const * const Cnf)
2048 {
2049 if(Debug)
2050 std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
2051
2052 Item::Done(Message, Hashes, Cnf);
2053
2054 string const FinalFile = GetFinalFilename();
2055 if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
2056 DestFile = FinalFile;
2057
2058 if(ParseDiffIndex(DestFile) == false)
2059 {
2060 Failed("Message: Couldn't parse pdiff index", Cnf);
2061 // queue for final move - this should happen even if we fail
2062 // while parsing (e.g. on sizelimit) and download the complete file.
2063 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
2064 return;
2065 }
2066
2067 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
2068
2069 Complete = true;
2070 Status = StatDone;
2071 Dequeue();
2072
2073 return;
2074 }
2075 /*}}}*/
2076 pkgAcqDiffIndex::~pkgAcqDiffIndex()
2077 {
2078 if (diffs != NULL)
2079 delete diffs;
2080 }
2081
2082 // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
2083 // ---------------------------------------------------------------------
2084 /* The package diff is added to the queue. one object is constructed
2085 * for each diff and the index
2086 */
2087 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire * const Owner,
2088 pkgAcqMetaClearSig * const TransactionManager,
2089 IndexTarget const &Target,
2090 vector<DiffInfo> const &diffs)
2091 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
2092 available_patches(diffs)
2093 {
2094 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2095
2096 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
2097
2098 Desc.Owner = this;
2099 Description = Target.Description;
2100 Desc.ShortDesc = Target.ShortDesc;
2101
2102 if(available_patches.empty() == true)
2103 {
2104 // we are done (yeah!), check hashes against the final file
2105 DestFile = GetKeepCompressedFileName(GetFinalFileNameFromURI(Target.URI), Target);
2106 Finish(true);
2107 }
2108 else
2109 {
2110 if (BootstrapPDiffWith(GetPartialFileNameFromURI(Target.URI), GetFinalFilename(), Target) == false)
2111 {
2112 Failed("Bootstrapping of " + DestFile + " failed", NULL);
2113 return;
2114 }
2115
2116 // get the next diff
2117 State = StateFetchDiff;
2118 QueueNextDiff();
2119 }
2120 }
2121 /*}}}*/
2122 void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
2123 {
2124 Item::Failed(Message,Cnf);
2125 Status = StatDone;
2126
2127 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2128 if(Debug)
2129 std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
2130 << "Falling back to normal index file acquire " << std::endl;
2131 RenameOnError(PDiffError);
2132 std::string const patchname = GetDiffsPatchFileName(DestFile);
2133 if (RealFileExists(patchname))
2134 rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
2135 new pkgAcqIndex(Owner, TransactionManager, Target);
2136 Finish();
2137 }
2138 /*}}}*/
2139 // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
2140 void pkgAcqIndexDiffs::Finish(bool allDone)
2141 {
2142 if(Debug)
2143 std::clog << "pkgAcqIndexDiffs::Finish(): "
2144 << allDone << " "
2145 << Desc.URI << std::endl;
2146
2147 // we restore the original name, this is required, otherwise
2148 // the file will be cleaned
2149 if(allDone)
2150 {
2151 std::string Final = GetFinalFilename();
2152 if (Target.KeepCompressed)
2153 {
2154 std::string const ext = flExtension(DestFile);
2155 if (ext.empty() == false)
2156 Final.append(".").append(ext);
2157 }
2158 TransactionManager->TransactionStageCopy(this, DestFile, Final);
2159
2160 // this is for the "real" finish
2161 Complete = true;
2162 Status = StatDone;
2163 Dequeue();
2164 if(Debug)
2165 std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
2166 return;
2167 }
2168 else
2169 DestFile.clear();
2170
2171 if(Debug)
2172 std::clog << "Finishing: " << Desc.URI << std::endl;
2173 Complete = false;
2174 Status = StatDone;
2175 Dequeue();
2176 return;
2177 }
2178 /*}}}*/
2179 bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
2180 {
2181 // calc sha1 of the just patched file
2182 std::string const FinalFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2183 if(!FileExists(FinalFile))
2184 {
2185 Failed("Message: No FinalFile " + FinalFile + " available", NULL);
2186 return false;
2187 }
2188
2189 FileFd fd(FinalFile, FileFd::ReadOnly, FileFd::Extension);
2190 Hashes LocalHashesCalc;
2191 LocalHashesCalc.AddFD(fd);
2192 HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
2193
2194 if(Debug)
2195 std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
2196
2197 HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
2198 if (unlikely(LocalHashes.usable() == false || TargetFileHashes.usable() == false))
2199 {
2200 Failed("Local/Expected hashes are not usable", NULL);
2201 return false;
2202 }
2203
2204
2205 // final file reached before all patches are applied
2206 if(LocalHashes == TargetFileHashes)
2207 {
2208 Finish(true);
2209 return true;
2210 }
2211
2212 // remove all patches until the next matching patch is found
2213 // this requires the Index file to be ordered
2214 for(vector<DiffInfo>::iterator I = available_patches.begin();
2215 available_patches.empty() == false &&
2216 I != available_patches.end() &&
2217 I->result_hashes != LocalHashes;
2218 ++I)
2219 {
2220 available_patches.erase(I);
2221 }
2222
2223 // error checking and falling back if no patch was found
2224 if(available_patches.empty() == true)
2225 {
2226 Failed("No patches left to reach target", NULL);
2227 return false;
2228 }
2229
2230 // queue the right diff
2231 Desc.URI = Target.URI + ".diff/" + available_patches[0].file + ".gz";
2232 Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
2233 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI + ".diff/" + available_patches[0].file), Target);
2234
2235 if(Debug)
2236 std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
2237
2238 QueueURI(Desc);
2239
2240 return true;
2241 }
2242 /*}}}*/
2243 void pkgAcqIndexDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
2244 pkgAcquire::MethodConfig const * const Cnf)
2245 {
2246 if(Debug)
2247 std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
2248
2249 Item::Done(Message, Hashes, Cnf);
2250
2251 std::string const FinalFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2252 std::string const PatchFile = GetDiffsPatchFileName(FinalFile);
2253
2254 // success in downloading a diff, enter ApplyDiff state
2255 if(State == StateFetchDiff)
2256 {
2257 Rename(DestFile, PatchFile);
2258
2259 if(Debug)
2260 std::clog << "Sending to rred method: " << FinalFile << std::endl;
2261
2262 State = StateApplyDiff;
2263 Local = true;
2264 Desc.URI = "rred:" + FinalFile;
2265 QueueURI(Desc);
2266 SetActiveSubprocess("rred");
2267 return;
2268 }
2269
2270 // success in download/apply a diff, queue next (if needed)
2271 if(State == StateApplyDiff)
2272 {
2273 // remove the just applied patch
2274 available_patches.erase(available_patches.begin());
2275 unlink(PatchFile.c_str());
2276
2277 // move into place
2278 if(Debug)
2279 {
2280 std::clog << "Moving patched file in place: " << std::endl
2281 << DestFile << " -> " << FinalFile << std::endl;
2282 }
2283 Rename(DestFile,FinalFile);
2284 chmod(FinalFile.c_str(),0644);
2285
2286 // see if there is more to download
2287 if(available_patches.empty() == false) {
2288 new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
2289 available_patches);
2290 return Finish();
2291 } else
2292 // update
2293 DestFile = FinalFile;
2294 return Finish(true);
2295 }
2296 }
2297 /*}}}*/
2298 std::string pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
2299 {
2300 if(State != StateApplyDiff)
2301 return pkgAcqBaseIndex::Custom600Headers();
2302 std::ostringstream patchhashes;
2303 HashStringList const ExpectedHashes = available_patches[0].patch_hashes;
2304 for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
2305 patchhashes << "\nPatch-0-" << hs->HashType() << "-Hash: " << hs->HashValue();
2306 patchhashes << pkgAcqBaseIndex::Custom600Headers();
2307 return patchhashes.str();
2308 }
2309 /*}}}*/
2310 pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
2311
2312 // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
2313 pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire * const Owner,
2314 pkgAcqMetaClearSig * const TransactionManager,
2315 IndexTarget const &Target,
2316 DiffInfo const &patch,
2317 std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
2318 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
2319 patch(patch), allPatches(allPatches), State(StateFetchDiff)
2320 {
2321 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
2322
2323 Desc.Owner = this;
2324 Description = Target.Description;
2325 Desc.ShortDesc = Target.ShortDesc;
2326
2327 Desc.URI = Target.URI + ".diff/" + patch.file + ".gz";
2328 Desc.Description = Description + " " + patch.file + string(".pdiff");
2329
2330 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI + ".diff/" + patch.file), Target);
2331
2332 if(Debug)
2333 std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
2334
2335 QueueURI(Desc);
2336 }
2337 /*}}}*/
2338 void pkgAcqIndexMergeDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
2339 {
2340 if(Debug)
2341 std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
2342
2343 Item::Failed(Message,Cnf);
2344 Status = StatDone;
2345
2346 // check if we are the first to fail, otherwise we are done here
2347 State = StateDoneDiff;
2348 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2349 I != allPatches->end(); ++I)
2350 if ((*I)->State == StateErrorDiff)
2351 return;
2352
2353 // first failure means we should fallback
2354 State = StateErrorDiff;
2355 if (Debug)
2356 std::clog << "Falling back to normal index file acquire" << std::endl;
2357 DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2358 RenameOnError(PDiffError);
2359 std::string const patchname = GetMergeDiffsPatchFileName(DestFile, patch.file);
2360 if (RealFileExists(patchname))
2361 rename(patchname.c_str(), std::string(patchname + ".FAILED").c_str());
2362 new pkgAcqIndex(Owner, TransactionManager, Target);
2363 DestFile.clear();
2364 }
2365 /*}}}*/
2366 void pkgAcqIndexMergeDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
2367 pkgAcquire::MethodConfig const * const Cnf)
2368 {
2369 if(Debug)
2370 std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
2371
2372 Item::Done(Message, Hashes, Cnf);
2373
2374 std::string const UncompressedFinalFile = GetPartialFileNameFromURI(Target.URI);
2375 std::string const FinalFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2376 if (State == StateFetchDiff)
2377 {
2378 Rename(DestFile, GetMergeDiffsPatchFileName(FinalFile, patch.file));
2379
2380 // check if this is the last completed diff
2381 State = StateDoneDiff;
2382 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2383 I != allPatches->end(); ++I)
2384 if ((*I)->State != StateDoneDiff)
2385 {
2386 if(Debug)
2387 std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
2388 return;
2389 }
2390
2391 // this is the last completed diff, so we are ready to apply now
2392 State = StateApplyDiff;
2393
2394 if (BootstrapPDiffWith(UncompressedFinalFile, GetFinalFilename(), Target) == false)
2395 {
2396 Failed("Bootstrapping of " + DestFile + " failed", NULL);
2397 return;
2398 }
2399
2400 if(Debug)
2401 std::clog << "Sending to rred method: " << FinalFile << std::endl;
2402
2403 Local = true;
2404 Desc.URI = "rred:" + FinalFile;
2405 QueueURI(Desc);
2406 SetActiveSubprocess("rred");
2407 return;
2408 }
2409 // success in download/apply all diffs, clean up
2410 else if (State == StateApplyDiff)
2411 {
2412 // move the result into place
2413 std::string const Final = GetKeepCompressedFileName(GetFinalFilename(), Target);
2414 if(Debug)
2415 std::clog << "Queue patched file in place: " << std::endl
2416 << DestFile << " -> " << Final << std::endl;
2417
2418 // queue for copy by the transaction manager
2419 TransactionManager->TransactionStageCopy(this, DestFile, Final);
2420
2421 // ensure the ed's are gone regardless of list-cleanup
2422 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2423 I != allPatches->end(); ++I)
2424 {
2425 std::string const PartialFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
2426 std::string const patch = GetMergeDiffsPatchFileName(PartialFile, (*I)->patch.file);
2427 unlink(patch.c_str());
2428 }
2429 unlink(FinalFile.c_str());
2430
2431 // all set and done
2432 Complete = true;
2433 if(Debug)
2434 std::clog << "allDone: " << DestFile << "\n" << std::endl;
2435 }
2436 }
2437 /*}}}*/
2438 std::string pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
2439 {
2440 if(State != StateApplyDiff)
2441 return pkgAcqBaseIndex::Custom600Headers();
2442 std::ostringstream patchhashes;
2443 unsigned int seen_patches = 0;
2444 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
2445 I != allPatches->end(); ++I)
2446 {
2447 HashStringList const ExpectedHashes = (*I)->patch.patch_hashes;
2448 for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
2449 patchhashes << "\nPatch-" << seen_patches << "-" << hs->HashType() << "-Hash: " << hs->HashValue();
2450 ++seen_patches;
2451 }
2452 patchhashes << pkgAcqBaseIndex::Custom600Headers();
2453 return patchhashes.str();
2454 }
2455 /*}}}*/
2456 pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
2457
2458 // AcqIndex::AcqIndex - Constructor /*{{{*/
2459 pkgAcqIndex::pkgAcqIndex(pkgAcquire * const Owner,
2460 pkgAcqMetaClearSig * const TransactionManager,
2461 IndexTarget const &Target)
2462 : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), Stage(STAGE_DOWNLOAD),
2463 CompressionExtensions(Target.Option(IndexTarget::COMPRESSIONTYPES))
2464 {
2465 Init(Target.URI, Target.Description, Target.ShortDesc);
2466
2467 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
2468 std::clog << "New pkgIndex with TransactionManager "
2469 << TransactionManager << std::endl;
2470 }
2471 /*}}}*/
2472 // AcqIndex::Init - defered Constructor /*{{{*/
2473 static void NextCompressionExtension(std::string &CurrentCompressionExtension, std::string &CompressionExtensions, bool const preview)
2474 {
2475 size_t const nextExt = CompressionExtensions.find(' ');
2476 if (nextExt == std::string::npos)
2477 {
2478 CurrentCompressionExtension = CompressionExtensions;
2479 if (preview == false)
2480 CompressionExtensions.clear();
2481 }
2482 else
2483 {
2484 CurrentCompressionExtension = CompressionExtensions.substr(0, nextExt);
2485 if (preview == false)
2486 CompressionExtensions = CompressionExtensions.substr(nextExt+1);
2487 }
2488 }
2489 void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
2490 string const &ShortDesc)
2491 {
2492 Stage = STAGE_DOWNLOAD;
2493
2494 DestFile = GetPartialFileNameFromURI(URI);
2495 NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, false);
2496
2497 if (CurrentCompressionExtension == "uncompressed")
2498 {
2499 Desc.URI = URI;
2500 }
2501 else if (CurrentCompressionExtension == "by-hash")
2502 {
2503 NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, true);
2504 if(unlikely(TransactionManager->MetaIndexParser == NULL || CurrentCompressionExtension.empty()))
2505 return;
2506 if (CurrentCompressionExtension != "uncompressed")
2507 {
2508 Desc.URI = URI + '.' + CurrentCompressionExtension;
2509 DestFile = DestFile + '.' + CurrentCompressionExtension;
2510 }
2511
2512 HashStringList const Hashes = GetExpectedHashes();
2513 HashString const * const TargetHash = Hashes.find(NULL);
2514 if (unlikely(TargetHash == nullptr))
2515 return;
2516 std::string const ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
2517 size_t const trailing_slash = Desc.URI.find_last_of("/");
2518 if (unlikely(trailing_slash == std::string::npos))
2519 return;
2520 Desc.URI = Desc.URI.replace(
2521 trailing_slash,
2522 Desc.URI.substr(trailing_slash+1).size()+1,
2523 ByHash);
2524 }
2525 else if (unlikely(CurrentCompressionExtension.empty()))
2526 return;
2527 else
2528 {
2529 Desc.URI = URI + '.' + CurrentCompressionExtension;
2530 DestFile = DestFile + '.' + CurrentCompressionExtension;
2531 }
2532
2533
2534 Desc.Description = URIDesc;
2535 Desc.Owner = this;
2536 Desc.ShortDesc = ShortDesc;
2537
2538 QueueURI(Desc);
2539 }
2540 /*}}}*/
2541 // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2542 // ---------------------------------------------------------------------
2543 /* The only header we use is the last-modified header. */
2544 string pkgAcqIndex::Custom600Headers() const
2545 {
2546 string Final = GetFinalFilename();
2547
2548 string msg = "\nIndex-File: true";
2549 struct stat Buf;
2550 if (stat(Final.c_str(),&Buf) == 0)
2551 msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
2552
2553 if(Target.IsOptional)
2554 msg += "\nFail-Ignore: true";
2555
2556 return msg;
2557 }
2558 /*}}}*/
2559 // AcqIndex::Failed - getting the indexfile failed /*{{{*/
2560 void pkgAcqIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
2561 {
2562 Item::Failed(Message,Cnf);
2563
2564 // authorisation matches will not be fixed by other compression types
2565 if (Status != StatAuthError)
2566 {
2567 if (CompressionExtensions.empty() == false)
2568 {
2569 Init(Target.URI, Desc.Description, Desc.ShortDesc);
2570 Status = StatIdle;
2571 return;
2572 }
2573 }
2574
2575 if(Target.IsOptional && GetExpectedHashes().empty() && Stage == STAGE_DOWNLOAD)
2576 Status = StatDone;
2577 else
2578 TransactionManager->AbortTransaction();
2579 }
2580 /*}}}*/
2581 // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
2582 void pkgAcqIndex::ReverifyAfterIMS()
2583 {
2584 // update destfile to *not* include the compression extension when doing
2585 // a reverify (as its uncompressed on disk already)
2586 DestFile = GetCompressedFileName(Target, GetPartialFileNameFromURI(Target.URI), CurrentCompressionExtension);
2587
2588 // copy FinalFile into partial/ so that we check the hash again
2589 string FinalFile = GetFinalFilename();
2590 Stage = STAGE_DECOMPRESS_AND_VERIFY;
2591 Desc.URI = "copy:" + FinalFile;
2592 QueueURI(Desc);
2593 }
2594 /*}}}*/
2595 // AcqIndex::Done - Finished a fetch /*{{{*/
2596 // ---------------------------------------------------------------------
2597 /* This goes through a number of states.. On the initial fetch the
2598 method could possibly return an alternate filename which points
2599 to the uncompressed version of the file. If this is so the file
2600 is copied into the partial directory. In all other cases the file
2601 is decompressed with a compressed uri. */
2602 void pkgAcqIndex::Done(string const &Message,
2603 HashStringList const &Hashes,
2604 pkgAcquire::MethodConfig const * const Cfg)
2605 {
2606 Item::Done(Message,Hashes,Cfg);
2607
2608 switch(Stage)
2609 {
2610 case STAGE_DOWNLOAD:
2611 StageDownloadDone(Message, Hashes, Cfg);
2612 break;
2613 case STAGE_DECOMPRESS_AND_VERIFY:
2614 StageDecompressDone(Message, Hashes, Cfg);
2615 break;
2616 }
2617 }
2618 /*}}}*/
2619 // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
2620 void pkgAcqIndex::StageDownloadDone(string const &Message, HashStringList const &,
2621 pkgAcquire::MethodConfig const * const)
2622 {
2623 Complete = true;
2624
2625 // Handle the unzipd case
2626 std::string FileName = LookupTag(Message,"Alt-Filename");
2627 if (FileName.empty() == false)
2628 {
2629 Stage = STAGE_DECOMPRESS_AND_VERIFY;
2630 Local = true;
2631 DestFile += ".decomp";
2632 Desc.URI = "copy:" + FileName;
2633 QueueURI(Desc);
2634 SetActiveSubprocess("copy");
2635 return;
2636 }
2637 FileName = LookupTag(Message,"Filename");
2638
2639 // Methods like e.g. "file:" will give us a (compressed) FileName that is
2640 // not the "DestFile" we set, in this case we uncompress from the local file
2641 if (FileName != DestFile && RealFileExists(DestFile) == false)
2642 {
2643 Local = true;
2644 if (Target.KeepCompressed == true)
2645 {
2646 // but if we don't keep the uncompress we copy the compressed file first
2647 Stage = STAGE_DOWNLOAD;
2648 Desc.URI = "copy:" + FileName;
2649 QueueURI(Desc);
2650 SetActiveSubprocess("copy");
2651 return;
2652 }
2653 }
2654 else
2655 EraseFileName = FileName;
2656
2657 // we need to verify the file against the current Release file again
2658 // on if-modfied-since hit to avoid a stale attack against us
2659 if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
2660 {
2661 // The files timestamp matches, reverify by copy into partial/
2662 EraseFileName = "";
2663 ReverifyAfterIMS();
2664 return;
2665 }
2666
2667 // get the binary name for your used compression type
2668 string decompProg;
2669 if(CurrentCompressionExtension == "uncompressed")
2670 decompProg = "copy";
2671 else
2672 decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
2673 if(decompProg.empty() == true)
2674 {
2675 _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
2676 return;
2677 }
2678
2679 if (Target.KeepCompressed == true)
2680 {
2681 DestFile = "/dev/null";
2682 EraseFileName.clear();
2683 }
2684 else
2685 DestFile += ".decomp";
2686
2687 // queue uri for the next stage
2688 Stage = STAGE_DECOMPRESS_AND_VERIFY;
2689 Desc.URI = decompProg + ":" + FileName;
2690 QueueURI(Desc);
2691 SetActiveSubprocess(decompProg);
2692 }
2693 /*}}}*/
2694 // AcqIndex::StageDecompressDone - Final verification /*{{{*/
2695 void pkgAcqIndex::StageDecompressDone(string const &,
2696 HashStringList const &,
2697 pkgAcquire::MethodConfig const * const)
2698 {
2699 if (Target.KeepCompressed == true && DestFile == "/dev/null")
2700 DestFile = GetPartialFileNameFromURI(Target.URI + '.' + CurrentCompressionExtension);
2701
2702 // Done, queue for rename on transaction finished
2703 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
2704 return;
2705 }
2706 /*}}}*/
2707 pkgAcqIndex::~pkgAcqIndex() {}
2708
2709
2710 // AcqArchive::AcqArchive - Constructor /*{{{*/
2711 // ---------------------------------------------------------------------
2712 /* This just sets up the initial fetch environment and queues the first
2713 possibilitiy */
2714 pkgAcqArchive::pkgAcqArchive(pkgAcquire * const Owner,pkgSourceList * const Sources,
2715 pkgRecords * const Recs,pkgCache::VerIterator const &Version,
2716 string &StoreFilename) :
2717 Item(Owner), d(NULL), LocalSource(false), Version(Version), Sources(Sources), Recs(Recs),
2718 StoreFilename(StoreFilename), Vf(Version.FileList()),
2719 Trusted(false)
2720 {
2721 Retries = _config->FindI("Acquire::Retries",0);
2722
2723 if (Version.Arch() == 0)
2724 {
2725 _error->Error(_("I wasn't able to locate a file for the %s package. "
2726 "This might mean you need to manually fix this package. "
2727 "(due to missing arch)"),
2728 Version.ParentPkg().FullName().c_str());
2729 return;
2730 }
2731
2732 /* We need to find a filename to determine the extension. We make the
2733 assumption here that all the available sources for this version share
2734 the same extension.. */
2735 // Skip not source sources, they do not have file fields.
2736 for (; Vf.end() == false; ++Vf)
2737 {
2738 if (Vf.File().Flagged(pkgCache::Flag::NotSource))
2739 continue;
2740 break;
2741 }
2742
2743 // Does not really matter here.. we are going to fail out below
2744 if (Vf.end() != true)
2745 {
2746 // If this fails to get a file name we will bomb out below.
2747 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2748 if (_error->PendingError() == true)
2749 return;
2750
2751 // Generate the final file name as: package_version_arch.foo
2752 StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
2753 QuoteString(Version.VerStr(),"_:") + '_' +
2754 QuoteString(Version.Arch(),"_:.") +
2755 "." + flExtension(Parse.FileName());
2756 }
2757
2758 // check if we have one trusted source for the package. if so, switch
2759 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2760 bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
2761 bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
2762 bool seenUntrusted = false;
2763 for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
2764 {
2765 pkgIndexFile *Index;
2766 if (Sources->FindIndex(i.File(),Index) == false)
2767 continue;
2768
2769 if (debugAuth == true)
2770 std::cerr << "Checking index: " << Index->Describe()
2771 << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
2772
2773 if (Index->IsTrusted() == true)
2774 {
2775 Trusted = true;
2776 if (allowUnauth == false)
2777 break;
2778 }
2779 else
2780 seenUntrusted = true;
2781 }
2782
2783 // "allow-unauthenticated" restores apts old fetching behaviour
2784 // that means that e.g. unauthenticated file:// uris are higher
2785 // priority than authenticated http:// uris
2786 if (allowUnauth == true && seenUntrusted == true)
2787 Trusted = false;
2788
2789 // Select a source
2790 if (QueueNext() == false && _error->PendingError() == false)
2791 _error->Error(_("Can't find a source to download version '%s' of '%s'"),
2792 Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
2793 }
2794 /*}}}*/
2795 // AcqArchive::QueueNext - Queue the next file source /*{{{*/
2796 // ---------------------------------------------------------------------
2797 /* This queues the next available file version for download. It checks if
2798 the archive is already available in the cache and stashs the MD5 for
2799 checking later. */
2800 bool pkgAcqArchive::QueueNext()
2801 {
2802 for (; Vf.end() == false; ++Vf)
2803 {
2804 pkgCache::PkgFileIterator const PkgF = Vf.File();
2805 // Ignore not source sources
2806 if (PkgF.Flagged(pkgCache::Flag::NotSource))
2807 continue;
2808
2809 // Try to cross match against the source list
2810 pkgIndexFile *Index;
2811 if (Sources->FindIndex(PkgF, Index) == false)
2812 continue;
2813 LocalSource = PkgF.Flagged(pkgCache::Flag::LocalSource);
2814
2815 // only try to get a trusted package from another source if that source
2816 // is also trusted
2817 if(Trusted && !Index->IsTrusted())
2818 continue;
2819
2820 // Grab the text package record
2821 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2822 if (_error->PendingError() == true)
2823 return false;
2824
2825 string PkgFile = Parse.FileName();
2826 ExpectedHashes = Parse.Hashes();
2827
2828 if (PkgFile.empty() == true)
2829 return _error->Error(_("The package index files are corrupted. No Filename: "
2830 "field for package %s."),
2831 Version.ParentPkg().Name());
2832
2833 Desc.URI = Index->ArchiveURI(PkgFile);
2834 Desc.Description = Index->ArchiveInfo(Version);
2835 Desc.Owner = this;
2836 Desc.ShortDesc = Version.ParentPkg().FullName(true);
2837
2838 // See if we already have the file. (Legacy filenames)
2839 FileSize = Version->Size;
2840 string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
2841 struct stat Buf;
2842 if (stat(FinalFile.c_str(),&Buf) == 0)
2843 {
2844 // Make sure the size matches
2845 if ((unsigned long long)Buf.st_size == Version->Size)
2846 {
2847 Complete = true;
2848 Local = true;
2849 Status = StatDone;
2850 StoreFilename = DestFile = FinalFile;
2851 return true;
2852 }
2853
2854 /* Hmm, we have a file and its size does not match, this means it is
2855 an old style mismatched arch */
2856 unlink(FinalFile.c_str());
2857 }
2858
2859 // Check it again using the new style output filenames
2860 FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
2861 if (stat(FinalFile.c_str(),&Buf) == 0)
2862 {
2863 // Make sure the size matches
2864 if ((unsigned long long)Buf.st_size == Version->Size)
2865 {
2866 Complete = true;
2867 Local = true;
2868 Status = StatDone;
2869 StoreFilename = DestFile = FinalFile;
2870 return true;
2871 }
2872
2873 /* Hmm, we have a file and its size does not match, this shouldn't
2874 happen.. */
2875 unlink(FinalFile.c_str());
2876 }
2877
2878 DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
2879
2880 // Check the destination file
2881 if (stat(DestFile.c_str(),&Buf) == 0)
2882 {
2883 // Hmm, the partial file is too big, erase it
2884 if ((unsigned long long)Buf.st_size > Version->Size)
2885 unlink(DestFile.c_str());
2886 else
2887 PartialSize = Buf.st_size;
2888 }
2889
2890 // Disables download of archives - useful if no real installation follows,
2891 // e.g. if we are just interested in proposed installation order
2892 if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2893 {
2894 Complete = true;
2895 Local = true;
2896 Status = StatDone;
2897 StoreFilename = DestFile = FinalFile;
2898 return true;
2899 }
2900
2901 // Create the item
2902 Local = false;
2903 QueueURI(Desc);
2904
2905 ++Vf;
2906 return true;
2907 }
2908 return false;
2909 }
2910 /*}}}*/
2911 // AcqArchive::Done - Finished fetching /*{{{*/
2912 // ---------------------------------------------------------------------
2913 /* */
2914 void pkgAcqArchive::Done(string const &Message, HashStringList const &Hashes,
2915 pkgAcquire::MethodConfig const * const Cfg)
2916 {
2917 Item::Done(Message, Hashes, Cfg);
2918
2919 // Grab the output filename
2920 std::string const FileName = LookupTag(Message,"Filename");
2921 if (DestFile != FileName && RealFileExists(DestFile) == false)
2922 {
2923 StoreFilename = DestFile = FileName;
2924 Local = true;
2925 Complete = true;
2926 return;
2927 }
2928
2929 // Done, move it into position
2930 string const FinalFile = GetFinalFilename();
2931 Rename(DestFile,FinalFile);
2932 StoreFilename = DestFile = FinalFile;
2933 Complete = true;
2934 }
2935 /*}}}*/
2936 // AcqArchive::Failed - Failure handler /*{{{*/
2937 // ---------------------------------------------------------------------
2938 /* Here we try other sources */
2939 void pkgAcqArchive::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
2940 {
2941 Item::Failed(Message,Cnf);
2942
2943 /* We don't really want to retry on failed media swaps, this prevents
2944 that. An interesting observation is that permanent failures are not
2945 recorded. */
2946 if (Cnf->Removable == true &&
2947 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2948 {
2949 // Vf = Version.FileList();
2950 while (Vf.end() == false) ++Vf;
2951 StoreFilename = string();
2952 return;
2953 }
2954
2955 Status = StatIdle;
2956 if (QueueNext() == false)
2957 {
2958 // This is the retry counter
2959 if (Retries != 0 &&
2960 Cnf->LocalOnly == false &&
2961 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2962 {
2963 Retries--;
2964 Vf = Version.FileList();
2965 if (QueueNext() == true)
2966 return;
2967 }
2968
2969 StoreFilename = string();
2970 Status = StatError;
2971 }
2972 }
2973 /*}}}*/
2974 APT_PURE bool pkgAcqArchive::IsTrusted() const /*{{{*/
2975 {
2976 return Trusted;
2977 }
2978 /*}}}*/
2979 void pkgAcqArchive::Finished() /*{{{*/
2980 {
2981 if (Status == pkgAcquire::Item::StatDone &&
2982 Complete == true)
2983 return;
2984 StoreFilename = string();
2985 }
2986 /*}}}*/
2987 std::string pkgAcqArchive::DescURI() const /*{{{*/
2988 {
2989 return Desc.URI;
2990 }
2991 /*}}}*/
2992 std::string pkgAcqArchive::ShortDesc() const /*{{{*/
2993 {
2994 return Desc.ShortDesc;
2995 }
2996 /*}}}*/
2997 pkgAcqArchive::~pkgAcqArchive() {}
2998
2999 // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
3000 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::VerIterator const &Ver,
3001 std::string const &DestDir, std::string const &DestFilename) :
3002 pkgAcquire::Item(Owner), d(NULL), SrcName(Ver.SourcePkgName()), SrcVersion(Ver.SourceVerStr())
3003 {
3004 Desc.URI = URI(Ver);
3005 Init(DestDir, DestFilename);
3006 }
3007 // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
3008 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::RlsFileIterator const &RlsFile,
3009 char const * const Component, char const * const SrcName, char const * const SrcVersion,
3010 const string &DestDir, const string &DestFilename) :
3011 pkgAcquire::Item(Owner), d(NULL), SrcName(SrcName), SrcVersion(SrcVersion)
3012 {
3013 Desc.URI = URI(RlsFile, Component, SrcName, SrcVersion);
3014 Init(DestDir, DestFilename);
3015 }
3016 pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner,
3017 std::string const &URI, char const * const SrcName, char const * const SrcVersion,
3018 const string &DestDir, const string &DestFilename) :
3019 pkgAcquire::Item(Owner), d(NULL), SrcName(SrcName), SrcVersion(SrcVersion)
3020 {
3021 Desc.URI = URI;
3022 Init(DestDir, DestFilename);
3023 }
3024 void pkgAcqChangelog::Init(std::string const &DestDir, std::string const &DestFilename)
3025 {
3026 if (Desc.URI.empty())
3027 {
3028 Status = StatError;
3029 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3030 strprintf(ErrorText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
3031 // Let the error message print something sensible rather than "Failed to fetch /"
3032 if (DestFilename.empty())
3033 DestFile = SrcName + ".changelog";
3034 else
3035 DestFile = DestFilename;
3036 Desc.URI = "changelog:/" + DestFile;
3037 return;
3038 }
3039
3040 if (DestDir.empty())
3041 {
3042 std::string const SandboxUser = _config->Find("APT::Sandbox::User");
3043 std::string const systemTemp = GetTempDir(SandboxUser);
3044 char tmpname[100];
3045 snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX", systemTemp.c_str());
3046 if (NULL == mkdtemp(tmpname))
3047 {
3048 _error->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName.c_str(), SrcVersion.c_str());
3049 Status = StatError;
3050 return;
3051 }
3052 DestFile = TemporaryDirectory = tmpname;
3053
3054 ChangeOwnerAndPermissionOfFile("Item::QueueURI", DestFile.c_str(),
3055 SandboxUser.c_str(), "root", 0700);
3056 }
3057 else
3058 DestFile = DestDir;
3059
3060 if (DestFilename.empty())
3061 DestFile = flCombine(DestFile, SrcName + ".changelog");
3062 else
3063 DestFile = flCombine(DestFile, DestFilename);
3064
3065 Desc.ShortDesc = "Changelog";
3066 strprintf(Desc.Description, "%s %s %s Changelog", URI::SiteOnly(Desc.URI).c_str(), SrcName.c_str(), SrcVersion.c_str());
3067 Desc.Owner = this;
3068 QueueURI(Desc);
3069 }
3070 /*}}}*/
3071 std::string pkgAcqChangelog::URI(pkgCache::VerIterator const &Ver) /*{{{*/
3072 {
3073 char const * const SrcName = Ver.SourcePkgName();
3074 char const * const SrcVersion = Ver.SourceVerStr();
3075 pkgCache::PkgFileIterator PkgFile;
3076 // find the first source for this version which promises a changelog
3077 for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
3078 {
3079 pkgCache::PkgFileIterator const PF = VF.File();
3080 if (PF.Flagged(pkgCache::Flag::NotSource) || PF->Release == 0)
3081 continue;
3082 PkgFile = PF;
3083 pkgCache::RlsFileIterator const RF = PF.ReleaseFile();
3084 std::string const uri = URI(RF, PF.Component(), SrcName, SrcVersion);
3085 if (uri.empty())
3086 continue;
3087 return uri;
3088 }
3089 return "";
3090 }
3091 std::string pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator const &Rls)
3092 {
3093 if (Rls.end() == true || (Rls->Label == 0 && Rls->Origin == 0))
3094 return "";
3095 std::string const serverConfig = "Acquire::Changelogs::URI";
3096 std::string server;
3097 #define APT_EMPTY_SERVER \
3098 if (server.empty() == false) \
3099 { \
3100 if (server != "no") \
3101 return server; \
3102 return ""; \
3103 }
3104 #define APT_CHECK_SERVER(X, Y) \
3105 if (Rls->X != 0) \
3106 { \
3107 std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
3108 server = _config->Find(specialServerConfig); \
3109 APT_EMPTY_SERVER \
3110 }
3111 // this way e.g. Debian-Security can fallback to Debian
3112 APT_CHECK_SERVER(Label, "Override::")
3113 APT_CHECK_SERVER(Origin, "Override::")
3114
3115 if (RealFileExists(Rls.FileName()))
3116 {
3117 _error->PushToStack();
3118 FileFd rf;
3119 /* This can be costly. A caller wanting to get millions of URIs might
3120 want to do this on its own once and use Override settings.
3121 We don't do this here as Origin/Label are not as unique as they
3122 should be so this could produce request order-dependent anomalies */
3123 if (OpenMaybeClearSignedFile(Rls.FileName(), rf) == true)
3124 {
3125 pkgTagFile TagFile(&rf, rf.Size());
3126 pkgTagSection Section;
3127 if (TagFile.Step(Section) == true)
3128 server = Section.FindS("Changelogs");
3129 }
3130 _error->RevertToStack();
3131 APT_EMPTY_SERVER
3132 }
3133
3134 APT_CHECK_SERVER(Label, "")
3135 APT_CHECK_SERVER(Origin, "")
3136 #undef APT_CHECK_SERVER
3137 #undef APT_EMPTY_SERVER
3138 return "";
3139 }
3140 std::string pkgAcqChangelog::URI(pkgCache::RlsFileIterator const &Rls,
3141 char const * const Component, char const * const SrcName,
3142 char const * const SrcVersion)
3143 {
3144 return URI(URITemplate(Rls), Component, SrcName, SrcVersion);
3145 }
3146 std::string pkgAcqChangelog::URI(std::string const &Template,
3147 char const * const Component, char const * const SrcName,
3148 char const * const SrcVersion)
3149 {
3150 if (Template.find("CHANGEPATH") == std::string::npos)
3151 return "";
3152
3153 // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
3154 std::string Src = SrcName;
3155 std::string path = APT::String::Startswith(SrcName, "lib") ? Src.substr(0, 4) : Src.substr(0,1);
3156 path.append("/").append(Src).append("/");
3157 path.append(Src).append("_").append(StripEpoch(SrcVersion));
3158 // we omit component for releases without one (= flat-style repositories)
3159 if (Component != NULL && strlen(Component) != 0)
3160 path = std::string(Component) + "/" + path;
3161
3162 return SubstVar(Template, "CHANGEPATH", path);
3163 }
3164 /*}}}*/
3165 // AcqChangelog::Failed - Failure handler /*{{{*/
3166 void pkgAcqChangelog::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
3167 {
3168 Item::Failed(Message,Cnf);
3169
3170 std::string errText;
3171 // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
3172 strprintf(errText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
3173
3174 // Error is probably something techy like 404 Not Found
3175 if (ErrorText.empty())
3176 ErrorText = errText;
3177 else
3178 ErrorText = errText + " (" + ErrorText + ")";
3179 return;
3180 }
3181 /*}}}*/
3182 // AcqChangelog::Done - Item downloaded OK /*{{{*/
3183 void pkgAcqChangelog::Done(string const &Message,HashStringList const &CalcHashes,
3184 pkgAcquire::MethodConfig const * const Cnf)
3185 {
3186 Item::Done(Message,CalcHashes,Cnf);
3187
3188 Complete = true;
3189 }
3190 /*}}}*/
3191 pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
3192 {
3193 if (TemporaryDirectory.empty() == false)
3194 {
3195 unlink(DestFile.c_str());
3196 rmdir(TemporaryDirectory.c_str());
3197 }
3198 }
3199 /*}}}*/
3200
3201 // AcqFile::pkgAcqFile - Constructor /*{{{*/
3202 pkgAcqFile::pkgAcqFile(pkgAcquire * const Owner,string const &URI, HashStringList const &Hashes,
3203 unsigned long long const Size,string const &Dsc,string const &ShortDesc,
3204 const string &DestDir, const string &DestFilename,
3205 bool const IsIndexFile) :
3206 Item(Owner), d(NULL), IsIndexFile(IsIndexFile), ExpectedHashes(Hashes)
3207 {
3208 Retries = _config->FindI("Acquire::Retries",0);
3209
3210 if(!DestFilename.empty())
3211 DestFile = DestFilename;
3212 else if(!DestDir.empty())
3213 DestFile = DestDir + "/" + flNotDir(URI);
3214 else
3215 DestFile = flNotDir(URI);
3216
3217 // Create the item
3218 Desc.URI = URI;
3219 Desc.Description = Dsc;
3220 Desc.Owner = this;
3221
3222 // Set the short description to the archive component
3223 Desc.ShortDesc = ShortDesc;
3224
3225 // Get the transfer sizes
3226 FileSize = Size;
3227 struct stat Buf;
3228 if (stat(DestFile.c_str(),&Buf) == 0)
3229 {
3230 // Hmm, the partial file is too big, erase it
3231 if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
3232 unlink(DestFile.c_str());
3233 else
3234 PartialSize = Buf.st_size;
3235 }
3236
3237 QueueURI(Desc);
3238 }
3239 /*}}}*/
3240 // AcqFile::Done - Item downloaded OK /*{{{*/
3241 void pkgAcqFile::Done(string const &Message,HashStringList const &CalcHashes,
3242 pkgAcquire::MethodConfig const * const Cnf)
3243 {
3244 Item::Done(Message,CalcHashes,Cnf);
3245
3246 std::string const FileName = LookupTag(Message,"Filename");
3247 Complete = true;
3248
3249 // The files timestamp matches
3250 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
3251 return;
3252
3253 // We have to copy it into place
3254 if (RealFileExists(DestFile.c_str()) == false)
3255 {
3256 Local = true;
3257 if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
3258 Cnf->Removable == true)
3259 {
3260 Desc.URI = "copy:" + FileName;
3261 QueueURI(Desc);
3262 return;
3263 }
3264
3265 // Erase the file if it is a symlink so we can overwrite it
3266 struct stat St;
3267 if (lstat(DestFile.c_str(),&St) == 0)
3268 {
3269 if (S_ISLNK(St.st_mode) != 0)
3270 unlink(DestFile.c_str());
3271 }
3272
3273 // Symlink the file
3274 if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
3275 {
3276 _error->PushToStack();
3277 _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
3278 std::stringstream msg;
3279 _error->DumpErrors(msg, GlobalError::DEBUG, false);
3280 _error->RevertToStack();
3281 ErrorText = msg.str();
3282 Status = StatError;
3283 Complete = false;
3284 }
3285 }
3286 }
3287 /*}}}*/
3288 // AcqFile::Failed - Failure handler /*{{{*/
3289 // ---------------------------------------------------------------------
3290 /* Here we try other sources */
3291 void pkgAcqFile::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
3292 {
3293 Item::Failed(Message,Cnf);
3294
3295 // This is the retry counter
3296 if (Retries != 0 &&
3297 Cnf->LocalOnly == false &&
3298 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
3299 {
3300 --Retries;
3301 QueueURI(Desc);
3302 Status = StatIdle;
3303 return;
3304 }
3305
3306 }
3307 /*}}}*/
3308 string pkgAcqFile::Custom600Headers() const /*{{{*/
3309 {
3310 if (IsIndexFile)
3311 return "\nIndex-File: true";
3312 return "";
3313 }
3314 /*}}}*/
3315 pkgAcqFile::~pkgAcqFile() {}