]>
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 string
const Dir(File
,0,File
.rfind('/'));
428 std::vector
<pkgTagSection::Tag
> Changes
;
429 Changes
.push_back(pkgTagSection::Tag::Rewrite("Filename", File
));
431 if (Section
->Write(Target
, TFRewritePackageOrder
, Changes
) == false)
433 return Target
.Write("\n", 1);
436 // SourceCopy::GetFile - Get the file information from the section /*{{{*/
437 // ---------------------------------------------------------------------
439 bool SourceCopy::GetFile(string
&File
,unsigned long long &Size
)
441 string Files
= Section
->FindS("Files");
442 if (Files
.empty() == true)
445 // Stash the / terminated directory prefix
446 string Base
= Section
->FindS("Directory");
447 if (Base
.empty() == false && Base
[Base
.length()-1] != '/')
450 // Read the first file triplet
451 const char *C
= Files
.c_str();
455 // Parse each of the elements
456 if (ParseQuoteWord(C
,MD5Hash
) == false ||
457 ParseQuoteWord(C
,sSize
) == false ||
458 ParseQuoteWord(C
,File
) == false)
459 return _error
->Error("Error parsing file record");
461 // Parse the size and append the directory
462 Size
= strtoull(sSize
.c_str(), NULL
, 10);
467 // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
468 bool SourceCopy::RewriteEntry(FileFd
&Target
, std::string
const &File
)
470 string
const Dir(File
,0,File
.rfind('/'));
471 std::vector
<pkgTagSection::Tag
> Changes
;
472 Changes
.push_back(pkgTagSection::Tag::Rewrite("Directory", Dir
));
474 if (Section
->Write(Target
, TFRewriteSourceOrder
, Changes
) == false)
476 return Target
.Write("\n", 1);
479 // SigVerify::Verify - Verify a files md5sum against its metaindex /*{{{*/
480 bool SigVerify::Verify(string prefix
, string file
, indexRecords
*MetaIndex
)
482 const indexRecords::checkSum
*Record
= MetaIndex
->Lookup(file
);
483 bool const Debug
= _config
->FindB("Debug::aptcdrom",false);
485 // we skip non-existing files in the verifcation of the Release file
486 // as non-existing files do not harm, but a warning scares people and
487 // makes it hard to strip unneeded files from an ISO like uncompressed
488 // indexes as it is done on the mirrors (see also LP: #255545 )
489 if(!RealFileExists(prefix
+file
))
492 cout
<< "Skipping nonexistent in " << prefix
<< " file " << file
<< std::endl
;
498 _error
->Warning(_("Can't find authentication record for: %s"), file
.c_str());
502 if (!Record
->Hashes
.VerifyFile(prefix
+file
))
504 _error
->Warning(_("Hash mismatch for: %s"),file
.c_str());
510 cout
<< "File: " << prefix
+file
<< endl
511 << "Expected Hash " << endl
;
512 for (HashStringList::const_iterator hs
= Record
->Hashes
.begin(); hs
!= Record
->Hashes
.end(); ++hs
)
513 std::cout
<< "\t- " << hs
->toStr() << std::endl
;
519 bool SigVerify::CopyMetaIndex(string CDROM
, string CDName
, /*{{{*/
520 string prefix
, string file
)
523 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s%s",CDName
.c_str(),
524 (prefix
).c_str() + CDROM
.length(),file
.c_str());
525 string TargetF
= _config
->FindDir("Dir::State::lists");
526 TargetF
+= URItoFileName(S
);
530 Target
.Open(TargetF
,FileFd::WriteAtomic
);
531 Rel
.Open(prefix
+ file
,FileFd::ReadOnly
);
532 if (CopyFile(Rel
,Target
) == false || Target
.Close() == false)
533 return _error
->Error("Copying of '%s' for '%s' from '%s' failed", file
.c_str(), CDName
.c_str(), prefix
.c_str());
534 ChangeOwnerAndPermissionOfFile("CopyPackages", TargetF
.c_str(), "root", "root", 0644);
539 bool SigVerify::CopyAndVerify(string CDROM
,string Name
,vector
<string
> &SigList
, /*{{{*/
540 vector
<string
> /*PkgList*/,vector
<string
> /*SrcList*/)
542 if (SigList
.empty() == true)
545 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
547 // Read all Release files
548 for (vector
<string
>::iterator I
= SigList
.begin(); I
!= SigList
.end(); ++I
)
551 cout
<< "Signature verify for: " << *I
<< endl
;
553 indexRecords
*MetaIndex
= new indexRecords
;
556 string
const releasegpg
= *I
+"Release.gpg";
557 string
const release
= *I
+"Release";
558 string
const inrelease
= *I
+"InRelease";
559 bool useInRelease
= true;
561 // a Release.gpg without a Release should never happen
562 if (RealFileExists(inrelease
) == true)
564 else if(RealFileExists(release
) == false || RealFileExists(releasegpg
) == false)
570 useInRelease
= false;
572 pid_t pid
= ExecFork();
574 _error
->Error("Fork failed");
579 if (useInRelease
== true)
580 ExecGPGV(inrelease
, inrelease
);
582 ExecGPGV(release
, releasegpg
);
585 if(!ExecWait(pid
, "gpgv")) {
586 _error
->Warning("Signature verification failed for: %s",
587 (useInRelease
? inrelease
.c_str() : releasegpg
.c_str()));
588 // something went wrong, don't copy the Release.gpg
589 // FIXME: delete any existing gpg file?
594 // Open the Release file and add it to the MetaIndex
595 if(!MetaIndex
->Load(release
))
597 _error
->Error("%s",MetaIndex
->ErrorText
.c_str());
601 // go over the Indexfiles and see if they verify
602 // if so, remove them from our copy of the lists
603 vector
<string
> keys
= MetaIndex
->MetaKeys();
604 for (vector
<string
>::iterator I
= keys
.begin(); I
!= keys
.end(); ++I
)
606 if(!Verify(prefix
,*I
, MetaIndex
)) {
607 // something went wrong, don't copy the Release.gpg
608 // FIXME: delete any existing gpg file?
614 // we need a fresh one for the Release.gpg
617 // everything was fine, copy the Release and Release.gpg file
618 if (useInRelease
== true)
619 CopyMetaIndex(CDROM
, Name
, prefix
, "InRelease");
622 CopyMetaIndex(CDROM
, Name
, prefix
, "Release");
623 CopyMetaIndex(CDROM
, Name
, prefix
, "Release.gpg");
630 // SigVerify::RunGPGV - deprecated wrapper calling ExecGPGV /*{{{*/
631 APT_NORETURN
bool SigVerify::RunGPGV(std::string
const &File
, std::string
const &FileOut
,
632 int const &statusfd
, int fd
[2]) {
633 ExecGPGV(File
, FileOut
, statusfd
, fd
);
635 APT_NORETURN
bool SigVerify::RunGPGV(std::string
const &File
, std::string
const &FileOut
,
636 int const &statusfd
) {
637 ExecGPGV(File
, FileOut
, statusfd
);
640 bool TranslationsCopy::CopyTranslations(string CDROM
,string Name
, /*{{{*/
641 vector
<string
> &List
, pkgCdromStatus
*log
)
643 OpProgress
*Progress
= NULL
;
644 if (List
.empty() == true)
648 Progress
= log
->GetOpProgress();
650 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
652 // Prepare the progress indicator
654 std::vector
<APT::Configuration::Compressor
> const compressor
= APT::Configuration::getCompressors();
655 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
659 std::string file
= *I
;
660 for (std::vector
<APT::Configuration::Compressor
>::const_iterator c
= compressor
.begin();
661 c
!= compressor
.end(); ++c
)
663 if (stat((file
+ c
->Extension
).c_str(), &Buf
) != 0)
670 return _error
->Errno("stat", "Stat failed for %s", file
.c_str());
671 TotalSize
+= Buf
.st_size
;
674 off_t CurrentSize
= 0;
675 unsigned int NotFound
= 0;
676 unsigned int WrongSize
= 0;
677 unsigned int Packages
= 0;
678 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
680 // Open the package file
681 FileFd
Pkg(*I
, FileFd::ReadOnly
, FileFd::Auto
);
682 off_t
const FileSize
= Pkg
.Size();
684 pkgTagFile
Parser(&Pkg
);
685 if (_error
->PendingError() == true)
688 // Open the output file
690 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s",Name
.c_str(),
691 (*I
).c_str() + CDROM
.length());
692 string TargetF
= _config
->FindDir("Dir::State::lists") + "partial/";
693 TargetF
+= URItoFileName(S
);
695 if (_config
->FindB("APT::CDROM::NoAct",false) == true)
697 TargetF
= "/dev/null";
698 Target
.Open(TargetF
,FileFd::WriteExists
);
700 Target
.Open(TargetF
,FileFd::WriteAtomic
);
702 if (_error
->PendingError() == true)
705 // Setup the progress meter
707 Progress
->OverallProgress(CurrentSize
,TotalSize
,FileSize
,
708 string("Reading Translation Indexes"));
712 Progress
->SubProgress(Pkg
.Size());
713 pkgTagSection Section
;
714 this->Section
= &Section
;
716 unsigned long Hits
= 0;
717 while (Parser
.Step(Section
) == true)
720 Progress
->Progress(Parser
.Offset());
722 if (Section
.Write(Target
) == false || Target
.Write("\n", 1) == false)
730 cout
<< " Processed by using Prefix '" << Prefix
<< "' and chop " << endl
;
732 if (_config
->FindB("APT::CDROM::NoAct",false) == false)
734 // Move out of the partial directory
736 string FinalF
= _config
->FindDir("Dir::State::lists");
737 FinalF
+= URItoFileName(S
);
738 if (rename(TargetF
.c_str(),FinalF
.c_str()) != 0)
739 return _error
->Errno("rename","Failed to rename");
740 ChangeOwnerAndPermissionOfFile("CopyTranslations", FinalF
.c_str(), "root", "root", 0644);
743 CurrentSize
+= FileSize
;
751 if(NotFound
== 0 && WrongSize
== 0)
752 ioprintf(msg
, _("Wrote %i records.\n"), Packages
);
753 else if (NotFound
!= 0 && WrongSize
== 0)
754 ioprintf(msg
, _("Wrote %i records with %i missing files.\n"),
756 else if (NotFound
== 0 && WrongSize
!= 0)
757 ioprintf(msg
, _("Wrote %i records with %i mismatched files\n"),
758 Packages
, WrongSize
);
759 if (NotFound
!= 0 && WrongSize
!= 0)
760 ioprintf(msg
, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages
, NotFound
, WrongSize
);
764 _error
->Warning("No valid records were found.");
766 if (NotFound
+ WrongSize
> 10)
767 _error
->Warning("A lot of entries were discarded, something may be wrong.\n");
773 APT_CONST
IndexCopy::~IndexCopy() {}