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