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