indexcopy.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: indexcopy.cc,v 1.6 2001/02/20 07:03:17 jgg Exp $
  4. /* ######################################################################
  5. Index Copying - Aid for copying and verifying the index files
  6. This class helps apt-cache reconstruct a damaged index files.
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include "indexcopy.h"
  11. #include <apt-pkg/error.h>
  12. #include <apt-pkg/progress.h>
  13. #include <apt-pkg/strutl.h>
  14. #include <apt-pkg/fileutl.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/tagfile.h>
  17. #include <iostream.h>
  18. #include <unistd.h>
  19. #include <sys/stat.h>
  20. #include <stdio.h>
  21. /*}}}*/
  22. // IndexCopy::CopyPackages - Copy the package files from the CD /*{{{*/
  23. // ---------------------------------------------------------------------
  24. /* */
  25. bool IndexCopy::CopyPackages(string CDROM,string Name,vector<string> &List)
  26. {
  27. if (List.size() == 0)
  28. return true;
  29. OpTextProgress Progress;
  30. bool NoStat = _config->FindB("APT::CDROM::Fast",false);
  31. bool Debug = _config->FindB("Debug::aptcdrom",false);
  32. // Prepare the progress indicator
  33. unsigned long TotalSize = 0;
  34. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  35. {
  36. struct stat Buf;
  37. if (stat(string(*I + GetFileName()).c_str(),&Buf) != 0 &&
  38. stat(string(*I + GetFileName() + ".gz").c_str(),&Buf) != 0)
  39. return _error->Errno("stat","Stat failed for %s",
  40. string(*I + GetFileName()).c_str());
  41. TotalSize += Buf.st_size;
  42. }
  43. unsigned long CurrentSize = 0;
  44. unsigned int NotFound = 0;
  45. unsigned int WrongSize = 0;
  46. unsigned int Packages = 0;
  47. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  48. {
  49. string OrigPath = string(*I,CDROM.length());
  50. unsigned long FileSize = 0;
  51. // Open the package file
  52. FileFd Pkg;
  53. if (FileExists(*I + GetFileName()) == true)
  54. {
  55. Pkg.Open(*I + GetFileName(),FileFd::ReadOnly);
  56. FileSize = Pkg.Size();
  57. }
  58. else
  59. {
  60. FileFd From(*I + GetFileName() + ".gz",FileFd::ReadOnly);
  61. if (_error->PendingError() == true)
  62. return false;
  63. FileSize = From.Size();
  64. // Get a temp file
  65. FILE *tmp = tmpfile();
  66. if (tmp == 0)
  67. return _error->Errno("tmpfile","Unable to create a tmp file");
  68. Pkg.Fd(dup(fileno(tmp)));
  69. fclose(tmp);
  70. // Fork gzip
  71. int Process = fork();
  72. if (Process < 0)
  73. return _error->Errno("fork","Couldn't fork gzip");
  74. // The child
  75. if (Process == 0)
  76. {
  77. dup2(From.Fd(),STDIN_FILENO);
  78. dup2(Pkg.Fd(),STDOUT_FILENO);
  79. SetCloseExec(STDIN_FILENO,false);
  80. SetCloseExec(STDOUT_FILENO,false);
  81. const char *Args[3];
  82. Args[0] = _config->Find("Dir::bin::gzip","gzip").c_str();
  83. Args[1] = "-d";
  84. Args[2] = 0;
  85. execvp(Args[0],(char **)Args);
  86. exit(100);
  87. }
  88. // Wait for gzip to finish
  89. if (ExecWait(Process,_config->Find("Dir::bin::gzip","gzip").c_str(),false) == false)
  90. return _error->Error("gzip failed, perhaps the disk is full.");
  91. Pkg.Seek(0);
  92. }
  93. pkgTagFile Parser(&Pkg);
  94. if (_error->PendingError() == true)
  95. return false;
  96. // Open the output file
  97. char S[400];
  98. sprintf(S,"cdrom:[%s]/%s%s",Name.c_str(),(*I).c_str() + CDROM.length(),
  99. GetFileName());
  100. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  101. TargetF += URItoFileName(S);
  102. if (_config->FindB("APT::CDROM::NoAct",false) == true)
  103. TargetF = "/dev/null";
  104. FileFd Target(TargetF,FileFd::WriteEmpty);
  105. FILE *TargetFl = fdopen(dup(Target.Fd()),"w");
  106. if (_error->PendingError() == true)
  107. return false;
  108. if (TargetFl == 0)
  109. return _error->Errno("fdopen","Failed to reopen fd");
  110. // Setup the progress meter
  111. Progress.OverallProgress(CurrentSize,TotalSize,FileSize,
  112. string("Reading ") + Type() + " Indexes");
  113. // Parse
  114. Progress.SubProgress(Pkg.Size());
  115. pkgTagSection Section;
  116. this->Section = &Section;
  117. string Prefix;
  118. unsigned long Hits = 0;
  119. unsigned long Chop = 0;
  120. while (Parser.Step(Section) == true)
  121. {
  122. Progress.Progress(Parser.Offset());
  123. string File;
  124. unsigned long Size;
  125. if (GetFile(File,Size) == false)
  126. {
  127. fclose(TargetFl);
  128. return false;
  129. }
  130. if (Chop != 0)
  131. File = OrigPath + ChopDirs(File,Chop);
  132. // See if the file exists
  133. bool Mangled = false;
  134. if (NoStat == false || Hits < 10)
  135. {
  136. // Attempt to fix broken structure
  137. if (Hits == 0)
  138. {
  139. if (ReconstructPrefix(Prefix,OrigPath,CDROM,File) == false &&
  140. ReconstructChop(Chop,*I,File) == false)
  141. {
  142. if (Debug == true)
  143. clog << "Missed: " << File << endl;
  144. NotFound++;
  145. continue;
  146. }
  147. if (Chop != 0)
  148. File = OrigPath + ChopDirs(File,Chop);
  149. }
  150. // Get the size
  151. struct stat Buf;
  152. if (stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0 ||
  153. Buf.st_size == 0)
  154. {
  155. // Attempt to fix busted symlink support for one instance
  156. string OrigFile = File;
  157. string::size_type Start = File.find("binary-");
  158. string::size_type End = File.find("/",Start+3);
  159. if (Start != string::npos && End != string::npos)
  160. {
  161. File.replace(Start,End-Start,"binary-all");
  162. Mangled = true;
  163. }
  164. if (Mangled == false ||
  165. stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0)
  166. {
  167. if (Debug == true)
  168. clog << "Missed(2): " << OrigFile << endl;
  169. NotFound++;
  170. continue;
  171. }
  172. }
  173. // Size match
  174. if ((unsigned)Buf.st_size != Size)
  175. {
  176. if (Debug == true)
  177. clog << "Wrong Size: " << File << endl;
  178. WrongSize++;
  179. continue;
  180. }
  181. }
  182. Packages++;
  183. Hits++;
  184. if (RewriteEntry(TargetFl,File) == false)
  185. {
  186. fclose(TargetFl);
  187. return false;
  188. }
  189. }
  190. fclose(TargetFl);
  191. if (Debug == true)
  192. cout << " Processed by using Prefix '" << Prefix << "' and chop " << Chop << endl;
  193. if (_config->FindB("APT::CDROM::NoAct",false) == false)
  194. {
  195. // Move out of the partial directory
  196. Target.Close();
  197. string FinalF = _config->FindDir("Dir::State::lists");
  198. FinalF += URItoFileName(S);
  199. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  200. return _error->Errno("rename","Failed to rename");
  201. // Copy the release file
  202. sprintf(S,"cdrom:[%s]/%sRelease",Name.c_str(),(*I).c_str() + CDROM.length());
  203. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  204. TargetF += URItoFileName(S);
  205. if (FileExists(*I + "Release") == true)
  206. {
  207. FileFd Target(TargetF,FileFd::WriteEmpty);
  208. FileFd Rel(*I + "Release",FileFd::ReadOnly);
  209. if (_error->PendingError() == true)
  210. return false;
  211. if (CopyFile(Rel,Target) == false)
  212. return false;
  213. }
  214. else
  215. {
  216. // Empty release file
  217. FileFd Target(TargetF,FileFd::WriteEmpty);
  218. }
  219. // Rename the release file
  220. FinalF = _config->FindDir("Dir::State::lists");
  221. FinalF += URItoFileName(S);
  222. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  223. return _error->Errno("rename","Failed to rename");
  224. }
  225. /* Mangle the source to be in the proper notation with
  226. prefix dist [component] */
  227. *I = string(*I,Prefix.length());
  228. ConvertToSourceList(CDROM,*I);
  229. *I = Prefix + ' ' + *I;
  230. CurrentSize += FileSize;
  231. }
  232. Progress.Done();
  233. // Some stats
  234. cout << "Wrote " << Packages << " records" ;
  235. if (NotFound != 0)
  236. cout << " with " << NotFound << " missing files";
  237. if (NotFound != 0 && WrongSize != 0)
  238. cout << " and";
  239. if (WrongSize != 0)
  240. cout << " with " << WrongSize << " mismatched files";
  241. cout << '.' << endl;
  242. if (Packages == 0)
  243. return _error->Warning("No valid records were found.");
  244. if (NotFound + WrongSize > 10)
  245. cout << "Alot of entries were discarded, something may be wrong." << endl;
  246. return true;
  247. }
  248. /*}}}*/
  249. // IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
  250. // ---------------------------------------------------------------------
  251. /* */
  252. string IndexCopy::ChopDirs(string Path,unsigned int Depth)
  253. {
  254. string::size_type I = 0;
  255. do
  256. {
  257. I = Path.find('/',I+1);
  258. Depth--;
  259. }
  260. while (I != string::npos && Depth != 0);
  261. if (I == string::npos)
  262. return string();
  263. return string(Path,I+1);
  264. }
  265. /*}}}*/
  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,
  271. string File)
  272. {
  273. bool Debug = _config->FindB("Debug::aptcdrom",false);
  274. unsigned int Depth = 1;
  275. string MyPrefix = Prefix;
  276. while (1)
  277. {
  278. struct stat Buf;
  279. if (stat(string(CD + MyPrefix + File).c_str(),&Buf) != 0)
  280. {
  281. if (Debug == true)
  282. cout << "Failed, " << CD + MyPrefix + File << endl;
  283. if (GrabFirst(OrigPath,MyPrefix,Depth++) == true)
  284. continue;
  285. return false;
  286. }
  287. else
  288. {
  289. Prefix = MyPrefix;
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. /*}}}*/
  296. // IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
  297. // ---------------------------------------------------------------------
  298. /* This removes path components from the filename and prepends the location
  299. of the package files until a file is found */
  300. bool IndexCopy::ReconstructChop(unsigned long &Chop,string Dir,string File)
  301. {
  302. // Attempt to reconstruct the filename
  303. unsigned long Depth = 0;
  304. while (1)
  305. {
  306. struct stat Buf;
  307. if (stat(string(Dir + File).c_str(),&Buf) != 0)
  308. {
  309. File = ChopDirs(File,1);
  310. Depth++;
  311. if (File.empty() == false)
  312. continue;
  313. return false;
  314. }
  315. else
  316. {
  317. Chop = Depth;
  318. return true;
  319. }
  320. }
  321. return false;
  322. }
  323. /*}}}*/
  324. // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
  325. // ---------------------------------------------------------------------
  326. /* We look for things in dists/ notation and convert them to
  327. <dist> <component> form otherwise it is left alone. This also strips
  328. the CD path.
  329. This implements a regex sort of like:
  330. (.*)/dists/([^/]*)/(.*)/binary-*
  331. ^ ^ ^- Component
  332. | |-------- Distribution
  333. |------------------- Path
  334. It was deciced to use only a single word for dist (rather than say
  335. unstable/non-us) to increase the chance that each CD gets a single
  336. line in sources.list.
  337. */
  338. void IndexCopy::ConvertToSourceList(string CD,string &Path)
  339. {
  340. char S[300];
  341. sprintf(S,"binary-%s",_config->Find("Apt::Architecture").c_str());
  342. // Strip the cdrom base path
  343. Path = string(Path,CD.length());
  344. if (Path.empty() == true)
  345. Path = "/";
  346. // Too short to be a dists/ type
  347. if (Path.length() < strlen("dists/"))
  348. return;
  349. // Not a dists type.
  350. if (stringcmp(Path.begin(),Path.begin()+strlen("dists/"),"dists/") != 0)
  351. return;
  352. // Isolate the dist
  353. string::size_type Slash = strlen("dists/");
  354. string::size_type Slash2 = Path.find('/',Slash + 1);
  355. if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
  356. return;
  357. string Dist = string(Path,Slash,Slash2 - Slash);
  358. // Isolate the component
  359. Slash = Slash2;
  360. for (unsigned I = 0; I != 10; I++)
  361. {
  362. Slash = Path.find('/',Slash+1);
  363. if (Slash == string::npos || Slash + 2 >= Path.length())
  364. return;
  365. string Comp = string(Path,Slash2+1,Slash - Slash2-1);
  366. // Verify the trailing binary- bit
  367. string::size_type BinSlash = Path.find('/',Slash + 1);
  368. if (Slash == string::npos)
  369. return;
  370. string Binary = string(Path,Slash+1,BinSlash - Slash-1);
  371. if (Binary != S && Binary != "source")
  372. continue;
  373. Path = Dist + ' ' + Comp;
  374. return;
  375. }
  376. }
  377. /*}}}*/
  378. // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
  379. // ---------------------------------------------------------------------
  380. /* */
  381. bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth)
  382. {
  383. string::size_type I = 0;
  384. do
  385. {
  386. I = Path.find('/',I+1);
  387. Depth--;
  388. }
  389. while (I != string::npos && Depth != 0);
  390. if (I == string::npos)
  391. return false;
  392. To = string(Path,0,I+1);
  393. return true;
  394. }
  395. /*}}}*/
  396. // PackageCopy::GetFile - Get the file information from the section /*{{{*/
  397. // ---------------------------------------------------------------------
  398. /* */
  399. bool PackageCopy::GetFile(string &File,unsigned long &Size)
  400. {
  401. File = Section->FindS("Filename");
  402. Size = Section->FindI("Size");
  403. if (File.empty() || Size == 0)
  404. return _error->Error("Cannot find filename or size tag");
  405. return true;
  406. }
  407. /*}}}*/
  408. // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  409. // ---------------------------------------------------------------------
  410. /* */
  411. bool PackageCopy::RewriteEntry(FILE *Target,string File)
  412. {
  413. TFRewriteData Changes[] = {{"Filename",File.c_str()},
  414. {}};
  415. if (TFRewrite(Target,*Section,TFRewritePackageOrder,Changes) == false)
  416. return false;
  417. fputc('\n',Target);
  418. return true;
  419. }
  420. /*}}}*/
  421. // SourceCopy::GetFile - Get the file information from the section /*{{{*/
  422. // ---------------------------------------------------------------------
  423. /* */
  424. bool SourceCopy::GetFile(string &File,unsigned long &Size)
  425. {
  426. string Files = Section->FindS("Files");
  427. if (Files.empty() == true)
  428. return false;
  429. // Stash the / terminated directory prefix
  430. string Base = Section->FindS("Directory");
  431. if (Base.empty() == false && Base[Base.length()-1] != '/')
  432. Base += '/';
  433. // Read the first file triplet
  434. const char *C = Files.c_str();
  435. string sSize;
  436. string MD5Hash;
  437. // Parse each of the elements
  438. if (ParseQuoteWord(C,MD5Hash) == false ||
  439. ParseQuoteWord(C,sSize) == false ||
  440. ParseQuoteWord(C,File) == false)
  441. return _error->Error("Error parsing file record");
  442. // Parse the size and append the directory
  443. Size = atoi(sSize.c_str());
  444. File = Base + File;
  445. return true;
  446. }
  447. /*}}}*/
  448. // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  449. // ---------------------------------------------------------------------
  450. /* */
  451. bool SourceCopy::RewriteEntry(FILE *Target,string File)
  452. {
  453. string Dir(File,0,File.rfind('/'));
  454. TFRewriteData Changes[] = {{"Directory",Dir.c_str()},
  455. {}};
  456. if (TFRewrite(Target,*Section,TFRewriteSourceOrder,Changes) == false)
  457. return false;
  458. fputc('\n',Target);
  459. return true;
  460. }
  461. /*}}}*/