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