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