1
// -*- mode: cpp; mode: fold -*-
3
// $Id: indexcopy.cc,v 1.3 2001/08/15 19:44:09 kojima 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 /*{{{*/
16
#include "indexcopy.h"
18
#include <apt-pkg/error.h>
19
#include <apt-pkg/progress.h>
20
#include <apt-pkg/strutl.h>
21
#include <apt-pkg/fileutl.h>
22
#include <apt-pkg/configuration.h>
23
#include <apt-pkg/tagfile.h>
31
// IndexCopy::CopyPackages - Copy the package files from the CD /*{{{*/
32
// ---------------------------------------------------------------------
34
bool IndexCopy::CopyPackages(string CDROM,string Name,vector<string> &List)
39
OpTextProgress Progress;
41
bool NoStat = _config->FindB("APT::CDROM::Fast",false);
42
bool Debug = _config->FindB("Debug::aptcdrom",false);
44
// Prepare the progress indicator
45
unsigned long TotalSize = 0;
46
for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
49
if (stat(string(*I + GetFileName()).c_str(),&Buf) != 0 &&
50
stat(string(*I + GetFileName() + ".gz").c_str(),&Buf) != 0)
51
return _error->Errno("stat","Stat failed for %s",
52
string(*I + GetFileName()).c_str());
53
TotalSize += Buf.st_size;
56
unsigned long CurrentSize = 0;
57
unsigned int NotFound = 0;
58
unsigned int WrongSize = 0;
59
unsigned int Packages = 0;
60
for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
62
string OrigPath = string(*I,CDROM.length());
63
unsigned long FileSize = 0;
65
// Open the package file
67
if (FileExists(*I + GetFileName()) == true)
69
Pkg.Open(*I + GetFileName(),FileFd::ReadOnly);
70
FileSize = Pkg.Size();
74
FileFd From(*I + GetFileName() + ".gz",FileFd::ReadOnly);
75
if (_error->PendingError() == true)
77
FileSize = From.Size();
80
FILE *tmp = tmpfile();
82
return _error->Errno("tmpfile","Unable to create a tmp file");
83
Pkg.Fd(dup(fileno(tmp)));
89
return _error->Errno("fork","Couldn't fork gzip");
94
dup2(From.Fd(),STDIN_FILENO);
95
dup2(Pkg.Fd(),STDOUT_FILENO);
96
SetCloseExec(STDIN_FILENO,false);
97
SetCloseExec(STDOUT_FILENO,false);
100
Args[0] = _config->Find("Dir::bin::gzip","gzip").c_str();
103
execvp(Args[0],(char **)Args);
107
// Wait for gzip to finish
108
if (ExecWait(Process,_config->Find("Dir::bin::gzip","gzip").c_str(),false) == false)
109
return _error->Error("gzip failed, perhaps the disk is full.");
114
pkgTagFile Parser(Pkg);
116
pkgTagFile Parser(&Pkg);
118
if (_error->PendingError() == true)
121
// Open the output file
123
sprintf(S,"cdrom:[%s]/%s%s",Name.c_str(),(*I).c_str() + CDROM.length(),
125
string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
126
TargetF += URItoFileName(S);
127
if (_config->FindB("APT::CDROM::NoAct",false) == true)
128
TargetF = "/dev/null";
129
FileFd Target(TargetF,FileFd::WriteEmpty);
130
if (_error->PendingError() == true)
133
// Setup the progress meter
134
Progress.OverallProgress(CurrentSize,TotalSize,FileSize,
135
string("Reading ") + Type() + " Indexes");
138
Progress.SubProgress(Pkg.Size());
139
pkgTagSection Section;
140
this->Section = &Section;
142
unsigned long Hits = 0;
143
unsigned long Chop = 0;
144
while (Parser.Step(Section) == true)
146
Progress.Progress(Parser.Offset());
149
if (GetFile(File,Size) == false)
153
File = OrigPath + ChopDirs(File,Chop);
155
// See if the file exists
156
bool Mangled = false;
157
if (NoStat == false || Hits < 10)
159
// Attempt to fix broken structure
162
if (ReconstructPrefix(Prefix,OrigPath,CDROM,File) == false &&
163
ReconstructChop(Chop,*I,File) == false)
166
clog << "Missed: " << File << endl;
171
File = OrigPath + ChopDirs(File,Chop);
176
if (stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0 ||
179
// Attempt to fix busted symlink support for one instance
180
string OrigFile = File;
181
string::size_type Start = File.find("binary-");
182
string::size_type End = File.find("/",Start+3);
183
if (Start != string::npos && End != string::npos)
185
File.replace(Start,End-Start,"binary-all");
189
if (Mangled == false ||
190
stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0)
193
clog << "Missed(2): " << OrigFile << endl;
200
if ((unsigned)Buf.st_size != Size)
203
clog << "Wrong Size: " << File << endl;
212
// Copy it to the target package file
213
if (Chop != 0 || Mangled == true)
215
if (RewriteEntry(Target,File) == false)
222
Section.GetSection(Start,Stop);
223
if (Target.Write(Start,Stop-Start) == false)
229
cout << " Processed by using Prefix '" << Prefix << "' and chop " << Chop << endl;
231
if (_config->FindB("APT::CDROM::NoAct",false) == false)
233
// Move out of the partial directory
235
string FinalF = _config->FindDir("Dir::State::lists");
236
FinalF += URItoFileName(S);
237
if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
238
return _error->Errno("rename","Failed to rename");
240
// Copy the release file
241
sprintf(S,"cdrom:[%s]/%sRelease",Name.c_str(),(*I).c_str() + CDROM.length());
242
string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
243
TargetF += URItoFileName(S);
244
if (FileExists(*I + "Release") == true)
246
FileFd Target(TargetF,FileFd::WriteEmpty);
247
FileFd Rel(*I + "Release",FileFd::ReadOnly);
248
if (_error->PendingError() == true)
251
if (CopyFile(Rel,Target) == false)
256
// Empty release file
257
FileFd Target(TargetF,FileFd::WriteEmpty);
260
// Rename the release file
261
FinalF = _config->FindDir("Dir::State::lists");
262
FinalF += URItoFileName(S);
263
if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
264
return _error->Errno("rename","Failed to rename");
267
/* Mangle the source to be in the proper notation with
268
prefix dist [component] */
269
*I = string(*I,Prefix.length());
270
ConvertToSourceList(CDROM,*I);
271
*I = Prefix + ' ' + *I;
273
CurrentSize += FileSize;
278
cout << "Wrote " << Packages << " records" ;
280
cout << " with " << NotFound << " missing files";
281
if (NotFound != 0 && WrongSize != 0)
284
cout << " with " << WrongSize << " mismatched files";
288
return _error->Warning("No valid records were found.");
290
if (NotFound + WrongSize > 10)
291
cout << "Alot of entries were discarded, something may be wrong." << endl;
296
// IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
297
// ---------------------------------------------------------------------
299
string IndexCopy::ChopDirs(string Path,unsigned int Depth)
301
string::size_type I = 0;
304
I = Path.find('/',I+1);
307
while (I != string::npos && Depth != 0);
309
if (I == string::npos)
312
return string(Path,I+1);
315
// IndexCopy::ReconstructPrefix - Fix strange prefixing /*{{{*/
316
// ---------------------------------------------------------------------
317
/* This prepends dir components from the path to the package files to
318
the path to the deb until it is found */
319
bool IndexCopy::ReconstructPrefix(string &Prefix,string OrigPath,string CD,
322
bool Debug = _config->FindB("Debug::aptcdrom",false);
323
unsigned int Depth = 1;
324
string MyPrefix = Prefix;
328
if (stat(string(CD + MyPrefix + File).c_str(),&Buf) != 0)
331
cout << "Failed, " << CD + MyPrefix + File << endl;
332
if (GrabFirst(OrigPath,MyPrefix,Depth++) == true)
346
// IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
347
// ---------------------------------------------------------------------
348
/* This removes path components from the filename and prepends the location
349
of the package files until a file is found */
350
bool IndexCopy::ReconstructChop(unsigned long &Chop,string Dir,string File)
352
// Attempt to reconstruct the filename
353
unsigned long Depth = 0;
357
if (stat(string(Dir + File).c_str(),&Buf) != 0)
359
File = ChopDirs(File,1);
361
if (File.empty() == false)
374
// IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
375
// ---------------------------------------------------------------------
376
/* We look for things in dists/ notation and convert them to
377
<dist> <component> form otherwise it is left alone. This also strips
380
This implements a regex sort of like:
381
(.*)/dists/([^/]*)/(.*)/binary-*
383
| |-------- Distribution
384
|------------------- Path
386
It was deciced to use only a single word for dist (rather than say
387
unstable/non-us) to increase the chance that each CD gets a single
388
line in sources.list.
390
void IndexCopy::ConvertToSourceList(string CD,string &Path)
393
sprintf(S,"binary-%s",_config->Find("Apt::Architecture").c_str());
395
// Strip the cdrom base path
396
Path = string(Path,CD.length());
397
if (Path.empty() == true)
400
// Too short to be a dists/ type
401
if (Path.length() < strlen("dists/"))
405
if (stringcmp(Path.begin(),Path.begin()+strlen("dists/"),"dists/") != 0)
409
string::size_type Slash = strlen("dists/");
410
string::size_type Slash2 = Path.find('/',Slash + 1);
411
if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
413
string Dist = string(Path,Slash,Slash2 - Slash);
415
// Isolate the component
417
for (unsigned I = 0; I != 10; I++)
419
Slash = Path.find('/',Slash+1);
420
if (Slash == string::npos || Slash + 2 >= Path.length())
422
string Comp = string(Path,Slash2+1,Slash - Slash2-1);
424
// Verify the trailing binary- bit
425
string::size_type BinSlash = Path.find('/',Slash + 1);
426
if (Slash == string::npos)
428
string Binary = string(Path,Slash+1,BinSlash - Slash-1);
430
if (Binary != S && Binary != "source")
433
Path = Dist + ' ' + Comp;
438
// IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
439
// ---------------------------------------------------------------------
441
bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth)
443
string::size_type I = 0;
446
I = Path.find('/',I+1);
449
while (I != string::npos && Depth != 0);
451
if (I == string::npos)
454
To = string(Path,0,I+1);
458
// IndexCopy::CopyWithReplace - Copy a section and replace text /*{{{*/
459
// ---------------------------------------------------------------------
461
bool IndexCopy::CopyWithReplace(FileFd &Target,const char *Tag,string New)
463
// Mangle the output filename
466
const char *Filename;
467
Section->Find(Tag,Filename,Stop);
469
/* We need to rewrite the filename field so we emit
470
all fields except the filename file and rewrite that one */
471
for (unsigned int I = 0; I != Section->Count(); I++)
473
Section->Get(Start,Stop,I);
474
if (Start <= Filename && Stop > Filename)
477
sprintf(S,"%s: %s\n",Tag,New.c_str());
478
if (I + 1 == Section->Count())
480
if (Target.Write(S,strlen(S)) == false)
485
if (Target.Write(Start,Stop-Start) == false)
487
if (Stop[-1] != '\n')
488
if (Target.Write("\n",1) == false)
492
if (Target.Write("\n",1) == false)
496
// PackageCopy::GetFile - Get the file information from the section /*{{{*/
497
// ---------------------------------------------------------------------
499
bool PackageCopy::GetFile(string &File,unsigned long &Size)
501
File = Section->FindS("Filename");
502
Size = Section->FindI("Size");
503
if (File.empty() || Size == 0)
504
return _error->Error("Cannot find filename or size tag");
508
// PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
509
// ---------------------------------------------------------------------
511
bool PackageCopy::RewriteEntry(FileFd &Target,string File)
513
return CopyWithReplace(Target,"Filename",File);
516
// SourceCopy::GetFile - Get the file information from the section /*{{{*/
517
// ---------------------------------------------------------------------
519
bool SourceCopy::GetFile(string &File,unsigned long &Size)
521
string Files = Section->FindS("Files");
522
if (Files.empty() == true)
525
// Stash the / terminated directory prefix
526
string Base = Section->FindS("Directory");
527
if (Base.empty() == false && Base[Base.length()-1] != '/')
530
// Iterate over the entire list grabbing each triplet
531
const char *C = Files.c_str();
535
// Parse each of the elements
536
if (ParseQuoteWord(C,MD5Hash) == false ||
537
ParseQuoteWord(C,sSize) == false ||
538
ParseQuoteWord(C,File) == false)
539
return _error->Error("Error parsing file record");
541
// Parse the size and append the directory
542
Size = atoi(sSize.c_str());
547
// SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
548
// ---------------------------------------------------------------------
550
bool SourceCopy::RewriteEntry(FileFd &Target,string File)
552
return CopyWithReplace(Target,"Directory",
553
string(File,0,File.rfind('/')));