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