indexcopy.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: indexcopy.cc,v 1.5 2000/05/10 06:02:26 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. if (_error->PendingError() == true)
  106. return false;
  107. // Setup the progress meter
  108. Progress.OverallProgress(CurrentSize,TotalSize,FileSize,
  109. string("Reading ") + Type() + " Indexes");
  110. // Parse
  111. Progress.SubProgress(Pkg.Size());
  112. pkgTagSection Section;
  113. this->Section = &Section;
  114. string Prefix;
  115. unsigned long Hits = 0;
  116. unsigned long Chop = 0;
  117. while (Parser.Step(Section) == true)
  118. {
  119. Progress.Progress(Parser.Offset());
  120. string File;
  121. unsigned long Size;
  122. if (GetFile(File,Size) == false)
  123. return false;
  124. if (Chop != 0)
  125. File = OrigPath + ChopDirs(File,Chop);
  126. // See if the file exists
  127. bool Mangled = false;
  128. if (NoStat == false || Hits < 10)
  129. {
  130. // Attempt to fix broken structure
  131. if (Hits == 0)
  132. {
  133. if (ReconstructPrefix(Prefix,OrigPath,CDROM,File) == false &&
  134. ReconstructChop(Chop,*I,File) == false)
  135. {
  136. if (Debug == true)
  137. clog << "Missed: " << File << endl;
  138. NotFound++;
  139. continue;
  140. }
  141. if (Chop != 0)
  142. File = OrigPath + ChopDirs(File,Chop);
  143. }
  144. // Get the size
  145. struct stat Buf;
  146. if (stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0 ||
  147. Buf.st_size == 0)
  148. {
  149. // Attempt to fix busted symlink support for one instance
  150. string OrigFile = File;
  151. string::size_type Start = File.find("binary-");
  152. string::size_type End = File.find("/",Start+3);
  153. if (Start != string::npos && End != string::npos)
  154. {
  155. File.replace(Start,End-Start,"binary-all");
  156. Mangled = true;
  157. }
  158. if (Mangled == false ||
  159. stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0)
  160. {
  161. if (Debug == true)
  162. clog << "Missed(2): " << OrigFile << endl;
  163. NotFound++;
  164. continue;
  165. }
  166. }
  167. // Size match
  168. if ((unsigned)Buf.st_size != Size)
  169. {
  170. if (Debug == true)
  171. clog << "Wrong Size: " << File << endl;
  172. WrongSize++;
  173. continue;
  174. }
  175. }
  176. Packages++;
  177. Hits++;
  178. // Copy it to the target package file
  179. if (Chop != 0 || Mangled == true)
  180. {
  181. if (RewriteEntry(Target,File) == false)
  182. continue;
  183. }
  184. else
  185. {
  186. const char *Start;
  187. const char *Stop;
  188. Section.GetSection(Start,Stop);
  189. if (Target.Write(Start,Stop-Start) == false)
  190. return false;
  191. }
  192. }
  193. if (Debug == true)
  194. cout << " Processed by using Prefix '" << Prefix << "' and chop " << Chop << endl;
  195. if (_config->FindB("APT::CDROM::NoAct",false) == false)
  196. {
  197. // Move out of the partial directory
  198. Target.Close();
  199. string FinalF = _config->FindDir("Dir::State::lists");
  200. FinalF += URItoFileName(S);
  201. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  202. return _error->Errno("rename","Failed to rename");
  203. // Copy the release file
  204. sprintf(S,"cdrom:[%s]/%sRelease",Name.c_str(),(*I).c_str() + CDROM.length());
  205. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  206. TargetF += URItoFileName(S);
  207. if (FileExists(*I + "Release") == true)
  208. {
  209. FileFd Target(TargetF,FileFd::WriteEmpty);
  210. FileFd Rel(*I + "Release",FileFd::ReadOnly);
  211. if (_error->PendingError() == true)
  212. return false;
  213. if (CopyFile(Rel,Target) == false)
  214. return false;
  215. }
  216. else
  217. {
  218. // Empty release file
  219. FileFd Target(TargetF,FileFd::WriteEmpty);
  220. }
  221. // Rename the release file
  222. FinalF = _config->FindDir("Dir::State::lists");
  223. FinalF += URItoFileName(S);
  224. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  225. return _error->Errno("rename","Failed to rename");
  226. }
  227. /* Mangle the source to be in the proper notation with
  228. prefix dist [component] */
  229. *I = string(*I,Prefix.length());
  230. ConvertToSourceList(CDROM,*I);
  231. *I = Prefix + ' ' + *I;
  232. CurrentSize += FileSize;
  233. }
  234. Progress.Done();
  235. // Some stats
  236. cout << "Wrote " << Packages << " records" ;
  237. if (NotFound != 0)
  238. cout << " with " << NotFound << " missing files";
  239. if (NotFound != 0 && WrongSize != 0)
  240. cout << " and";
  241. if (WrongSize != 0)
  242. cout << " with " << WrongSize << " mismatched files";
  243. cout << '.' << endl;
  244. if (Packages == 0)
  245. return _error->Warning("No valid records were found.");
  246. if (NotFound + WrongSize > 10)
  247. cout << "Alot of entries were discarded, something may be wrong." << endl;
  248. return true;
  249. }
  250. /*}}}*/
  251. // IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
  252. // ---------------------------------------------------------------------
  253. /* */
  254. string IndexCopy::ChopDirs(string Path,unsigned int Depth)
  255. {
  256. string::size_type I = 0;
  257. do
  258. {
  259. I = Path.find('/',I+1);
  260. Depth--;
  261. }
  262. while (I != string::npos && Depth != 0);
  263. if (I == string::npos)
  264. return string();
  265. return string(Path,I+1);
  266. }
  267. /*}}}*/
  268. // IndexCopy::ReconstructPrefix - Fix strange prefixing /*{{{*/
  269. // ---------------------------------------------------------------------
  270. /* This prepends dir components from the path to the package files to
  271. the path to the deb until it is found */
  272. bool IndexCopy::ReconstructPrefix(string &Prefix,string OrigPath,string CD,
  273. string File)
  274. {
  275. bool Debug = _config->FindB("Debug::aptcdrom",false);
  276. unsigned int Depth = 1;
  277. string MyPrefix = Prefix;
  278. while (1)
  279. {
  280. struct stat Buf;
  281. if (stat(string(CD + MyPrefix + File).c_str(),&Buf) != 0)
  282. {
  283. if (Debug == true)
  284. cout << "Failed, " << CD + MyPrefix + File << endl;
  285. if (GrabFirst(OrigPath,MyPrefix,Depth++) == true)
  286. continue;
  287. return false;
  288. }
  289. else
  290. {
  291. Prefix = MyPrefix;
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. /*}}}*/
  298. // IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
  299. // ---------------------------------------------------------------------
  300. /* This removes path components from the filename and prepends the location
  301. of the package files until a file is found */
  302. bool IndexCopy::ReconstructChop(unsigned long &Chop,string Dir,string File)
  303. {
  304. // Attempt to reconstruct the filename
  305. unsigned long Depth = 0;
  306. while (1)
  307. {
  308. struct stat Buf;
  309. if (stat(string(Dir + File).c_str(),&Buf) != 0)
  310. {
  311. File = ChopDirs(File,1);
  312. Depth++;
  313. if (File.empty() == false)
  314. continue;
  315. return false;
  316. }
  317. else
  318. {
  319. Chop = Depth;
  320. return true;
  321. }
  322. }
  323. return false;
  324. }
  325. /*}}}*/
  326. // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
  327. // ---------------------------------------------------------------------
  328. /* We look for things in dists/ notation and convert them to
  329. <dist> <component> form otherwise it is left alone. This also strips
  330. the CD path.
  331. This implements a regex sort of like:
  332. (.*)/dists/([^/]*)/(.*)/binary-*
  333. ^ ^ ^- Component
  334. | |-------- Distribution
  335. |------------------- Path
  336. It was deciced to use only a single word for dist (rather than say
  337. unstable/non-us) to increase the chance that each CD gets a single
  338. line in sources.list.
  339. */
  340. void IndexCopy::ConvertToSourceList(string CD,string &Path)
  341. {
  342. char S[300];
  343. sprintf(S,"binary-%s",_config->Find("Apt::Architecture").c_str());
  344. // Strip the cdrom base path
  345. Path = string(Path,CD.length());
  346. if (Path.empty() == true)
  347. Path = "/";
  348. // Too short to be a dists/ type
  349. if (Path.length() < strlen("dists/"))
  350. return;
  351. // Not a dists type.
  352. if (stringcmp(Path.begin(),Path.begin()+strlen("dists/"),"dists/") != 0)
  353. return;
  354. // Isolate the dist
  355. string::size_type Slash = strlen("dists/");
  356. string::size_type Slash2 = Path.find('/',Slash + 1);
  357. if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
  358. return;
  359. string Dist = string(Path,Slash,Slash2 - Slash);
  360. // Isolate the component
  361. Slash = Slash2;
  362. for (unsigned I = 0; I != 10; I++)
  363. {
  364. Slash = Path.find('/',Slash+1);
  365. if (Slash == string::npos || Slash + 2 >= Path.length())
  366. return;
  367. string Comp = string(Path,Slash2+1,Slash - Slash2-1);
  368. // Verify the trailing binary- bit
  369. string::size_type BinSlash = Path.find('/',Slash + 1);
  370. if (Slash == string::npos)
  371. return;
  372. string Binary = string(Path,Slash+1,BinSlash - Slash-1);
  373. if (Binary != S && Binary != "source")
  374. continue;
  375. Path = Dist + ' ' + Comp;
  376. return;
  377. }
  378. }
  379. /*}}}*/
  380. // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
  381. // ---------------------------------------------------------------------
  382. /* */
  383. bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth)
  384. {
  385. string::size_type I = 0;
  386. do
  387. {
  388. I = Path.find('/',I+1);
  389. Depth--;
  390. }
  391. while (I != string::npos && Depth != 0);
  392. if (I == string::npos)
  393. return false;
  394. To = string(Path,0,I+1);
  395. return true;
  396. }
  397. /*}}}*/
  398. // IndexCopy::CopyWithReplace - Copy a section and replace text /*{{{*/
  399. // ---------------------------------------------------------------------
  400. /* */
  401. bool IndexCopy::CopyWithReplace(FileFd &Target,const char *Tag,string New)
  402. {
  403. // Mangle the output filename
  404. const char *Start;
  405. const char *Stop;
  406. const char *Filename;
  407. Section->Find(Tag,Filename,Stop);
  408. /* We need to rewrite the filename field so we emit
  409. all fields except the filename file and rewrite that one */
  410. for (unsigned int I = 0; I != Section->Count(); I++)
  411. {
  412. Section->Get(Start,Stop,I);
  413. if (Start <= Filename && Stop > Filename)
  414. {
  415. char S[500];
  416. sprintf(S,"%s: %s\n",Tag,New.c_str());
  417. if (I + 1 == Section->Count())
  418. strcat(S,"\n");
  419. if (Target.Write(S,strlen(S)) == false)
  420. return false;
  421. }
  422. else
  423. {
  424. if (Target.Write(Start,Stop-Start) == false)
  425. return false;
  426. if (Stop[-1] != '\n')
  427. if (Target.Write("\n",1) == false)
  428. return false;
  429. }
  430. }
  431. if (Target.Write("\n",1) == false)
  432. return false;
  433. }
  434. /*}}}*/
  435. // PackageCopy::GetFile - Get the file information from the section /*{{{*/
  436. // ---------------------------------------------------------------------
  437. /* */
  438. bool PackageCopy::GetFile(string &File,unsigned long &Size)
  439. {
  440. File = Section->FindS("Filename");
  441. Size = Section->FindI("Size");
  442. if (File.empty() || Size == 0)
  443. return _error->Error("Cannot find filename or size tag");
  444. return true;
  445. }
  446. /*}}}*/
  447. // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  448. // ---------------------------------------------------------------------
  449. /* */
  450. bool PackageCopy::RewriteEntry(FileFd &Target,string File)
  451. {
  452. return CopyWithReplace(Target,"Filename",File);
  453. }
  454. /*}}}*/
  455. // SourceCopy::GetFile - Get the file information from the section /*{{{*/
  456. // ---------------------------------------------------------------------
  457. /* */
  458. bool SourceCopy::GetFile(string &File,unsigned long &Size)
  459. {
  460. string Files = Section->FindS("Files");
  461. if (Files.empty() == true)
  462. return false;
  463. // Stash the / terminated directory prefix
  464. string Base = Section->FindS("Directory");
  465. if (Base.empty() == false && Base[Base.length()-1] != '/')
  466. Base += '/';
  467. // Iterate over the entire list grabbing each triplet
  468. const char *C = Files.c_str();
  469. string sSize;
  470. string MD5Hash;
  471. // Parse each of the elements
  472. if (ParseQuoteWord(C,MD5Hash) == false ||
  473. ParseQuoteWord(C,sSize) == false ||
  474. ParseQuoteWord(C,File) == false)
  475. return _error->Error("Error parsing file record");
  476. // Parse the size and append the directory
  477. Size = atoi(sSize.c_str());
  478. File = Base + File;
  479. return true;
  480. }
  481. /*}}}*/
  482. // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  483. // ---------------------------------------------------------------------
  484. /* */
  485. bool SourceCopy::RewriteEntry(FileFd &Target,string File)
  486. {
  487. return CopyWithReplace(Target,"Directory",
  488. string(File,0,File.rfind('/')));
  489. }
  490. /*}}}*/