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