indexcopy.cc 15 KB

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