]>
git.saurik.com Git - apt.git/blob - apt-pkg/indexcopy.cc
144c508bef3b7fe8d4bacc255cf417876ccd2d4b
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)
111 FILE *TargetFl
= fdopen(dup(Target
.Fd()),"w");
113 return _error
->Errno("fdopen","Failed to reopen fd");
115 // Setup the progress meter
117 Progress
->OverallProgress(CurrentSize
,TotalSize
,FileSize
,
118 string("Reading ") + Type() + " Indexes");
122 Progress
->SubProgress(Pkg
.Size());
123 pkgTagSection Section
;
124 this->Section
= &Section
;
126 unsigned long Hits
= 0;
127 unsigned long Chop
= 0;
128 while (Parser
.Step(Section
) == true)
131 Progress
->Progress(Parser
.Offset());
133 unsigned long long Size
;
134 if (GetFile(File
,Size
) == false)
141 File
= OrigPath
+ ChopDirs(File
,Chop
);
143 // See if the file exists
144 if (NoStat
== false || Hits
< 10)
146 // Attempt to fix broken structure
149 if (ReconstructPrefix(Prefix
,OrigPath
,CDROM
,File
) == false &&
150 ReconstructChop(Chop
,*I
,File
) == false)
153 clog
<< "Missed: " << File
<< endl
;
158 File
= OrigPath
+ ChopDirs(File
,Chop
);
163 if (stat((CDROM
+ Prefix
+ File
).c_str(),&Buf
) != 0 ||
166 bool Mangled
= false;
167 // Attempt to fix busted symlink support for one instance
168 string OrigFile
= File
;
169 string::size_type Start
= File
.find("binary-");
170 string::size_type End
= File
.find("/",Start
+3);
171 if (Start
!= string::npos
&& End
!= string::npos
)
173 File
.replace(Start
,End
-Start
,"binary-all");
177 if (Mangled
== false ||
178 stat((CDROM
+ Prefix
+ File
).c_str(),&Buf
) != 0)
181 clog
<< "Missed(2): " << OrigFile
<< endl
;
188 if ((unsigned long long)Buf
.st_size
!= Size
)
191 clog
<< "Wrong Size: " << File
<< endl
;
200 if (RewriteEntry(TargetFl
,File
) == false)
209 cout
<< " Processed by using Prefix '" << Prefix
<< "' and chop " << Chop
<< endl
;
211 if (_config
->FindB("APT::CDROM::NoAct",false) == false)
213 // Move out of the partial directory
215 string FinalF
= _config
->FindDir("Dir::State::lists");
216 FinalF
+= URItoFileName(S
);
217 if (rename(TargetF
.c_str(),FinalF
.c_str()) != 0)
218 return _error
->Errno("rename","Failed to rename");
219 ChangeOwnerAndPermissionOfFile("CopyPackages", FinalF
.c_str(), "root", "root", 0644);
222 /* Mangle the source to be in the proper notation with
223 prefix dist [component] */
224 *I
= string(*I
,Prefix
.length());
225 ConvertToSourceList(CDROM
,*I
);
226 *I
= Prefix
+ ' ' + *I
;
228 CurrentSize
+= FileSize
;
236 if(NotFound
== 0 && WrongSize
== 0)
237 ioprintf(msg
, _("Wrote %i records.\n"), Packages
);
238 else if (NotFound
!= 0 && WrongSize
== 0)
239 ioprintf(msg
, _("Wrote %i records with %i missing files.\n"),
241 else if (NotFound
== 0 && WrongSize
!= 0)
242 ioprintf(msg
, _("Wrote %i records with %i mismatched files\n"),
243 Packages
, WrongSize
);
244 if (NotFound
!= 0 && WrongSize
!= 0)
245 ioprintf(msg
, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages
, NotFound
, WrongSize
);
249 _error
->Warning("No valid records were found.");
251 if (NotFound
+ WrongSize
> 10)
252 _error
->Warning("A lot of entries were discarded, something may be wrong.\n");
258 // IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
259 // ---------------------------------------------------------------------
261 string
IndexCopy::ChopDirs(string Path
,unsigned int Depth
)
263 string::size_type I
= 0;
266 I
= Path
.find('/',I
+1);
269 while (I
!= string::npos
&& Depth
!= 0);
271 if (I
== string::npos
)
274 return string(Path
,I
+1);
277 // IndexCopy::ReconstructPrefix - Fix strange prefixing /*{{{*/
278 // ---------------------------------------------------------------------
279 /* This prepends dir components from the path to the package files to
280 the path to the deb until it is found */
281 bool IndexCopy::ReconstructPrefix(string
&Prefix
,string OrigPath
,string CD
,
284 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
285 unsigned int Depth
= 1;
286 string MyPrefix
= Prefix
;
290 if (stat((CD
+ MyPrefix
+ File
).c_str(),&Buf
) != 0)
293 cout
<< "Failed, " << CD
+ MyPrefix
+ File
<< endl
;
294 if (GrabFirst(OrigPath
,MyPrefix
,Depth
++) == true)
308 // IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
309 // ---------------------------------------------------------------------
310 /* This removes path components from the filename and prepends the location
311 of the package files until a file is found */
312 bool IndexCopy::ReconstructChop(unsigned long &Chop
,string Dir
,string File
)
314 // Attempt to reconstruct the filename
315 unsigned long Depth
= 0;
319 if (stat((Dir
+ File
).c_str(),&Buf
) != 0)
321 File
= ChopDirs(File
,1);
323 if (File
.empty() == false)
336 // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
337 // ---------------------------------------------------------------------
338 /* We look for things in dists/ notation and convert them to
339 <dist> <component> form otherwise it is left alone. This also strips
342 This implements a regex sort of like:
343 (.*)/dists/([^/]*)/(.*)/binary-*
345 | |-------- Distribution
346 |------------------- Path
348 It was deciced to use only a single word for dist (rather than say
349 unstable/non-us) to increase the chance that each CD gets a single
350 line in sources.list.
352 void IndexCopy::ConvertToSourceList(string CD
,string
&Path
)
354 // Strip the cdrom base path
355 Path
= string(Path
,CD
.length());
356 if (Path
.empty() == true)
359 // Too short to be a dists/ type
360 if (Path
.length() < strlen("dists/"))
364 if (stringcmp(Path
.c_str(),Path
.c_str()+strlen("dists/"),"dists/") != 0)
368 string::size_type Slash
= strlen("dists/");
369 string::size_type Slash2
= Path
.find('/',Slash
+ 1);
370 if (Slash2
== string::npos
|| Slash2
+ 2 >= Path
.length())
372 string Dist
= string(Path
,Slash
,Slash2
- Slash
);
374 // Isolate the component
376 for (unsigned I
= 0; I
!= 10; I
++)
378 Slash
= Path
.find('/',Slash
+1);
379 if (Slash
== string::npos
|| Slash
+ 2 >= Path
.length())
381 string Comp
= string(Path
,Slash2
+1,Slash
- Slash2
-1);
383 // Verify the trailing binary- bit
384 string::size_type BinSlash
= Path
.find('/',Slash
+ 1);
385 if (Slash
== string::npos
)
387 string Binary
= string(Path
,Slash
+1,BinSlash
- Slash
-1);
389 if (strncmp(Binary
.c_str(), "binary-", strlen("binary-")) == 0)
391 Binary
.erase(0, strlen("binary-"));
392 if (APT::Configuration::checkArchitecture(Binary
) == false)
395 else if (Binary
!= "source")
398 Path
= Dist
+ ' ' + Comp
;
403 // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
404 // ---------------------------------------------------------------------
406 bool IndexCopy::GrabFirst(string Path
,string
&To
,unsigned int Depth
)
408 string::size_type I
= 0;
411 I
= Path
.find('/',I
+1);
414 while (I
!= string::npos
&& Depth
!= 0);
416 if (I
== string::npos
)
419 To
= string(Path
,0,I
+1);
423 // PackageCopy::GetFile - Get the file information from the section /*{{{*/
424 // ---------------------------------------------------------------------
426 bool PackageCopy::GetFile(string
&File
,unsigned long long &Size
)
428 File
= Section
->FindS("Filename");
429 Size
= Section
->FindI("Size");
430 if (File
.empty() || Size
== 0)
431 return _error
->Error("Cannot find filename or size tag");
435 // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
436 // ---------------------------------------------------------------------
438 bool PackageCopy::RewriteEntry(FILE *Target
,string File
)
440 TFRewriteData Changes
[] = {{ "Filename", File
.c_str(), NULL
},
441 { NULL
, NULL
, NULL
}};
443 if (TFRewrite(Target
,*Section
,TFRewritePackageOrder
,Changes
) == false)
449 // SourceCopy::GetFile - Get the file information from the section /*{{{*/
450 // ---------------------------------------------------------------------
452 bool SourceCopy::GetFile(string
&File
,unsigned long long &Size
)
454 string Files
= Section
->FindS("Files");
455 if (Files
.empty() == true)
458 // Stash the / terminated directory prefix
459 string Base
= Section
->FindS("Directory");
460 if (Base
.empty() == false && Base
[Base
.length()-1] != '/')
463 // Read the first file triplet
464 const char *C
= Files
.c_str();
468 // Parse each of the elements
469 if (ParseQuoteWord(C
,MD5Hash
) == false ||
470 ParseQuoteWord(C
,sSize
) == false ||
471 ParseQuoteWord(C
,File
) == false)
472 return _error
->Error("Error parsing file record");
474 // Parse the size and append the directory
475 Size
= strtoull(sSize
.c_str(), NULL
, 10);
480 // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
481 // ---------------------------------------------------------------------
483 bool SourceCopy::RewriteEntry(FILE *Target
,string File
)
485 string
Dir(File
,0,File
.rfind('/'));
486 TFRewriteData Changes
[] = {{ "Directory", Dir
.c_str(), NULL
},
487 { NULL
, NULL
, NULL
}};
489 if (TFRewrite(Target
,*Section
,TFRewriteSourceOrder
,Changes
) == false)
495 // SigVerify::Verify - Verify a files md5sum against its metaindex /*{{{*/
496 // ---------------------------------------------------------------------
498 bool SigVerify::Verify(string prefix
, string file
, indexRecords
*MetaIndex
)
500 const indexRecords::checkSum
*Record
= MetaIndex
->Lookup(file
);
501 bool const Debug
= _config
->FindB("Debug::aptcdrom",false);
503 // we skip non-existing files in the verifcation of the Release file
504 // as non-existing files do not harm, but a warning scares people and
505 // makes it hard to strip unneeded files from an ISO like uncompressed
506 // indexes as it is done on the mirrors (see also LP: #255545 )
507 if(!RealFileExists(prefix
+file
))
510 cout
<< "Skipping nonexistent in " << prefix
<< " file " << file
<< std::endl
;
516 _error
->Warning(_("Can't find authentication record for: %s"), file
.c_str());
520 if (!Record
->Hashes
.VerifyFile(prefix
+file
))
522 _error
->Warning(_("Hash mismatch for: %s"),file
.c_str());
528 cout
<< "File: " << prefix
+file
<< endl
529 << "Expected Hash " << endl
;
530 for (HashStringList::const_iterator hs
= Record
->Hashes
.begin(); hs
!= Record
->Hashes
.end(); ++hs
)
531 std::cout
<< "\t- " << hs
->toStr() << std::endl
;
537 bool SigVerify::CopyMetaIndex(string CDROM
, string CDName
, /*{{{*/
538 string prefix
, string file
)
541 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s%s",CDName
.c_str(),
542 (prefix
).c_str() + CDROM
.length(),file
.c_str());
543 string TargetF
= _config
->FindDir("Dir::State::lists");
544 TargetF
+= URItoFileName(S
);
548 Target
.Open(TargetF
,FileFd::WriteAtomic
);
549 Rel
.Open(prefix
+ file
,FileFd::ReadOnly
);
550 if (CopyFile(Rel
,Target
) == false || Target
.Close() == false)
551 return _error
->Error("Copying of '%s' for '%s' from '%s' failed", file
.c_str(), CDName
.c_str(), prefix
.c_str());
552 ChangeOwnerAndPermissionOfFile("CopyPackages", TargetF
.c_str(), "root", "root", 0644);
557 bool SigVerify::CopyAndVerify(string CDROM
,string Name
,vector
<string
> &SigList
, /*{{{*/
558 vector
<string
> /*PkgList*/,vector
<string
> /*SrcList*/)
560 if (SigList
.empty() == true)
563 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
565 // Read all Release files
566 for (vector
<string
>::iterator I
= SigList
.begin(); I
!= SigList
.end(); ++I
)
569 cout
<< "Signature verify for: " << *I
<< endl
;
571 indexRecords
*MetaIndex
= new indexRecords
;
574 string
const releasegpg
= *I
+"Release.gpg";
575 string
const release
= *I
+"Release";
576 string
const inrelease
= *I
+"InRelease";
577 bool useInRelease
= true;
579 // a Release.gpg without a Release should never happen
580 if (RealFileExists(inrelease
) == true)
582 else if(RealFileExists(release
) == false || RealFileExists(releasegpg
) == false)
588 useInRelease
= false;
590 pid_t pid
= ExecFork();
592 _error
->Error("Fork failed");
597 if (useInRelease
== true)
598 ExecGPGV(inrelease
, inrelease
);
600 ExecGPGV(release
, releasegpg
);
603 if(!ExecWait(pid
, "gpgv")) {
604 _error
->Warning("Signature verification failed for: %s",
605 (useInRelease
? inrelease
.c_str() : releasegpg
.c_str()));
606 // something went wrong, don't copy the Release.gpg
607 // FIXME: delete any existing gpg file?
612 // Open the Release file and add it to the MetaIndex
613 if(!MetaIndex
->Load(release
))
615 _error
->Error("%s",MetaIndex
->ErrorText
.c_str());
619 // go over the Indexfiles and see if they verify
620 // if so, remove them from our copy of the lists
621 vector
<string
> keys
= MetaIndex
->MetaKeys();
622 for (vector
<string
>::iterator I
= keys
.begin(); I
!= keys
.end(); ++I
)
624 if(!Verify(prefix
,*I
, MetaIndex
)) {
625 // something went wrong, don't copy the Release.gpg
626 // FIXME: delete any existing gpg file?
632 // we need a fresh one for the Release.gpg
635 // everything was fine, copy the Release and Release.gpg file
636 if (useInRelease
== true)
637 CopyMetaIndex(CDROM
, Name
, prefix
, "InRelease");
640 CopyMetaIndex(CDROM
, Name
, prefix
, "Release");
641 CopyMetaIndex(CDROM
, Name
, prefix
, "Release.gpg");
648 // SigVerify::RunGPGV - deprecated wrapper calling ExecGPGV /*{{{*/
649 APT_NORETURN
bool SigVerify::RunGPGV(std::string
const &File
, std::string
const &FileOut
,
650 int const &statusfd
, int fd
[2]) {
651 ExecGPGV(File
, FileOut
, statusfd
, fd
);
653 APT_NORETURN
bool SigVerify::RunGPGV(std::string
const &File
, std::string
const &FileOut
,
654 int const &statusfd
) {
655 ExecGPGV(File
, FileOut
, statusfd
);
658 bool TranslationsCopy::CopyTranslations(string CDROM
,string Name
, /*{{{*/
659 vector
<string
> &List
, pkgCdromStatus
*log
)
661 OpProgress
*Progress
= NULL
;
662 if (List
.empty() == true)
666 Progress
= log
->GetOpProgress();
668 bool Debug
= _config
->FindB("Debug::aptcdrom",false);
670 // Prepare the progress indicator
672 std::vector
<APT::Configuration::Compressor
> const compressor
= APT::Configuration::getCompressors();
673 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
677 std::string file
= *I
;
678 for (std::vector
<APT::Configuration::Compressor
>::const_iterator c
= compressor
.begin();
679 c
!= compressor
.end(); ++c
)
681 if (stat((file
+ c
->Extension
).c_str(), &Buf
) != 0)
688 return _error
->Errno("stat", "Stat failed for %s", file
.c_str());
689 TotalSize
+= Buf
.st_size
;
692 off_t CurrentSize
= 0;
693 unsigned int NotFound
= 0;
694 unsigned int WrongSize
= 0;
695 unsigned int Packages
= 0;
696 for (vector
<string
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
698 // Open the package file
699 FileFd
Pkg(*I
, FileFd::ReadOnly
, FileFd::Auto
);
700 off_t
const FileSize
= Pkg
.Size();
702 pkgTagFile
Parser(&Pkg
);
703 if (_error
->PendingError() == true)
706 // Open the output file
708 snprintf(S
,sizeof(S
),"cdrom:[%s]/%s",Name
.c_str(),
709 (*I
).c_str() + CDROM
.length());
710 string TargetF
= _config
->FindDir("Dir::State::lists") + "partial/";
711 TargetF
+= URItoFileName(S
);
713 if (_config
->FindB("APT::CDROM::NoAct",false) == true)
715 TargetF
= "/dev/null";
716 Target
.Open(TargetF
,FileFd::WriteExists
);
718 Target
.Open(TargetF
,FileFd::WriteAtomic
);
720 if (_error
->PendingError() == true)
722 FILE *TargetFl
= fdopen(dup(Target
.Fd()),"w");
724 return _error
->Errno("fdopen","Failed to reopen fd");
726 // Setup the progress meter
728 Progress
->OverallProgress(CurrentSize
,TotalSize
,FileSize
,
729 string("Reading Translation Indexes"));
733 Progress
->SubProgress(Pkg
.Size());
734 pkgTagSection Section
;
735 this->Section
= &Section
;
737 unsigned long Hits
= 0;
738 while (Parser
.Step(Section
) == true)
741 Progress
->Progress(Parser
.Offset());
745 Section
.GetSection(Start
,Stop
);
746 fwrite(Start
,Stop
-Start
, 1, TargetFl
);
747 fputc('\n',TargetFl
);
755 cout
<< " Processed by using Prefix '" << Prefix
<< "' and chop " << endl
;
757 if (_config
->FindB("APT::CDROM::NoAct",false) == false)
759 // Move out of the partial directory
761 string FinalF
= _config
->FindDir("Dir::State::lists");
762 FinalF
+= URItoFileName(S
);
763 if (rename(TargetF
.c_str(),FinalF
.c_str()) != 0)
764 return _error
->Errno("rename","Failed to rename");
765 ChangeOwnerAndPermissionOfFile("CopyTranslations", FinalF
.c_str(), "root", "root", 0644);
769 CurrentSize
+= FileSize
;
777 if(NotFound
== 0 && WrongSize
== 0)
778 ioprintf(msg
, _("Wrote %i records.\n"), Packages
);
779 else if (NotFound
!= 0 && WrongSize
== 0)
780 ioprintf(msg
, _("Wrote %i records with %i missing files.\n"),
782 else if (NotFound
== 0 && WrongSize
!= 0)
783 ioprintf(msg
, _("Wrote %i records with %i mismatched files\n"),
784 Packages
, WrongSize
);
785 if (NotFound
!= 0 && WrongSize
!= 0)
786 ioprintf(msg
, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages
, NotFound
, WrongSize
);
790 _error
->Warning("No valid records were found.");
792 if (NotFound
+ WrongSize
> 10)
793 _error
->Warning("A lot of entries were discarded, something may be wrong.\n");
800 APT_CONST
IndexCopy::~IndexCopy() {}