]> git.saurik.com Git - apt.git/blame_incremental - apt-pkg/acquire-item.cc
* debian/rules:
[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 <apt-pkg/acquire-item.h>
17#include <apt-pkg/configuration.h>
18#include <apt-pkg/aptconfiguration.h>
19#include <apt-pkg/sourcelist.h>
20#include <apt-pkg/vendorlist.h>
21#include <apt-pkg/error.h>
22#include <apt-pkg/strutl.h>
23#include <apt-pkg/fileutl.h>
24#include <apt-pkg/md5.h>
25#include <apt-pkg/sha1.h>
26#include <apt-pkg/tagfile.h>
27
28#include <apti18n.h>
29
30#include <sys/stat.h>
31#include <unistd.h>
32#include <errno.h>
33#include <string>
34#include <sstream>
35#include <stdio.h>
36 /*}}}*/
37
38using namespace std;
39
40// Acquire::Item::Item - Constructor /*{{{*/
41// ---------------------------------------------------------------------
42/* */
43pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
44 PartialSize(0), Mode(0), ID(0), Complete(false),
45 Local(false), QueueCounter(0)
46{
47 Owner->Add(this);
48 Status = StatIdle;
49}
50 /*}}}*/
51// Acquire::Item::~Item - Destructor /*{{{*/
52// ---------------------------------------------------------------------
53/* */
54pkgAcquire::Item::~Item()
55{
56 Owner->Remove(this);
57}
58 /*}}}*/
59// Acquire::Item::Failed - Item failed to download /*{{{*/
60// ---------------------------------------------------------------------
61/* We return to an idle state if there are still other queues that could
62 fetch this object */
63void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
64{
65 Status = StatIdle;
66 ErrorText = LookupTag(Message,"Message");
67 if (QueueCounter <= 1)
68 {
69 /* This indicates that the file is not available right now but might
70 be sometime later. If we do a retry cycle then this should be
71 retried [CDROMs] */
72 if (Cnf->LocalOnly == true &&
73 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
74 {
75 Status = StatIdle;
76 Dequeue();
77 return;
78 }
79
80 Status = StatError;
81 Dequeue();
82 }
83}
84 /*}}}*/
85// Acquire::Item::Start - Item has begun to download /*{{{*/
86// ---------------------------------------------------------------------
87/* Stash status and the file size. Note that setting Complete means
88 sub-phases of the acquire process such as decompresion are operating */
89void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
90{
91 Status = StatFetching;
92 if (FileSize == 0 && Complete == false)
93 FileSize = Size;
94}
95 /*}}}*/
96// Acquire::Item::Done - Item downloaded OK /*{{{*/
97// ---------------------------------------------------------------------
98/* */
99void pkgAcquire::Item::Done(string Message,unsigned long Size,string Hash,
100 pkgAcquire::MethodConfig *Cnf)
101{
102 // We just downloaded something..
103 string FileName = LookupTag(Message,"Filename");
104 // we only inform the Log class if it was actually not a local thing
105 if (Complete == false && !Local && FileName == DestFile)
106 {
107 if (Owner->Log != 0)
108 Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
109 }
110
111 if (FileSize == 0)
112 FileSize= Size;
113
114 Status = StatDone;
115 ErrorText = string();
116 Owner->Dequeue(this);
117}
118 /*}}}*/
119// Acquire::Item::Rename - Rename a file /*{{{*/
120// ---------------------------------------------------------------------
121/* This helper function is used by alot of item methods as thier final
122 step */
123void pkgAcquire::Item::Rename(string From,string To)
124{
125 if (rename(From.c_str(),To.c_str()) != 0)
126 {
127 char S[300];
128 snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
129 From.c_str(),To.c_str());
130 Status = StatError;
131 ErrorText = S;
132 }
133}
134 /*}}}*/
135// AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
136// ---------------------------------------------------------------------
137/* Get the DiffIndex file first and see if there are patches availabe
138 * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
139 * patches. If anything goes wrong in that process, it will fall back to
140 * the original packages file
141 */
142pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
143 string URI,string URIDesc,string ShortDesc,
144 HashString ExpectedHash)
145 : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
146 Description(URIDesc)
147{
148
149 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
150
151 Desc.Description = URIDesc + "/DiffIndex";
152 Desc.Owner = this;
153 Desc.ShortDesc = ShortDesc;
154 Desc.URI = URI + ".diff/Index";
155
156 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
157 DestFile += URItoFileName(URI) + string(".DiffIndex");
158
159 if(Debug)
160 std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
161
162 // look for the current package file
163 CurrentPackagesFile = _config->FindDir("Dir::State::lists");
164 CurrentPackagesFile += URItoFileName(RealURI);
165
166 // FIXME: this file:/ check is a hack to prevent fetching
167 // from local sources. this is really silly, and
168 // should be fixed cleanly as soon as possible
169 if(!FileExists(CurrentPackagesFile) ||
170 Desc.URI.substr(0,strlen("file:/")) == "file:/")
171 {
172 // we don't have a pkg file or we don't want to queue
173 if(Debug)
174 std::clog << "No index file, local or canceld by user" << std::endl;
175 Failed("", NULL);
176 return;
177 }
178
179 if(Debug)
180 std::clog << "pkgAcqIndexDiffs::pkgAcqIndexDiffs(): "
181 << CurrentPackagesFile << std::endl;
182
183 QueueURI(Desc);
184
185}
186 /*}}}*/
187// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
188// ---------------------------------------------------------------------
189/* The only header we use is the last-modified header. */
190string pkgAcqDiffIndex::Custom600Headers()
191{
192 string Final = _config->FindDir("Dir::State::lists");
193 Final += URItoFileName(RealURI) + string(".IndexDiff");
194
195 if(Debug)
196 std::clog << "Custom600Header-IMS: " << Final << std::endl;
197
198 struct stat Buf;
199 if (stat(Final.c_str(),&Buf) != 0)
200 return "\nIndex-File: true";
201
202 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
203}
204 /*}}}*/
205bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
206{
207 if(Debug)
208 std::clog << "pkgAcqIndexDiffs::ParseIndexDiff() " << IndexDiffFile
209 << std::endl;
210
211 pkgTagSection Tags;
212 string ServerSha1;
213 vector<DiffInfo> available_patches;
214
215 FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
216 pkgTagFile TF(&Fd);
217 if (_error->PendingError() == true)
218 return false;
219
220 if(TF.Step(Tags) == true)
221 {
222 bool found = false;
223 DiffInfo d;
224 string size;
225
226 string const tmp = Tags.FindS("SHA1-Current");
227 std::stringstream ss(tmp);
228 ss >> ServerSha1 >> size;
229 unsigned long const ServerSize = atol(size.c_str());
230
231 FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
232 SHA1Summation SHA1;
233 SHA1.AddFD(fd.Fd(), fd.Size());
234 string const local_sha1 = SHA1.Result();
235
236 if(local_sha1 == ServerSha1)
237 {
238 // we have the same sha1 as the server
239 if(Debug)
240 std::clog << "Package file is up-to-date" << std::endl;
241 // set found to true, this will queue a pkgAcqIndexDiffs with
242 // a empty availabe_patches
243 found = true;
244 }
245 else
246 {
247 if(Debug)
248 std::clog << "SHA1-Current: " << ServerSha1 << std::endl;
249
250 // check the historie and see what patches we need
251 string const history = Tags.FindS("SHA1-History");
252 std::stringstream hist(history);
253 while(hist >> d.sha1 >> size >> d.file)
254 {
255 // read until the first match is found
256 // from that point on, we probably need all diffs
257 if(d.sha1 == local_sha1)
258 found=true;
259 else if (found == false)
260 continue;
261
262 if(Debug)
263 std::clog << "Need to get diff: " << d.file << std::endl;
264 available_patches.push_back(d);
265 }
266
267 if (available_patches.empty() == false)
268 {
269 // patching with too many files is rather slow compared to a fast download
270 unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
271 if (fileLimit != 0 && fileLimit < available_patches.size())
272 {
273 if (Debug)
274 std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
275 << ") so fallback to complete download" << std::endl;
276 return false;
277 }
278
279 // see if the patches are too big
280 found = false; // it was true and it will be true again at the end
281 d = *available_patches.begin();
282 string const firstPatch = d.file;
283 unsigned long patchesSize = 0;
284 std::stringstream patches(Tags.FindS("SHA1-Patches"));
285 while(patches >> d.sha1 >> size >> d.file)
286 {
287 if (firstPatch == d.file)
288 found = true;
289 else if (found == false)
290 continue;
291
292 patchesSize += atol(size.c_str());
293 }
294 unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
295 if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
296 {
297 if (Debug)
298 std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
299 << ") so fallback to complete download" << std::endl;
300 return false;
301 }
302 }
303 }
304
305 // we have something, queue the next diff
306 if(found)
307 {
308 // queue the diffs
309 string::size_type const last_space = Description.rfind(" ");
310 if(last_space != string::npos)
311 Description.erase(last_space, Description.size()-last_space);
312 new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
313 ExpectedHash, ServerSha1, available_patches);
314 Complete = false;
315 Status = StatDone;
316 Dequeue();
317 return true;
318 }
319 }
320
321 // Nothing found, report and return false
322 // Failing here is ok, if we return false later, the full
323 // IndexFile is queued
324 if(Debug)
325 std::clog << "Can't find a patch in the index file" << std::endl;
326 return false;
327}
328 /*}}}*/
329void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
330{
331 if(Debug)
332 std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << std::endl
333 << "Falling back to normal index file aquire" << std::endl;
334
335 new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
336 ExpectedHash);
337
338 Complete = false;
339 Status = StatDone;
340 Dequeue();
341}
342 /*}}}*/
343void pkgAcqDiffIndex::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
344 pkgAcquire::MethodConfig *Cnf)
345{
346 if(Debug)
347 std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
348
349 Item::Done(Message,Size,Md5Hash,Cnf);
350
351 string FinalFile;
352 FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
353
354 // sucess in downloading the index
355 // rename the index
356 FinalFile += string(".IndexDiff");
357 if(Debug)
358 std::clog << "Renaming: " << DestFile << " -> " << FinalFile
359 << std::endl;
360 Rename(DestFile,FinalFile);
361 chmod(FinalFile.c_str(),0644);
362 DestFile = FinalFile;
363
364 if(!ParseDiffIndex(DestFile))
365 return Failed("", NULL);
366
367 Complete = true;
368 Status = StatDone;
369 Dequeue();
370 return;
371}
372 /*}}}*/
373// AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
374// ---------------------------------------------------------------------
375/* The package diff is added to the queue. one object is constructed
376 * for each diff and the index
377 */
378pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
379 string URI,string URIDesc,string ShortDesc,
380 HashString ExpectedHash,
381 string ServerSha1,
382 vector<DiffInfo> diffs)
383 : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
384 available_patches(diffs), ServerSha1(ServerSha1)
385{
386
387 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
388 DestFile += URItoFileName(URI);
389
390 Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
391
392 Description = URIDesc;
393 Desc.Owner = this;
394 Desc.ShortDesc = ShortDesc;
395
396 if(available_patches.size() == 0)
397 {
398 // we are done (yeah!)
399 Finish(true);
400 }
401 else
402 {
403 // get the next diff
404 State = StateFetchDiff;
405 QueueNextDiff();
406 }
407}
408 /*}}}*/
409void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
410{
411 if(Debug)
412 std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
413 << "Falling back to normal index file aquire" << std::endl;
414 new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
415 ExpectedHash);
416 Finish();
417}
418 /*}}}*/
419// Finish - helper that cleans the item out of the fetcher queue /*{{{*/
420void pkgAcqIndexDiffs::Finish(bool allDone)
421{
422 // we restore the original name, this is required, otherwise
423 // the file will be cleaned
424 if(allDone)
425 {
426 DestFile = _config->FindDir("Dir::State::lists");
427 DestFile += URItoFileName(RealURI);
428
429 if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
430 {
431 Status = StatAuthError;
432 ErrorText = _("MD5Sum mismatch");
433 Rename(DestFile,DestFile + ".FAILED");
434 Dequeue();
435 return;
436 }
437
438 // this is for the "real" finish
439 Complete = true;
440 Status = StatDone;
441 Dequeue();
442 if(Debug)
443 std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
444 return;
445 }
446
447 if(Debug)
448 std::clog << "Finishing: " << Desc.URI << std::endl;
449 Complete = false;
450 Status = StatDone;
451 Dequeue();
452 return;
453}
454 /*}}}*/
455bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
456{
457
458 // calc sha1 of the just patched file
459 string FinalFile = _config->FindDir("Dir::State::lists");
460 FinalFile += URItoFileName(RealURI);
461
462 FileFd fd(FinalFile, FileFd::ReadOnly);
463 SHA1Summation SHA1;
464 SHA1.AddFD(fd.Fd(), fd.Size());
465 string local_sha1 = string(SHA1.Result());
466 if(Debug)
467 std::clog << "QueueNextDiff: "
468 << FinalFile << " (" << local_sha1 << ")"<<std::endl;
469
470 // final file reached before all patches are applied
471 if(local_sha1 == ServerSha1)
472 {
473 Finish(true);
474 return true;
475 }
476
477 // remove all patches until the next matching patch is found
478 // this requires the Index file to be ordered
479 for(vector<DiffInfo>::iterator I=available_patches.begin();
480 available_patches.size() > 0 &&
481 I != available_patches.end() &&
482 (*I).sha1 != local_sha1;
483 I++)
484 {
485 available_patches.erase(I);
486 }
487
488 // error checking and falling back if no patch was found
489 if(available_patches.size() == 0)
490 {
491 Failed("", NULL);
492 return false;
493 }
494
495 // queue the right diff
496 Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
497 Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
498 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
499 DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
500
501 if(Debug)
502 std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
503
504 QueueURI(Desc);
505
506 return true;
507}
508 /*}}}*/
509void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
510 pkgAcquire::MethodConfig *Cnf)
511{
512 if(Debug)
513 std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
514
515 Item::Done(Message,Size,Md5Hash,Cnf);
516
517 string FinalFile;
518 FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
519
520 // sucess in downloading a diff, enter ApplyDiff state
521 if(State == StateFetchDiff)
522 {
523
524 if(Debug)
525 std::clog << "Sending to gzip method: " << FinalFile << std::endl;
526
527 string FileName = LookupTag(Message,"Filename");
528 State = StateUnzipDiff;
529 Local = true;
530 Desc.URI = "gzip:" + FileName;
531 DestFile += ".decomp";
532 QueueURI(Desc);
533 Mode = "gzip";
534 return;
535 }
536
537 // sucess in downloading a diff, enter ApplyDiff state
538 if(State == StateUnzipDiff)
539 {
540
541 // rred excepts the patch as $FinalFile.ed
542 Rename(DestFile,FinalFile+".ed");
543
544 if(Debug)
545 std::clog << "Sending to rred method: " << FinalFile << std::endl;
546
547 State = StateApplyDiff;
548 Local = true;
549 Desc.URI = "rred:" + FinalFile;
550 QueueURI(Desc);
551 Mode = "rred";
552 return;
553 }
554
555
556 // success in download/apply a diff, queue next (if needed)
557 if(State == StateApplyDiff)
558 {
559 // remove the just applied patch
560 available_patches.erase(available_patches.begin());
561
562 // move into place
563 if(Debug)
564 {
565 std::clog << "Moving patched file in place: " << std::endl
566 << DestFile << " -> " << FinalFile << std::endl;
567 }
568 Rename(DestFile,FinalFile);
569 chmod(FinalFile.c_str(),0644);
570
571 // see if there is more to download
572 if(available_patches.size() > 0) {
573 new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
574 ExpectedHash, ServerSha1, available_patches);
575 return Finish();
576 } else
577 return Finish(true);
578 }
579}
580 /*}}}*/
581// AcqIndex::AcqIndex - Constructor /*{{{*/
582// ---------------------------------------------------------------------
583/* The package file is added to the queue and a second class is
584 instantiated to fetch the revision file */
585pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
586 string URI,string URIDesc,string ShortDesc,
587 HashString ExpectedHash, string comprExt)
588 : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
589{
590 Decompression = false;
591 Erase = false;
592
593 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
594 DestFile += URItoFileName(URI);
595
596 if(comprExt.empty())
597 {
598 // autoselect the compression method
599 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
600 if (types.empty() == true)
601 comprExt = "plain";
602 else
603 comprExt = "." + types[0];
604 }
605 CompressionExtension = ((comprExt == "plain" || comprExt == ".") ? "" : comprExt);
606
607 Desc.URI = URI + CompressionExtension;
608
609 Desc.Description = URIDesc;
610 Desc.Owner = this;
611 Desc.ShortDesc = ShortDesc;
612
613 QueueURI(Desc);
614}
615 /*}}}*/
616// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
617// ---------------------------------------------------------------------
618/* The only header we use is the last-modified header. */
619string pkgAcqIndex::Custom600Headers()
620{
621 string Final = _config->FindDir("Dir::State::lists");
622 Final += URItoFileName(RealURI);
623 if (_config->FindB("Acquire::GzipIndexes",false))
624 Final += ".gz";
625
626 struct stat Buf;
627 if (stat(Final.c_str(),&Buf) != 0)
628 return "\nIndex-File: true";
629
630 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
631}
632 /*}}}*/
633void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
634{
635 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
636
637 for (std::vector<std::string>::const_iterator t = types.begin();
638 t != types.end(); t++)
639 {
640 // jump over all already tried compression types
641 const unsigned int nameLen = Desc.URI.size() - (*t).size();
642 if(Desc.URI.substr(nameLen) != *t)
643 continue;
644
645 // we want to try it with the next extension (and make sure to
646 // not skip over the end)
647 t++;
648 if (t == types.end())
649 break;
650
651 // queue new download
652 Desc.URI = Desc.URI.substr(0, nameLen) + *t;
653 new pkgAcqIndex(Owner, RealURI, Desc.Description, Desc.ShortDesc,
654 ExpectedHash, string(".").append(*t));
655
656 Status = StatDone;
657 Complete = false;
658 Dequeue();
659 return;
660 }
661
662 // on decompression failure, remove bad versions in partial/
663 if(Decompression && Erase) {
664 string s = _config->FindDir("Dir::State::lists") + "partial/";
665 s += URItoFileName(RealURI);
666 unlink(s.c_str());
667 }
668
669 Item::Failed(Message,Cnf);
670}
671 /*}}}*/
672// AcqIndex::Done - Finished a fetch /*{{{*/
673// ---------------------------------------------------------------------
674/* This goes through a number of states.. On the initial fetch the
675 method could possibly return an alternate filename which points
676 to the uncompressed version of the file. If this is so the file
677 is copied into the partial directory. In all other cases the file
678 is decompressed with a gzip uri. */
679void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
680 pkgAcquire::MethodConfig *Cfg)
681{
682 Item::Done(Message,Size,Hash,Cfg);
683
684 if (Decompression == true)
685 {
686 if (_config->FindB("Debug::pkgAcquire::Auth", false))
687 {
688 std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
689 std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
690 }
691
692 if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
693 {
694 Status = StatAuthError;
695 ErrorText = _("Hash Sum mismatch");
696 Rename(DestFile,DestFile + ".FAILED");
697 return;
698 }
699 // Done, move it into position
700 string FinalFile = _config->FindDir("Dir::State::lists");
701 FinalFile += URItoFileName(RealURI);
702 Rename(DestFile,FinalFile);
703 chmod(FinalFile.c_str(),0644);
704
705 /* We restore the original name to DestFile so that the clean operation
706 will work OK */
707 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
708 DestFile += URItoFileName(RealURI);
709
710 // Remove the compressed version.
711 if (Erase == true)
712 unlink(DestFile.c_str());
713 return;
714 }
715
716 Erase = false;
717 Complete = true;
718
719 string compExt = flExtension(flNotDir(URI(Desc.URI).Path));
720
721 // If we enable compressed indexes and already have gzip, keep it
722 if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz") {
723 string FinalFile = _config->FindDir("Dir::State::lists");
724 FinalFile += URItoFileName(RealURI) + ".gz";
725 //if(Debug)
726 // std::clog << "pkgAcqIndex: keeping gzipped " << FinalFile << endl;
727 Rename(DestFile,FinalFile);
728 chmod(FinalFile.c_str(),0644);
729
730 // Update DestFile for .gz suffix so that the clean operation keeps it
731 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
732 DestFile += URItoFileName(RealURI) + ".gz";
733 return;
734 }
735
736 // Handle the unzipd case
737 string FileName = LookupTag(Message,"Alt-Filename");
738 if (FileName.empty() == false)
739 {
740 // The files timestamp matches
741 if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
742 return;
743 Decompression = true;
744 Local = true;
745 DestFile += ".decomp";
746 Desc.URI = "copy:" + FileName;
747 QueueURI(Desc);
748 Mode = "copy";
749 return;
750 }
751
752 FileName = LookupTag(Message,"Filename");
753 if (FileName.empty() == true)
754 {
755 Status = StatError;
756 ErrorText = "Method gave a blank filename";
757 }
758
759 // The files timestamp matches
760 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
761 return;
762
763 if (FileName == DestFile)
764 Erase = true;
765 else
766 Local = true;
767
768 string decompProg;
769
770 // get the binary name for your used compression type
771 decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
772 if(decompProg.empty() == false);
773 // flExtensions returns the full name if no extension is found
774 // this is why we have this complicated compare operation here
775 // FIMXE: add a new flJustExtension() that return "" if no
776 // extension is found and use that above so that it can
777 // be tested against ""
778 else if(compExt == flNotDir(URI(Desc.URI).Path))
779 decompProg = "copy";
780 else {
781 _error->Error("Unsupported extension: %s", compExt.c_str());
782 return;
783 }
784
785 Decompression = true;
786 DestFile += ".decomp";
787 Desc.URI = decompProg + ":" + FileName;
788 QueueURI(Desc);
789 Mode = decompProg.c_str();
790}
791 /*}}}*/
792// AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
793// ---------------------------------------------------------------------
794/* The Translation file is added to the queue */
795pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
796 string URI,string URIDesc,string ShortDesc)
797 : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
798{
799}
800 /*}}}*/
801// AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
802// ---------------------------------------------------------------------
803/* */
804void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
805{
806 if (Cnf->LocalOnly == true ||
807 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
808 {
809 // Ignore this
810 Status = StatDone;
811 Complete = false;
812 Dequeue();
813 return;
814 }
815
816 Item::Failed(Message,Cnf);
817}
818 /*}}}*/
819pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
820 string URI,string URIDesc,string ShortDesc,
821 string MetaIndexURI, string MetaIndexURIDesc,
822 string MetaIndexShortDesc,
823 const vector<IndexTarget*>* IndexTargets,
824 indexRecords* MetaIndexParser) :
825 Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
826 MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
827 MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
828{
829 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
830 DestFile += URItoFileName(URI);
831
832 // remove any partial downloaded sig-file in partial/.
833 // it may confuse proxies and is too small to warrant a
834 // partial download anyway
835 unlink(DestFile.c_str());
836
837 // Create the item
838 Desc.Description = URIDesc;
839 Desc.Owner = this;
840 Desc.ShortDesc = ShortDesc;
841 Desc.URI = URI;
842
843 string Final = _config->FindDir("Dir::State::lists");
844 Final += URItoFileName(RealURI);
845 struct stat Buf;
846 if (stat(Final.c_str(),&Buf) == 0)
847 {
848 // File was already in place. It needs to be re-downloaded/verified
849 // because Release might have changed, we do give it a differnt
850 // name than DestFile because otherwise the http method will
851 // send If-Range requests and there are too many broken servers
852 // out there that do not understand them
853 LastGoodSig = DestFile+".reverify";
854 Rename(Final,LastGoodSig);
855 }
856
857 QueueURI(Desc);
858}
859 /*}}}*/
860// pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
861// ---------------------------------------------------------------------
862/* The only header we use is the last-modified header. */
863string pkgAcqMetaSig::Custom600Headers()
864{
865 struct stat Buf;
866 if (stat(LastGoodSig.c_str(),&Buf) != 0)
867 return "\nIndex-File: true";
868
869 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
870}
871
872void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
873 pkgAcquire::MethodConfig *Cfg)
874{
875 Item::Done(Message,Size,MD5,Cfg);
876
877 string FileName = LookupTag(Message,"Filename");
878 if (FileName.empty() == true)
879 {
880 Status = StatError;
881 ErrorText = "Method gave a blank filename";
882 return;
883 }
884
885 if (FileName != DestFile)
886 {
887 // We have to copy it into place
888 Local = true;
889 Desc.URI = "copy:" + FileName;
890 QueueURI(Desc);
891 return;
892 }
893
894 Complete = true;
895
896 // put the last known good file back on i-m-s hit (it will
897 // be re-verified again)
898 // Else do nothing, we have the new file in DestFile then
899 if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
900 Rename(LastGoodSig, DestFile);
901
902 // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
903 new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
904 DestFile, IndexTargets, MetaIndexParser);
905
906}
907 /*}}}*/
908void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
909{
910 string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
911
912 // if we get a network error we fail gracefully
913 if(Status == StatTransientNetworkError)
914 {
915 Item::Failed(Message,Cnf);
916 // move the sigfile back on transient network failures
917 if(FileExists(DestFile))
918 Rename(LastGoodSig,Final);
919
920 // set the status back to , Item::Failed likes to reset it
921 Status = pkgAcquire::Item::StatTransientNetworkError;
922 return;
923 }
924
925 // Delete any existing sigfile when the acquire failed
926 unlink(Final.c_str());
927
928 // queue a pkgAcqMetaIndex with no sigfile
929 new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
930 "", IndexTargets, MetaIndexParser);
931
932 if (Cnf->LocalOnly == true ||
933 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
934 {
935 // Ignore this
936 Status = StatDone;
937 Complete = false;
938 Dequeue();
939 return;
940 }
941
942 Item::Failed(Message,Cnf);
943}
944 /*}}}*/
945pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
946 string URI,string URIDesc,string ShortDesc,
947 string SigFile,
948 const vector<struct IndexTarget*>* IndexTargets,
949 indexRecords* MetaIndexParser) :
950 Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
951 MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
952{
953 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
954 DestFile += URItoFileName(URI);
955
956 // Create the item
957 Desc.Description = URIDesc;
958 Desc.Owner = this;
959 Desc.ShortDesc = ShortDesc;
960 Desc.URI = URI;
961
962 QueueURI(Desc);
963}
964 /*}}}*/
965// pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
966// ---------------------------------------------------------------------
967/* The only header we use is the last-modified header. */
968string pkgAcqMetaIndex::Custom600Headers()
969{
970 string Final = _config->FindDir("Dir::State::lists");
971 Final += URItoFileName(RealURI);
972
973 struct stat Buf;
974 if (stat(Final.c_str(),&Buf) != 0)
975 return "\nIndex-File: true";
976
977 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
978}
979 /*}}}*/
980void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash, /*{{{*/
981 pkgAcquire::MethodConfig *Cfg)
982{
983 Item::Done(Message,Size,Hash,Cfg);
984
985 // MetaIndexes are done in two passes: one to download the
986 // metaindex with an appropriate method, and a second to verify it
987 // with the gpgv method
988
989 if (AuthPass == true)
990 {
991 AuthDone(Message);
992 }
993 else
994 {
995 RetrievalDone(Message);
996 if (!Complete)
997 // Still more retrieving to do
998 return;
999
1000 if (SigFile == "")
1001 {
1002 // There was no signature file, so we are finished. Download
1003 // the indexes without verification.
1004 QueueIndexes(false);
1005 }
1006 else
1007 {
1008 // There was a signature file, so pass it to gpgv for
1009 // verification
1010
1011 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1012 std::cerr << "Metaindex acquired, queueing gpg verification ("
1013 << SigFile << "," << DestFile << ")\n";
1014 AuthPass = true;
1015 Desc.URI = "gpgv:" + SigFile;
1016 QueueURI(Desc);
1017 Mode = "gpgv";
1018 }
1019 }
1020}
1021 /*}}}*/
1022void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
1023{
1024 // We have just finished downloading a Release file (it is not
1025 // verified yet)
1026
1027 string FileName = LookupTag(Message,"Filename");
1028 if (FileName.empty() == true)
1029 {
1030 Status = StatError;
1031 ErrorText = "Method gave a blank filename";
1032 return;
1033 }
1034
1035 if (FileName != DestFile)
1036 {
1037 Local = true;
1038 Desc.URI = "copy:" + FileName;
1039 QueueURI(Desc);
1040 return;
1041 }
1042
1043 // see if the download was a IMSHit
1044 IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
1045 Complete = true;
1046
1047 string FinalFile = _config->FindDir("Dir::State::lists");
1048 FinalFile += URItoFileName(RealURI);
1049
1050 // If we get a IMS hit we can remove the empty file in partial
1051 // othersie we move the file in place
1052 if (IMSHit)
1053 unlink(DestFile.c_str());
1054 else
1055 Rename(DestFile,FinalFile);
1056
1057 chmod(FinalFile.c_str(),0644);
1058 DestFile = FinalFile;
1059}
1060 /*}}}*/
1061void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
1062{
1063 // At this point, the gpgv method has succeeded, so there is a
1064 // valid signature from a key in the trusted keyring. We
1065 // perform additional verification of its contents, and use them
1066 // to verify the indexes we are about to download
1067
1068 if (!MetaIndexParser->Load(DestFile))
1069 {
1070 Status = StatAuthError;
1071 ErrorText = MetaIndexParser->ErrorText;
1072 return;
1073 }
1074
1075 if (!VerifyVendor(Message))
1076 {
1077 return;
1078 }
1079
1080 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1081 std::cerr << "Signature verification succeeded: "
1082 << DestFile << std::endl;
1083
1084 // Download further indexes with verification
1085 QueueIndexes(true);
1086
1087 // Done, move signature file into position
1088
1089 string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
1090 URItoFileName(RealURI) + ".gpg";
1091 Rename(SigFile,VerifiedSigFile);
1092 chmod(VerifiedSigFile.c_str(),0644);
1093}
1094 /*}}}*/
1095void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
1096{
1097 for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
1098 Target != IndexTargets->end();
1099 Target++)
1100 {
1101 HashString ExpectedIndexHash;
1102 if (verify)
1103 {
1104 const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
1105 if (!Record)
1106 {
1107 Status = StatAuthError;
1108 ErrorText = "Unable to find expected entry "
1109 + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
1110 return;
1111 }
1112 ExpectedIndexHash = Record->Hash;
1113 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1114 {
1115 std::cerr << "Queueing: " << (*Target)->URI << std::endl;
1116 std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
1117 }
1118 if (ExpectedIndexHash.empty())
1119 {
1120 Status = StatAuthError;
1121 ErrorText = "Unable to find hash sum for "
1122 + (*Target)->MetaKey + " in Meta-index file";
1123 return;
1124 }
1125 }
1126
1127 // Queue Packages file (either diff or full packages files, depending
1128 // on the users option)
1129 if(_config->FindB("Acquire::PDiffs",true) == true)
1130 new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
1131 (*Target)->ShortDesc, ExpectedIndexHash);
1132 else
1133 new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
1134 (*Target)->ShortDesc, ExpectedIndexHash);
1135 }
1136}
1137 /*}}}*/
1138bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
1139{
1140// // Maybe this should be made available from above so we don't have
1141// // to read and parse it every time?
1142// pkgVendorList List;
1143// List.ReadMainList();
1144
1145// const Vendor* Vndr = NULL;
1146// for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
1147// {
1148// string::size_type pos = (*I).find("VALIDSIG ");
1149// if (_config->FindB("Debug::Vendor", false))
1150// std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
1151// << std::endl;
1152// if (pos != std::string::npos)
1153// {
1154// string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
1155// if (_config->FindB("Debug::Vendor", false))
1156// std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
1157// std::endl;
1158// Vndr = List.FindVendor(Fingerprint) != "";
1159// if (Vndr != NULL);
1160// break;
1161// }
1162// }
1163 string::size_type pos;
1164
1165 // check for missing sigs (that where not fatal because otherwise we had
1166 // bombed earlier)
1167 string missingkeys;
1168 string msg = _("There is no public key available for the "
1169 "following key IDs:\n");
1170 pos = Message.find("NO_PUBKEY ");
1171 if (pos != std::string::npos)
1172 {
1173 string::size_type start = pos+strlen("NO_PUBKEY ");
1174 string Fingerprint = Message.substr(start, Message.find("\n")-start);
1175 missingkeys += (Fingerprint);
1176 }
1177 if(!missingkeys.empty())
1178 _error->Warning("%s", string(msg+missingkeys).c_str());
1179
1180 string Transformed = MetaIndexParser->GetExpectedDist();
1181
1182 if (Transformed == "../project/experimental")
1183 {
1184 Transformed = "experimental";
1185 }
1186
1187 pos = Transformed.rfind('/');
1188 if (pos != string::npos)
1189 {
1190 Transformed = Transformed.substr(0, pos);
1191 }
1192
1193 if (Transformed == ".")
1194 {
1195 Transformed = "";
1196 }
1197
1198 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1199 {
1200 std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
1201 std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
1202 std::cerr << "Transformed Dist: " << Transformed << std::endl;
1203 }
1204
1205 if (MetaIndexParser->CheckDist(Transformed) == false)
1206 {
1207 // This might become fatal one day
1208// Status = StatAuthError;
1209// ErrorText = "Conflicting distribution; expected "
1210// + MetaIndexParser->GetExpectedDist() + " but got "
1211// + MetaIndexParser->GetDist();
1212// return false;
1213 if (!Transformed.empty())
1214 {
1215 _error->Warning("Conflicting distribution: %s (expected %s but got %s)",
1216 Desc.Description.c_str(),
1217 Transformed.c_str(),
1218 MetaIndexParser->GetDist().c_str());
1219 }
1220 }
1221
1222 return true;
1223}
1224 /*}}}*/
1225// pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
1226// ---------------------------------------------------------------------
1227/* */
1228void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
1229{
1230 if (AuthPass == true)
1231 {
1232 // if we fail the authentication but got the file via a IMS-Hit
1233 // this means that the file wasn't downloaded and that it might be
1234 // just stale (server problem, proxy etc). we delete what we have
1235 // queue it again without i-m-s
1236 // alternatively we could just unlink the file and let the user try again
1237 if (IMSHit)
1238 {
1239 Complete = false;
1240 Local = false;
1241 AuthPass = false;
1242 unlink(DestFile.c_str());
1243
1244 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1245 DestFile += URItoFileName(RealURI);
1246 Desc.URI = RealURI;
1247 QueueURI(Desc);
1248 return;
1249 }
1250
1251 // gpgv method failed
1252 _error->Warning("GPG error: %s: %s",
1253 Desc.Description.c_str(),
1254 LookupTag(Message,"Message").c_str());
1255
1256 }
1257
1258 // No Release file was present, or verification failed, so fall
1259 // back to queueing Packages files without verification
1260 QueueIndexes(false);
1261}
1262 /*}}}*/
1263// AcqArchive::AcqArchive - Constructor /*{{{*/
1264// ---------------------------------------------------------------------
1265/* This just sets up the initial fetch environment and queues the first
1266 possibilitiy */
1267pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
1268 pkgRecords *Recs,pkgCache::VerIterator const &Version,
1269 string &StoreFilename) :
1270 Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
1271 StoreFilename(StoreFilename), Vf(Version.FileList()),
1272 Trusted(false)
1273{
1274 Retries = _config->FindI("Acquire::Retries",0);
1275
1276 if (Version.Arch() == 0)
1277 {
1278 _error->Error(_("I wasn't able to locate a file for the %s package. "
1279 "This might mean you need to manually fix this package. "
1280 "(due to missing arch)"),
1281 Version.ParentPkg().Name());
1282 return;
1283 }
1284
1285 /* We need to find a filename to determine the extension. We make the
1286 assumption here that all the available sources for this version share
1287 the same extension.. */
1288 // Skip not source sources, they do not have file fields.
1289 for (; Vf.end() == false; Vf++)
1290 {
1291 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
1292 continue;
1293 break;
1294 }
1295
1296 // Does not really matter here.. we are going to fail out below
1297 if (Vf.end() != true)
1298 {
1299 // If this fails to get a file name we will bomb out below.
1300 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
1301 if (_error->PendingError() == true)
1302 return;
1303
1304 // Generate the final file name as: package_version_arch.foo
1305 StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
1306 QuoteString(Version.VerStr(),"_:") + '_' +
1307 QuoteString(Version.Arch(),"_:.") +
1308 "." + flExtension(Parse.FileName());
1309 }
1310
1311 // check if we have one trusted source for the package. if so, switch
1312 // to "TrustedOnly" mode
1313 for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
1314 {
1315 pkgIndexFile *Index;
1316 if (Sources->FindIndex(i.File(),Index) == false)
1317 continue;
1318 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1319 {
1320 std::cerr << "Checking index: " << Index->Describe()
1321 << "(Trusted=" << Index->IsTrusted() << ")\n";
1322 }
1323 if (Index->IsTrusted()) {
1324 Trusted = true;
1325 break;
1326 }
1327 }
1328
1329 // "allow-unauthenticated" restores apts old fetching behaviour
1330 // that means that e.g. unauthenticated file:// uris are higher
1331 // priority than authenticated http:// uris
1332 if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
1333 Trusted = false;
1334
1335 // Select a source
1336 if (QueueNext() == false && _error->PendingError() == false)
1337 _error->Error(_("I wasn't able to locate file for the %s package. "
1338 "This might mean you need to manually fix this package."),
1339 Version.ParentPkg().Name());
1340}
1341 /*}}}*/
1342// AcqArchive::QueueNext - Queue the next file source /*{{{*/
1343// ---------------------------------------------------------------------
1344/* This queues the next available file version for download. It checks if
1345 the archive is already available in the cache and stashs the MD5 for
1346 checking later. */
1347bool pkgAcqArchive::QueueNext()
1348{
1349 for (; Vf.end() == false; Vf++)
1350 {
1351 // Ignore not source sources
1352 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
1353 continue;
1354
1355 // Try to cross match against the source list
1356 pkgIndexFile *Index;
1357 if (Sources->FindIndex(Vf.File(),Index) == false)
1358 continue;
1359
1360 // only try to get a trusted package from another source if that source
1361 // is also trusted
1362 if(Trusted && !Index->IsTrusted())
1363 continue;
1364
1365 // Grab the text package record
1366 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
1367 if (_error->PendingError() == true)
1368 return false;
1369
1370 string PkgFile = Parse.FileName();
1371 if(Parse.SHA256Hash() != "")
1372 ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
1373 else if (Parse.SHA1Hash() != "")
1374 ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
1375 else
1376 ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
1377 if (PkgFile.empty() == true)
1378 return _error->Error(_("The package index files are corrupted. No Filename: "
1379 "field for package %s."),
1380 Version.ParentPkg().Name());
1381
1382 Desc.URI = Index->ArchiveURI(PkgFile);
1383 Desc.Description = Index->ArchiveInfo(Version);
1384 Desc.Owner = this;
1385 Desc.ShortDesc = Version.ParentPkg().Name();
1386
1387 // See if we already have the file. (Legacy filenames)
1388 FileSize = Version->Size;
1389 string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
1390 struct stat Buf;
1391 if (stat(FinalFile.c_str(),&Buf) == 0)
1392 {
1393 // Make sure the size matches
1394 if ((unsigned)Buf.st_size == Version->Size)
1395 {
1396 Complete = true;
1397 Local = true;
1398 Status = StatDone;
1399 StoreFilename = DestFile = FinalFile;
1400 return true;
1401 }
1402
1403 /* Hmm, we have a file and its size does not match, this means it is
1404 an old style mismatched arch */
1405 unlink(FinalFile.c_str());
1406 }
1407
1408 // Check it again using the new style output filenames
1409 FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
1410 if (stat(FinalFile.c_str(),&Buf) == 0)
1411 {
1412 // Make sure the size matches
1413 if ((unsigned)Buf.st_size == Version->Size)
1414 {
1415 Complete = true;
1416 Local = true;
1417 Status = StatDone;
1418 StoreFilename = DestFile = FinalFile;
1419 return true;
1420 }
1421
1422 /* Hmm, we have a file and its size does not match, this shouldnt
1423 happen.. */
1424 unlink(FinalFile.c_str());
1425 }
1426
1427 DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
1428
1429 // Check the destination file
1430 if (stat(DestFile.c_str(),&Buf) == 0)
1431 {
1432 // Hmm, the partial file is too big, erase it
1433 if ((unsigned)Buf.st_size > Version->Size)
1434 unlink(DestFile.c_str());
1435 else
1436 PartialSize = Buf.st_size;
1437 }
1438
1439 // Create the item
1440 Local = false;
1441 Desc.URI = Index->ArchiveURI(PkgFile);
1442 Desc.Description = Index->ArchiveInfo(Version);
1443 Desc.Owner = this;
1444 Desc.ShortDesc = Version.ParentPkg().Name();
1445 QueueURI(Desc);
1446
1447 Vf++;
1448 return true;
1449 }
1450 return false;
1451}
1452 /*}}}*/
1453// AcqArchive::Done - Finished fetching /*{{{*/
1454// ---------------------------------------------------------------------
1455/* */
1456void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
1457 pkgAcquire::MethodConfig *Cfg)
1458{
1459 Item::Done(Message,Size,CalcHash,Cfg);
1460
1461 // Check the size
1462 if (Size != Version->Size)
1463 {
1464 Status = StatError;
1465 ErrorText = _("Size mismatch");
1466 return;
1467 }
1468
1469 // Check the hash
1470 if(ExpectedHash.toStr() != CalcHash)
1471 {
1472 Status = StatError;
1473 ErrorText = _("Hash Sum mismatch");
1474 if(FileExists(DestFile))
1475 Rename(DestFile,DestFile + ".FAILED");
1476 return;
1477 }
1478
1479 // Grab the output filename
1480 string FileName = LookupTag(Message,"Filename");
1481 if (FileName.empty() == true)
1482 {
1483 Status = StatError;
1484 ErrorText = "Method gave a blank filename";
1485 return;
1486 }
1487
1488 Complete = true;
1489
1490 // Reference filename
1491 if (FileName != DestFile)
1492 {
1493 StoreFilename = DestFile = FileName;
1494 Local = true;
1495 return;
1496 }
1497
1498 // Done, move it into position
1499 string FinalFile = _config->FindDir("Dir::Cache::Archives");
1500 FinalFile += flNotDir(StoreFilename);
1501 Rename(DestFile,FinalFile);
1502
1503 StoreFilename = DestFile = FinalFile;
1504 Complete = true;
1505}
1506 /*}}}*/
1507// AcqArchive::Failed - Failure handler /*{{{*/
1508// ---------------------------------------------------------------------
1509/* Here we try other sources */
1510void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
1511{
1512 ErrorText = LookupTag(Message,"Message");
1513
1514 /* We don't really want to retry on failed media swaps, this prevents
1515 that. An interesting observation is that permanent failures are not
1516 recorded. */
1517 if (Cnf->Removable == true &&
1518 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
1519 {
1520 // Vf = Version.FileList();
1521 while (Vf.end() == false) Vf++;
1522 StoreFilename = string();
1523 Item::Failed(Message,Cnf);
1524 return;
1525 }
1526
1527 if (QueueNext() == false)
1528 {
1529 // This is the retry counter
1530 if (Retries != 0 &&
1531 Cnf->LocalOnly == false &&
1532 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
1533 {
1534 Retries--;
1535 Vf = Version.FileList();
1536 if (QueueNext() == true)
1537 return;
1538 }
1539
1540 StoreFilename = string();
1541 Item::Failed(Message,Cnf);
1542 }
1543}
1544 /*}}}*/
1545// AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
1546// ---------------------------------------------------------------------
1547bool pkgAcqArchive::IsTrusted()
1548{
1549 return Trusted;
1550}
1551 /*}}}*/
1552// AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
1553// ---------------------------------------------------------------------
1554/* */
1555void pkgAcqArchive::Finished()
1556{
1557 if (Status == pkgAcquire::Item::StatDone &&
1558 Complete == true)
1559 return;
1560 StoreFilename = string();
1561}
1562 /*}}}*/
1563// AcqFile::pkgAcqFile - Constructor /*{{{*/
1564// ---------------------------------------------------------------------
1565/* The file is added to the queue */
1566pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
1567 unsigned long Size,string Dsc,string ShortDesc,
1568 const string &DestDir, const string &DestFilename,
1569 bool IsIndexFile) :
1570 Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
1571{
1572 Retries = _config->FindI("Acquire::Retries",0);
1573
1574 if(!DestFilename.empty())
1575 DestFile = DestFilename;
1576 else if(!DestDir.empty())
1577 DestFile = DestDir + "/" + flNotDir(URI);
1578 else
1579 DestFile = flNotDir(URI);
1580
1581 // Create the item
1582 Desc.URI = URI;
1583 Desc.Description = Dsc;
1584 Desc.Owner = this;
1585
1586 // Set the short description to the archive component
1587 Desc.ShortDesc = ShortDesc;
1588
1589 // Get the transfer sizes
1590 FileSize = Size;
1591 struct stat Buf;
1592 if (stat(DestFile.c_str(),&Buf) == 0)
1593 {
1594 // Hmm, the partial file is too big, erase it
1595 if ((unsigned)Buf.st_size > Size)
1596 unlink(DestFile.c_str());
1597 else
1598 PartialSize = Buf.st_size;
1599 }
1600
1601 QueueURI(Desc);
1602}
1603 /*}}}*/
1604// AcqFile::Done - Item downloaded OK /*{{{*/
1605// ---------------------------------------------------------------------
1606/* */
1607void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
1608 pkgAcquire::MethodConfig *Cnf)
1609{
1610 Item::Done(Message,Size,CalcHash,Cnf);
1611
1612 // Check the hash
1613 if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
1614 {
1615 Status = StatError;
1616 ErrorText = "Hash Sum mismatch";
1617 Rename(DestFile,DestFile + ".FAILED");
1618 return;
1619 }
1620
1621 string FileName = LookupTag(Message,"Filename");
1622 if (FileName.empty() == true)
1623 {
1624 Status = StatError;
1625 ErrorText = "Method gave a blank filename";
1626 return;
1627 }
1628
1629 Complete = true;
1630
1631 // The files timestamp matches
1632 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
1633 return;
1634
1635 // We have to copy it into place
1636 if (FileName != DestFile)
1637 {
1638 Local = true;
1639 if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
1640 Cnf->Removable == true)
1641 {
1642 Desc.URI = "copy:" + FileName;
1643 QueueURI(Desc);
1644 return;
1645 }
1646
1647 // Erase the file if it is a symlink so we can overwrite it
1648 struct stat St;
1649 if (lstat(DestFile.c_str(),&St) == 0)
1650 {
1651 if (S_ISLNK(St.st_mode) != 0)
1652 unlink(DestFile.c_str());
1653 }
1654
1655 // Symlink the file
1656 if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
1657 {
1658 ErrorText = "Link to " + DestFile + " failure ";
1659 Status = StatError;
1660 Complete = false;
1661 }
1662 }
1663}
1664 /*}}}*/
1665// AcqFile::Failed - Failure handler /*{{{*/
1666// ---------------------------------------------------------------------
1667/* Here we try other sources */
1668void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
1669{
1670 ErrorText = LookupTag(Message,"Message");
1671
1672 // This is the retry counter
1673 if (Retries != 0 &&
1674 Cnf->LocalOnly == false &&
1675 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
1676 {
1677 Retries--;
1678 QueueURI(Desc);
1679 return;
1680 }
1681
1682 Item::Failed(Message,Cnf);
1683}
1684 /*}}}*/
1685// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
1686// ---------------------------------------------------------------------
1687/* The only header we use is the last-modified header. */
1688string pkgAcqFile::Custom600Headers()
1689{
1690 if (IsIndexFile)
1691 return "\nIndex-File: true";
1692}
1693 /*}}}*/