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