]>
git.saurik.com Git - apt.git/blob - apt-pkg/indexcopy.cc
1 // -*- mode: cpp; mode: fold -*-
3 // $Id: indexcopy.cc,v 1.10 2002/03/26 07:38:58 jgg Exp $
4 /* ######################################################################
6 Index Copying - Aid for copying and verifying the index files
8 This class helps apt-cache reconstruct a damaged index files.
10 ##################################################################### */
12 // Include Files /*{{{*/
15 #include <apt-pkg/error.h>
16 #include <apt-pkg/progress.h>
17 #include <apt-pkg/strutl.h>
18 #include <apt-pkg/fileutl.h>
19 #include <apt-pkg/aptconfiguration.h>
20 #include <apt-pkg/configuration.h>
21 #include <apt-pkg/tagfile.h>
22 #include <apt-pkg/indexrecords.h>
23 #include <apt-pkg/cdrom.h>
24 #include <apt-pkg/gpgv.h>
25 #include <apt-pkg/hashes.h>
35 #include "indexcopy.h"
41 // IndexCopy::CopyPackages - Copy the package files from the CD /*{{{*/
42 // ---------------------------------------------------------------------
44 bool IndexCopy::CopyPackages(string CDROM
,string Name
,vector
<string
> &List
,
47 OpProgress
*Progress
= NULL
;
48 if (List
.empty() == true)
52 Progress
= log
->GetOpProgress();
54 bool NoStat
= _config
->FindB("APT::CDROM::Fast",false);
55 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
57 // Prepare the progress indicator
59 std::vector
<APT::Configuration::Compressor
> const compressor
= APT::Configuration::getCompressors();
60 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
64 std::string file
= std::string(*I
).append(GetFileName());
65 for (std::vector
<APT::Configuration::Compressor
>::const_iterator c
= compressor
.begin();
66 c
!= compressor
.end(); ++c
)
68 if (stat((file
+ c
->Extension
).c_str(), &Buf
) != 0)
75 return _error
->Errno("stat", "Stat failed for %s", file
.c_str());
76 TotalSize
+= Buf
.st_size
;
79 off_t CurrentSize
= 0;
80 unsigned int NotFound
= 0;
81 unsigned int WrongSize
= 0;
82 unsigned int Packages
= 0;
83 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
85 string OrigPath
= string(*I
,CDROM
.length());
87 // Open the package file
88 FileFd
Pkg(*I
+ GetFileName(), FileFd::ReadOnly
, FileFd::Auto
);
89 off_t
const FileSize
= Pkg
.Size();
91 pkgTagFile
Parser(&Pkg
);
92 if (_error
->PendingError() == true)
95 // Open the output file
97 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s%s",Name
.c_str(),
98 (*I
).c_str() + CDROM
.length(),GetFileName());
99 string TargetF
= _config
->FindDir("Dir::State::lists") + "partial/";
100 TargetF
+= URItoFileName(S
);
102 if (_config
->FindB("APT::CDROM::NoAct",false) == true)
104 TargetF
= "/dev/null";
105 Target
.Open(TargetF
,FileFd::WriteExists
);
107 Target
.Open(TargetF
,FileFd::WriteAtomic
);
109 if (_error
->PendingError() == true)
112 // Setup the progress meter
114 Progress
->OverallProgress(CurrentSize
,TotalSize
,FileSize
,
115 string("Reading ") + Type() + " Indexes");
119 Progress
->SubProgress(Pkg
.Size());
120 pkgTagSection Section
;
121 this->Section
= &Section
;
123 unsigned long Hits
= 0;
124 unsigned long Chop
= 0;
125 while (Parser
.Step(Section
) == true)
128 Progress
->Progress(Parser
.Offset());
130 unsigned long long Size
;
131 if (GetFile(File
,Size
) == false)
135 File
= OrigPath
+ ChopDirs(File
,Chop
);
137 // See if the file exists
138 if (NoStat
== false || Hits
< 10)
140 // Attempt to fix broken structure
143 if (ReconstructPrefix(Prefix
,OrigPath
,CDROM
,File
) == false &&
144 ReconstructChop(Chop
,*I
,File
) == false)
147 clog
<< "Missed: " << File
<< endl
;
152 File
= OrigPath
+ ChopDirs(File
,Chop
);
157 if (stat((CDROM
+ Prefix
+ File
).c_str(),&Buf
) != 0 ||
160 bool Mangled
= false;
161 // Attempt to fix busted symlink support for one instance
162 string OrigFile
= File
;
163 string::size_type Start
= File
.find("binary-");
164 string::size_type End
= File
.find("/",Start
+3);
165 if (Start
!= string::npos
&& End
!= string::npos
)
167 File
.replace(Start
,End
-Start
,"binary-all");
171 if (Mangled
== false ||
172 stat((CDROM
+ Prefix
+ File
).c_str(),&Buf
) != 0)
175 clog
<< "Missed(2): " << OrigFile
<< endl
;
182 if ((unsigned long long)Buf
.st_size
!= Size
)
185 clog
<< "Wrong Size: " << File
<< endl
;
194 if (RewriteEntry(Target
, File
) == false)
199 cout
<< " Processed by using Prefix '" << Prefix
<< "' and chop " << Chop
<< endl
;
201 if (_config
->FindB("APT::CDROM::NoAct",false) == false)
203 // Move out of the partial directory
205 string FinalF
= _config
->FindDir("Dir::State::lists");
206 FinalF
+= URItoFileName(S
);
207 if (rename(TargetF
.c_str(),FinalF
.c_str()) != 0)
208 return _error
->Errno("rename","Failed to rename");
209 ChangeOwnerAndPermissionOfFile("CopyPackages", FinalF
.c_str(), "root", "root", 0644);
212 /* Mangle the source to be in the proper notation with
213 prefix dist [component] */
214 *I
= string(*I
,Prefix
.length());
215 ConvertToSourceList(CDROM
,*I
);
216 *I
= Prefix
+ ' ' + *I
;
218 CurrentSize
+= FileSize
;
226 if(NotFound
== 0 && WrongSize
== 0)
227 ioprintf(msg
, _("Wrote %i records.\n"), Packages
);
228 else if (NotFound
!= 0 && WrongSize
== 0)
229 ioprintf(msg
, _("Wrote %i records with %i missing files.\n"),
231 else if (NotFound
== 0 && WrongSize
!= 0)
232 ioprintf(msg
, _("Wrote %i records with %i mismatched files\n"),
233 Packages
, WrongSize
);
234 if (NotFound
!= 0 && WrongSize
!= 0)
235 ioprintf(msg
, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages
, NotFound
, WrongSize
);
239 _error
->Warning("No valid records were found.");
241 if (NotFound
+ WrongSize
> 10)
242 _error
->Warning("A lot of entries were discarded, something may be wrong.\n");
247 // IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
248 // ---------------------------------------------------------------------
250 string
IndexCopy::ChopDirs(string Path
,unsigned int Depth
)
252 string::size_type I
= 0;
255 I
= Path
.find('/',I
+1);
258 while (I
!= string::npos
&& Depth
!= 0);
260 if (I
== string::npos
)
263 return string(Path
,I
+1);
266 // IndexCopy::ReconstructPrefix - Fix strange prefixing /*{{{*/
267 // ---------------------------------------------------------------------
268 /* This prepends dir components from the path to the package files to
269 the path to the deb until it is found */
270 bool IndexCopy::ReconstructPrefix(string
&Prefix
,string OrigPath
,string CD
,
273 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
274 unsigned int Depth
= 1;
275 string MyPrefix
= Prefix
;
279 if (stat((CD
+ MyPrefix
+ File
).c_str(),&Buf
) != 0)
282 cout
<< "Failed, " << CD
+ MyPrefix
+ File
<< endl
;
283 if (GrabFirst(OrigPath
,MyPrefix
,Depth
++) == true)
297 // IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
298 // ---------------------------------------------------------------------
299 /* This removes path components from the filename and prepends the location
300 of the package files until a file is found */
301 bool IndexCopy::ReconstructChop(unsigned long &Chop
,string Dir
,string File
)
303 // Attempt to reconstruct the filename
304 unsigned long Depth
= 0;
308 if (stat((Dir
+ File
).c_str(),&Buf
) != 0)
310 File
= ChopDirs(File
,1);
312 if (File
.empty() == false)
325 // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
326 // ---------------------------------------------------------------------
327 /* We look for things in dists/ notation and convert them to
328 <dist> <component> form otherwise it is left alone. This also strips
331 This implements a regex sort of like:
332 (.*)/dists/([^/]*)/(.*)/binary-*
334 | |-------- Distribution
335 |------------------- Path
337 It was deciced to use only a single word for dist (rather than say
338 unstable/non-us) to increase the chance that each CD gets a single
339 line in sources.list.
341 void IndexCopy::ConvertToSourceList(string CD
,string
&Path
)
343 // Strip the cdrom base path
344 Path
= string(Path
,CD
.length());
345 if (Path
.empty() == true)
348 // Too short to be a dists/ type
349 if (Path
.length() < strlen("dists/"))
353 if (stringcmp(Path
.c_str(),Path
.c_str()+strlen("dists/"),"dists/") != 0)
357 string::size_type Slash
= strlen("dists/");
358 string::size_type Slash2
= Path
.find('/',Slash
+ 1);
359 if (Slash2
== string::npos
|| Slash2
+ 2 >= Path
.length())
361 string Dist
= string(Path
,Slash
,Slash2
- Slash
);
363 // Isolate the component
365 for (unsigned I
= 0; I
!= 10; I
++)
367 Slash
= Path
.find('/',Slash
+1);
368 if (Slash
== string::npos
|| Slash
+ 2 >= Path
.length())
370 string Comp
= string(Path
,Slash2
+1,Slash
- Slash2
-1);
372 // Verify the trailing binary- bit
373 string::size_type BinSlash
= Path
.find('/',Slash
+ 1);
374 if (Slash
== string::npos
)
376 string Binary
= string(Path
,Slash
+1,BinSlash
- Slash
-1);
378 if (strncmp(Binary
.c_str(), "binary-", strlen("binary-")) == 0)
380 Binary
.erase(0, strlen("binary-"));
381 if (APT::Configuration::checkArchitecture(Binary
) == false)
384 else if (Binary
!= "source")
387 Path
= Dist
+ ' ' + Comp
;
392 // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
393 // ---------------------------------------------------------------------
395 bool IndexCopy::GrabFirst(string Path
,string
&To
,unsigned int Depth
)
397 string::size_type I
= 0;
400 I
= Path
.find('/',I
+1);
403 while (I
!= string::npos
&& Depth
!= 0);
405 if (I
== string::npos
)
408 To
= string(Path
,0,I
+1);
412 // PackageCopy::GetFile - Get the file information from the section /*{{{*/
413 // ---------------------------------------------------------------------
415 bool PackageCopy::GetFile(string
&File
,unsigned long long &Size
)
417 File
= Section
->FindS("Filename");
418 Size
= Section
->FindI("Size");
419 if (File
.empty() || Size
== 0)
420 return _error
->Error("Cannot find filename or size tag");
424 // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
425 bool PackageCopy::RewriteEntry(FileFd
&Target
,string
const &File
)
427 std::vector
<pkgTagSection::Tag
> Changes
;
428 Changes
.push_back(pkgTagSection::Tag::Rewrite("Filename", File
));
430 if (Section
->Write(Target
, TFRewritePackageOrder
, Changes
) == false)
432 return Target
.Write("\n", 1);
435 // SourceCopy::GetFile - Get the file information from the section /*{{{*/
436 // ---------------------------------------------------------------------
438 bool SourceCopy::GetFile(string
&File
,unsigned long long &Size
)
440 string Files
= Section
->FindS("Files");
441 if (Files
.empty() == true)
444 // Stash the / terminated directory prefix
445 string Base
= Section
->FindS("Directory");
446 if (Base
.empty() == false && Base
[Base
.length()-1] != '/')
449 // Read the first file triplet
450 const char *C
= Files
.c_str();
454 // Parse each of the elements
455 if (ParseQuoteWord(C
,MD5Hash
) == false ||
456 ParseQuoteWord(C
,sSize
) == false ||
457 ParseQuoteWord(C
,File
) == false)
458 return _error
->Error("Error parsing file record");
460 // Parse the size and append the directory
461 Size
= strtoull(sSize
.c_str(), NULL
, 10);
466 // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
467 bool SourceCopy::RewriteEntry(FileFd
&Target
, std::string
const &File
)
469 string
const Dir(File
,0,File
.rfind('/'));
470 std::vector
<pkgTagSection::Tag
> Changes
;
471 Changes
.push_back(pkgTagSection::Tag::Rewrite("Directory", Dir
));
473 if (Section
->Write(Target
, TFRewriteSourceOrder
, Changes
) == false)
475 return Target
.Write("\n", 1);
478 // SigVerify::Verify - Verify a files md5sum against its metaindex /*{{{*/
479 bool SigVerify::Verify(string prefix
, string file
, indexRecords
*MetaIndex
)
481 const indexRecords::checkSum
*Record
= MetaIndex
->Lookup(file
);
482 bool const Debug
= _config
->FindB("Debug::aptcdrom",false);
484 // we skip non-existing files in the verifcation of the Release file
485 // as non-existing files do not harm, but a warning scares people and
486 // makes it hard to strip unneeded files from an ISO like uncompressed
487 // indexes as it is done on the mirrors (see also LP: #255545 )
488 if(!RealFileExists(prefix
+file
))
491 cout
<< "Skipping nonexistent in " << prefix
<< " file " << file
<< std::endl
;
497 _error
->Warning(_("Can't find authentication record for: %s"), file
.c_str());
501 if (!Record
->Hashes
.VerifyFile(prefix
+file
))
503 _error
->Warning(_("Hash mismatch for: %s"),file
.c_str());
509 cout
<< "File: " << prefix
+file
<< endl
510 << "Expected Hash " << endl
;
511 for (HashStringList::const_iterator hs
= Record
->Hashes
.begin(); hs
!= Record
->Hashes
.end(); ++hs
)
512 std::cout
<< "\t- " << hs
->toStr() << std::endl
;
518 bool SigVerify::CopyMetaIndex(string CDROM
, string CDName
, /*{{{*/
519 string prefix
, string file
)
522 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s%s",CDName
.c_str(),
523 (prefix
).c_str() + CDROM
.length(),file
.c_str());
524 string TargetF
= _config
->FindDir("Dir::State::lists");
525 TargetF
+= URItoFileName(S
);
529 Target
.Open(TargetF
,FileFd::WriteAtomic
);
530 Rel
.Open(prefix
+ file
,FileFd::ReadOnly
);
531 if (CopyFile(Rel
,Target
) == false || Target
.Close() == false)
532 return _error
->Error("Copying of '%s' for '%s' from '%s' failed", file
.c_str(), CDName
.c_str(), prefix
.c_str());
533 ChangeOwnerAndPermissionOfFile("CopyPackages", TargetF
.c_str(), "root", "root", 0644);
538 bool SigVerify::CopyAndVerify(string CDROM
,string Name
,vector
<string
> &SigList
, /*{{{*/
539 vector
<string
> /*PkgList*/,vector
<string
> /*SrcList*/)
541 if (SigList
.empty() == true)
544 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
546 // Read all Release files
547 for (vector
<string
>::iterator I
= SigList
.begin(); I
!= SigList
.end(); ++I
)
550 cout
<< "Signature verify for: " << *I
<< endl
;
552 indexRecords
*MetaIndex
= new indexRecords
;
555 string
const releasegpg
= *I
+"Release.gpg";
556 string
const release
= *I
+"Release";
557 string
const inrelease
= *I
+"InRelease";
558 bool useInRelease
= true;
560 // a Release.gpg without a Release should never happen
561 if (RealFileExists(inrelease
) == true)
563 else if(RealFileExists(release
) == false || RealFileExists(releasegpg
) == false)
569 useInRelease
= false;
571 pid_t pid
= ExecFork();
573 _error
->Error("Fork failed");
578 if (useInRelease
== true)
579 ExecGPGV(inrelease
, inrelease
);
581 ExecGPGV(release
, releasegpg
);
584 if(!ExecWait(pid
, "gpgv")) {
585 _error
->Warning("Signature verification failed for: %s",
586 (useInRelease
? inrelease
.c_str() : releasegpg
.c_str()));
587 // something went wrong, don't copy the Release.gpg
588 // FIXME: delete any existing gpg file?
593 // Open the Release file and add it to the MetaIndex
594 if(!MetaIndex
->Load(release
))
596 _error
->Error("%s",MetaIndex
->ErrorText
.c_str());
600 // go over the Indexfiles and see if they verify
601 // if so, remove them from our copy of the lists
602 vector
<string
> keys
= MetaIndex
->MetaKeys();
603 for (vector
<string
>::iterator I
= keys
.begin(); I
!= keys
.end(); ++I
)
605 if(!Verify(prefix
,*I
, MetaIndex
)) {
606 // something went wrong, don't copy the Release.gpg
607 // FIXME: delete any existing gpg file?
613 // we need a fresh one for the Release.gpg
616 // everything was fine, copy the Release and Release.gpg file
617 if (useInRelease
== true)
618 CopyMetaIndex(CDROM
, Name
, prefix
, "InRelease");
621 CopyMetaIndex(CDROM
, Name
, prefix
, "Release");
622 CopyMetaIndex(CDROM
, Name
, prefix
, "Release.gpg");
629 // SigVerify::RunGPGV - deprecated wrapper calling ExecGPGV /*{{{*/
630 APT_NORETURN
bool SigVerify::RunGPGV(std::string
const &File
, std::string
const &FileOut
,
631 int const &statusfd
, int fd
[2]) {
632 ExecGPGV(File
, FileOut
, statusfd
, fd
);
634 APT_NORETURN
bool SigVerify::RunGPGV(std::string
const &File
, std::string
const &FileOut
,
635 int const &statusfd
) {
636 ExecGPGV(File
, FileOut
, statusfd
);
639 bool TranslationsCopy::CopyTranslations(string CDROM
,string Name
, /*{{{*/
640 vector
<string
> &List
, pkgCdromStatus
*log
)
642 OpProgress
*Progress
= NULL
;
643 if (List
.empty() == true)
647 Progress
= log
->GetOpProgress();
649 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
651 // Prepare the progress indicator
653 std::vector
<APT::Configuration::Compressor
> const compressor
= APT::Configuration::getCompressors();
654 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
658 std::string file
= *I
;
659 for (std::vector
<APT::Configuration::Compressor
>::const_iterator c
= compressor
.begin();
660 c
!= compressor
.end(); ++c
)
662 if (stat((file
+ c
->Extension
).c_str(), &Buf
) != 0)
669 return _error
->Errno("stat", "Stat failed for %s", file
.c_str());
670 TotalSize
+= Buf
.st_size
;
673 off_t CurrentSize
= 0;
674 unsigned int NotFound
= 0;
675 unsigned int WrongSize
= 0;
676 unsigned int Packages
= 0;
677 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
679 // Open the package file
680 FileFd
Pkg(*I
, FileFd::ReadOnly
, FileFd::Auto
);
681 off_t
const FileSize
= Pkg
.Size();
683 pkgTagFile
Parser(&Pkg
);
684 if (_error
->PendingError() == true)
687 // Open the output file
689 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s",Name
.c_str(),
690 (*I
).c_str() + CDROM
.length());
691 string TargetF
= _config
->FindDir("Dir::State::lists") + "partial/";
692 TargetF
+= URItoFileName(S
);
694 if (_config
->FindB("APT::CDROM::NoAct",false) == true)
696 TargetF
= "/dev/null";
697 Target
.Open(TargetF
,FileFd::WriteExists
);
699 Target
.Open(TargetF
,FileFd::WriteAtomic
);
701 if (_error
->PendingError() == true)
704 // Setup the progress meter
706 Progress
->OverallProgress(CurrentSize
,TotalSize
,FileSize
,
707 string("Reading Translation Indexes"));
711 Progress
->SubProgress(Pkg
.Size());
712 pkgTagSection Section
;
713 this->Section
= &Section
;
715 unsigned long Hits
= 0;
716 while (Parser
.Step(Section
) == true)
719 Progress
->Progress(Parser
.Offset());
721 if (Section
.Write(Target
) == false || Target
.Write("\n", 1) == false)
729 cout
<< " Processed by using Prefix '" << Prefix
<< "' and chop " << endl
;
731 if (_config
->FindB("APT::CDROM::NoAct",false) == false)
733 // Move out of the partial directory
735 string FinalF
= _config
->FindDir("Dir::State::lists");
736 FinalF
+= URItoFileName(S
);
737 if (rename(TargetF
.c_str(),FinalF
.c_str()) != 0)
738 return _error
->Errno("rename","Failed to rename");
739 ChangeOwnerAndPermissionOfFile("CopyTranslations", FinalF
.c_str(), "root", "root", 0644);
742 CurrentSize
+= FileSize
;
750 if(NotFound
== 0 && WrongSize
== 0)
751 ioprintf(msg
, _("Wrote %i records.\n"), Packages
);
752 else if (NotFound
!= 0 && WrongSize
== 0)
753 ioprintf(msg
, _("Wrote %i records with %i missing files.\n"),
755 else if (NotFound
== 0 && WrongSize
!= 0)
756 ioprintf(msg
, _("Wrote %i records with %i mismatched files\n"),
757 Packages
, WrongSize
);
758 if (NotFound
!= 0 && WrongSize
!= 0)
759 ioprintf(msg
, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages
, NotFound
, WrongSize
);
763 _error
->Warning("No valid records were found.");
765 if (NotFound
+ WrongSize
> 10)
766 _error
->Warning("A lot of entries were discarded, something may be wrong.\n");
772 IndexCopy::IndexCopy() {}
773 APT_CONST
IndexCopy::~IndexCopy() {}
775 PackageCopy::PackageCopy() : IndexCopy() {}
776 APT_CONST
PackageCopy::~PackageCopy() {}
777 SourceCopy::SourceCopy() : IndexCopy() {}
778 APT_CONST
SourceCopy::~SourceCopy() {}
779 TranslationsCopy::TranslationsCopy() {}
780 APT_CONST
TranslationsCopy::~TranslationsCopy() {}
781 SigVerify::SigVerify() {}
782 APT_CONST
SigVerify::~SigVerify() {}