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