]> git.saurik.com Git - apt.git/blame - apt-pkg/acquire-item.cc
Only rename StatError files in AbortTransaction()
[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 {
ea7682a0 1071 std::string const PartialFile = GetPartialFileNameFromURI(RealURI);
03bfbc96
MV
1072 std::string patch = PartialFile + ".ed." + (*I)->patch.file + ".gz";
1073 std::cerr << patch << std::endl;
34d6ece7
DK
1074 unlink(patch.c_str());
1075 }
1076
47d2bc78
DK
1077 // all set and done
1078 Complete = true;
1079 if(Debug)
1080 std::clog << "allDone: " << DestFile << "\n" << std::endl;
1081 }
1082}
1083 /*}}}*/
651bddad
MV
1084// AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
1085bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList const &Hashes)
1086{
1e8ba0d4 1087 if(MetaKey != "" && Hashes.usable())
651bddad
MV
1088 {
1089 indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
1090 if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
1091 {
1092 printHashSumComparision(RealURI, Record->Hashes, Hashes);
1093 return false;
1094 }
1095 }
1096 return true;
1097}
8267fbd9 1098 /*}}}*/
0118833a
AL
1099// AcqIndex::AcqIndex - Constructor /*{{{*/
1100// ---------------------------------------------------------------------
8267fbd9
DK
1101/* The package file is added to the queue and a second class is
1102 instantiated to fetch the revision file */
b2e465d6 1103pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
b3d44315 1104 string URI,string URIDesc,string ShortDesc,
916b8910 1105 HashStringList const &ExpectedHash)
a64bf0eb 1106 : pkgAcqBaseIndex(Owner, 0, NULL, ExpectedHash, NULL)
0118833a 1107{
a64bf0eb
MV
1108 RealURI = URI;
1109
56472095 1110 AutoSelectCompression();
21638c3a
MV
1111 Init(URI, URIDesc, ShortDesc);
1112
1113 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
715c65de
MV
1114 std::clog << "New pkgIndex with TransactionManager "
1115 << TransactionManager << std::endl;
56472095 1116}
56472095 1117 /*}}}*/
21638c3a 1118// AcqIndex::AcqIndex - Constructor /*{{{*/
e05672e8 1119pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
715c65de 1120 pkgAcqMetaBase *TransactionManager,
56472095 1121 IndexTarget const *Target,
8267fbd9 1122 HashStringList const &ExpectedHash,
56472095 1123 indexRecords *MetaIndexParser)
8267fbd9 1124 : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHash,
a64bf0eb 1125 MetaIndexParser)
56472095 1126{
a64bf0eb
MV
1127 RealURI = Target->URI;
1128
56472095
MV
1129 // autoselect the compression method
1130 AutoSelectCompression();
1131 Init(Target->URI, Target->Description, Target->ShortDesc);
1132
e05672e8 1133 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
715c65de
MV
1134 std::clog << "New pkgIndex with TransactionManager "
1135 << TransactionManager << std::endl;
56472095
MV
1136}
1137 /*}}}*/
21638c3a 1138// AcqIndex::AutoSelectCompression - Select compression /*{{{*/
56472095
MV
1139void pkgAcqIndex::AutoSelectCompression()
1140{
5d885723 1141 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
651bddad 1142 CompressionExtensions = "";
b3501edb 1143 if (ExpectedHashes.usable())
5d885723 1144 {
651bddad
MV
1145 for (std::vector<std::string>::const_iterator t = types.begin();
1146 t != types.end(); ++t)
1147 {
1148 std::string CompressedMetaKey = string(Target->MetaKey).append(".").append(*t);
8267fbd9 1149 if (*t == "uncompressed" ||
651bddad
MV
1150 MetaIndexParser->Exists(CompressedMetaKey) == true)
1151 CompressionExtensions.append(*t).append(" ");
1152 }
5d885723
DK
1153 }
1154 else
1155 {
1156 for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
651bddad 1157 CompressionExtensions.append(*t).append(" ");
5d885723 1158 }
651bddad
MV
1159 if (CompressionExtensions.empty() == false)
1160 CompressionExtensions.erase(CompressionExtensions.end()-1);
5d885723 1161}
8267fbd9 1162 /*}}}*/
5d885723 1163// AcqIndex::Init - defered Constructor /*{{{*/
8267fbd9 1164void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
3f073d44
MV
1165 string const &ShortDesc)
1166{
651bddad 1167 Stage = STAGE_DOWNLOAD;
13e8426f 1168
ea7682a0 1169 DestFile = GetPartialFileNameFromURI(URI);
8267fe24 1170
1e8ba0d4
MV
1171 CurrentCompressionExtension = CompressionExtensions.substr(0, CompressionExtensions.find(' '));
1172 if (CurrentCompressionExtension == "uncompressed")
b11f9599 1173 {
5d885723 1174 Desc.URI = URI;
e39698a4
MV
1175 if(Target)
1176 MetaKey = string(Target->MetaKey);
b11f9599 1177 }
5d885723 1178 else
b11f9599 1179 {
1e8ba0d4
MV
1180 Desc.URI = URI + '.' + CurrentCompressionExtension;
1181 DestFile = DestFile + '.' + CurrentCompressionExtension;
e39698a4 1182 if(Target)
1e8ba0d4 1183 MetaKey = string(Target->MetaKey) + '.' + CurrentCompressionExtension;
b11f9599
MV
1184 }
1185
1186 // load the filesize
e39698a4
MV
1187 if(MetaIndexParser)
1188 {
1189 indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
1190 if(Record)
1191 FileSize = Record->Size;
8267fbd9 1192
59194959 1193 InitByHashIfNeeded(MetaKey);
e39698a4 1194 }
b3d44315 1195
b2e465d6 1196 Desc.Description = URIDesc;
8267fe24 1197 Desc.Owner = this;
b2e465d6 1198 Desc.ShortDesc = ShortDesc;
5d885723 1199
8267fe24 1200 QueueURI(Desc);
0118833a
AL
1201}
1202 /*}}}*/
59194959 1203// AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
59194959
MV
1204void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
1205{
1206 // TODO:
1207 // - (maybe?) add support for by-hash into the sources.list as flag
1208 // - make apt-ftparchive generate the hashes (and expire?)
1209 std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
1210 if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
1211 _config->FindB(HostKnob, false) == true ||
1212 MetaIndexParser->GetSupportsAcquireByHash())
1213 {
1214 indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
1215 if(Record)
1216 {
1217 // FIXME: should we really use the best hash here? or a fixed one?
1218 const HashString *TargetHash = Record->Hashes.find("");
1219 std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
1220 size_t trailing_slash = Desc.URI.find_last_of("/");
1221 Desc.URI = Desc.URI.replace(
1222 trailing_slash,
1223 Desc.URI.substr(trailing_slash+1).size()+1,
1224 ByHash);
1225 } else {
1226 _error->Warning(
1227 "Fetching ByHash requested but can not find record for %s",
1228 MetaKey.c_str());
1229 }
1230 }
1231}
1232 /*}}}*/
0a8a80e5 1233// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
0118833a 1234// ---------------------------------------------------------------------
0a8a80e5 1235/* The only header we use is the last-modified header. */
b3501edb 1236string pkgAcqIndex::Custom600Headers() const
0118833a 1237{
3f073d44 1238 string Final = GetFinalFilename();
8267fbd9 1239
97b65b10 1240 string msg = "\nIndex-File: true";
0a8a80e5 1241 struct stat Buf;
3a1f49c4 1242 if (stat(Final.c_str(),&Buf) == 0)
97b65b10
MV
1243 msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1244
1245 return msg;
0118833a
AL
1246}
1247 /*}}}*/
8267fbd9
DK
1248// pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
1249void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
debc84b2 1250{
651bddad 1251 size_t const nextExt = CompressionExtensions.find(' ');
5d885723 1252 if (nextExt != std::string::npos)
e85b4cd5 1253 {
651bddad 1254 CompressionExtensions = CompressionExtensions.substr(nextExt+1);
5d885723 1255 Init(RealURI, Desc.Description, Desc.ShortDesc);
6abe2699 1256 return;
0d7a243d
EL
1257 }
1258
17ff0930 1259 // on decompression failure, remove bad versions in partial/
651bddad
MV
1260 if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
1261 {
1e8ba0d4 1262 unlink(EraseFileName.c_str());
debc84b2
MZ
1263 }
1264
debc84b2 1265 Item::Failed(Message,Cnf);
56472095
MV
1266
1267 /// cancel the entire transaction
715c65de 1268 TransactionManager->AbortTransaction();
debc84b2 1269}
92fcbfc1 1270 /*}}}*/
8267fbd9 1271// pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
3f073d44 1272std::string pkgAcqIndex::GetFinalFilename() const
63b7249e
MV
1273{
1274 std::string FinalFile = _config->FindDir("Dir::State::lists");
3f073d44 1275 FinalFile += URItoFileName(RealURI);
b0f4b486 1276 if (_config->FindB("Acquire::GzipIndexes",false) == true)
1e8ba0d4 1277 FinalFile += '.' + CurrentCompressionExtension;
63b7249e
MV
1278 return FinalFile;
1279}
8267fbd9
DK
1280 /*}}}*/
1281// AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
916b8910 1282void pkgAcqIndex::ReverifyAfterIMS()
63b7249e 1283{
c36db2b5
MV
1284 // update destfile to *not* include the compression extension when doing
1285 // a reverify (as its uncompressed on disk already)
ea7682a0 1286 DestFile = GetPartialFileNameFromURI(RealURI);
c36db2b5
MV
1287
1288 // adjust DestFile if its compressed on disk
b0f4b486 1289 if (_config->FindB("Acquire::GzipIndexes",false) == true)
1e8ba0d4 1290 DestFile += '.' + CurrentCompressionExtension;
63b7249e
MV
1291
1292 // copy FinalFile into partial/ so that we check the hash again
3f073d44 1293 string FinalFile = GetFinalFilename();
651bddad 1294 Stage = STAGE_DECOMPRESS_AND_VERIFY;
63b7249e
MV
1295 Desc.URI = "copy:" + FinalFile;
1296 QueueURI(Desc);
1297}
8267fbd9
DK
1298 /*}}}*/
1299// AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
899e4ded
MV
1300bool pkgAcqIndex::ValidateFile(const std::string &FileName)
1301{
1302 // FIXME: this can go away once we only ever download stuff that
1303 // has a valid hash and we never do GET based probing
1304 // FIXME2: this also leaks debian-isms into the code and should go therefore
1305
1306 /* Always validate the index file for correctness (all indexes must
1307 * have a Package field) (LP: #346386) (Closes: #627642)
1308 */
651bddad 1309 FileFd fd(FileName, FileFd::ReadOnly, FileFd::Extension);
899e4ded
MV
1310 // Only test for correctness if the content of the file is not empty
1311 // (empty is ok)
1312 if (fd.Size() > 0)
1313 {
1314 pkgTagSection sec;
1315 pkgTagFile tag(&fd);
1316
1317 // all our current indexes have a field 'Package' in each section
1318 if (_error->PendingError() == true ||
1319 tag.Step(sec) == false ||
1320 sec.Exists("Package") == false)
1321 return false;
1322 }
1323 return true;
1324}
8267fbd9 1325 /*}}}*/
8b89e57f
AL
1326// AcqIndex::Done - Finished a fetch /*{{{*/
1327// ---------------------------------------------------------------------
1328/* This goes through a number of states.. On the initial fetch the
1329 method could possibly return an alternate filename which points
1330 to the uncompressed version of the file. If this is so the file
1331 is copied into the partial directory. In all other cases the file
b6f0063c 1332 is decompressed with a compressed uri. */
651bddad
MV
1333void pkgAcqIndex::Done(string Message,
1334 unsigned long long Size,
c8aa88aa 1335 HashStringList const &Hashes,
459681d3 1336 pkgAcquire::MethodConfig *Cfg)
8b89e57f 1337{
b3501edb 1338 Item::Done(Message,Size,Hashes,Cfg);
63b7249e 1339
651bddad 1340 switch(Stage)
8b89e57f 1341 {
651bddad
MV
1342 case STAGE_DOWNLOAD:
1343 StageDownloadDone(Message, Hashes, Cfg);
1344 break;
1345 case STAGE_DECOMPRESS_AND_VERIFY:
1346 StageDecompressDone(Message, Hashes, Cfg);
1347 break;
5f6c6c6e 1348 }
651bddad 1349}
8267fbd9
DK
1350 /*}}}*/
1351// AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
651bddad
MV
1352void pkgAcqIndex::StageDownloadDone(string Message,
1353 HashStringList const &Hashes,
1354 pkgAcquire::MethodConfig *Cfg)
1355{
1356 // First check if the calculcated Hash of the (compressed) downloaded
1357 // file matches the hash we have in the MetaIndexRecords for this file
1358 if(VerifyHashByMetaKey(Hashes) == false)
5f6c6c6e 1359 {
651bddad
MV
1360 RenameOnError(HashSumMismatch);
1361 Failed(Message, Cfg);
1362 return;
8b89e57f 1363 }
bfd22fc0 1364
8267fe24 1365 Complete = true;
8267fbd9 1366
8b89e57f
AL
1367 // Handle the unzipd case
1368 string FileName = LookupTag(Message,"Alt-Filename");
1369 if (FileName.empty() == false)
1370 {
651bddad 1371 Stage = STAGE_DECOMPRESS_AND_VERIFY;
a6568219 1372 Local = true;
8b89e57f 1373 DestFile += ".decomp";
8267fe24
AL
1374 Desc.URI = "copy:" + FileName;
1375 QueueURI(Desc);
eeac6897 1376 SetActiveSubprocess("copy");
8b89e57f
AL
1377 return;
1378 }
1379
1380 FileName = LookupTag(Message,"Filename");
1381 if (FileName.empty() == true)
1382 {
1383 Status = StatError;
1384 ErrorText = "Method gave a blank filename";
1385 }
5d885723 1386
651bddad
MV
1387 // Methods like e.g. "file:" will give us a (compressed) FileName that is
1388 // not the "DestFile" we set, in this case we uncompress from the local file
1389 if (FileName != DestFile)
a6568219 1390 Local = true;
1e8ba0d4
MV
1391 else
1392 EraseFileName = FileName;
daff4aa3 1393
651bddad
MV
1394 // we need to verify the file against the current Release file again
1395 // on if-modfied-since hit to avoid a stale attack against us
1396 if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
ca7fd76c 1397 {
651bddad
MV
1398 // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
1399 // file when its doing the indexcopy
1400 if (RealURI.substr(0,6) == "cdrom:")
1401 return;
b0f4b486 1402
651bddad 1403 // The files timestamp matches, reverify by copy into partial/
1e8ba0d4 1404 EraseFileName = "";
651bddad 1405 ReverifyAfterIMS();
8b89e57f 1406 return;
ca7fd76c 1407 }
e85b4cd5 1408
651bddad 1409 // If we have compressed indexes enabled, queue for hash verification
b0f4b486 1410 if (_config->FindB("Acquire::GzipIndexes",false))
ca7fd76c 1411 {
ea7682a0 1412 DestFile = GetPartialFileNameFromURI(RealURI + '.' + CurrentCompressionExtension);
1e8ba0d4 1413 EraseFileName = "";
651bddad 1414 Stage = STAGE_DECOMPRESS_AND_VERIFY;
ca7fd76c
MV
1415 Desc.URI = "copy:" + FileName;
1416 QueueURI(Desc);
4dbfe436 1417 SetActiveSubprocess("copy");
bb109d0b 1418 return;
1419 }
1420
e85b4cd5 1421 // get the binary name for your used compression type
651bddad 1422 string decompProg;
1e8ba0d4 1423 if(CurrentCompressionExtension == "uncompressed")
0d7a243d 1424 decompProg = "copy";
651bddad 1425 else
1e8ba0d4 1426 decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
651bddad
MV
1427 if(decompProg.empty() == true)
1428 {
1e8ba0d4 1429 _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
debc84b2
MZ
1430 return;
1431 }
1432
651bddad
MV
1433 // queue uri for the next stage
1434 Stage = STAGE_DECOMPRESS_AND_VERIFY;
8b89e57f 1435 DestFile += ".decomp";
e85b4cd5 1436 Desc.URI = decompProg + ":" + FileName;
8267fe24 1437 QueueURI(Desc);
eeac6897 1438 SetActiveSubprocess(decompProg);
8b89e57f 1439}
8267fbd9
DK
1440 /*}}}*/
1441// pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
651bddad
MV
1442void pkgAcqIndex::StageDecompressDone(string Message,
1443 HashStringList const &Hashes,
1444 pkgAcquire::MethodConfig *Cfg)
1445{
1446 if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
1447 {
1448 Desc.URI = RealURI;
1449 RenameOnError(HashSumMismatch);
1450 printHashSumComparision(RealURI, ExpectedHashes, Hashes);
1451 Failed(Message, Cfg);
1452 return;
1453 }
1454
1455 if(!ValidateFile(DestFile))
1456 {
1457 RenameOnError(InvalidFormat);
1458 Failed(Message, Cfg);
1459 return;
1460 }
8267fbd9 1461
1e8ba0d4
MV
1462 // remove the compressed version of the file
1463 unlink(EraseFileName.c_str());
8267fbd9 1464
651bddad
MV
1465 // Done, queue for rename on transaction finished
1466 TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
8267fbd9 1467
651bddad
MV
1468 return;
1469}
92fcbfc1 1470 /*}}}*/
a52f938b
OS
1471// AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
1472// ---------------------------------------------------------------------
1473/* The Translation file is added to the queue */
1474pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
8267fbd9 1475 string URI,string URIDesc,string ShortDesc)
916b8910 1476 : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashStringList())
a52f938b 1477{
ab53c018 1478}
8267fbd9
DK
1479pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
1480 pkgAcqMetaBase *TransactionManager,
e05672e8 1481 IndexTarget const * const Target,
8267fbd9 1482 HashStringList const &ExpectedHashes,
e05672e8 1483 indexRecords *MetaIndexParser)
715c65de 1484 : pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser)
ab53c018 1485{
1dca8dc5
MV
1486 // load the filesize
1487 indexRecords::checkSum *Record = MetaIndexParser->Lookup(string(Target->MetaKey));
1488 if(Record)
1489 FileSize = Record->Size;
963b16dc
MV
1490}
1491 /*}}}*/
1492// AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
b3501edb 1493string pkgAcqIndexTrans::Custom600Headers() const
963b16dc 1494{
3f073d44 1495 string Final = GetFinalFilename();
ca7fd76c 1496
c91d9a63
DK
1497 struct stat Buf;
1498 if (stat(Final.c_str(),&Buf) != 0)
a3f7fff8
MV
1499 return "\nFail-Ignore: true\nIndex-File: true";
1500 return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
a52f938b 1501}
a52f938b
OS
1502 /*}}}*/
1503// AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
a52f938b
OS
1504void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
1505{
651bddad 1506 size_t const nextExt = CompressionExtensions.find(' ');
5d885723
DK
1507 if (nextExt != std::string::npos)
1508 {
651bddad 1509 CompressionExtensions = CompressionExtensions.substr(nextExt+1);
5d885723
DK
1510 Init(RealURI, Desc.Description, Desc.ShortDesc);
1511 Status = StatIdle;
1512 return;
1513 }
1514
4dbfe436
DK
1515 Item::Failed(Message,Cnf);
1516
e05672e8 1517 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
8267fbd9 1518 if (Cnf->LocalOnly == true ||
a52f938b 1519 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
8267fbd9 1520 {
a52f938b
OS
1521 // Ignore this
1522 Status = StatDone;
a52f938b 1523 }
a52f938b
OS
1524}
1525 /*}}}*/
8267fbd9 1526// AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
715c65de 1527void pkgAcqMetaBase::Add(Item *I)
e6e89390 1528{
715c65de 1529 Transaction.push_back(I);
e6e89390 1530}
61aea84d 1531 /*}}}*/
8267fbd9 1532// AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
715c65de
MV
1533void pkgAcqMetaBase::AbortTransaction()
1534{
1535 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1536 std::clog << "AbortTransaction: " << TransactionManager << std::endl;
1537
631a7dc7 1538 // ensure the toplevel is in error state too
715c65de
MV
1539 for (std::vector<Item*>::iterator I = Transaction.begin();
1540 I != Transaction.end(); ++I)
1541 {
1542 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1543 std::clog << " Cancel: " << (*I)->DestFile << std::endl;
1544 // the transaction will abort, so stop anything that is idle
1545 if ((*I)->Status == pkgAcquire::Item::StatIdle)
1546 (*I)->Status = pkgAcquire::Item::StatDone;
0b844e23 1547
edd007cd
MV
1548 // kill failed files in partial
1549 if ((*I)->Status == pkgAcquire::Item::StatError)
1550 {
1551 std::string const PartialFile = GetPartialFileName(flNotDir((*I)->DestFile));
1552 if(FileExists(PartialFile))
1553 Rename(PartialFile, PartialFile + ".FAILED");
1554 }
715c65de
MV
1555 }
1556}
1557 /*}}}*/
8267fbd9 1558// AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
715c65de
MV
1559bool pkgAcqMetaBase::TransactionHasError()
1560{
1561 for (pkgAcquire::ItemIterator I = Transaction.begin();
1562 I != Transaction.end(); ++I)
1563 if((*I)->Status != pkgAcquire::Item::StatDone &&
1564 (*I)->Status != pkgAcquire::Item::StatIdle)
1565 return true;
1566
1567 return false;
1568}
61aea84d
MV
1569 /*}}}*/
1570// AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
715c65de
MV
1571void pkgAcqMetaBase::CommitTransaction()
1572{
1573 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1574 std::clog << "CommitTransaction: " << this << std::endl;
1575
1576 // move new files into place *and* remove files that are not
1577 // part of the transaction but are still on disk
1578 for (std::vector<Item*>::iterator I = Transaction.begin();
1579 I != Transaction.end(); ++I)
1580 {
1581 if((*I)->PartialFile != "")
1582 {
5684f71f
DK
1583 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
1584 std::clog << "mv " << (*I)->PartialFile << " -> "<< (*I)->DestFile << " "
1585 << (*I)->DescURI() << std::endl;
1586
1587 Rename((*I)->PartialFile, (*I)->DestFile);
ea7682a0 1588 ChangeOwnerAndPermissionOfFile("CommitTransaction", (*I)->DestFile.c_str(), "root", "root", 0644);
5684f71f 1589
715c65de
MV
1590 } else {
1591 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
5684f71f 1592 std::clog << "rm "
03bfbc96 1593 << (*I)->DestFile
5684f71f 1594 << " "
03bfbc96
MV
1595 << (*I)->DescURI()
1596 << std::endl;
715c65de
MV
1597 unlink((*I)->DestFile.c_str());
1598 }
1599 // mark that this transaction is finished
1600 (*I)->TransactionManager = 0;
1601 }
1602}
61aea84d 1603 /*}}}*/
61a360be 1604// AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
fa3a96a1
MV
1605void pkgAcqMetaBase::TransactionStageCopy(Item *I,
1606 const std::string &From,
1607 const std::string &To)
1608{
1609 I->PartialFile = From;
1610 I->DestFile = To;
1611}
61aea84d 1612 /*}}}*/
61a360be 1613// AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
fa3a96a1
MV
1614void pkgAcqMetaBase::TransactionStageRemoval(Item *I,
1615 const std::string &FinalFile)
1616{
1617 I->PartialFile = "";
1618 I->DestFile = FinalFile;
1619}
61aea84d 1620 /*}}}*/
61aea84d 1621// AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
2d0a7bb4
MV
1622bool pkgAcqMetaBase::CheckStopAuthentication(const std::string &RealURI,
1623 const std::string &Message)
e6e89390 1624{
2d0a7bb4
MV
1625 // FIXME: this entire function can do now that we disallow going to
1626 // a unauthenticated state and can cleanly rollback
1627
e6e89390 1628 string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
8267fbd9 1629
e6e89390
MV
1630 if(FileExists(Final))
1631 {
1632 Status = StatTransientNetworkError;
1633 _error->Warning(_("An error occurred during the signature "
1634 "verification. The repository is not updated "
1635 "and the previous index files will be used. "
1636 "GPG error: %s: %s\n"),
1637 Desc.Description.c_str(),
1638 LookupTag(Message,"Message").c_str());
1639 RunScripts("APT::Update::Auth-Failure");
1640 return true;
1641 } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
1642 /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
1643 _error->Error(_("GPG error: %s: %s"),
1644 Desc.Description.c_str(),
1645 LookupTag(Message,"Message").c_str());
1646 Status = StatError;
1647 return true;
1648 } else {
1649 _error->Warning(_("GPG error: %s: %s"),
1650 Desc.Description.c_str(),
1651 LookupTag(Message,"Message").c_str());
1652 }
8267fbd9 1653 // gpgv method failed
e6e89390
MV
1654 ReportMirrorFailure("GPGFailure");
1655 return false;
1656}
1657 /*}}}*/
8267fbd9 1658// AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
61aea84d 1659pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
715c65de 1660 pkgAcqMetaBase *TransactionManager,
b3d44315 1661 string URI,string URIDesc,string ShortDesc,
2737f28a 1662 string MetaIndexFile,
b3d44315
MV
1663 const vector<IndexTarget*>* IndexTargets,
1664 indexRecords* MetaIndexParser) :
8267fbd9 1665 pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser,
c045cc02
MV
1666 HashStringList(), TransactionManager),
1667 RealURI(URI), MetaIndexFile(MetaIndexFile), URIDesc(URIDesc),
fa3a96a1 1668 ShortDesc(ShortDesc)
0118833a 1669{
0a8a80e5 1670 DestFile = _config->FindDir("Dir::State::lists") + "partial/";
1ce24318 1671 DestFile += URItoFileName(RealURI);
b3d44315 1672
8267fbd9
DK
1673 // remove any partial downloaded sig-file in partial/.
1674 // it may confuse proxies and is too small to warrant a
47eb38f4 1675 // partial download anyway
f6237efd
MV
1676 unlink(DestFile.c_str());
1677
715c65de 1678 // set the TransactionManager
e05672e8 1679 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
715c65de
MV
1680 std::clog << "New pkgAcqMetaSig with TransactionManager "
1681 << TransactionManager << std::endl;
1f4dd8fd 1682
8267fe24 1683 // Create the item
b2e465d6 1684 Desc.Description = URIDesc;
8267fe24 1685 Desc.Owner = this;
b3d44315
MV
1686 Desc.ShortDesc = ShortDesc;
1687 Desc.URI = URI;
2737f28a 1688
8267fe24 1689 QueueURI(Desc);
ffcccd62
DK
1690}
1691 /*}}}*/
1692pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
1693{
0118833a
AL
1694}
1695 /*}}}*/
b3d44315 1696// pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
0118833a 1697// ---------------------------------------------------------------------
b3501edb 1698string pkgAcqMetaSig::Custom600Headers() const
0118833a 1699{
27e6c17a
MV
1700 std::string Header = GetCustom600Headers(RealURI);
1701 return Header;
0118833a 1702}
61aea84d 1703 /*}}}*/
8267fbd9 1704// pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
61aea84d
MV
1705// ---------------------------------------------------------------------
1706/* The only header we use is the last-modified header. */
1707void pkgAcqMetaSig::Done(string Message,unsigned long long Size,
1708 HashStringList const &Hashes,
b3d44315 1709 pkgAcquire::MethodConfig *Cfg)
c88edf1d 1710{
b3501edb 1711 Item::Done(Message, Size, Hashes, Cfg);
c88edf1d 1712
1ce24318 1713 if(AuthPass == false)
c88edf1d 1714 {
f3097647 1715 if(CheckDownloadDone(Message, RealURI) == true)
1ce24318 1716 {
f3097647
MV
1717 // destfile will be modified to point to MetaIndexFile for the
1718 // gpgv method, so we need to save it here
1719 MetaIndexFileSignature = DestFile;
1720 QueueForSignatureVerify(MetaIndexFile, MetaIndexFileSignature);
1ce24318 1721 }
2737f28a
MV
1722 return;
1723 }
8267fbd9 1724 else
1f4dd8fd 1725 {
ba8a8421 1726 if(CheckAuthDone(Message, RealURI) == true)
f3097647
MV
1727 {
1728 std::string FinalFile = _config->FindDir("Dir::State::lists");
1729 FinalFile += URItoFileName(RealURI);
f3097647
MV
1730 TransactionManager->TransactionStageCopy(this, MetaIndexFileSignature, FinalFile);
1731 }
1ce24318 1732 }
c88edf1d
AL
1733}
1734 /*}}}*/
92fcbfc1 1735void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
681d76d0 1736{
47eb38f4 1737 string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
e8b1db38 1738
673c9469 1739 // check if we need to fail at this point
2d0a7bb4 1740 if (AuthPass == true && CheckStopAuthentication(RealURI, Message))
e8b1db38 1741 return;
e8b1db38 1742
631a7dc7
MV
1743 // FIXME: meh, this is not really elegant
1744 string InReleaseURI = RealURI.replace(RealURI.rfind("Release.gpg"), 12,
1745 "InRelease");
1746 string FinalInRelease = _config->FindDir("Dir::State::lists") + URItoFileName(InReleaseURI);
1747
c99fe2e1 1748 if (RealFileExists(Final) || RealFileExists(FinalInRelease))
631a7dc7 1749 {
c99fe2e1
MV
1750 std::string downgrade_msg;
1751 strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
1752 URIDesc.c_str());
1753 if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
1754 {
1755 // meh, the users wants to take risks (we still mark the packages
1756 // from this repository as unauthenticated)
1757 _error->Warning("%s", downgrade_msg.c_str());
1758 _error->Warning(_("This is normally not allowed, but the option "
1759 "Acquire::AllowDowngradeToInsecureRepositories was "
1760 "given to override it."));
1761
1762 } else {
1763 _error->Error("%s", downgrade_msg.c_str());
1764 Rename(MetaIndexFile, MetaIndexFile+".FAILED");
4dbfe436 1765 Item::Failed("Message: " + downgrade_msg, Cnf);
c99fe2e1
MV
1766 TransactionManager->AbortTransaction();
1767 return;
1768 }
631a7dc7 1769 }
7e5f33eb 1770
1f4dd8fd
MV
1771 // this ensures that any file in the lists/ dir is removed by the
1772 // transaction
ea7682a0 1773 DestFile = GetPartialFileNameFromURI(RealURI);
fa3a96a1 1774 TransactionManager->TransactionStageRemoval(this, DestFile);
24057ad6 1775
631a7dc7 1776 // only allow going further if the users explicitely wants it
c99fe2e1 1777 if(_config->FindB("Acquire::AllowInsecureRepositories") == true)
631a7dc7
MV
1778 {
1779 // we parse the indexes here because at this point the user wanted
1780 // a repository that may potentially harm him
1781 MetaIndexParser->Load(MetaIndexFile);
c045cc02 1782 QueueIndexes(true);
bca84917
MV
1783 }
1784 else
1785 {
c99fe2e1 1786 _error->Warning("Use --allow-insecure-repositories to force the update");
631a7dc7
MV
1787 }
1788
4dbfe436
DK
1789 Item::Failed(Message,Cnf);
1790
e05672e8 1791 // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
4dbfe436 1792 if (Cnf->LocalOnly == true ||
e05672e8 1793 StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
4dbfe436 1794 {
e05672e8
MV
1795 // Ignore this
1796 Status = StatDone;
e05672e8 1797 }
681d76d0 1798}
92fcbfc1
DK
1799 /*}}}*/
1800pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
715c65de 1801 pkgAcqMetaBase *TransactionManager,
b3d44315 1802 string URI,string URIDesc,string ShortDesc,
2737f28a 1803 string MetaIndexSigURI,string MetaIndexSigURIDesc, string MetaIndexSigShortDesc,
fa3b260f 1804 const vector<IndexTarget*>* IndexTargets,
b3d44315 1805 indexRecords* MetaIndexParser) :
c045cc02
MV
1806 pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser, HashStringList(),
1807 TransactionManager),
1808 RealURI(URI), URIDesc(URIDesc), ShortDesc(ShortDesc),
2737f28a
MV
1809 MetaIndexSigURI(MetaIndexSigURI), MetaIndexSigURIDesc(MetaIndexSigURIDesc),
1810 MetaIndexSigShortDesc(MetaIndexSigShortDesc)
b3d44315 1811{
715c65de
MV
1812 if(TransactionManager == NULL)
1813 {
1814 this->TransactionManager = this;
1815 this->TransactionManager->Add(this);
1816 }
e05672e8
MV
1817
1818 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
715c65de
MV
1819 std::clog << "New pkgAcqMetaIndex with TransactionManager "
1820 << this->TransactionManager << std::endl;
1821
b3d44315 1822
e05672e8
MV
1823 Init(URIDesc, ShortDesc);
1824}
1825 /*}}}*/
8267fbd9 1826// pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
e05672e8
MV
1827void pkgAcqMetaIndex::Init(std::string URIDesc, std::string ShortDesc)
1828{
ea7682a0 1829 DestFile = GetPartialFileNameFromURI(RealURI);
56472095 1830
b3d44315
MV
1831 // Create the item
1832 Desc.Description = URIDesc;
1833 Desc.Owner = this;
1834 Desc.ShortDesc = ShortDesc;
e05672e8 1835 Desc.URI = RealURI;
b3d44315 1836
d0cfa8ad
MV
1837 // we expect more item
1838 ExpectedAdditionalItems = IndexTargets->size();
b3d44315
MV
1839 QueueURI(Desc);
1840}
8267fbd9 1841 /*}}}*/
b3d44315
MV
1842// pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
1843// ---------------------------------------------------------------------
b3501edb 1844string pkgAcqMetaIndex::Custom600Headers() const
b3d44315 1845{
27e6c17a 1846 return GetCustom600Headers(RealURI);
b3d44315 1847}
92fcbfc1 1848 /*}}}*/
f3097647
MV
1849void pkgAcqMetaIndex::Done(string Message,unsigned long long Size, /*{{{*/
1850 HashStringList const &Hashes,
b3d44315
MV
1851 pkgAcquire::MethodConfig *Cfg)
1852{
b3501edb 1853 Item::Done(Message,Size,Hashes,Cfg);
b3d44315 1854
f3097647 1855 if(CheckDownloadDone(Message, RealURI))
b3d44315 1856 {
f3097647
MV
1857 // we have a Release file, now download the Signature, all further
1858 // verify/queue for additional downloads will be done in the
1859 // pkgAcqMetaSig::Done() code
1860 std::string MetaIndexFile = DestFile;
1861 new pkgAcqMetaSig(Owner, TransactionManager,
1862 MetaIndexSigURI, MetaIndexSigURIDesc,
1863 MetaIndexSigShortDesc, MetaIndexFile, IndexTargets,
1864 MetaIndexParser);
fce72602 1865
f3097647
MV
1866 string FinalFile = _config->FindDir("Dir::State::lists");
1867 FinalFile += URItoFileName(RealURI);
1868 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
b3d44315 1869 }
f3097647
MV
1870}
1871 /*}}}*/
ba8a8421 1872bool pkgAcqMetaBase::CheckAuthDone(string Message, const string &RealURI) /*{{{*/
f3097647
MV
1873{
1874 // At this point, the gpgv method has succeeded, so there is a
1875 // valid signature from a key in the trusted keyring. We
1876 // perform additional verification of its contents, and use them
1877 // to verify the indexes we are about to download
b3d44315 1878
f3097647
MV
1879 if (!MetaIndexParser->Load(DestFile))
1880 {
1881 Status = StatAuthError;
1882 ErrorText = MetaIndexParser->ErrorText;
1883 return false;
b3d44315 1884 }
56bc3358 1885
f3097647 1886 if (!VerifyVendor(Message, RealURI))
56bc3358 1887 {
f3097647 1888 return false;
56bc3358 1889 }
f3097647
MV
1890
1891 if (_config->FindB("Debug::pkgAcquire::Auth", false))
1892 std::cerr << "Signature verification succeeded: "
1893 << DestFile << std::endl;
1894
1895 // Download further indexes with verification
1896 //
1897 // it would be really nice if we could simply do
1898 // if (IMSHit == false) QueueIndexes(true)
1899 // and skip the download if the Release file has not changed
1900 // - but right now the list cleaner will needs to be tricked
1901 // to not delete all our packages/source indexes in this case
1902 QueueIndexes(true);
1903
1904 return true;
1905}
1906 /*}}}*/
27e6c17a
MV
1907// pkgAcqMetaBase::GetCustom600Headers - Get header for AcqMetaBase /*{{{*/
1908// ---------------------------------------------------------------------
1909string pkgAcqMetaBase::GetCustom600Headers(const string &RealURI) const
1910{
1911 std::string Header = "\nIndex-File: true";
1912 std::string MaximumSize;
1913 strprintf(MaximumSize, "\nMaximum-Size: %i",
1914 _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
1915 Header += MaximumSize;
1916
1917 string FinalFile = _config->FindDir("Dir::State::lists");
1918 FinalFile += URItoFileName(RealURI);
1919
1920 struct stat Buf;
1921 if (stat(FinalFile.c_str(),&Buf) == 0)
1922 Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
1923
1924 return Header;
1925}
1926 /*}}}*/
5684f71f 1927// pkgAcqMetaBase::QueueForSignatureVerify /*{{{*/
f3097647
MV
1928void pkgAcqMetaBase::QueueForSignatureVerify(const std::string &MetaIndexFile,
1929 const std::string &MetaIndexFileSignature)
1930{
1931 AuthPass = true;
1932 Desc.URI = "gpgv:" + MetaIndexFileSignature;
1933 DestFile = MetaIndexFile;
1934 QueueURI(Desc);
1935 SetActiveSubprocess("gpgv");
b3d44315 1936}
92fcbfc1 1937 /*}}}*/
5684f71f 1938// pkgAcqMetaBase::CheckDownloadDone /*{{{*/
f3097647
MV
1939bool pkgAcqMetaBase::CheckDownloadDone(const std::string &Message,
1940 const std::string &RealURI)
b3d44315
MV
1941{
1942 // We have just finished downloading a Release file (it is not
1943 // verified yet)
1944
1945 string FileName = LookupTag(Message,"Filename");
1946 if (FileName.empty() == true)
1947 {
1948 Status = StatError;
1949 ErrorText = "Method gave a blank filename";
f3097647 1950 return false;
b3d44315
MV
1951 }
1952
1953 if (FileName != DestFile)
1954 {
1955 Local = true;
1956 Desc.URI = "copy:" + FileName;
1957 QueueURI(Desc);
f3097647 1958 return false;
b3d44315
MV
1959 }
1960
fce72602 1961 // make sure to verify against the right file on I-M-S hit
f381d68d 1962 IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
fce72602
MV
1963 if(IMSHit)
1964 {
1965 string FinalFile = _config->FindDir("Dir::State::lists");
1966 FinalFile += URItoFileName(RealURI);
1967 DestFile = FinalFile;
1968 }
2737f28a 1969
f3097647 1970 // set Item to complete as the remaining work is all local (verify etc)
b3d44315 1971 Complete = true;
b3d44315 1972
f3097647 1973 return true;
b3d44315 1974}
92fcbfc1 1975 /*}}}*/
c045cc02 1976void pkgAcqMetaBase::QueueIndexes(bool verify) /*{{{*/
b3d44315 1977{
8e3900d0
DK
1978 bool transInRelease = false;
1979 {
1980 std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
1981 for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
1982 // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
1983 if (k->find("Translation-") != std::string::npos)
1984 {
1985 transInRelease = true;
1986 break;
1987 }
1988 }
1989
d0cfa8ad
MV
1990 // at this point the real Items are loaded in the fetcher
1991 ExpectedAdditionalItems = 0;
fa3b260f 1992 for (vector <IndexTarget*>::const_iterator Target = IndexTargets->begin();
b3d44315 1993 Target != IndexTargets->end();
f7f0d6c7 1994 ++Target)
b3d44315 1995 {
b3501edb
DK
1996 HashStringList ExpectedIndexHashes;
1997 const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
a5b9f489 1998 bool compressedAvailable = false;
1207cf3f 1999 if (Record == NULL)
b3d44315 2000 {
a5b9f489
DK
2001 if ((*Target)->IsOptional() == true)
2002 {
2003 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
2004 for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
e788a834 2005 if (MetaIndexParser->Exists((*Target)->MetaKey + "." + *t) == true)
a5b9f489
DK
2006 {
2007 compressedAvailable = true;
2008 break;
2009 }
2010 }
2011 else if (verify == true)
ab53c018 2012 {
1207cf3f
DK
2013 Status = StatAuthError;
2014 strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
2015 return;
ab53c018 2016 }
1207cf3f
DK
2017 }
2018 else
2019 {
b3501edb 2020 ExpectedIndexHashes = Record->Hashes;
1207cf3f 2021 if (_config->FindB("Debug::pkgAcquire::Auth", false))
ab53c018 2022 {
b3501edb
DK
2023 std::cerr << "Queueing: " << (*Target)->URI << std::endl
2024 << "Expected Hash:" << std::endl;
2025 for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
2026 std::cerr << "\t- " << hs->toStr() << std::endl;
1207cf3f
DK
2027 std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
2028 }
b3501edb 2029 if (verify == true && ExpectedIndexHashes.empty() == true && (*Target)->IsOptional() == false)
1207cf3f
DK
2030 {
2031 Status = StatAuthError;
2032 strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
2033 return;
ab53c018
DK
2034 }
2035 }
2036
2037 if ((*Target)->IsOptional() == true)
2038 {
f456b60b 2039 if (transInRelease == false || Record != NULL || compressedAvailable == true)
8e3900d0 2040 {
f55602cb 2041 if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
e788a834 2042 MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true)
715c65de 2043 new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
f55602cb 2044 else
715c65de 2045 new pkgAcqIndexTrans(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
8e3900d0 2046 }
ab53c018 2047 continue;
b3d44315 2048 }
e1430400
DK
2049
2050 /* Queue Packages file (either diff or full packages files, depending
2051 on the users option) - we also check if the PDiff Index file is listed
2052 in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
2053 instead, but passing the required info to it is to much hassle */
2054 if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
e788a834 2055 MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
715c65de 2056 new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
e1430400 2057 else
715c65de 2058 new pkgAcqIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
b3d44315
MV
2059 }
2060}
92fcbfc1 2061 /*}}}*/
f3097647 2062bool pkgAcqMetaBase::VerifyVendor(string Message, const string &RealURI)/*{{{*/
b3d44315 2063{
ce424cd4
MV
2064 string::size_type pos;
2065
2066 // check for missing sigs (that where not fatal because otherwise we had
2067 // bombed earlier)
2068 string missingkeys;
400ad7a4 2069 string msg = _("There is no public key available for the "
ce424cd4
MV
2070 "following key IDs:\n");
2071 pos = Message.find("NO_PUBKEY ");
2072 if (pos != std::string::npos)
2073 {
2074 string::size_type start = pos+strlen("NO_PUBKEY ");
2075 string Fingerprint = Message.substr(start, Message.find("\n")-start);
2076 missingkeys += (Fingerprint);
2077 }
2078 if(!missingkeys.empty())
e788a834 2079 _error->Warning("%s", (msg + missingkeys).c_str());
b3d44315
MV
2080
2081 string Transformed = MetaIndexParser->GetExpectedDist();
2082
2083 if (Transformed == "../project/experimental")
2084 {
2085 Transformed = "experimental";
2086 }
2087
ce424cd4 2088 pos = Transformed.rfind('/');
b3d44315
MV
2089 if (pos != string::npos)
2090 {
2091 Transformed = Transformed.substr(0, pos);
2092 }
2093
2094 if (Transformed == ".")
2095 {
2096 Transformed = "";
2097 }
2098
0323317c
DK
2099 if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
2100 MetaIndexParser->GetValidUntil() > 0) {
2101 time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
2102 if (invalid_since > 0)
2103 // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
2104 // the time since then the file is invalid - formated in the same way as in
2105 // the download progress display (e.g. 7d 3h 42min 1s)
457bea86
MV
2106 return _error->Error(
2107 _("Release file for %s is expired (invalid since %s). "
2108 "Updates for this repository will not be applied."),
2109 RealURI.c_str(), TimeToStr(invalid_since).c_str());
1ddb8596
DK
2110 }
2111
b3d44315
MV
2112 if (_config->FindB("Debug::pkgAcquire::Auth", false))
2113 {
2114 std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
2115 std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
2116 std::cerr << "Transformed Dist: " << Transformed << std::endl;
2117 }
2118
2119 if (MetaIndexParser->CheckDist(Transformed) == false)
2120 {
2121 // This might become fatal one day
2122// Status = StatAuthError;
2123// ErrorText = "Conflicting distribution; expected "
2124// + MetaIndexParser->GetExpectedDist() + " but got "
2125// + MetaIndexParser->GetDist();
2126// return false;
2127 if (!Transformed.empty())
2128 {
1ddb8596 2129 _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
b3d44315
MV
2130 Desc.Description.c_str(),
2131 Transformed.c_str(),
2132 MetaIndexParser->GetDist().c_str());
2133 }
2134 }
2135
2136 return true;
2137}
92fcbfc1 2138 /*}}}*/
8267fbd9 2139// pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
4dbfe436
DK
2140void pkgAcqMetaIndex::Failed(string Message,
2141 pkgAcquire::MethodConfig * Cnf)
b3d44315 2142{
4dbfe436
DK
2143 pkgAcquire::Item::Failed(Message, Cnf);
2144 Status = StatDone;
2145
673c9469 2146 string FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
09475beb 2147
673c9469
MV
2148 _error->Warning(_("The repository '%s' does not have a Release file. "
2149 "This is deprecated, please contact the owner of the "
2150 "repository."), URIDesc.c_str());
c5fced38 2151
673c9469 2152 // No Release file was present so fall
b3d44315 2153 // back to queueing Packages files without verification
631a7dc7 2154 // only allow going further if the users explicitely wants it
c99fe2e1 2155 if(_config->FindB("Acquire::AllowInsecureRepositories") == true)
631a7dc7 2156 {
673c9469 2157 // Done, queue for rename on transaction finished
1d970e6c 2158 if (FileExists(DestFile))
1d970e6c 2159 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
1d970e6c 2160
673c9469 2161 // queue without any kind of hashsum support
631a7dc7 2162 QueueIndexes(false);
bca84917
MV
2163 } else {
2164 // warn if the repository is unsinged
c99fe2e1 2165 _error->Warning("Use --allow-insecure-repositories to force the update");
1d970e6c
MV
2166 TransactionManager->AbortTransaction();
2167 Status = StatError;
2168 return;
8267fbd9 2169 }
b3d44315 2170}
681d76d0 2171 /*}}}*/
8267fbd9 2172void pkgAcqMetaIndex::Finished() /*{{{*/
56472095
MV
2173{
2174 if(_config->FindB("Debug::Acquire::Transaction", false) == true)
2175 std::clog << "Finished: " << DestFile <<std::endl;
715c65de
MV
2176 if(TransactionManager != NULL &&
2177 TransactionManager->TransactionHasError() == false)
2178 TransactionManager->CommitTransaction();
56472095 2179}
8267fbd9 2180 /*}}}*/
fe0f7911
DK
2181pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
2182 string const &URI, string const &URIDesc, string const &ShortDesc,
2183 string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
2184 string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
fa3b260f 2185 const vector<IndexTarget*>* IndexTargets,
fe0f7911 2186 indexRecords* MetaIndexParser) :
715c65de 2187 pkgAcqMetaIndex(Owner, NULL, URI, URIDesc, ShortDesc, MetaSigURI, MetaSigURIDesc,MetaSigShortDesc, IndexTargets, MetaIndexParser),
2737f28a
MV
2188 MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
2189 MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
fe0f7911 2190{
d0cfa8ad
MV
2191 // index targets + (worst case:) Release/Release.gpg
2192 ExpectedAdditionalItems = IndexTargets->size() + 2;
2193
fe0f7911
DK
2194}
2195 /*}}}*/
ffcccd62
DK
2196pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
2197{
ffcccd62
DK
2198}
2199 /*}}}*/
8d6c5839
MV
2200// pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
2201// ---------------------------------------------------------------------
b3501edb 2202string pkgAcqMetaClearSig::Custom600Headers() const
8d6c5839 2203{
27e6c17a
MV
2204 string Header = GetCustom600Headers(RealURI);
2205 Header += "\nFail-Ignore: true";
2206 return Header;
8d6c5839
MV
2207}
2208 /*}}}*/
a9bb651a
MV
2209// pkgAcqMetaClearSig::Done - We got a file /*{{{*/
2210// ---------------------------------------------------------------------
0be13f1c
MV
2211void pkgAcqMetaClearSig::Done(std::string Message,unsigned long long /*Size*/,
2212 HashStringList const &/*Hashes*/,
a9bb651a 2213 pkgAcquire::MethodConfig *Cnf)
fe0f7911 2214{
e84d3803
MV
2215 // if we expect a ClearTextSignature (InRelase), ensure that
2216 // this is what we get and if not fail to queue a
2217 // Release/Release.gpg, see #346386
a9bb651a 2218 if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
e84d3803 2219 {
e84d3803 2220 pkgAcquire::Item::Failed(Message, Cnf);
631a7dc7
MV
2221 RenameOnError(NotClearsigned);
2222 TransactionManager->AbortTransaction();
e84d3803
MV
2223 return;
2224 }
f3097647
MV
2225
2226 if(AuthPass == false)
2227 {
2228 if(CheckDownloadDone(Message, RealURI) == true)
2229 QueueForSignatureVerify(DestFile, DestFile);
2230 return;
2231 }
2232 else
2233 {
ba8a8421 2234 if(CheckAuthDone(Message, RealURI) == true)
f3097647
MV
2235 {
2236 string FinalFile = _config->FindDir("Dir::State::lists");
2237 FinalFile += URItoFileName(RealURI);
2238
2239 // queue for copy in place
2240 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
2241 }
2242 }
a9bb651a
MV
2243}
2244 /*}}}*/
2245void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
2246{
4dbfe436
DK
2247 Item::Failed(Message, Cnf);
2248
a9bb651a
MV
2249 // we failed, we will not get additional items from this method
2250 ExpectedAdditionalItems = 0;
e84d3803 2251
fe0f7911
DK
2252 if (AuthPass == false)
2253 {
7712d13b
MV
2254 // Queue the 'old' InRelease file for removal if we try Release.gpg
2255 // as otherwise the file will stay around and gives a false-auth
2256 // impression (CVE-2012-0214)
de498a52
DK
2257 string FinalFile = _config->FindDir("Dir::State::lists");
2258 FinalFile.append(URItoFileName(RealURI));
fa3a96a1 2259 TransactionManager->TransactionStageRemoval(this, FinalFile);
4dbfe436 2260 Status = StatDone;
de498a52 2261
715c65de 2262 new pkgAcqMetaIndex(Owner, TransactionManager,
fe0f7911 2263 MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
2737f28a 2264 MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
fe0f7911 2265 IndexTargets, MetaIndexParser);
fe0f7911
DK
2266 }
2267 else
673c9469 2268 {
2d0a7bb4 2269 if(CheckStopAuthentication(RealURI, Message))
673c9469
MV
2270 return;
2271
2272 _error->Warning(_("The data from '%s' is not signed. Packages "
2273 "from that repository can not be authenticated."),
2274 URIDesc.c_str());
2275
2276 // No Release file was present, or verification failed, so fall
2277 // back to queueing Packages files without verification
2278 // only allow going further if the users explicitely wants it
2279 if(_config->FindB("Acquire::AllowInsecureRepositories") == true)
2280 {
4dbfe436
DK
2281 Status = StatDone;
2282
673c9469
MV
2283 /* Always move the meta index, even if gpgv failed. This ensures
2284 * that PackageFile objects are correctly filled in */
4dbfe436 2285 if (FileExists(DestFile))
673c9469
MV
2286 {
2287 string FinalFile = _config->FindDir("Dir::State::lists");
2288 FinalFile += URItoFileName(RealURI);
2289 /* InRelease files become Release files, otherwise
2290 * they would be considered as trusted later on */
2291 RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
2292 "Release");
2293 FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
2294 "Release");
4dbfe436 2295
673c9469
MV
2296 // Done, queue for rename on transaction finished
2297 TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
2298 }
2299 QueueIndexes(false);
2300 } else {
4dbfe436 2301 // warn if the repository is unsigned
673c9469
MV
2302 _error->Warning("Use --allow-insecure-repositories to force the update");
2303 TransactionManager->AbortTransaction();
2304 Status = StatError;
4dbfe436 2305 }
673c9469 2306 }
fe0f7911
DK
2307}
2308 /*}}}*/
03e39e59
AL
2309// AcqArchive::AcqArchive - Constructor /*{{{*/
2310// ---------------------------------------------------------------------
17caf1b1
AL
2311/* This just sets up the initial fetch environment and queues the first
2312 possibilitiy */
03e39e59 2313pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
30e1eab5
AL
2314 pkgRecords *Recs,pkgCache::VerIterator const &Version,
2315 string &StoreFilename) :
fa3b260f 2316 Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
b3d44315
MV
2317 StoreFilename(StoreFilename), Vf(Version.FileList()),
2318 Trusted(false)
03e39e59 2319{
7d8afa39 2320 Retries = _config->FindI("Acquire::Retries",0);
813c8eea
AL
2321
2322 if (Version.Arch() == 0)
bdae53f1 2323 {
d1f1f6a8 2324 _error->Error(_("I wasn't able to locate a file for the %s package. "
7a3c2ab0
AL
2325 "This might mean you need to manually fix this package. "
2326 "(due to missing arch)"),
40f8a8ba 2327 Version.ParentPkg().FullName().c_str());
bdae53f1
AL
2328 return;
2329 }
813c8eea 2330
b2e465d6
AL
2331 /* We need to find a filename to determine the extension. We make the
2332 assumption here that all the available sources for this version share
2333 the same extension.. */
2334 // Skip not source sources, they do not have file fields.
69c2ecbd 2335 for (; Vf.end() == false; ++Vf)
b2e465d6
AL
2336 {
2337 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
2338 continue;
2339 break;
2340 }
2341
2342 // Does not really matter here.. we are going to fail out below
2343 if (Vf.end() != true)
2344 {
2345 // If this fails to get a file name we will bomb out below.
2346 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2347 if (_error->PendingError() == true)
2348 return;
2349
2350 // Generate the final file name as: package_version_arch.foo
2351 StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
2352 QuoteString(Version.VerStr(),"_:") + '_' +
2353 QuoteString(Version.Arch(),"_:.") +
2354 "." + flExtension(Parse.FileName());
2355 }
b3d44315
MV
2356
2357 // check if we have one trusted source for the package. if so, switch
6c34ccca
DK
2358 // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
2359 bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
2360 bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
2361 bool seenUntrusted = false;
f7f0d6c7 2362 for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
b3d44315
MV
2363 {
2364 pkgIndexFile *Index;
2365 if (Sources->FindIndex(i.File(),Index) == false)
2366 continue;
6c34ccca
DK
2367
2368 if (debugAuth == true)
b3d44315 2369 std::cerr << "Checking index: " << Index->Describe()
6c34ccca
DK
2370 << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
2371
2372 if (Index->IsTrusted() == true)
2373 {
b3d44315 2374 Trusted = true;
6c34ccca
DK
2375 if (allowUnauth == false)
2376 break;
b3d44315 2377 }
6c34ccca
DK
2378 else
2379 seenUntrusted = true;
b3d44315
MV
2380 }
2381
a3371852
MV
2382 // "allow-unauthenticated" restores apts old fetching behaviour
2383 // that means that e.g. unauthenticated file:// uris are higher
2384 // priority than authenticated http:// uris
6c34ccca 2385 if (allowUnauth == true && seenUntrusted == true)
a3371852
MV
2386 Trusted = false;
2387
03e39e59 2388 // Select a source
b185acc2 2389 if (QueueNext() == false && _error->PendingError() == false)
d57f6084
DK
2390 _error->Error(_("Can't find a source to download version '%s' of '%s'"),
2391 Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
b185acc2
AL
2392}
2393 /*}}}*/
2394// AcqArchive::QueueNext - Queue the next file source /*{{{*/
2395// ---------------------------------------------------------------------
17caf1b1
AL
2396/* This queues the next available file version for download. It checks if
2397 the archive is already available in the cache and stashs the MD5 for
2398 checking later. */
b185acc2 2399bool pkgAcqArchive::QueueNext()
a722b2c5 2400{
f7f0d6c7 2401 for (; Vf.end() == false; ++Vf)
03e39e59
AL
2402 {
2403 // Ignore not source sources
2404 if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
2405 continue;
2406
2407 // Try to cross match against the source list
b2e465d6
AL
2408 pkgIndexFile *Index;
2409 if (Sources->FindIndex(Vf.File(),Index) == false)
2410 continue;
03e39e59 2411
b3d44315
MV
2412 // only try to get a trusted package from another source if that source
2413 // is also trusted
2414 if(Trusted && !Index->IsTrusted())
2415 continue;
2416
03e39e59
AL
2417 // Grab the text package record
2418 pkgRecords::Parser &Parse = Recs->Lookup(Vf);
2419 if (_error->PendingError() == true)
b185acc2 2420 return false;
b3501edb 2421
b2e465d6 2422 string PkgFile = Parse.FileName();
b3501edb
DK
2423 ExpectedHashes = Parse.Hashes();
2424
03e39e59 2425 if (PkgFile.empty() == true)
b2e465d6
AL
2426 return _error->Error(_("The package index files are corrupted. No Filename: "
2427 "field for package %s."),
2428 Version.ParentPkg().Name());
a6568219 2429
b3d44315
MV
2430 Desc.URI = Index->ArchiveURI(PkgFile);
2431 Desc.Description = Index->ArchiveInfo(Version);
2432 Desc.Owner = this;
40f8a8ba 2433 Desc.ShortDesc = Version.ParentPkg().FullName(true);
b3d44315 2434
17caf1b1 2435 // See if we already have the file. (Legacy filenames)
a6568219
AL
2436 FileSize = Version->Size;
2437 string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
2438 struct stat Buf;
2439 if (stat(FinalFile.c_str(),&Buf) == 0)
2440 {
2441 // Make sure the size matches
73da43e9 2442 if ((unsigned long long)Buf.st_size == Version->Size)
a6568219
AL
2443 {
2444 Complete = true;
2445 Local = true;
2446 Status = StatDone;
30e1eab5 2447 StoreFilename = DestFile = FinalFile;
b185acc2 2448 return true;
a6568219
AL
2449 }
2450
6b1ff003
AL
2451 /* Hmm, we have a file and its size does not match, this means it is
2452 an old style mismatched arch */
a6568219
AL
2453 unlink(FinalFile.c_str());
2454 }
17caf1b1
AL
2455
2456 // Check it again using the new style output filenames
2457 FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
2458 if (stat(FinalFile.c_str(),&Buf) == 0)
2459 {
2460 // Make sure the size matches
73da43e9 2461 if ((unsigned long long)Buf.st_size == Version->Size)
17caf1b1
AL
2462 {
2463 Complete = true;
2464 Local = true;
2465 Status = StatDone;
2466 StoreFilename = DestFile = FinalFile;
2467 return true;
2468 }
2469
1e3f4083 2470 /* Hmm, we have a file and its size does not match, this shouldn't
17caf1b1
AL
2471 happen.. */
2472 unlink(FinalFile.c_str());
2473 }
2474
2475 DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
6b1ff003
AL
2476
2477 // Check the destination file
2478 if (stat(DestFile.c_str(),&Buf) == 0)
2479 {
2480 // Hmm, the partial file is too big, erase it
73da43e9 2481 if ((unsigned long long)Buf.st_size > Version->Size)
6b1ff003
AL
2482 unlink(DestFile.c_str());
2483 else
5684f71f 2484 {
6b1ff003 2485 PartialSize = Buf.st_size;
021eb717 2486 ChangeOwnerAndPermissionOfFile("pkgAcqArchive::QueueNext", DestFile.c_str(), "_apt", "root", 0600);
5684f71f 2487 }
6b1ff003 2488 }
de31189f
DK
2489
2490 // Disables download of archives - useful if no real installation follows,
2491 // e.g. if we are just interested in proposed installation order
2492 if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
2493 {
2494 Complete = true;
2495 Local = true;
2496 Status = StatDone;
2497 StoreFilename = DestFile = FinalFile;
2498 return true;
2499 }
2500
03e39e59 2501 // Create the item
b2e465d6 2502 Local = false;
03e39e59 2503 QueueURI(Desc);
b185acc2 2504
f7f0d6c7 2505 ++Vf;
b185acc2 2506 return true;
03e39e59 2507 }
b185acc2
AL
2508 return false;
2509}
03e39e59
AL
2510 /*}}}*/
2511// AcqArchive::Done - Finished fetching /*{{{*/
2512// ---------------------------------------------------------------------
2513/* */
b3501edb 2514void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
459681d3 2515 pkgAcquire::MethodConfig *Cfg)
03e39e59 2516{
b3501edb 2517 Item::Done(Message, Size, CalcHashes, Cfg);
03e39e59
AL
2518
2519 // Check the size
2520 if (Size != Version->Size)
2521 {
3c8030a4 2522 RenameOnError(SizeMismatch);
03e39e59
AL
2523 return;
2524 }
b3501edb 2525
0d29b9d4 2526 // FIXME: could this empty() check impose *any* sort of security issue?
b3501edb 2527 if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
03e39e59 2528 {
3c8030a4 2529 RenameOnError(HashSumMismatch);
b3501edb 2530 printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
495e5cb2 2531 return;
03e39e59 2532 }
a6568219
AL
2533
2534 // Grab the output filename
03e39e59
AL
2535 string FileName = LookupTag(Message,"Filename");
2536 if (FileName.empty() == true)
2537 {
2538 Status = StatError;
2539 ErrorText = "Method gave a blank filename";
2540 return;
2541 }
a6568219 2542
30e1eab5 2543 // Reference filename
a6568219
AL
2544 if (FileName != DestFile)
2545 {
30e1eab5 2546 StoreFilename = DestFile = FileName;
a6568219 2547 Local = true;
5684f71f 2548 Complete = true;
a6568219
AL
2549 return;
2550 }
5684f71f 2551
a6568219
AL
2552 // Done, move it into position
2553 string FinalFile = _config->FindDir("Dir::Cache::Archives");
17caf1b1 2554 FinalFile += flNotDir(StoreFilename);
a6568219 2555 Rename(DestFile,FinalFile);
ea7682a0 2556 ChangeOwnerAndPermissionOfFile("pkgAcqArchive::Done", FinalFile.c_str(), "root", "root", 0644);
30e1eab5 2557 StoreFilename = DestFile = FinalFile;
03e39e59
AL
2558 Complete = true;
2559}
2560 /*}}}*/
db890fdb
AL
2561// AcqArchive::Failed - Failure handler /*{{{*/
2562// ---------------------------------------------------------------------
2563/* Here we try other sources */
7d8afa39 2564void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
db890fdb
AL
2565{
2566 ErrorText = LookupTag(Message,"Message");
b2e465d6
AL
2567
2568 /* We don't really want to retry on failed media swaps, this prevents
2569 that. An interesting observation is that permanent failures are not
2570 recorded. */
2571 if (Cnf->Removable == true &&
2572 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2573 {
2574 // Vf = Version.FileList();
f7f0d6c7 2575 while (Vf.end() == false) ++Vf;
b2e465d6
AL
2576 StoreFilename = string();
2577 Item::Failed(Message,Cnf);
2578 return;
2579 }
2580
db890fdb 2581 if (QueueNext() == false)
7d8afa39
AL
2582 {
2583 // This is the retry counter
2584 if (Retries != 0 &&
2585 Cnf->LocalOnly == false &&
2586 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2587 {
2588 Retries--;
2589 Vf = Version.FileList();
2590 if (QueueNext() == true)
2591 return;
2592 }
2593
9dbb421f 2594 StoreFilename = string();
7d8afa39
AL
2595 Item::Failed(Message,Cnf);
2596 }
db890fdb
AL
2597}
2598 /*}}}*/
92fcbfc1 2599// AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
b3d44315 2600// ---------------------------------------------------------------------
b3501edb 2601APT_PURE bool pkgAcqArchive::IsTrusted() const
b3d44315
MV
2602{
2603 return Trusted;
2604}
92fcbfc1 2605 /*}}}*/
ab559b35
AL
2606// AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
2607// ---------------------------------------------------------------------
2608/* */
2609void pkgAcqArchive::Finished()
2610{
2611 if (Status == pkgAcquire::Item::StatDone &&
2612 Complete == true)
2613 return;
2614 StoreFilename = string();
2615}
2616 /*}}}*/
36375005
AL
2617// AcqFile::pkgAcqFile - Constructor /*{{{*/
2618// ---------------------------------------------------------------------
2619/* The file is added to the queue */
b3501edb 2620pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
73da43e9 2621 unsigned long long Size,string Dsc,string ShortDesc,
77278c2b
MV
2622 const string &DestDir, const string &DestFilename,
2623 bool IsIndexFile) :
fa3b260f 2624 Item(Owner, Hashes), IsIndexFile(IsIndexFile)
36375005 2625{
08cfc005
AL
2626 Retries = _config->FindI("Acquire::Retries",0);
2627
46e00f9d
MV
2628 if(!DestFilename.empty())
2629 DestFile = DestFilename;
2630 else if(!DestDir.empty())
2631 DestFile = DestDir + "/" + flNotDir(URI);
2632 else
2633 DestFile = flNotDir(URI);
2634
36375005
AL
2635 // Create the item
2636 Desc.URI = URI;
2637 Desc.Description = Dsc;
2638 Desc.Owner = this;
2639
2640 // Set the short description to the archive component
2641 Desc.ShortDesc = ShortDesc;
2642
2643 // Get the transfer sizes
2644 FileSize = Size;
2645 struct stat Buf;
2646 if (stat(DestFile.c_str(),&Buf) == 0)
2647 {
2648 // Hmm, the partial file is too big, erase it
ed9665ae 2649 if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
36375005
AL
2650 unlink(DestFile.c_str());
2651 else
5684f71f 2652 {
36375005 2653 PartialSize = Buf.st_size;
ea7682a0 2654 ChangeOwnerAndPermissionOfFile("pkgAcqFile", DestFile.c_str(), "_apt", "root", 0600);
5684f71f 2655 }
36375005 2656 }
092ae175 2657
36375005
AL
2658 QueueURI(Desc);
2659}
2660 /*}}}*/
2661// AcqFile::Done - Item downloaded OK /*{{{*/
2662// ---------------------------------------------------------------------
2663/* */
b3501edb 2664void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
459681d3 2665 pkgAcquire::MethodConfig *Cnf)
36375005 2666{
b3501edb 2667 Item::Done(Message,Size,CalcHashes,Cnf);
495e5cb2 2668
8a8feb29 2669 // Check the hash
b3501edb 2670 if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
b3c39978 2671 {
3c8030a4 2672 RenameOnError(HashSumMismatch);
b3501edb 2673 printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
495e5cb2 2674 return;
b3c39978
AL
2675 }
2676
36375005
AL
2677 string FileName = LookupTag(Message,"Filename");
2678 if (FileName.empty() == true)
2679 {
2680 Status = StatError;
2681 ErrorText = "Method gave a blank filename";
2682 return;
2683 }
2684
2685 Complete = true;
2686
2687 // The files timestamp matches
2688 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
2689 return;
2690
2691 // We have to copy it into place
2692 if (FileName != DestFile)
2693 {
2694 Local = true;
459681d3
AL
2695 if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
2696 Cnf->Removable == true)
917ae805
AL
2697 {
2698 Desc.URI = "copy:" + FileName;
2699 QueueURI(Desc);
2700 return;
2701 }
2702
83ab33fc
AL
2703 // Erase the file if it is a symlink so we can overwrite it
2704 struct stat St;
2705 if (lstat(DestFile.c_str(),&St) == 0)
2706 {
2707 if (S_ISLNK(St.st_mode) != 0)
2708 unlink(DestFile.c_str());
2709 }
2710
2711 // Symlink the file
917ae805
AL
2712 if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
2713 {
83ab33fc 2714 ErrorText = "Link to " + DestFile + " failure ";
917ae805
AL
2715 Status = StatError;
2716 Complete = false;
2717 }
36375005
AL
2718 }
2719}
2720 /*}}}*/
08cfc005
AL
2721// AcqFile::Failed - Failure handler /*{{{*/
2722// ---------------------------------------------------------------------
2723/* Here we try other sources */
2724void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
2725{
2726 ErrorText = LookupTag(Message,"Message");
2727
2728 // This is the retry counter
2729 if (Retries != 0 &&
2730 Cnf->LocalOnly == false &&
2731 StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
2732 {
2733 Retries--;
2734 QueueURI(Desc);
2735 return;
2736 }
2737
2738 Item::Failed(Message,Cnf);
2739}
2740 /*}}}*/
77278c2b
MV
2741// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
2742// ---------------------------------------------------------------------
2743/* The only header we use is the last-modified header. */
b3501edb 2744string pkgAcqFile::Custom600Headers() const
77278c2b
MV
2745{
2746 if (IsIndexFile)
2747 return "\nIndex-File: true";
61a07c57 2748 return "";
77278c2b
MV
2749}
2750 /*}}}*/