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