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