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