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