]> git.saurik.com Git - apt.git/blame_incremental - apt-pkg/acquire-item.cc
add gzip test and todo
[apt.git] / apt-pkg / acquire-item.cc
... / ...
CommitLineData
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
51using namespace std;
52
53static 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 /*{{{*/
67pkgAcquire::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/* */
81pkgAcquire::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 */
90void 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 */
125void 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/* */
135void 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 */
158void 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 /*}}}*/
170bool 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// ---------------------------------------------------------------------
198void 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 */
244pkgAcqSubIndex::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. */
271string 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 /*}}}*/
282void 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 /*}}}*/
294void 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 /*}}}*/
345bool 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 */
361pkgAcqDiffIndex::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. */
412string 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 /*}}}*/
427bool 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 /*}}}*/
585void 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 /*}}}*/
598void 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 */
633pkgAcqIndexDiffs::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 /*}}}*/
667void 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 /*{{{*/
677void pkgAcqIndexDiffs::Finish(bool allDone)
678{
679 // we restore the original name, this is required, otherwise
680 // the file will be cleaned
681 if(allDone)
682 {
683 DestFile = _config->FindDir("Dir::State::lists");
684 DestFile += URItoFileName(RealURI);
685
686 if(HashSums().usable() && !HashSums().VerifyFile(DestFile))
687 {
688 RenameOnError(HashSumMismatch);
689 Dequeue();
690 return;
691 }
692
693 // this is for the "real" finish
694 Complete = true;
695 Status = StatDone;
696 Dequeue();
697 if(Debug)
698 std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
699 return;
700 }
701
702 if(Debug)
703 std::clog << "Finishing: " << Desc.URI << std::endl;
704 Complete = false;
705 Status = StatDone;
706 Dequeue();
707 return;
708}
709 /*}}}*/
710bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
711{
712
713 // calc sha1 of the just patched file
714 string FinalFile = _config->FindDir("Dir::State::lists");
715 FinalFile += URItoFileName(RealURI);
716
717 FileFd fd(FinalFile, FileFd::ReadOnly);
718 SHA1Summation SHA1;
719 SHA1.AddFD(fd);
720 string local_sha1 = string(SHA1.Result());
721 if(Debug)
722 std::clog << "QueueNextDiff: "
723 << FinalFile << " (" << local_sha1 << ")"<<std::endl;
724
725 // final file reached before all patches are applied
726 if(local_sha1 == ServerSha1)
727 {
728 Finish(true);
729 return true;
730 }
731
732 // remove all patches until the next matching patch is found
733 // this requires the Index file to be ordered
734 for(vector<DiffInfo>::iterator I=available_patches.begin();
735 available_patches.empty() == false &&
736 I != available_patches.end() &&
737 I->sha1 != local_sha1;
738 ++I)
739 {
740 available_patches.erase(I);
741 }
742
743 // error checking and falling back if no patch was found
744 if(available_patches.empty() == true)
745 {
746 Failed("", NULL);
747 return false;
748 }
749
750 // queue the right diff
751 Desc.URI = RealURI + ".diff/" + available_patches[0].file + ".gz";
752 Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
753 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
754 DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
755
756 if(Debug)
757 std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
758
759 QueueURI(Desc);
760
761 return true;
762}
763 /*}}}*/
764void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size, HashStringList const &Hashes, /*{{{*/
765 pkgAcquire::MethodConfig *Cnf)
766{
767 if(Debug)
768 std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
769
770 Item::Done(Message, Size, Hashes, Cnf);
771
772 string FinalFile;
773 FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
774
775 // success in downloading a diff, enter ApplyDiff state
776 if(State == StateFetchDiff)
777 {
778
779 // rred excepts the patch as $FinalFile.ed
780 Rename(DestFile,FinalFile+".ed");
781
782 if(Debug)
783 std::clog << "Sending to rred method: " << FinalFile << std::endl;
784
785 State = StateApplyDiff;
786 Local = true;
787 Desc.URI = "rred:" + FinalFile;
788 QueueURI(Desc);
789 Mode = "rred";
790 return;
791 }
792
793
794 // success in download/apply a diff, queue next (if needed)
795 if(State == StateApplyDiff)
796 {
797 // remove the just applied patch
798 available_patches.erase(available_patches.begin());
799 unlink((FinalFile + ".ed").c_str());
800
801 // move into place
802 if(Debug)
803 {
804 std::clog << "Moving patched file in place: " << std::endl
805 << DestFile << " -> " << FinalFile << std::endl;
806 }
807 Rename(DestFile,FinalFile);
808 chmod(FinalFile.c_str(),0644);
809
810 // see if there is more to download
811 if(available_patches.empty() == false) {
812 new pkgAcqIndexDiffs(Owner, TransactionID, Target,
813 ExpectedHashes, MetaIndexParser,
814 ServerSha1, available_patches);
815 return Finish();
816 } else
817 return Finish(true);
818 }
819}
820 /*}}}*/
821// AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
822pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
823 unsigned long TransactionID,
824 struct IndexTarget const * const Target,
825 HashStringList const &ExpectedHashes,
826 indexRecords *MetaIndexParser,
827 DiffInfo const &patch,
828 std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
829 : pkgAcqBaseIndex(Owner, TransactionID, Target, ExpectedHashes, MetaIndexParser),
830 patch(patch), allPatches(allPatches), State(StateFetchDiff)
831{
832
833 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
834 DestFile += URItoFileName(Target->URI);
835
836 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
837
838 RealURI = Target->URI;
839 Desc.Owner = this;
840 Description = Target->Description;
841 Desc.ShortDesc = Target->ShortDesc;
842
843 Desc.URI = RealURI + ".diff/" + patch.file + ".gz";
844 Desc.Description = Description + " " + patch.file + string(".pdiff");
845 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
846 DestFile += URItoFileName(RealURI + ".diff/" + patch.file);
847
848 if(Debug)
849 std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
850
851 QueueURI(Desc);
852}
853 /*}}}*/
854void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
855{
856 if(Debug)
857 std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
858 Complete = false;
859 Status = StatDone;
860 Dequeue();
861
862 // check if we are the first to fail, otherwise we are done here
863 State = StateDoneDiff;
864 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
865 I != allPatches->end(); ++I)
866 if ((*I)->State == StateErrorDiff)
867 return;
868
869 // first failure means we should fallback
870 State = StateErrorDiff;
871 std::clog << "Falling back to normal index file acquire" << std::endl;
872 new pkgAcqIndex(Owner, TransactionID, Target, ExpectedHashes, MetaIndexParser);
873}
874 /*}}}*/
875void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
876 pkgAcquire::MethodConfig *Cnf)
877{
878 if(Debug)
879 std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
880
881 Item::Done(Message,Size,Hashes,Cnf);
882
883 string const FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
884
885 if (State == StateFetchDiff)
886 {
887 // rred expects the patch as $FinalFile.ed.$patchname.gz
888 Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
889
890 // check if this is the last completed diff
891 State = StateDoneDiff;
892 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
893 I != allPatches->end(); ++I)
894 if ((*I)->State != StateDoneDiff)
895 {
896 if(Debug)
897 std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
898 return;
899 }
900
901 // this is the last completed diff, so we are ready to apply now
902 State = StateApplyDiff;
903
904 if(Debug)
905 std::clog << "Sending to rred method: " << FinalFile << std::endl;
906
907 Local = true;
908 Desc.URI = "rred:" + FinalFile;
909 QueueURI(Desc);
910 Mode = "rred";
911 return;
912 }
913 // success in download/apply all diffs, clean up
914 else if (State == StateApplyDiff)
915 {
916 // see if we really got the expected file
917 if(ExpectedHashes.usable() && !ExpectedHashes.VerifyFile(DestFile))
918 {
919 RenameOnError(HashSumMismatch);
920 return;
921 }
922
923 // move the result into place
924 if(Debug)
925 std::clog << "Moving patched file in place: " << std::endl
926 << DestFile << " -> " << FinalFile << std::endl;
927 Rename(DestFile, FinalFile);
928 chmod(FinalFile.c_str(), 0644);
929
930 // otherwise lists cleanup will eat the file
931 DestFile = FinalFile;
932
933 // ensure the ed's are gone regardless of list-cleanup
934 for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
935 I != allPatches->end(); ++I)
936 {
937 std::string patch = FinalFile + ".ed." + (*I)->patch.file + ".gz";
938 unlink(patch.c_str());
939 }
940
941 // all set and done
942 Complete = true;
943 if(Debug)
944 std::clog << "allDone: " << DestFile << "\n" << std::endl;
945 }
946}
947 /*}}}*/
948// AcqIndex::AcqIndex - Constructor /*{{{*/
949// ---------------------------------------------------------------------
950/* The package file is added to the queue and a second class is
951 instantiated to fetch the revision file */
952pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
953 string URI,string URIDesc,string ShortDesc,
954 HashStringList const &ExpectedHash, string comprExt)
955 : pkgAcqBaseIndex(Owner, 0, NULL, ExpectedHash, NULL), RealURI(URI)
956{
957 AutoSelectCompression();
958 Init(URI, URIDesc, ShortDesc);
959
960 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
961 std::clog << "New pkgIndex with TransactionID "
962 << TransactionID << std::endl;
963}
964 /*}}}*/
965// AcqIndex::AcqIndex - Constructor /*{{{*/
966// ---------------------------------------------------------------------
967pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
968 unsigned long TransactionID,
969 IndexTarget const *Target,
970 HashStringList const &ExpectedHash,
971 indexRecords *MetaIndexParser)
972 : pkgAcqBaseIndex(Owner, TransactionID, Target, ExpectedHash,
973 MetaIndexParser), RealURI(Target->URI)
974{
975 // autoselect the compression method
976 AutoSelectCompression();
977 Init(Target->URI, Target->Description, Target->ShortDesc);
978
979 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
980 std::clog << "New pkgIndex with TransactionID "
981 << TransactionID << std::endl;
982}
983 /*}}}*/
984// AcqIndex::AutoSelectCompression - Select compression /*{{{*/
985// ---------------------------------------------------------------------
986void pkgAcqIndex::AutoSelectCompression()
987{
988 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
989 CompressionExtension = "";
990 if (ExpectedHashes.usable())
991 {
992 for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
993 if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
994 CompressionExtension.append(*t).append(" ");
995 }
996 else
997 {
998 for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
999 CompressionExtension.append(*t).append(" ");
1000 }
1001 if (CompressionExtension.empty() == false)
1002 CompressionExtension.erase(CompressionExtension.end()-1);
1003}
1004// AcqIndex::Init - defered Constructor /*{{{*/
1005void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &ShortDesc) {
1006 Decompression = false;
1007 Erase = false;
1008
1009 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1010 DestFile += URItoFileName(URI);
1011
1012 std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
1013 if (comprExt == "uncompressed")
1014 {
1015 Desc.URI = URI;
1016 if(Target)
1017 MetaKey = string(Target->MetaKey);
1018 }
1019 else
1020 {
1021 Desc.URI = URI + '.' + comprExt;
1022 if(Target)
1023 MetaKey = string(Target->MetaKey) + '.' + comprExt;
1024 }
1025
1026 // load the filesize
1027 if(MetaIndexParser)
1028 {
1029 indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
1030 if(Record)
1031 FileSize = Record->Size;
1032
1033 InitByHashIfNeeded(MetaKey);
1034 }
1035
1036 Desc.Description = URIDesc;
1037 Desc.Owner = this;
1038 Desc.ShortDesc = ShortDesc;
1039
1040 QueueURI(Desc);
1041}
1042 /*}}}*/
1043// AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
1044// ---------------------------------------------------------------------
1045/* */
1046void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
1047{
1048 // TODO:
1049 // - (maybe?) add support for by-hash into the sources.list as flag
1050 // - make apt-ftparchive generate the hashes (and expire?)
1051 std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
1052 if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
1053 _config->FindB(HostKnob, false) == true ||
1054 MetaIndexParser->GetSupportsAcquireByHash())
1055 {
1056 indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
1057 if(Record)
1058 {
1059 // FIXME: should we really use the best hash here? or a fixed one?
1060 const HashString *TargetHash = Record->Hashes.find("");
1061 std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
1062 size_t trailing_slash = Desc.URI.find_last_of("/");
1063 Desc.URI = Desc.URI.replace(
1064 trailing_slash,
1065 Desc.URI.substr(trailing_slash+1).size()+1,
1066 ByHash);
1067 } else {
1068 _error->Warning(
1069 "Fetching ByHash requested but can not find record for %s",
1070 MetaKey.c_str());
1071 }
1072 }
1073}
1074 /*}}}*/
1075// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1076// ---------------------------------------------------------------------
1077/* The only header we use is the last-modified header. */
1078string pkgAcqIndex::Custom600Headers() const
1079{
1080 string Final = _config->FindDir("Dir::State::lists");
1081 Final += URItoFileName(RealURI);
1082 if (_config->FindB("Acquire::GzipIndexes",false))
1083 Final += ".gz";
1084
1085 string msg = "\nIndex-File: true";
1086 // FIXME: this really should use "IndexTarget::IsOptional()" but that
1087 // seems to be difficult without breaking ABI
1088 if (ShortDesc().find("Translation") != 0)
1089 msg += "\nFail-Ignore: true";
1090 struct stat Buf;
1091 if (stat(Final.c_str(),&Buf) == 0)
1092 msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1093
1094 return msg;
1095}
1096 /*}}}*/
1097void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
1098{
1099 size_t const nextExt = CompressionExtension.find(' ');
1100 if (nextExt != std::string::npos)
1101 {
1102 CompressionExtension = CompressionExtension.substr(nextExt+1);
1103 Init(RealURI, Desc.Description, Desc.ShortDesc);
1104 return;
1105 }
1106
1107 // on decompression failure, remove bad versions in partial/
1108 if (Decompression && Erase) {
1109 string s = _config->FindDir("Dir::State::lists") + "partial/";
1110 s.append(URItoFileName(RealURI));
1111 unlink(s.c_str());
1112 }
1113
1114 Item::Failed(Message,Cnf);
1115
1116 /// cancel the entire transaction
1117 Owner->AbortTransaction(TransactionID);
1118}
1119 /*}}}*/
1120// AcqIndex::Done - Finished a fetch /*{{{*/
1121// ---------------------------------------------------------------------
1122/* This goes through a number of states.. On the initial fetch the
1123 method could possibly return an alternate filename which points
1124 to the uncompressed version of the file. If this is so the file
1125 is copied into the partial directory. In all other cases the file
1126 is decompressed with a gzip uri. */
1127void pkgAcqIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes,
1128 pkgAcquire::MethodConfig *Cfg)
1129{
1130 Item::Done(Message,Size,Hashes,Cfg);
1131
1132 if (Decompression == true)
1133 {
1134 if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
1135 {
1136 RenameOnError(HashSumMismatch);
1137 printHashSumComparision(RealURI, ExpectedHashes, Hashes);
1138 Failed(Message, Cfg);
1139 return;
1140 }
1141
1142 // FIXME: this can go away once we only ever download stuff that
1143 // has a valid hash and we never do GET based probing
1144 //
1145 /* Always verify the index file for correctness (all indexes must
1146 * have a Package field) (LP: #346386) (Closes: #627642)
1147 */
1148 FileFd fd(DestFile, FileFd::ReadOnly);
1149 // Only test for correctness if the file is not empty (empty is ok)
1150 if (fd.FileSize() > 0)
1151 {
1152 pkgTagSection sec;
1153 pkgTagFile tag(&fd);
1154
1155 // all our current indexes have a field 'Package' in each section
1156 if (_error->PendingError() == true || tag.Step(sec) == false || sec.Exists("Package") == false)
1157 {
1158 RenameOnError(InvalidFormat);
1159 Failed(Message, Cfg);
1160 return;
1161 }
1162 }
1163
1164 // Done, queue for rename on transaction finished
1165 PartialFile = DestFile;
1166
1167 string FinalFile = _config->FindDir("Dir::State::lists");
1168 FinalFile += URItoFileName(RealURI);
1169 DestFile = FinalFile;
1170#if 0
1171 /* We restore the original name to DestFile so that the clean operation
1172 will work OK */
1173 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1174 DestFile += URItoFileName(RealURI);
1175
1176 // Remove the compressed version.
1177 if (Erase == true)
1178 unlink(DestFile.c_str());
1179#endif
1180 return;
1181 } else {
1182 // FIXME: use the same method to find
1183 // check the compressed hash too
1184 if(MetaKey != "" && Hashes.size() > 0)
1185 {
1186 indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
1187 if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
1188 {
1189 RenameOnError(HashSumMismatch);
1190 printHashSumComparision(RealURI, Record->Hashes, Hashes);
1191 Failed(Message, Cfg);
1192 return;
1193 }
1194 }
1195 }
1196
1197 Erase = false;
1198 Complete = true;
1199
1200 // Handle the unzipd case
1201 string FileName = LookupTag(Message,"Alt-Filename");
1202 if (FileName.empty() == false)
1203 {
1204 // The files timestamp matches
1205 if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
1206 return;
1207 Decompression = true;
1208 Local = true;
1209 DestFile += ".decomp";
1210 Desc.URI = "copy:" + FileName;
1211 QueueURI(Desc);
1212 Mode = "copy";
1213 return;
1214 }
1215
1216 FileName = LookupTag(Message,"Filename");
1217 if (FileName.empty() == true)
1218 {
1219 Status = StatError;
1220 ErrorText = "Method gave a blank filename";
1221 }
1222
1223 std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
1224
1225 // The files timestamp matches
1226 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true) {
1227 if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
1228 // Update DestFile for .gz suffix so that the clean operation keeps it
1229 DestFile += ".gz";
1230 return;
1231 }
1232
1233 if (FileName == DestFile)
1234 Erase = true;
1235 else
1236 Local = true;
1237
1238 string decompProg;
1239
1240 // If we enable compressed indexes and already have gzip, keep it
1241 if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz" && !Local) {
1242 string FinalFile = _config->FindDir("Dir::State::lists");
1243 FinalFile += URItoFileName(RealURI) + ".gz";
1244 Rename(DestFile,FinalFile);
1245 chmod(FinalFile.c_str(),0644);
1246
1247 // Update DestFile for .gz suffix so that the clean operation keeps it
1248 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1249 DestFile += URItoFileName(RealURI) + ".gz";
1250 return;
1251 }
1252
1253 // get the binary name for your used compression type
1254 decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
1255 if(decompProg.empty() == false);
1256 else if(compExt == "uncompressed")
1257 decompProg = "copy";
1258 else {
1259 _error->Error("Unsupported extension: %s", compExt.c_str());
1260 return;
1261 }
1262
1263 Decompression = true;
1264 DestFile += ".decomp";
1265 Desc.URI = decompProg + ":" + FileName;
1266 QueueURI(Desc);
1267
1268 // FIXME: this points to a c++ string that goes out of scope
1269 Mode = decompProg.c_str();
1270}
1271 /*}}}*/
1272// AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
1273// ---------------------------------------------------------------------
1274/* The Translation file is added to the queue */
1275pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
1276 string URI,string URIDesc,string ShortDesc)
1277 : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashStringList(), "")
1278{
1279}
1280 /*}}}*/
1281pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
1282 unsigned long TransactionID,
1283 IndexTarget const * const Target,
1284 HashStringList const &ExpectedHashes,
1285 indexRecords *MetaIndexParser)
1286 : pkgAcqIndex(Owner, TransactionID, Target, ExpectedHashes, MetaIndexParser)
1287{
1288 // load the filesize
1289 indexRecords::checkSum *Record = MetaIndexParser->Lookup(string(Target->MetaKey));
1290 if(Record)
1291 FileSize = Record->Size;
1292}
1293 /*}}}*/
1294// AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
1295// ---------------------------------------------------------------------
1296string pkgAcqIndexTrans::Custom600Headers() const
1297{
1298 string Final = _config->FindDir("Dir::State::lists");
1299 Final += URItoFileName(RealURI);
1300
1301 struct stat Buf;
1302 if (stat(Final.c_str(),&Buf) != 0)
1303 return "\nFail-Ignore: true\nIndex-File: true";
1304 return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1305}
1306 /*}}}*/
1307// AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
1308// ---------------------------------------------------------------------
1309/* */
1310void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
1311{
1312 size_t const nextExt = CompressionExtension.find(' ');
1313 if (nextExt != std::string::npos)
1314 {
1315 CompressionExtension = CompressionExtension.substr(nextExt+1);
1316 Init(RealURI, Desc.Description, Desc.ShortDesc);
1317 Status = StatIdle;
1318 return;
1319 }
1320
1321 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1322 if (Cnf->LocalOnly == true ||
1323 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
1324 {
1325 // Ignore this
1326 Status = StatDone;
1327 Complete = false;
1328 Dequeue();
1329 return;
1330 }
1331
1332 Item::Failed(Message,Cnf);
1333}
1334 /*}}}*/
1335pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
1336 unsigned long TransactionID,
1337 string URI,string URIDesc,string ShortDesc,
1338 string MetaIndexFile,
1339 const vector<IndexTarget*>* IndexTargets,
1340 indexRecords* MetaIndexParser) :
1341 Item(Owner, HashStringList(), TransactionID), RealURI(URI),
1342 MetaIndexParser(MetaIndexParser), MetaIndexFile(MetaIndexFile),
1343 IndexTargets(IndexTargets), AuthPass(false), IMSHit(false)
1344{
1345 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1346 DestFile += URItoFileName(URI);
1347
1348 // remove any partial downloaded sig-file in partial/.
1349 // it may confuse proxies and is too small to warrant a
1350 // partial download anyway
1351 unlink(DestFile.c_str());
1352
1353 // set the TransactionID
1354 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1355 std::clog << "New pkgAcqMetaSig with TransactionID "
1356 << TransactionID << std::endl;
1357
1358 // Create the item
1359 Desc.Description = URIDesc;
1360 Desc.Owner = this;
1361 Desc.ShortDesc = ShortDesc;
1362 Desc.URI = URI;
1363
1364 QueueURI(Desc);
1365}
1366 /*}}}*/
1367pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1368{
1369}
1370 /*}}}*/
1371// pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
1372// ---------------------------------------------------------------------
1373/* The only header we use is the last-modified header. */
1374string pkgAcqMetaSig::Custom600Headers() const
1375{
1376 string FinalFile = _config->FindDir("Dir::State::lists");
1377 FinalFile += URItoFileName(RealURI);
1378
1379 struct stat Buf;
1380 if (stat(FinalFile.c_str(),&Buf) != 0)
1381 return "\nIndex-File: true";
1382
1383 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1384}
1385
1386void pkgAcqMetaSig::Done(string Message,unsigned long long Size, HashStringList const &Hashes,
1387 pkgAcquire::MethodConfig *Cfg)
1388{
1389 Item::Done(Message, Size, Hashes, Cfg);
1390
1391 string FileName = LookupTag(Message,"Filename");
1392 if (FileName.empty() == true)
1393 {
1394 Status = StatError;
1395 ErrorText = "Method gave a blank filename";
1396 return;
1397 }
1398
1399 if (FileName != DestFile)
1400 {
1401 // We have to copy it into place
1402 Local = true;
1403 Desc.URI = "copy:" + FileName;
1404 QueueURI(Desc);
1405 return;
1406 }
1407
1408 if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
1409 IMSHit = true;
1410
1411 // adjust paths if its a ims-hit
1412 if(IMSHit)
1413 {
1414 string FinalFile = _config->FindDir("Dir::State::lists");
1415 FinalFile += URItoFileName(RealURI);
1416
1417 DestFile = PartialFile = FinalFile;
1418 }
1419
1420 // queue for verify
1421 if(AuthPass == false)
1422 {
1423 AuthPass = true;
1424 Desc.URI = "gpgv:" + DestFile;
1425 DestFile = MetaIndexFile;
1426 QueueURI(Desc);
1427 return;
1428 }
1429
1430 // queue to copy the file in place if it was not a ims hit, on ims
1431 // hit the file is already at the right place
1432 if(IMSHit == false)
1433 {
1434 PartialFile = _config->FindDir("Dir::State::lists") + "partial/";
1435 PartialFile += URItoFileName(RealURI);
1436
1437 DestFile = _config->FindDir("Dir::State::lists");
1438 DestFile += URItoFileName(RealURI);
1439 }
1440
1441 Complete = true;
1442
1443}
1444 /*}}}*/
1445void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
1446{
1447 string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
1448
1449 // this ensures that any file in the lists/ dir is removed by the
1450 // transaction
1451 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1452 DestFile += URItoFileName(RealURI);
1453 PartialFile = "";
1454
1455 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
1456 if (Cnf->LocalOnly == true ||
1457 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
1458 {
1459 // Ignore this
1460 Status = StatDone;
1461 Complete = false;
1462 Dequeue();
1463 return;
1464 }
1465 Item::Failed(Message,Cnf);
1466}
1467 /*}}}*/
1468pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
1469 unsigned long TransactionID,
1470 string URI,string URIDesc,string ShortDesc,
1471 string MetaIndexSigURI,string MetaIndexSigURIDesc, string MetaIndexSigShortDesc,
1472 const vector<IndexTarget*>* IndexTargets,
1473 indexRecords* MetaIndexParser) :
1474 Item(Owner, HashStringList(), TransactionID), RealURI(URI), IndexTargets(IndexTargets),
1475 MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false),
1476 MetaIndexSigURI(MetaIndexSigURI), MetaIndexSigURIDesc(MetaIndexSigURIDesc),
1477 MetaIndexSigShortDesc(MetaIndexSigShortDesc)
1478{
1479 if(TransactionID == 0)
1480 this->TransactionID = (unsigned long)this;
1481
1482 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1483 std::clog << "New pkgAcqMetaIndex with TransactionID "
1484 << TransactionID << std::endl;
1485
1486 Init(URIDesc, ShortDesc);
1487}
1488 /*}}}*/
1489// pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
1490void pkgAcqMetaIndex::Init(std::string URIDesc, std::string ShortDesc)
1491{
1492 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1493 DestFile += URItoFileName(RealURI);
1494
1495 // Create the item
1496 Desc.Description = URIDesc;
1497 Desc.Owner = this;
1498 Desc.ShortDesc = ShortDesc;
1499 Desc.URI = RealURI;
1500
1501 // we expect more item
1502 ExpectedAdditionalItems = IndexTargets->size();
1503 QueueURI(Desc);
1504}
1505// pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
1506// ---------------------------------------------------------------------
1507/* The only header we use is the last-modified header. */
1508string pkgAcqMetaIndex::Custom600Headers() const
1509{
1510 string Final = _config->FindDir("Dir::State::lists");
1511 Final += URItoFileName(RealURI);
1512
1513 struct stat Buf;
1514 if (stat(Final.c_str(),&Buf) != 0)
1515 return "\nIndex-File: true";
1516
1517 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1518}
1519 /*}}}*/
1520void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
1521 pkgAcquire::MethodConfig *Cfg)
1522{
1523 Item::Done(Message,Size,Hashes,Cfg);
1524
1525 // MetaIndexes are done in two passes: one to download the
1526 // metaindex with an appropriate method, and a second to verify it
1527 // with the gpgv method
1528
1529 if (AuthPass == true)
1530 {
1531 AuthDone(Message);
1532
1533 // all cool, move Release file into place
1534 Complete = true;
1535 }
1536 else
1537 {
1538 RetrievalDone(Message);
1539 if (!Complete)
1540 // Still more retrieving to do
1541 return;
1542
1543 if (SigFile == "")
1544 {
1545 // load indexes, the signature will downloaded afterwards
1546 MetaIndexParser->Load(DestFile);
1547 QueueIndexes(true);
1548 }
1549 else
1550 {
1551 // FIXME: move this into pkgAcqMetaClearSig::Done on the next
1552 // ABI break
1553
1554 // if we expect a ClearTextSignature (InRelase), ensure that
1555 // this is what we get and if not fail to queue a
1556 // Release/Release.gpg, see #346386
1557 if (SigFile == DestFile && !StartsWithGPGClearTextSignature(DestFile))
1558 {
1559 Failed(Message, Cfg);
1560 return;
1561 }
1562
1563 // There was a signature file, so pass it to gpgv for
1564 // verification
1565 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1566 std::cerr << "Metaindex acquired, queueing gpg verification ("
1567 << SigFile << "," << DestFile << ")\n";
1568 AuthPass = true;
1569 Desc.URI = "gpgv:" + SigFile;
1570 QueueURI(Desc);
1571 Mode = "gpgv";
1572 return;
1573 }
1574 }
1575
1576 if (Complete == true)
1577 {
1578 string FinalFile = _config->FindDir("Dir::State::lists");
1579 FinalFile += URItoFileName(RealURI);
1580 if (SigFile == DestFile)
1581 SigFile = FinalFile;
1582 // queue for copy in place
1583 PartialFile = DestFile;
1584 DestFile = FinalFile;
1585 }
1586}
1587 /*}}}*/
1588void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
1589{
1590 // We have just finished downloading a Release file (it is not
1591 // verified yet)
1592
1593 string FileName = LookupTag(Message,"Filename");
1594 if (FileName.empty() == true)
1595 {
1596 Status = StatError;
1597 ErrorText = "Method gave a blank filename";
1598 return;
1599 }
1600
1601 if (FileName != DestFile)
1602 {
1603 Local = true;
1604 Desc.URI = "copy:" + FileName;
1605 QueueURI(Desc);
1606 return;
1607 }
1608
1609 // make sure to verify against the right file on I-M-S hit
1610 IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
1611 if(IMSHit)
1612 {
1613 string FinalFile = _config->FindDir("Dir::State::lists");
1614 FinalFile += URItoFileName(RealURI);
1615 if (SigFile == DestFile)
1616 {
1617 SigFile = FinalFile;
1618#if 0
1619 // constructor of pkgAcqMetaClearSig moved it out of the way,
1620 // now move it back in on IMS hit for the 'old' file
1621 string const OldClearSig = DestFile + ".reverify";
1622 if (RealFileExists(OldClearSig) == true)
1623 Rename(OldClearSig, FinalFile);
1624#endif
1625 }
1626 DestFile = FinalFile;
1627 }
1628
1629 // queue a signature
1630 if(SigFile != DestFile)
1631 new pkgAcqMetaSig(Owner, TransactionID,
1632 MetaIndexSigURI, MetaIndexSigURIDesc,
1633 MetaIndexSigShortDesc, DestFile, IndexTargets,
1634 MetaIndexParser);
1635
1636 Complete = true;
1637}
1638 /*}}}*/
1639void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
1640{
1641 // At this point, the gpgv method has succeeded, so there is a
1642 // valid signature from a key in the trusted keyring. We
1643 // perform additional verification of its contents, and use them
1644 // to verify the indexes we are about to download
1645
1646 if (!MetaIndexParser->Load(DestFile))
1647 {
1648 Status = StatAuthError;
1649 ErrorText = MetaIndexParser->ErrorText;
1650 return;
1651 }
1652
1653 if (!VerifyVendor(Message))
1654 {
1655 return;
1656 }
1657
1658 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1659 std::cerr << "Signature verification succeeded: "
1660 << DestFile << std::endl;
1661
1662 // Download further indexes with verification
1663 QueueIndexes(true);
1664
1665#if 0
1666 // is it a clearsigned MetaIndex file?
1667 if (DestFile == SigFile)
1668 return;
1669
1670 // Done, move signature file into position
1671 string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
1672 URItoFileName(RealURI) + ".gpg";
1673 Rename(SigFile,VerifiedSigFile);
1674 chmod(VerifiedSigFile.c_str(),0644);
1675#endif
1676}
1677 /*}}}*/
1678void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
1679{
1680 bool transInRelease = false;
1681 {
1682 std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
1683 for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
1684 // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
1685 if (k->find("Translation-") != std::string::npos)
1686 {
1687 transInRelease = true;
1688 break;
1689 }
1690 }
1691
1692 // at this point the real Items are loaded in the fetcher
1693 ExpectedAdditionalItems = 0;
1694 for (vector <IndexTarget*>::const_iterator Target = IndexTargets->begin();
1695 Target != IndexTargets->end();
1696 ++Target)
1697 {
1698 HashStringList ExpectedIndexHashes;
1699 const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
1700 bool compressedAvailable = false;
1701 if (Record == NULL)
1702 {
1703 if ((*Target)->IsOptional() == true)
1704 {
1705 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
1706 for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
1707 if (MetaIndexParser->Exists((*Target)->MetaKey + "." + *t) == true)
1708 {
1709 compressedAvailable = true;
1710 break;
1711 }
1712 }
1713 else if (verify == true)
1714 {
1715 Status = StatAuthError;
1716 strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
1717 return;
1718 }
1719 }
1720 else
1721 {
1722 ExpectedIndexHashes = Record->Hashes;
1723 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1724 {
1725 std::cerr << "Queueing: " << (*Target)->URI << std::endl
1726 << "Expected Hash:" << std::endl;
1727 for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
1728 std::cerr << "\t- " << hs->toStr() << std::endl;
1729 std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
1730 }
1731 if (verify == true && ExpectedIndexHashes.empty() == true && (*Target)->IsOptional() == false)
1732 {
1733 Status = StatAuthError;
1734 strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
1735 return;
1736 }
1737 }
1738
1739 if ((*Target)->IsOptional() == true)
1740 {
1741 if ((*Target)->IsSubIndex() == true)
1742 new pkgAcqSubIndex(Owner, TransactionID,
1743 (*Target)->URI, (*Target)->Description,
1744 (*Target)->ShortDesc, ExpectedIndexHashes);
1745 else if (transInRelease == false || Record != NULL || compressedAvailable == true)
1746 {
1747 if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
1748 MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true)
1749 new pkgAcqDiffIndex(Owner, TransactionID, *Target, ExpectedIndexHashes, MetaIndexParser);
1750 else
1751 new pkgAcqIndexTrans(Owner, TransactionID, *Target, ExpectedIndexHashes, MetaIndexParser);
1752 }
1753 continue;
1754 }
1755
1756 /* Queue Packages file (either diff or full packages files, depending
1757 on the users option) - we also check if the PDiff Index file is listed
1758 in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
1759 instead, but passing the required info to it is to much hassle */
1760 if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
1761 MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
1762 new pkgAcqDiffIndex(Owner, TransactionID, *Target, ExpectedIndexHashes, MetaIndexParser);
1763 else
1764 new pkgAcqIndex(Owner, TransactionID, *Target, ExpectedIndexHashes, MetaIndexParser);
1765 }
1766}
1767 /*}}}*/
1768bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
1769{
1770 string::size_type pos;
1771
1772 // check for missing sigs (that where not fatal because otherwise we had
1773 // bombed earlier)
1774 string missingkeys;
1775 string msg = _("There is no public key available for the "
1776 "following key IDs:\n");
1777 pos = Message.find("NO_PUBKEY ");
1778 if (pos != std::string::npos)
1779 {
1780 string::size_type start = pos+strlen("NO_PUBKEY ");
1781 string Fingerprint = Message.substr(start, Message.find("\n")-start);
1782 missingkeys += (Fingerprint);
1783 }
1784 if(!missingkeys.empty())
1785 _error->Warning("%s", (msg + missingkeys).c_str());
1786
1787 string Transformed = MetaIndexParser->GetExpectedDist();
1788
1789 if (Transformed == "../project/experimental")
1790 {
1791 Transformed = "experimental";
1792 }
1793
1794 pos = Transformed.rfind('/');
1795 if (pos != string::npos)
1796 {
1797 Transformed = Transformed.substr(0, pos);
1798 }
1799
1800 if (Transformed == ".")
1801 {
1802 Transformed = "";
1803 }
1804
1805 if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
1806 MetaIndexParser->GetValidUntil() > 0) {
1807 time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
1808 if (invalid_since > 0)
1809 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
1810 // the time since then the file is invalid - formated in the same way as in
1811 // the download progress display (e.g. 7d 3h 42min 1s)
1812 return _error->Error(
1813 _("Release file for %s is expired (invalid since %s). "
1814 "Updates for this repository will not be applied."),
1815 RealURI.c_str(), TimeToStr(invalid_since).c_str());
1816 }
1817
1818 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1819 {
1820 std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
1821 std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
1822 std::cerr << "Transformed Dist: " << Transformed << std::endl;
1823 }
1824
1825 if (MetaIndexParser->CheckDist(Transformed) == false)
1826 {
1827 // This might become fatal one day
1828// Status = StatAuthError;
1829// ErrorText = "Conflicting distribution; expected "
1830// + MetaIndexParser->GetExpectedDist() + " but got "
1831// + MetaIndexParser->GetDist();
1832// return false;
1833 if (!Transformed.empty())
1834 {
1835 _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
1836 Desc.Description.c_str(),
1837 Transformed.c_str(),
1838 MetaIndexParser->GetDist().c_str());
1839 }
1840 }
1841
1842 return true;
1843}
1844 /*}}}*/
1845// pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
1846// ---------------------------------------------------------------------
1847/* */
1848void pkgAcqMetaIndex::Failed(string Message,
1849 pkgAcquire::MethodConfig * /*Cnf*/)
1850{
1851 if (AuthPass == true)
1852 {
1853 // gpgv method failed, if we have a good signature
1854 string LastGoodSigFile = _config->FindDir("Dir::State::lists");
1855 LastGoodSigFile += URItoFileName(RealURI);
1856 if (DestFile != SigFile)
1857 LastGoodSigFile.append(".gpg");
1858
1859 if(FileExists(LastGoodSigFile))
1860 {
1861 Status = StatTransientNetworkError;
1862 _error->Warning(_("An error occurred during the signature "
1863 "verification. The repository is not updated "
1864 "and the previous index files will be used. "
1865 "GPG error: %s: %s\n"),
1866 Desc.Description.c_str(),
1867 LookupTag(Message,"Message").c_str());
1868 RunScripts("APT::Update::Auth-Failure");
1869 return;
1870 } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
1871 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
1872 _error->Error(_("GPG error: %s: %s"),
1873 Desc.Description.c_str(),
1874 LookupTag(Message,"Message").c_str());
1875 Status = StatError;
1876 return;
1877 } else {
1878 _error->Warning(_("GPG error: %s: %s"),
1879 Desc.Description.c_str(),
1880 LookupTag(Message,"Message").c_str());
1881 }
1882 // gpgv method failed
1883 ReportMirrorFailure("GPGFailure");
1884 }
1885
1886 /* Always move the meta index, even if gpgv failed. This ensures
1887 * that PackageFile objects are correctly filled in */
1888 if (FileExists(DestFile)) {
1889 string FinalFile = _config->FindDir("Dir::State::lists");
1890 FinalFile += URItoFileName(RealURI);
1891 /* InRelease files become Release files, otherwise
1892 * they would be considered as trusted later on */
1893 if (SigFile == DestFile) {
1894 RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
1895 "Release");
1896 FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
1897 "Release");
1898 SigFile = FinalFile;
1899 }
1900
1901 // Done, queue for rename on transaction finished
1902 PartialFile = DestFile;
1903 DestFile = FinalFile;
1904 }
1905
1906 // No Release file was present, or verification failed, so fall
1907 // back to queueing Packages files without verification
1908 QueueIndexes(false);
1909}
1910 /*}}}*/
1911
1912void pkgAcqMetaIndex::Finished()
1913{
1914 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1915 std::clog << "Finished: " << DestFile <<std::endl;
1916 if(Owner->TransactionHasError(TransactionID) == false &&
1917 TransactionID > 0)
1918 Owner->CommitTransaction(TransactionID);
1919}
1920
1921
1922pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
1923 string const &URI, string const &URIDesc, string const &ShortDesc,
1924 string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
1925 string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
1926 const vector<IndexTarget*>* IndexTargets,
1927 indexRecords* MetaIndexParser) :
1928 pkgAcqMetaIndex(Owner, (unsigned long)this, URI, URIDesc, ShortDesc, MetaSigURI, MetaSigURIDesc,MetaSigShortDesc, IndexTargets, MetaIndexParser),
1929 MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
1930 MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
1931{
1932 SigFile = DestFile;
1933
1934 // index targets + (worst case:) Release/Release.gpg
1935 ExpectedAdditionalItems = IndexTargets->size() + 2;
1936
1937#if 0
1938 // keep the old InRelease around in case of transistent network errors
1939 string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
1940 if (RealFileExists(Final) == true)
1941 {
1942 string const LastGoodSig = DestFile + ".reverify";
1943 Rename(Final,LastGoodSig);
1944 }
1945#endif
1946}
1947 /*}}}*/
1948pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
1949{
1950#if 0
1951 // if the file was never queued undo file-changes done in the constructor
1952 if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false)
1953 {
1954 string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
1955 string const LastGoodSig = DestFile + ".reverify";
1956 if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
1957 Rename(LastGoodSig, Final);
1958 }
1959#endif
1960}
1961 /*}}}*/
1962// pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
1963// ---------------------------------------------------------------------
1964// FIXME: this can go away once the InRelease file is used widely
1965string pkgAcqMetaClearSig::Custom600Headers() const
1966{
1967 string Final = _config->FindDir("Dir::State::lists");
1968 Final += URItoFileName(RealURI);
1969
1970 struct stat Buf;
1971 if (stat(Final.c_str(),&Buf) != 0)
1972 {
1973 if (stat(Final.c_str(),&Buf) != 0)
1974 return "\nIndex-File: true\nFail-Ignore: true\n";
1975 }
1976
1977 return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1978}
1979 /*}}}*/
1980void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
1981{
1982 // we failed, we will not get additional items from this method
1983 ExpectedAdditionalItems = 0;
1984
1985 if (AuthPass == false)
1986 {
1987 // Queue the 'old' InRelease file for removal if we try Release.gpg
1988 // as otherwise the file will stay around and gives a false-auth
1989 // impression (CVE-2012-0214)
1990 string FinalFile = _config->FindDir("Dir::State::lists");
1991 FinalFile.append(URItoFileName(RealURI));
1992 PartialFile = "";
1993 DestFile = FinalFile;
1994
1995 new pkgAcqMetaIndex(Owner, TransactionID,
1996 MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
1997 MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
1998 IndexTargets, MetaIndexParser);
1999 if (Cnf->LocalOnly == true ||
2000 StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
2001 Dequeue();
2002 }
2003 else
2004 pkgAcqMetaIndex::Failed(Message, Cnf);
2005}
2006 /*}}}*/
2007// AcqArchive::AcqArchive - Constructor /*{{{*/
2008// ---------------------------------------------------------------------
2009/* This just sets up the initial fetch environment and queues the first
2010 possibilitiy */
2011pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
2012 pkgRecords *Recs,pkgCache::VerIterator const &Version,
2013 string &StoreFilename) :
2014 Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
2015 StoreFilename(StoreFilename), Vf(Version.FileList()),
2016 Trusted(false)
2017{
2018 Retries = _config->FindI("Acquire::Retries",0);
2019
2020 if (Version.Arch() == 0)
2021 {
2022 _error->Error(_("I wasn't able to locate a file for the %s package. "
2023 "This might mean you need to manually fix this package. "
2024 "(due to missing arch)"),
2025 Version.ParentPkg().FullName().c_str());
2026 return;
2027 }
2028
2029 /* We need to find a filename to determine the extension. We make the
2030 assumption here that all the available sources for this version share
2031 the same extension.. */
2032 // Skip not source sources, they do not have file fields.
2033 for (; Vf.end() == false; ++Vf)
2034 {
2035 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
2036 continue;
2037 break;
2038 }
2039
2040 // Does not really matter here.. we are going to fail out below
2041 if (Vf.end() != true)
2042 {
2043 // If this fails to get a file name we will bomb out below.
2044 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2045 if (_error->PendingError() == true)
2046 return;
2047
2048 // Generate the final file name as: package_version_arch.foo
2049 StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
2050 QuoteString(Version.VerStr(),"_:") + '_' +
2051 QuoteString(Version.Arch(),"_:.") +
2052 "." + flExtension(Parse.FileName());
2053 }
2054
2055 // check if we have one trusted source for the package. if so, switch
2056 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2057 bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
2058 bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
2059 bool seenUntrusted = false;
2060 for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
2061 {
2062 pkgIndexFile *Index;
2063 if (Sources->FindIndex(i.File(),Index) == false)
2064 continue;
2065
2066 if (debugAuth == true)
2067 std::cerr << "Checking index: " << Index->Describe()
2068 << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
2069
2070 if (Index->IsTrusted() == true)
2071 {
2072 Trusted = true;
2073 if (allowUnauth == false)
2074 break;
2075 }
2076 else
2077 seenUntrusted = true;
2078 }
2079
2080 // "allow-unauthenticated" restores apts old fetching behaviour
2081 // that means that e.g. unauthenticated file:// uris are higher
2082 // priority than authenticated http:// uris
2083 if (allowUnauth == true && seenUntrusted == true)
2084 Trusted = false;
2085
2086 // Select a source
2087 if (QueueNext() == false && _error->PendingError() == false)
2088 _error->Error(_("Can't find a source to download version '%s' of '%s'"),
2089 Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
2090}
2091 /*}}}*/
2092// AcqArchive::QueueNext - Queue the next file source /*{{{*/
2093// ---------------------------------------------------------------------
2094/* This queues the next available file version for download. It checks if
2095 the archive is already available in the cache and stashs the MD5 for
2096 checking later. */
2097bool pkgAcqArchive::QueueNext()
2098{
2099 for (; Vf.end() == false; ++Vf)
2100 {
2101 // Ignore not source sources
2102 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
2103 continue;
2104
2105 // Try to cross match against the source list
2106 pkgIndexFile *Index;
2107 if (Sources->FindIndex(Vf.File(),Index) == false)
2108 continue;
2109
2110 // only try to get a trusted package from another source if that source
2111 // is also trusted
2112 if(Trusted && !Index->IsTrusted())
2113 continue;
2114
2115 // Grab the text package record
2116 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2117 if (_error->PendingError() == true)
2118 return false;
2119
2120 string PkgFile = Parse.FileName();
2121 ExpectedHashes = Parse.Hashes();
2122
2123 if (PkgFile.empty() == true)
2124 return _error->Error(_("The package index files are corrupted. No Filename: "
2125 "field for package %s."),
2126 Version.ParentPkg().Name());
2127
2128 Desc.URI = Index->ArchiveURI(PkgFile);
2129 Desc.Description = Index->ArchiveInfo(Version);
2130 Desc.Owner = this;
2131 Desc.ShortDesc = Version.ParentPkg().FullName(true);
2132
2133 // See if we already have the file. (Legacy filenames)
2134 FileSize = Version->Size;
2135 string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
2136 struct stat Buf;
2137 if (stat(FinalFile.c_str(),&Buf) == 0)
2138 {
2139 // Make sure the size matches
2140 if ((unsigned long long)Buf.st_size == Version->Size)
2141 {
2142 Complete = true;
2143 Local = true;
2144 Status = StatDone;
2145 StoreFilename = DestFile = FinalFile;
2146 return true;
2147 }
2148
2149 /* Hmm, we have a file and its size does not match, this means it is
2150 an old style mismatched arch */
2151 unlink(FinalFile.c_str());
2152 }
2153
2154 // Check it again using the new style output filenames
2155 FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
2156 if (stat(FinalFile.c_str(),&Buf) == 0)
2157 {
2158 // Make sure the size matches
2159 if ((unsigned long long)Buf.st_size == Version->Size)
2160 {
2161 Complete = true;
2162 Local = true;
2163 Status = StatDone;
2164 StoreFilename = DestFile = FinalFile;
2165 return true;
2166 }
2167
2168 /* Hmm, we have a file and its size does not match, this shouldn't
2169 happen.. */
2170 unlink(FinalFile.c_str());
2171 }
2172
2173 DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
2174
2175 // Check the destination file
2176 if (stat(DestFile.c_str(),&Buf) == 0)
2177 {
2178 // Hmm, the partial file is too big, erase it
2179 if ((unsigned long long)Buf.st_size > Version->Size)
2180 unlink(DestFile.c_str());
2181 else
2182 PartialSize = Buf.st_size;
2183 }
2184
2185 // Disables download of archives - useful if no real installation follows,
2186 // e.g. if we are just interested in proposed installation order
2187 if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2188 {
2189 Complete = true;
2190 Local = true;
2191 Status = StatDone;
2192 StoreFilename = DestFile = FinalFile;
2193 return true;
2194 }
2195
2196 // Create the item
2197 Local = false;
2198 QueueURI(Desc);
2199
2200 ++Vf;
2201 return true;
2202 }
2203 return false;
2204}
2205 /*}}}*/
2206// AcqArchive::Done - Finished fetching /*{{{*/
2207// ---------------------------------------------------------------------
2208/* */
2209void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
2210 pkgAcquire::MethodConfig *Cfg)
2211{
2212 Item::Done(Message, Size, CalcHashes, Cfg);
2213
2214 // Check the size
2215 if (Size != Version->Size)
2216 {
2217 RenameOnError(SizeMismatch);
2218 return;
2219 }
2220
2221 // FIXME: could this empty() check impose *any* sort of security issue?
2222 if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
2223 {
2224 RenameOnError(HashSumMismatch);
2225 printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
2226 return;
2227 }
2228
2229 // Grab the output filename
2230 string FileName = LookupTag(Message,"Filename");
2231 if (FileName.empty() == true)
2232 {
2233 Status = StatError;
2234 ErrorText = "Method gave a blank filename";
2235 return;
2236 }
2237
2238 Complete = true;
2239
2240 // Reference filename
2241 if (FileName != DestFile)
2242 {
2243 StoreFilename = DestFile = FileName;
2244 Local = true;
2245 return;
2246 }
2247
2248 // Done, move it into position
2249 string FinalFile = _config->FindDir("Dir::Cache::Archives");
2250 FinalFile += flNotDir(StoreFilename);
2251 Rename(DestFile,FinalFile);
2252
2253 StoreFilename = DestFile = FinalFile;
2254 Complete = true;
2255}
2256 /*}}}*/
2257// AcqArchive::Failed - Failure handler /*{{{*/
2258// ---------------------------------------------------------------------
2259/* Here we try other sources */
2260void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
2261{
2262 ErrorText = LookupTag(Message,"Message");
2263
2264 /* We don't really want to retry on failed media swaps, this prevents
2265 that. An interesting observation is that permanent failures are not
2266 recorded. */
2267 if (Cnf->Removable == true &&
2268 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2269 {
2270 // Vf = Version.FileList();
2271 while (Vf.end() == false) ++Vf;
2272 StoreFilename = string();
2273 Item::Failed(Message,Cnf);
2274 return;
2275 }
2276
2277 if (QueueNext() == false)
2278 {
2279 // This is the retry counter
2280 if (Retries != 0 &&
2281 Cnf->LocalOnly == false &&
2282 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2283 {
2284 Retries--;
2285 Vf = Version.FileList();
2286 if (QueueNext() == true)
2287 return;
2288 }
2289
2290 StoreFilename = string();
2291 Item::Failed(Message,Cnf);
2292 }
2293}
2294 /*}}}*/
2295// AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
2296// ---------------------------------------------------------------------
2297APT_PURE bool pkgAcqArchive::IsTrusted() const
2298{
2299 return Trusted;
2300}
2301 /*}}}*/
2302// AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
2303// ---------------------------------------------------------------------
2304/* */
2305void pkgAcqArchive::Finished()
2306{
2307 if (Status == pkgAcquire::Item::StatDone &&
2308 Complete == true)
2309 return;
2310 StoreFilename = string();
2311}
2312 /*}}}*/
2313// AcqFile::pkgAcqFile - Constructor /*{{{*/
2314// ---------------------------------------------------------------------
2315/* The file is added to the queue */
2316pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
2317 unsigned long long Size,string Dsc,string ShortDesc,
2318 const string &DestDir, const string &DestFilename,
2319 bool IsIndexFile) :
2320 Item(Owner, Hashes), IsIndexFile(IsIndexFile)
2321{
2322 Retries = _config->FindI("Acquire::Retries",0);
2323
2324 if(!DestFilename.empty())
2325 DestFile = DestFilename;
2326 else if(!DestDir.empty())
2327 DestFile = DestDir + "/" + flNotDir(URI);
2328 else
2329 DestFile = flNotDir(URI);
2330
2331 // Create the item
2332 Desc.URI = URI;
2333 Desc.Description = Dsc;
2334 Desc.Owner = this;
2335
2336 // Set the short description to the archive component
2337 Desc.ShortDesc = ShortDesc;
2338
2339 // Get the transfer sizes
2340 FileSize = Size;
2341 struct stat Buf;
2342 if (stat(DestFile.c_str(),&Buf) == 0)
2343 {
2344 // Hmm, the partial file is too big, erase it
2345 if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
2346 unlink(DestFile.c_str());
2347 else
2348 PartialSize = Buf.st_size;
2349 }
2350
2351 QueueURI(Desc);
2352}
2353 /*}}}*/
2354// AcqFile::Done - Item downloaded OK /*{{{*/
2355// ---------------------------------------------------------------------
2356/* */
2357void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
2358 pkgAcquire::MethodConfig *Cnf)
2359{
2360 Item::Done(Message,Size,CalcHashes,Cnf);
2361
2362 // Check the hash
2363 if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
2364 {
2365 RenameOnError(HashSumMismatch);
2366 printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
2367 return;
2368 }
2369
2370 string FileName = LookupTag(Message,"Filename");
2371 if (FileName.empty() == true)
2372 {
2373 Status = StatError;
2374 ErrorText = "Method gave a blank filename";
2375 return;
2376 }
2377
2378 Complete = true;
2379
2380 // The files timestamp matches
2381 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
2382 return;
2383
2384 // We have to copy it into place
2385 if (FileName != DestFile)
2386 {
2387 Local = true;
2388 if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
2389 Cnf->Removable == true)
2390 {
2391 Desc.URI = "copy:" + FileName;
2392 QueueURI(Desc);
2393 return;
2394 }
2395
2396 // Erase the file if it is a symlink so we can overwrite it
2397 struct stat St;
2398 if (lstat(DestFile.c_str(),&St) == 0)
2399 {
2400 if (S_ISLNK(St.st_mode) != 0)
2401 unlink(DestFile.c_str());
2402 }
2403
2404 // Symlink the file
2405 if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
2406 {
2407 ErrorText = "Link to " + DestFile + " failure ";
2408 Status = StatError;
2409 Complete = false;
2410 }
2411 }
2412}
2413 /*}}}*/
2414// AcqFile::Failed - Failure handler /*{{{*/
2415// ---------------------------------------------------------------------
2416/* Here we try other sources */
2417void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
2418{
2419 ErrorText = LookupTag(Message,"Message");
2420
2421 // This is the retry counter
2422 if (Retries != 0 &&
2423 Cnf->LocalOnly == false &&
2424 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2425 {
2426 Retries--;
2427 QueueURI(Desc);
2428 return;
2429 }
2430
2431 Item::Failed(Message,Cnf);
2432}
2433 /*}}}*/
2434// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2435// ---------------------------------------------------------------------
2436/* The only header we use is the last-modified header. */
2437string pkgAcqFile::Custom600Headers() const
2438{
2439 if (IsIndexFile)
2440 return "\nIndex-File: true";
2441 return "";
2442}
2443 /*}}}*/