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