indexcopy.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: indexcopy.cc,v 1.4 2000/01/16 05:36: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. 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. void IndexCopy::ConvertToSourceList(string CD,string &Path)
  332. {
  333. char S[300];
  334. sprintf(S,"binary-%s",_config->Find("Apt::Architecture").c_str());
  335. // Strip the cdrom base path
  336. Path = string(Path,CD.length());
  337. if (Path.empty() == true)
  338. Path = "/";
  339. // Too short to be a dists/ type
  340. if (Path.length() < strlen("dists/"))
  341. return;
  342. // Not a dists type.
  343. if (stringcmp(Path.begin(),Path.begin()+strlen("dists/"),"dists/") != 0)
  344. return;
  345. // Isolate the dist
  346. string::size_type Slash = strlen("dists/");
  347. string::size_type Slash2 = Path.find('/',Slash + 1);
  348. if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
  349. return;
  350. string Dist = string(Path,Slash,Slash2 - Slash);
  351. // Isolate the component
  352. Slash = Path.find('/',Slash2+1);
  353. if (Slash == string::npos || Slash + 2 >= Path.length())
  354. return;
  355. string Comp = string(Path,Slash2+1,Slash - Slash2-1);
  356. // Verify the trailing binar - bit
  357. Slash2 = Path.find('/',Slash + 1);
  358. if (Slash == string::npos)
  359. return;
  360. string Binary = string(Path,Slash+1,Slash2 - Slash-1);
  361. if (Binary != S && Binary != "source")
  362. return;
  363. Path = Dist + ' ' + Comp;
  364. }
  365. /*}}}*/
  366. // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
  367. // ---------------------------------------------------------------------
  368. /* */
  369. bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth)
  370. {
  371. string::size_type I = 0;
  372. do
  373. {
  374. I = Path.find('/',I+1);
  375. Depth--;
  376. }
  377. while (I != string::npos && Depth != 0);
  378. if (I == string::npos)
  379. return false;
  380. To = string(Path,0,I+1);
  381. return true;
  382. }
  383. /*}}}*/
  384. // IndexCopy::CopyWithReplace - Copy a section and replace text /*{{{*/
  385. // ---------------------------------------------------------------------
  386. /* */
  387. bool IndexCopy::CopyWithReplace(FileFd &Target,const char *Tag,string New)
  388. {
  389. // Mangle the output filename
  390. const char *Start;
  391. const char *Stop;
  392. const char *Filename;
  393. Section->Find(Tag,Filename,Stop);
  394. /* We need to rewrite the filename field so we emit
  395. all fields except the filename file and rewrite that one */
  396. for (unsigned int I = 0; I != Section->Count(); I++)
  397. {
  398. Section->Get(Start,Stop,I);
  399. if (Start <= Filename && Stop > Filename)
  400. {
  401. char S[500];
  402. sprintf(S,"%s: %s\n",Tag,New.c_str());
  403. if (I + 1 == Section->Count())
  404. strcat(S,"\n");
  405. if (Target.Write(S,strlen(S)) == false)
  406. return false;
  407. }
  408. else
  409. {
  410. if (Target.Write(Start,Stop-Start) == false)
  411. return false;
  412. if (Stop[-1] != '\n')
  413. if (Target.Write("\n",1) == false)
  414. return false;
  415. }
  416. }
  417. if (Target.Write("\n",1) == false)
  418. return false;
  419. }
  420. /*}}}*/
  421. // PackageCopy::GetFile - Get the file information from the section /*{{{*/
  422. // ---------------------------------------------------------------------
  423. /* */
  424. bool PackageCopy::GetFile(string &File,unsigned long &Size)
  425. {
  426. File = Section->FindS("Filename");
  427. Size = Section->FindI("Size");
  428. if (File.empty() || Size == 0)
  429. return _error->Error("Cannot find filename or size tag");
  430. return true;
  431. }
  432. /*}}}*/
  433. // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  434. // ---------------------------------------------------------------------
  435. /* */
  436. bool PackageCopy::RewriteEntry(FileFd &Target,string File)
  437. {
  438. return CopyWithReplace(Target,"Filename",File);
  439. }
  440. /*}}}*/
  441. // SourceCopy::GetFile - Get the file information from the section /*{{{*/
  442. // ---------------------------------------------------------------------
  443. /* */
  444. bool SourceCopy::GetFile(string &File,unsigned long &Size)
  445. {
  446. string Files = Section->FindS("Files");
  447. if (Files.empty() == true)
  448. return false;
  449. // Stash the / terminated directory prefix
  450. string Base = Section->FindS("Directory");
  451. if (Base.empty() == false && Base[Base.length()-1] != '/')
  452. Base += '/';
  453. // Iterate over the entire list grabbing each triplet
  454. const char *C = Files.c_str();
  455. string sSize;
  456. string MD5Hash;
  457. // Parse each of the elements
  458. if (ParseQuoteWord(C,MD5Hash) == false ||
  459. ParseQuoteWord(C,sSize) == false ||
  460. ParseQuoteWord(C,File) == false)
  461. return _error->Error("Error parsing file record");
  462. // Parse the size and append the directory
  463. Size = atoi(sSize.c_str());
  464. File = Base + File;
  465. return true;
  466. }
  467. /*}}}*/
  468. // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  469. // ---------------------------------------------------------------------
  470. /* */
  471. bool SourceCopy::RewriteEntry(FileFd &Target,string File)
  472. {
  473. return CopyWithReplace(Target,"Directory",
  474. string(File,0,File.rfind('/')));
  475. }
  476. /*}}}*/