]> git.saurik.com Git - apt.git/blame - apt-pkg/acquire-item.cc
* apt-pkg/acquire-item.cc:
[apt.git] / apt-pkg / acquire-item.cc
CommitLineData
0118833a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
b3d44315 3// $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
0118833a
AL
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.
b185acc2 12
0118833a
AL
13 ##################################################################### */
14 /*}}}*/
15// Include Files /*{{{*/
16#ifdef __GNUG__
17#pragma implementation "apt-pkg/acquire-item.h"
18#endif
19#include <apt-pkg/acquire-item.h>
20#include <apt-pkg/configuration.h>
b2e465d6 21#include <apt-pkg/sourcelist.h>
b3d44315 22#include <apt-pkg/vendorlist.h>
03e39e59 23#include <apt-pkg/error.h>
cdcc6d34 24#include <apt-pkg/strutl.h>
36375005 25#include <apt-pkg/fileutl.h>
b3d44315 26#include <apt-pkg/md5.h>
0a8a80e5 27
b2e465d6
AL
28#include <apti18n.h>
29
0a8a80e5
AL
30#include <sys/stat.h>
31#include <unistd.h>
c88edf1d 32#include <errno.h>
5819a761 33#include <string>
c88edf1d 34#include <stdio.h>
0118833a
AL
35 /*}}}*/
36
b3d44315 37using namespace std;
5819a761 38
0118833a
AL
39// Acquire::Item::Item - Constructor /*{{{*/
40// ---------------------------------------------------------------------
41/* */
8267fe24 42pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
6b1ff003
AL
43 PartialSize(0), Mode(0), ID(0), Complete(false),
44 Local(false), QueueCounter(0)
0118833a
AL
45{
46 Owner->Add(this);
c88edf1d 47 Status = StatIdle;
0118833a
AL
48}
49 /*}}}*/
50// Acquire::Item::~Item - Destructor /*{{{*/
51// ---------------------------------------------------------------------
52/* */
53pkgAcquire::Item::~Item()
54{
55 Owner->Remove(this);
56}
57 /*}}}*/
c88edf1d
AL
58// Acquire::Item::Failed - Item failed to download /*{{{*/
59// ---------------------------------------------------------------------
93bf083d
AL
60/* We return to an idle state if there are still other queues that could
61 fetch this object */
7d8afa39 62void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
c88edf1d 63{
93bf083d 64 Status = StatIdle;
db890fdb 65 ErrorText = LookupTag(Message,"Message");
361593e9 66 UsedMirror = LookupTag(Message,"UsedMirror");
c88edf1d 67 if (QueueCounter <= 1)
93bf083d 68 {
a72ace20 69 /* This indicates that the file is not available right now but might
7d8afa39 70 be sometime later. If we do a retry cycle then this should be
17caf1b1 71 retried [CDROMs] */
7d8afa39
AL
72 if (Cnf->LocalOnly == true &&
73 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
a72ace20
AL
74 {
75 Status = StatIdle;
681d76d0 76 Dequeue();
a72ace20
AL
77 return;
78 }
79
93bf083d 80 Status = StatError;
681d76d0 81 Dequeue();
93bf083d 82 }
36280399
MV
83
84 // report mirror failure back to LP if we actually use a mirror
f0b509cd
MV
85 string FailReason = LookupTag(Message, "FailReason");
86 if(FailReason.size() != 0)
87 ReportMirrorFailure(FailReason);
88 else
89 ReportMirrorFailure(ErrorText);
c88edf1d
AL
90}
91 /*}}}*/
8267fe24
AL
92// Acquire::Item::Start - Item has begun to download /*{{{*/
93// ---------------------------------------------------------------------
17caf1b1
AL
94/* Stash status and the file size. Note that setting Complete means
95 sub-phases of the acquire process such as decompresion are operating */
727f18af 96void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
8267fe24
AL
97{
98 Status = StatFetching;
99 if (FileSize == 0 && Complete == false)
100 FileSize = Size;
101}
102 /*}}}*/
c88edf1d
AL
103// Acquire::Item::Done - Item downloaded OK /*{{{*/
104// ---------------------------------------------------------------------
105/* */
459681d3
AL
106void pkgAcquire::Item::Done(string Message,unsigned long Size,string,
107 pkgAcquire::MethodConfig *Cnf)
c88edf1d 108{
b98f2859
AL
109 // We just downloaded something..
110 string FileName = LookupTag(Message,"Filename");
36280399 111 UsedMirror = LookupTag(Message,"UsedMirror");
b98f2859
AL
112 if (Complete == false && FileName == DestFile)
113 {
114 if (Owner->Log != 0)
115 Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
116 }
aa0e1101
AL
117
118 if (FileSize == 0)
119 FileSize= Size;
c88edf1d
AL
120 Status = StatDone;
121 ErrorText = string();
122 Owner->Dequeue(this);
123}
124 /*}}}*/
8b89e57f
AL
125// Acquire::Item::Rename - Rename a file /*{{{*/
126// ---------------------------------------------------------------------
127/* This helper function is used by alot of item methods as thier final
128 step */
129void pkgAcquire::Item::Rename(string From,string To)
130{
131 if (rename(From.c_str(),To.c_str()) != 0)
132 {
133 char S[300];
0fcd01de 134 snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
8b89e57f
AL
135 From.c_str(),To.c_str());
136 Status = StatError;
137 ErrorText = S;
7a3c2ab0 138 }
8b89e57f
AL
139}
140 /*}}}*/
0118833a 141
36280399
MV
142void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
143{
59271f62
MV
144 // we only act if a mirror was used at all
145 if(UsedMirror.empty())
146 return;
36280399
MV
147#if 0
148 std::cerr << "\nReportMirrorFailure: "
149 << UsedMirror
59271f62 150 << " Uri: " << DescURI()
36280399
MV
151 << " FailCode: "
152 << FailCode << std::endl;
153#endif
154 const char *Args[40];
155 unsigned int i = 0;
156 string report = _config->Find("Methods::Mirror::ProblemReporting",
157 "/usr/bin/apt-report-mirror-failure");
158 if(!FileExists(report))
159 return;
160 Args[i++] = report.c_str();
161 Args[i++] = UsedMirror.c_str();
f0b509cd 162 Args[i++] = DescURI().c_str();
36280399 163 Args[i++] = FailCode.c_str();
361593e9 164 Args[i++] = NULL;
36280399
MV
165 pid_t pid = ExecFork();
166 if(pid < 0)
167 {
168 _error->Error("ReportMirrorFailure Fork failed");
169 return;
170 }
171 else if(pid == 0)
172 {
361593e9
MV
173 execvp(Args[0], (char**)Args);
174 std::cerr << "Could not exec " << Args[0] << std::endl;
175 _exit(100);
36280399
MV
176 }
177 if(!ExecWait(pid, "report-mirror-failure"))
178 {
179 _error->Warning("Couldn't report problem to '%s'",
361593e9 180 _config->Find("Methods::Mirror::ProblemReporting").c_str());
36280399
MV
181 }
182}
183
184
0118833a
AL
185// AcqIndex::AcqIndex - Constructor /*{{{*/
186// ---------------------------------------------------------------------
187/* The package file is added to the queue and a second class is
b2e465d6
AL
188 instantiated to fetch the revision file */
189pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
b3d44315
MV
190 string URI,string URIDesc,string ShortDesc,
191 string ExpectedMD5, string comprExt) :
192 Item(Owner), RealURI(URI), ExpectedMD5(ExpectedMD5)
0118833a 193{
8b89e57f 194 Decompression = false;
bfd22fc0 195 Erase = false;
13e8426f 196
0a8a80e5 197 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
b2e465d6 198 DestFile += URItoFileName(URI);
8267fe24 199
b3d44315
MV
200 if(comprExt.empty())
201 {
13e8426f 202 // autoselect the compression method
4577fda2 203 if(FileExists("/bin/bzip2"))
13e8426f
MV
204 CompressionExtension = ".bz2";
205 else
206 CompressionExtension = ".gz";
b3d44315 207 } else {
13e8426f 208 CompressionExtension = comprExt;
b3d44315 209 }
13e8426f 210 Desc.URI = URI + CompressionExtension;
b3d44315 211
b2e465d6 212 Desc.Description = URIDesc;
8267fe24 213 Desc.Owner = this;
b2e465d6 214 Desc.ShortDesc = ShortDesc;
8267fe24
AL
215
216 QueueURI(Desc);
0118833a
AL
217}
218 /*}}}*/
0a8a80e5 219// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
0118833a 220// ---------------------------------------------------------------------
0a8a80e5
AL
221/* The only header we use is the last-modified header. */
222string pkgAcqIndex::Custom600Headers()
0118833a 223{
0a8a80e5 224 string Final = _config->FindDir("Dir::State::lists");
b2e465d6 225 Final += URItoFileName(RealURI);
0a8a80e5
AL
226
227 struct stat Buf;
228 if (stat(Final.c_str(),&Buf) != 0)
a72ace20 229 return "\nIndex-File: true";
a72ace20 230 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
0118833a
AL
231}
232 /*}}}*/
debc84b2
MZ
233
234void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
235{
236 // no .bz2 found, retry with .gz
46e00f9d 237 if(Desc.URI.substr(Desc.URI.size()-3) == "bz2") {
debc84b2 238 Desc.URI = Desc.URI.substr(0,Desc.URI.size()-3) + "gz";
b3d44315
MV
239
240 // retry with a gzip one
241 new pkgAcqIndex(Owner, RealURI, Desc.Description,Desc.ShortDesc,
242 ExpectedMD5, string(".gz"));
243 Status = StatDone;
244 Complete = false;
245 Dequeue();
debc84b2
MZ
246 return;
247 }
248
249
250 Item::Failed(Message,Cnf);
251}
252
253
8b89e57f
AL
254// AcqIndex::Done - Finished a fetch /*{{{*/
255// ---------------------------------------------------------------------
256/* This goes through a number of states.. On the initial fetch the
257 method could possibly return an alternate filename which points
258 to the uncompressed version of the file. If this is so the file
259 is copied into the partial directory. In all other cases the file
260 is decompressed with a gzip uri. */
459681d3
AL
261void pkgAcqIndex::Done(string Message,unsigned long Size,string MD5,
262 pkgAcquire::MethodConfig *Cfg)
8b89e57f 263{
459681d3 264 Item::Done(Message,Size,MD5,Cfg);
8b89e57f
AL
265
266 if (Decompression == true)
267 {
b3d44315
MV
268 if (_config->FindB("Debug::pkgAcquire::Auth", false))
269 {
270 std::cerr << std::endl << RealURI << ": Computed MD5: " << MD5;
271 std::cerr << " Expected MD5: " << ExpectedMD5 << std::endl;
272 }
273
274 if (MD5.empty())
275 {
276 MD5Summation sum;
277 FileFd Fd(DestFile, FileFd::ReadOnly);
278 sum.AddFD(Fd.Fd(), Fd.Size());
279 Fd.Close();
280 MD5 = (string)sum.Result();
281 }
282
283 if (!ExpectedMD5.empty() && MD5 != ExpectedMD5)
284 {
285 Status = StatAuthError;
286 ErrorText = _("MD5Sum mismatch");
287 Rename(DestFile,DestFile + ".FAILED");
59271f62 288 ReportMirrorFailure("HashChecksumFailure");
b3d44315
MV
289 return;
290 }
8b89e57f
AL
291 // Done, move it into position
292 string FinalFile = _config->FindDir("Dir::State::lists");
b2e465d6 293 FinalFile += URItoFileName(RealURI);
8b89e57f 294 Rename(DestFile,FinalFile);
7a3c2ab0 295 chmod(FinalFile.c_str(),0644);
bfd22fc0 296
7a7fa5f0
AL
297 /* We restore the original name to DestFile so that the clean operation
298 will work OK */
299 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
b2e465d6 300 DestFile += URItoFileName(RealURI);
7a7fa5f0 301
bfd22fc0
AL
302 // Remove the compressed version.
303 if (Erase == true)
bfd22fc0 304 unlink(DestFile.c_str());
8b89e57f
AL
305 return;
306 }
bfd22fc0
AL
307
308 Erase = false;
8267fe24 309 Complete = true;
bfd22fc0 310
8b89e57f
AL
311 // Handle the unzipd case
312 string FileName = LookupTag(Message,"Alt-Filename");
313 if (FileName.empty() == false)
314 {
315 // The files timestamp matches
316 if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
317 return;
b3d44315 318
8b89e57f 319 Decompression = true;
a6568219 320 Local = true;
8b89e57f 321 DestFile += ".decomp";
8267fe24
AL
322 Desc.URI = "copy:" + FileName;
323 QueueURI(Desc);
b98f2859 324 Mode = "copy";
8b89e57f
AL
325 return;
326 }
327
328 FileName = LookupTag(Message,"Filename");
329 if (FileName.empty() == true)
330 {
331 Status = StatError;
332 ErrorText = "Method gave a blank filename";
333 }
334
335 // The files timestamp matches
336 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
337 return;
bfd22fc0
AL
338
339 if (FileName == DestFile)
340 Erase = true;
8267fe24 341 else
a6568219 342 Local = true;
8b89e57f 343
46e00f9d 344 string compExt = Desc.URI.substr(Desc.URI.size()-3);
debc84b2
MZ
345 char *decompProg;
346 if(compExt == "bz2")
347 decompProg = "bzip2";
348 else if(compExt == ".gz")
349 decompProg = "gzip";
350 else {
351 _error->Error("Unsupported extension: %s", compExt.c_str());
352 return;
353 }
354
8b89e57f
AL
355 Decompression = true;
356 DestFile += ".decomp";
debc84b2 357 Desc.URI = string(decompProg) + ":" + FileName;
8267fe24 358 QueueURI(Desc);
debc84b2 359 Mode = decompProg;
8b89e57f 360}
8b89e57f 361
b3d44315
MV
362pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
363 string URI,string URIDesc,string ShortDesc,
364 string MetaIndexURI, string MetaIndexURIDesc,
365 string MetaIndexShortDesc,
366 const vector<IndexTarget*>* IndexTargets,
367 indexRecords* MetaIndexParser) :
368 Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
46e00f9d
MV
369 MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
370 MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
0118833a 371{
0a8a80e5 372 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
b2e465d6 373 DestFile += URItoFileName(URI);
b3d44315 374
f6237efd
MV
375 // remove any partial downloaded sig-file. it may confuse proxies
376 // and is too small to warrant a partial download anyway
377 unlink(DestFile.c_str());
378
8267fe24 379 // Create the item
b2e465d6 380 Desc.Description = URIDesc;
8267fe24 381 Desc.Owner = this;
b3d44315
MV
382 Desc.ShortDesc = ShortDesc;
383 Desc.URI = URI;
384
385
386 string Final = _config->FindDir("Dir::State::lists");
387 Final += URItoFileName(RealURI);
388 struct stat Buf;
389 if (stat(Final.c_str(),&Buf) == 0)
390 {
391 // File was already in place. It needs to be re-verified
392 // because Release might have changed, so Move it into partial
393 Rename(Final,DestFile);
394 }
8267fe24 395
8267fe24 396 QueueURI(Desc);
0118833a
AL
397}
398 /*}}}*/
b3d44315 399// pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
0118833a 400// ---------------------------------------------------------------------
0a8a80e5 401/* The only header we use is the last-modified header. */
b3d44315 402string pkgAcqMetaSig::Custom600Headers()
0118833a 403{
0a8a80e5 404 struct stat Buf;
2aab5956 405 if (stat(DestFile.c_str(),&Buf) != 0)
a72ace20 406 return "\nIndex-File: true";
a789b983 407
a72ace20 408 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
0118833a 409}
b3d44315
MV
410
411void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
412 pkgAcquire::MethodConfig *Cfg)
c88edf1d 413{
459681d3 414 Item::Done(Message,Size,MD5,Cfg);
c88edf1d
AL
415
416 string FileName = LookupTag(Message,"Filename");
417 if (FileName.empty() == true)
418 {
419 Status = StatError;
420 ErrorText = "Method gave a blank filename";
8b89e57f 421 return;
c88edf1d 422 }
8b89e57f 423
c88edf1d
AL
424 if (FileName != DestFile)
425 {
b3d44315 426 // We have to copy it into place
a6568219 427 Local = true;
8267fe24
AL
428 Desc.URI = "copy:" + FileName;
429 QueueURI(Desc);
c88edf1d
AL
430 return;
431 }
b3d44315
MV
432
433 Complete = true;
434
435 // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
436 new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
437 DestFile, IndexTargets, MetaIndexParser);
438
c88edf1d
AL
439}
440 /*}}}*/
b3d44315 441void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
681d76d0 442{
a789b983 443
75dd8af1 444 // if we get a network error we fail gracefully
25182152 445 if(LookupTag(Message,"FailReason") == "Timeout" ||
0c1b7be9 446 LookupTag(Message,"FailReason") == "TmpResolveFailure" ||
75dd8af1 447 LookupTag(Message,"FailReason") == "ConnectionRefused") {
24057ad6
MV
448 Item::Failed(Message,Cnf);
449 return;
450 }
451
75dd8af1
MV
452 // Delete any existing sigfile when the acquire failed
453 string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
454 unlink(Final.c_str());
455
b3d44315
MV
456 // queue a pkgAcqMetaIndex with no sigfile
457 new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
458 "", IndexTargets, MetaIndexParser);
459
681d76d0
AL
460 if (Cnf->LocalOnly == true ||
461 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
462 {
2b154e53
AL
463 // Ignore this
464 Status = StatDone;
465 Complete = false;
681d76d0
AL
466 Dequeue();
467 return;
468 }
469
470 Item::Failed(Message,Cnf);
471}
b3d44315
MV
472
473pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner,
474 string URI,string URIDesc,string ShortDesc,
475 string SigFile,
476 const vector<struct IndexTarget*>* IndexTargets,
477 indexRecords* MetaIndexParser) :
46e00f9d 478 Item(Owner), RealURI(URI), SigFile(SigFile), AuthPass(false),
f381d68d 479 MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets), IMSHit(false)
b3d44315 480{
b3d44315
MV
481 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
482 DestFile += URItoFileName(URI);
483
484 // Create the item
485 Desc.Description = URIDesc;
486 Desc.Owner = this;
487 Desc.ShortDesc = ShortDesc;
488 Desc.URI = URI;
489
490 QueueURI(Desc);
491}
492
493 /*}}}*/
494// pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
495// ---------------------------------------------------------------------
496/* The only header we use is the last-modified header. */
497string pkgAcqMetaIndex::Custom600Headers()
498{
499 string Final = _config->FindDir("Dir::State::lists");
500 Final += URItoFileName(RealURI);
501
502 struct stat Buf;
503 if (stat(Final.c_str(),&Buf) != 0)
504 return "\nIndex-File: true";
505
506 return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
507}
508
509void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string MD5,
510 pkgAcquire::MethodConfig *Cfg)
511{
512 Item::Done(Message,Size,MD5,Cfg);
513
514 // MetaIndexes are done in two passes: one to download the
515 // metaindex with an appropriate method, and a second to verify it
516 // with the gpgv method
517
518 if (AuthPass == true)
519 {
520 AuthDone(Message);
521 }
522 else
523 {
524 RetrievalDone(Message);
525 if (!Complete)
526 // Still more retrieving to do
527 return;
528
529 if (SigFile == "")
530 {
531 // There was no signature file, so we are finished. Download
532 // the indexes without verification.
533 QueueIndexes(false);
534 }
535 else
536 {
537 // There was a signature file, so pass it to gpgv for
538 // verification
539
540 if (_config->FindB("Debug::pkgAcquire::Auth", false))
541 std::cerr << "Metaindex acquired, queueing gpg verification ("
542 << SigFile << "," << DestFile << ")\n";
543 AuthPass = true;
544 Desc.URI = "gpgv:" + SigFile;
545 QueueURI(Desc);
546 Mode = "gpgv";
547 }
548 }
549}
550
551void pkgAcqMetaIndex::RetrievalDone(string Message)
552{
553 // We have just finished downloading a Release file (it is not
554 // verified yet)
555
556 string FileName = LookupTag(Message,"Filename");
557 if (FileName.empty() == true)
558 {
559 Status = StatError;
560 ErrorText = "Method gave a blank filename";
561 return;
562 }
563
564 if (FileName != DestFile)
565 {
566 Local = true;
567 Desc.URI = "copy:" + FileName;
568 QueueURI(Desc);
569 return;
570 }
571
f381d68d
MV
572 // see if the download was a IMSHit
573 IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
574
b3d44315
MV
575 Complete = true;
576
577 string FinalFile = _config->FindDir("Dir::State::lists");
578 FinalFile += URItoFileName(RealURI);
579
580 // The files timestamp matches
581 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == false)
582 {
583 // Move it into position
584 Rename(DestFile,FinalFile);
585 }
586 DestFile = FinalFile;
587}
588
589void pkgAcqMetaIndex::AuthDone(string Message)
590{
591 // At this point, the gpgv method has succeeded, so there is a
592 // valid signature from a key in the trusted keyring. We
593 // perform additional verification of its contents, and use them
594 // to verify the indexes we are about to download
595
596 if (!MetaIndexParser->Load(DestFile))
597 {
598 Status = StatAuthError;
599 ErrorText = MetaIndexParser->ErrorText;
600 return;
601 }
602
ce424cd4 603 if (!VerifyVendor(Message))
b3d44315
MV
604 {
605 return;
606 }
607
608 if (_config->FindB("Debug::pkgAcquire::Auth", false))
609 std::cerr << "Signature verification succeeded: "
610 << DestFile << std::endl;
611
612 // Download further indexes with verification
613 QueueIndexes(true);
614
615 // Done, move signature file into position
616
617 string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
618 URItoFileName(RealURI) + ".gpg";
619 Rename(SigFile,VerifiedSigFile);
620 chmod(VerifiedSigFile.c_str(),0644);
621}
622
623void pkgAcqMetaIndex::QueueIndexes(bool verify)
624{
625 for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
626 Target != IndexTargets->end();
627 Target++)
628 {
629 string ExpectedIndexMD5;
630 if (verify)
631 {
632 const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
633 if (!Record)
634 {
635 Status = StatAuthError;
636 ErrorText = "Unable to find expected entry "
637 + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
638 return;
639 }
640 ExpectedIndexMD5 = Record->MD5Hash;
641 if (_config->FindB("Debug::pkgAcquire::Auth", false))
642 {
643 std::cerr << "Queueing: " << (*Target)->URI << std::endl;
644 std::cerr << "Expected MD5: " << ExpectedIndexMD5 << std::endl;
645 }
646 if (ExpectedIndexMD5.empty())
647 {
648 Status = StatAuthError;
649 ErrorText = "Unable to find MD5 sum for "
650 + (*Target)->MetaKey + " in Meta-index file";
651 return;
652 }
653 }
654
655 // Queue Packages file
656 new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
657 (*Target)->ShortDesc, ExpectedIndexMD5);
658 }
659}
660
ce424cd4 661bool pkgAcqMetaIndex::VerifyVendor(string Message)
b3d44315
MV
662{
663// // Maybe this should be made available from above so we don't have
664// // to read and parse it every time?
665// pkgVendorList List;
666// List.ReadMainList();
667
668// const Vendor* Vndr = NULL;
669// for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
670// {
671// string::size_type pos = (*I).find("VALIDSIG ");
672// if (_config->FindB("Debug::Vendor", false))
673// std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
674// << std::endl;
675// if (pos != std::string::npos)
676// {
677// string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
678// if (_config->FindB("Debug::Vendor", false))
679// std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
680// std::endl;
681// Vndr = List.FindVendor(Fingerprint) != "";
682// if (Vndr != NULL);
683// break;
684// }
685// }
ce424cd4
MV
686 string::size_type pos;
687
688 // check for missing sigs (that where not fatal because otherwise we had
689 // bombed earlier)
690 string missingkeys;
400ad7a4 691 string msg = _("There is no public key available for the "
ce424cd4
MV
692 "following key IDs:\n");
693 pos = Message.find("NO_PUBKEY ");
694 if (pos != std::string::npos)
695 {
696 string::size_type start = pos+strlen("NO_PUBKEY ");
697 string Fingerprint = Message.substr(start, Message.find("\n")-start);
698 missingkeys += (Fingerprint);
699 }
700 if(!missingkeys.empty())
701 _error->Warning("%s", string(msg+missingkeys).c_str());
b3d44315
MV
702
703 string Transformed = MetaIndexParser->GetExpectedDist();
704
705 if (Transformed == "../project/experimental")
706 {
707 Transformed = "experimental";
708 }
709
ce424cd4 710 pos = Transformed.rfind('/');
b3d44315
MV
711 if (pos != string::npos)
712 {
713 Transformed = Transformed.substr(0, pos);
714 }
715
716 if (Transformed == ".")
717 {
718 Transformed = "";
719 }
720
721 if (_config->FindB("Debug::pkgAcquire::Auth", false))
722 {
723 std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
724 std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
725 std::cerr << "Transformed Dist: " << Transformed << std::endl;
726 }
727
728 if (MetaIndexParser->CheckDist(Transformed) == false)
729 {
730 // This might become fatal one day
731// Status = StatAuthError;
732// ErrorText = "Conflicting distribution; expected "
733// + MetaIndexParser->GetExpectedDist() + " but got "
734// + MetaIndexParser->GetDist();
735// return false;
736 if (!Transformed.empty())
737 {
738 _error->Warning("Conflicting distribution: %s (expected %s but got %s)",
739 Desc.Description.c_str(),
740 Transformed.c_str(),
741 MetaIndexParser->GetDist().c_str());
742 }
743 }
744
745 return true;
746}
747 /*}}}*/
748// pkgAcqMetaIndex::Failed - no Release file present or no signature
749// file present /*{{{*/
750// ---------------------------------------------------------------------
751/* */
752void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
753{
754 if (AuthPass == true)
755 {
f381d68d
MV
756 // if we fail the authentication but got the file via a IMS-Hit
757 // this means that the file wasn't downloaded and that it might be
758 // just stale (server problem, proxy etc). we delete what we have
759 // queue it again without i-m-s
760 // alternatively we could just unlink the file and let the user try again
761 if (IMSHit)
762 {
763 Complete = false;
764 Local = false;
765 AuthPass = false;
766 unlink(DestFile.c_str());
767
768 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
769 DestFile += URItoFileName(RealURI);
770 Desc.URI = RealURI;
771 QueueURI(Desc);
772 return;
773 }
774
775 // gpgv method failed
59271f62 776 ReportMirrorFailure("GPGFailure");
b3d44315
MV
777 _error->Warning("GPG error: %s: %s",
778 Desc.Description.c_str(),
779 LookupTag(Message,"Message").c_str());
f381d68d 780
b3d44315
MV
781 }
782
783 // No Release file was present, or verification failed, so fall
784 // back to queueing Packages files without verification
785 QueueIndexes(false);
786}
787
681d76d0 788 /*}}}*/
03e39e59
AL
789
790// AcqArchive::AcqArchive - Constructor /*{{{*/
791// ---------------------------------------------------------------------
17caf1b1
AL
792/* This just sets up the initial fetch environment and queues the first
793 possibilitiy */
03e39e59 794pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
30e1eab5
AL
795 pkgRecords *Recs,pkgCache::VerIterator const &Version,
796 string &StoreFilename) :
797 Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
b3d44315
MV
798 StoreFilename(StoreFilename), Vf(Version.FileList()),
799 Trusted(false)
03e39e59 800{
7d8afa39 801 Retries = _config->FindI("Acquire::Retries",0);
813c8eea
AL
802
803 if (Version.Arch() == 0)
bdae53f1 804 {
d1f1f6a8 805 _error->Error(_("I wasn't able to locate a file for the %s package. "
7a3c2ab0
AL
806 "This might mean you need to manually fix this package. "
807 "(due to missing arch)"),
813c8eea 808 Version.ParentPkg().Name());
bdae53f1
AL
809 return;
810 }
813c8eea 811
b2e465d6
AL
812 /* We need to find a filename to determine the extension. We make the
813 assumption here that all the available sources for this version share
814 the same extension.. */
815 // Skip not source sources, they do not have file fields.
816 for (; Vf.end() == false; Vf++)
817 {
818 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
819 continue;
820 break;
821 }
822
823 // Does not really matter here.. we are going to fail out below
824 if (Vf.end() != true)
825 {
826 // If this fails to get a file name we will bomb out below.
827 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
828 if (_error->PendingError() == true)
829 return;
830
831 // Generate the final file name as: package_version_arch.foo
832 StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
833 QuoteString(Version.VerStr(),"_:") + '_' +
834 QuoteString(Version.Arch(),"_:.") +
835 "." + flExtension(Parse.FileName());
836 }
b3d44315
MV
837
838 // check if we have one trusted source for the package. if so, switch
839 // to "TrustedOnly" mode
840 for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
841 {
842 pkgIndexFile *Index;
843 if (Sources->FindIndex(i.File(),Index) == false)
844 continue;
845 if (_config->FindB("Debug::pkgAcquire::Auth", false))
846 {
847 std::cerr << "Checking index: " << Index->Describe()
848 << "(Trusted=" << Index->IsTrusted() << ")\n";
849 }
850 if (Index->IsTrusted()) {
851 Trusted = true;
852 break;
853 }
854 }
855
a3371852
MV
856 // "allow-unauthenticated" restores apts old fetching behaviour
857 // that means that e.g. unauthenticated file:// uris are higher
858 // priority than authenticated http:// uris
859 if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
860 Trusted = false;
861
03e39e59 862 // Select a source
b185acc2 863 if (QueueNext() == false && _error->PendingError() == false)
b2e465d6
AL
864 _error->Error(_("I wasn't able to locate file for the %s package. "
865 "This might mean you need to manually fix this package."),
b185acc2
AL
866 Version.ParentPkg().Name());
867}
868 /*}}}*/
869// AcqArchive::QueueNext - Queue the next file source /*{{{*/
870// ---------------------------------------------------------------------
17caf1b1
AL
871/* This queues the next available file version for download. It checks if
872 the archive is already available in the cache and stashs the MD5 for
873 checking later. */
b185acc2 874bool pkgAcqArchive::QueueNext()
b2e465d6 875{
03e39e59
AL
876 for (; Vf.end() == false; Vf++)
877 {
878 // Ignore not source sources
879 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
880 continue;
881
882 // Try to cross match against the source list
b2e465d6
AL
883 pkgIndexFile *Index;
884 if (Sources->FindIndex(Vf.File(),Index) == false)
885 continue;
03e39e59 886
b3d44315
MV
887 // only try to get a trusted package from another source if that source
888 // is also trusted
889 if(Trusted && !Index->IsTrusted())
890 continue;
891
03e39e59
AL
892 // Grab the text package record
893 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
894 if (_error->PendingError() == true)
b185acc2 895 return false;
03e39e59 896
b2e465d6 897 string PkgFile = Parse.FileName();
03e39e59
AL
898 MD5 = Parse.MD5Hash();
899 if (PkgFile.empty() == true)
b2e465d6
AL
900 return _error->Error(_("The package index files are corrupted. No Filename: "
901 "field for package %s."),
902 Version.ParentPkg().Name());
a6568219 903
b3d44315
MV
904 Desc.URI = Index->ArchiveURI(PkgFile);
905 Desc.Description = Index->ArchiveInfo(Version);
906 Desc.Owner = this;
907 Desc.ShortDesc = Version.ParentPkg().Name();
908
17caf1b1 909 // See if we already have the file. (Legacy filenames)
a6568219
AL
910 FileSize = Version->Size;
911 string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
912 struct stat Buf;
913 if (stat(FinalFile.c_str(),&Buf) == 0)
914 {
915 // Make sure the size matches
916 if ((unsigned)Buf.st_size == Version->Size)
917 {
918 Complete = true;
919 Local = true;
920 Status = StatDone;
30e1eab5 921 StoreFilename = DestFile = FinalFile;
b185acc2 922 return true;
a6568219
AL
923 }
924
6b1ff003
AL
925 /* Hmm, we have a file and its size does not match, this means it is
926 an old style mismatched arch */
a6568219
AL
927 unlink(FinalFile.c_str());
928 }
17caf1b1
AL
929
930 // Check it again using the new style output filenames
931 FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
932 if (stat(FinalFile.c_str(),&Buf) == 0)
933 {
934 // Make sure the size matches
935 if ((unsigned)Buf.st_size == Version->Size)
936 {
937 Complete = true;
938 Local = true;
939 Status = StatDone;
940 StoreFilename = DestFile = FinalFile;
941 return true;
942 }
943
944 /* Hmm, we have a file and its size does not match, this shouldnt
945 happen.. */
946 unlink(FinalFile.c_str());
947 }
948
949 DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
6b1ff003
AL
950
951 // Check the destination file
952 if (stat(DestFile.c_str(),&Buf) == 0)
953 {
954 // Hmm, the partial file is too big, erase it
955 if ((unsigned)Buf.st_size > Version->Size)
956 unlink(DestFile.c_str());
957 else
958 PartialSize = Buf.st_size;
959 }
960
03e39e59 961 // Create the item
b2e465d6
AL
962 Local = false;
963 Desc.URI = Index->ArchiveURI(PkgFile);
964 Desc.Description = Index->ArchiveInfo(Version);
03e39e59
AL
965 Desc.Owner = this;
966 Desc.ShortDesc = Version.ParentPkg().Name();
967 QueueURI(Desc);
b185acc2
AL
968
969 Vf++;
970 return true;
03e39e59 971 }
b185acc2
AL
972 return false;
973}
03e39e59
AL
974 /*}}}*/
975// AcqArchive::Done - Finished fetching /*{{{*/
976// ---------------------------------------------------------------------
977/* */
459681d3
AL
978void pkgAcqArchive::Done(string Message,unsigned long Size,string Md5Hash,
979 pkgAcquire::MethodConfig *Cfg)
03e39e59 980{
459681d3 981 Item::Done(Message,Size,Md5Hash,Cfg);
03e39e59
AL
982
983 // Check the size
984 if (Size != Version->Size)
985 {
bdae53f1 986 Status = StatError;
b2e465d6 987 ErrorText = _("Size mismatch");
03e39e59
AL
988 return;
989 }
990
991 // Check the md5
992 if (Md5Hash.empty() == false && MD5.empty() == false)
993 {
994 if (Md5Hash != MD5)
995 {
bdae53f1 996 Status = StatError;
b2e465d6 997 ErrorText = _("MD5Sum mismatch");
13e8426f
MV
998 if(FileExists(DestFile))
999 Rename(DestFile,DestFile + ".FAILED");
03e39e59
AL
1000 return;
1001 }
1002 }
a6568219
AL
1003
1004 // Grab the output filename
03e39e59
AL
1005 string FileName = LookupTag(Message,"Filename");
1006 if (FileName.empty() == true)
1007 {
1008 Status = StatError;
1009 ErrorText = "Method gave a blank filename";
1010 return;
1011 }
a6568219
AL
1012
1013 Complete = true;
30e1eab5
AL
1014
1015 // Reference filename
a6568219
AL
1016 if (FileName != DestFile)
1017 {
30e1eab5 1018 StoreFilename = DestFile = FileName;
a6568219
AL
1019 Local = true;
1020 return;
1021 }
1022
1023 // Done, move it into position
1024 string FinalFile = _config->FindDir("Dir::Cache::Archives");
17caf1b1 1025 FinalFile += flNotDir(StoreFilename);
a6568219 1026 Rename(DestFile,FinalFile);
03e39e59 1027
30e1eab5 1028 StoreFilename = DestFile = FinalFile;
03e39e59
AL
1029 Complete = true;
1030}
1031 /*}}}*/
db890fdb
AL
1032// AcqArchive::Failed - Failure handler /*{{{*/
1033// ---------------------------------------------------------------------
1034/* Here we try other sources */
7d8afa39 1035void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
db890fdb
AL
1036{
1037 ErrorText = LookupTag(Message,"Message");
b2e465d6
AL
1038
1039 /* We don't really want to retry on failed media swaps, this prevents
1040 that. An interesting observation is that permanent failures are not
1041 recorded. */
1042 if (Cnf->Removable == true &&
1043 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
1044 {
1045 // Vf = Version.FileList();
1046 while (Vf.end() == false) Vf++;
1047 StoreFilename = string();
1048 Item::Failed(Message,Cnf);
1049 return;
1050 }
1051
db890fdb 1052 if (QueueNext() == false)
7d8afa39
AL
1053 {
1054 // This is the retry counter
1055 if (Retries != 0 &&
1056 Cnf->LocalOnly == false &&
1057 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
1058 {
1059 Retries--;
1060 Vf = Version.FileList();
1061 if (QueueNext() == true)
1062 return;
1063 }
1064
9dbb421f 1065 StoreFilename = string();
7d8afa39
AL
1066 Item::Failed(Message,Cnf);
1067 }
db890fdb
AL
1068}
1069 /*}}}*/
b3d44315
MV
1070// AcqArchive::IsTrusted - Determine whether this archive comes from a
1071// trusted source /*{{{*/
1072// ---------------------------------------------------------------------
1073bool pkgAcqArchive::IsTrusted()
1074{
1075 return Trusted;
1076}
1077
ab559b35
AL
1078// AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
1079// ---------------------------------------------------------------------
1080/* */
1081void pkgAcqArchive::Finished()
1082{
1083 if (Status == pkgAcquire::Item::StatDone &&
1084 Complete == true)
1085 return;
1086 StoreFilename = string();
1087}
1088 /*}}}*/
36375005
AL
1089
1090// AcqFile::pkgAcqFile - Constructor /*{{{*/
1091// ---------------------------------------------------------------------
1092/* The file is added to the queue */
1093pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string MD5,
46e00f9d
MV
1094 unsigned long Size,string Dsc,string ShortDesc,
1095 const string &DestDir, const string &DestFilename) :
b3c39978 1096 Item(Owner), Md5Hash(MD5)
36375005 1097{
08cfc005
AL
1098 Retries = _config->FindI("Acquire::Retries",0);
1099
46e00f9d
MV
1100 if(!DestFilename.empty())
1101 DestFile = DestFilename;
1102 else if(!DestDir.empty())
1103 DestFile = DestDir + "/" + flNotDir(URI);
1104 else
1105 DestFile = flNotDir(URI);
1106
36375005
AL
1107 // Create the item
1108 Desc.URI = URI;
1109 Desc.Description = Dsc;
1110 Desc.Owner = this;
1111
1112 // Set the short description to the archive component
1113 Desc.ShortDesc = ShortDesc;
1114
1115 // Get the transfer sizes
1116 FileSize = Size;
1117 struct stat Buf;
1118 if (stat(DestFile.c_str(),&Buf) == 0)
1119 {
1120 // Hmm, the partial file is too big, erase it
1121 if ((unsigned)Buf.st_size > Size)
1122 unlink(DestFile.c_str());
1123 else
1124 PartialSize = Buf.st_size;
1125 }
092ae175 1126
36375005
AL
1127 QueueURI(Desc);
1128}
1129 /*}}}*/
1130// AcqFile::Done - Item downloaded OK /*{{{*/
1131// ---------------------------------------------------------------------
1132/* */
459681d3
AL
1133void pkgAcqFile::Done(string Message,unsigned long Size,string MD5,
1134 pkgAcquire::MethodConfig *Cnf)
36375005 1135{
b3c39978
AL
1136 // Check the md5
1137 if (Md5Hash.empty() == false && MD5.empty() == false)
1138 {
1139 if (Md5Hash != MD5)
1140 {
1141 Status = StatError;
1142 ErrorText = "MD5Sum mismatch";
1143 Rename(DestFile,DestFile + ".FAILED");
1144 return;
1145 }
1146 }
1147
459681d3 1148 Item::Done(Message,Size,MD5,Cnf);
36375005
AL
1149
1150 string FileName = LookupTag(Message,"Filename");
1151 if (FileName.empty() == true)
1152 {
1153 Status = StatError;
1154 ErrorText = "Method gave a blank filename";
1155 return;
1156 }
1157
1158 Complete = true;
1159
1160 // The files timestamp matches
1161 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
1162 return;
1163
1164 // We have to copy it into place
1165 if (FileName != DestFile)
1166 {
1167 Local = true;
459681d3
AL
1168 if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
1169 Cnf->Removable == true)
917ae805
AL
1170 {
1171 Desc.URI = "copy:" + FileName;
1172 QueueURI(Desc);
1173 return;
1174 }
1175
83ab33fc
AL
1176 // Erase the file if it is a symlink so we can overwrite it
1177 struct stat St;
1178 if (lstat(DestFile.c_str(),&St) == 0)
1179 {
1180 if (S_ISLNK(St.st_mode) != 0)
1181 unlink(DestFile.c_str());
1182 }
1183
1184 // Symlink the file
917ae805
AL
1185 if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
1186 {
83ab33fc 1187 ErrorText = "Link to " + DestFile + " failure ";
917ae805
AL
1188 Status = StatError;
1189 Complete = false;
1190 }
36375005
AL
1191 }
1192}
1193 /*}}}*/
08cfc005
AL
1194// AcqFile::Failed - Failure handler /*{{{*/
1195// ---------------------------------------------------------------------
1196/* Here we try other sources */
1197void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
1198{
1199 ErrorText = LookupTag(Message,"Message");
1200
1201 // This is the retry counter
1202 if (Retries != 0 &&
1203 Cnf->LocalOnly == false &&
1204 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
1205 {
1206 Retries--;
1207 QueueURI(Desc);
1208 return;
1209 }
1210
1211 Item::Failed(Message,Cnf);
1212}
1213 /*}}}*/