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