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