indexcopy.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: indexcopy.cc,v 1.7 2001/03/13 05:23:42 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. snprintf(S,sizeof(S),"cdrom:[%s]/%s%s",Name.c_str(),
  99. (*I).c_str() + CDROM.length(),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. snprintf(S,sizeof(S),"cdrom:[%s]/%sRelease",Name.c_str(),
  203. (*I).c_str() + CDROM.length());
  204. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  205. TargetF += URItoFileName(S);
  206. if (FileExists(*I + "Release") == true)
  207. {
  208. FileFd Target(TargetF,FileFd::WriteEmpty);
  209. FileFd Rel(*I + "Release",FileFd::ReadOnly);
  210. if (_error->PendingError() == true)
  211. return false;
  212. if (CopyFile(Rel,Target) == false)
  213. return false;
  214. }
  215. else
  216. {
  217. // Empty release file
  218. FileFd Target(TargetF,FileFd::WriteEmpty);
  219. }
  220. // Rename the release file
  221. FinalF = _config->FindDir("Dir::State::lists");
  222. FinalF += URItoFileName(S);
  223. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  224. return _error->Errno("rename","Failed to rename");
  225. }
  226. /* Mangle the source to be in the proper notation with
  227. prefix dist [component] */
  228. *I = string(*I,Prefix.length());
  229. ConvertToSourceList(CDROM,*I);
  230. *I = Prefix + ' ' + *I;
  231. CurrentSize += FileSize;
  232. }
  233. Progress.Done();
  234. // Some stats
  235. cout << "Wrote " << Packages << " records" ;
  236. if (NotFound != 0)
  237. cout << " with " << NotFound << " missing files";
  238. if (NotFound != 0 && WrongSize != 0)
  239. cout << " and";
  240. if (WrongSize != 0)
  241. cout << " with " << WrongSize << " mismatched files";
  242. cout << '.' << endl;
  243. if (Packages == 0)
  244. return _error->Warning("No valid records were found.");
  245. if (NotFound + WrongSize > 10)
  246. cout << "Alot of entries were discarded, something may be wrong." << endl;
  247. return true;
  248. }
  249. /*}}}*/
  250. // IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
  251. // ---------------------------------------------------------------------
  252. /* */
  253. string IndexCopy::ChopDirs(string Path,unsigned int Depth)
  254. {
  255. string::size_type I = 0;
  256. do
  257. {
  258. I = Path.find('/',I+1);
  259. Depth--;
  260. }
  261. while (I != string::npos && Depth != 0);
  262. if (I == string::npos)
  263. return string();
  264. return string(Path,I+1);
  265. }
  266. /*}}}*/
  267. // IndexCopy::ReconstructPrefix - Fix strange prefixing /*{{{*/
  268. // ---------------------------------------------------------------------
  269. /* This prepends dir components from the path to the package files to
  270. the path to the deb until it is found */
  271. bool IndexCopy::ReconstructPrefix(string &Prefix,string OrigPath,string CD,
  272. string File)
  273. {
  274. bool Debug = _config->FindB("Debug::aptcdrom",false);
  275. unsigned int Depth = 1;
  276. string MyPrefix = Prefix;
  277. while (1)
  278. {
  279. struct stat Buf;
  280. if (stat(string(CD + MyPrefix + File).c_str(),&Buf) != 0)
  281. {
  282. if (Debug == true)
  283. cout << "Failed, " << CD + MyPrefix + File << endl;
  284. if (GrabFirst(OrigPath,MyPrefix,Depth++) == true)
  285. continue;
  286. return false;
  287. }
  288. else
  289. {
  290. Prefix = MyPrefix;
  291. return true;
  292. }
  293. }
  294. return false;
  295. }
  296. /*}}}*/
  297. // IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
  298. // ---------------------------------------------------------------------
  299. /* This removes path components from the filename and prepends the location
  300. of the package files until a file is found */
  301. bool IndexCopy::ReconstructChop(unsigned long &Chop,string Dir,string File)
  302. {
  303. // Attempt to reconstruct the filename
  304. unsigned long Depth = 0;
  305. while (1)
  306. {
  307. struct stat Buf;
  308. if (stat(string(Dir + File).c_str(),&Buf) != 0)
  309. {
  310. File = ChopDirs(File,1);
  311. Depth++;
  312. if (File.empty() == false)
  313. continue;
  314. return false;
  315. }
  316. else
  317. {
  318. Chop = Depth;
  319. return true;
  320. }
  321. }
  322. return false;
  323. }
  324. /*}}}*/
  325. // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
  326. // ---------------------------------------------------------------------
  327. /* We look for things in dists/ notation and convert them to
  328. <dist> <component> form otherwise it is left alone. This also strips
  329. the CD path.
  330. This implements a regex sort of like:
  331. (.*)/dists/([^/]*)/(.*)/binary-*
  332. ^ ^ ^- Component
  333. | |-------- Distribution
  334. |------------------- Path
  335. It was deciced to use only a single word for dist (rather than say
  336. unstable/non-us) to increase the chance that each CD gets a single
  337. line in sources.list.
  338. */
  339. void IndexCopy::ConvertToSourceList(string CD,string &Path)
  340. {
  341. char S[300];
  342. snprintf(S,sizeof(S),"binary-%s",_config->Find("Apt::Architecture").c_str());
  343. // Strip the cdrom base path
  344. Path = string(Path,CD.length());
  345. if (Path.empty() == true)
  346. Path = "/";
  347. // Too short to be a dists/ type
  348. if (Path.length() < strlen("dists/"))
  349. return;
  350. // Not a dists type.
  351. if (stringcmp(Path.begin(),Path.begin()+strlen("dists/"),"dists/") != 0)
  352. return;
  353. // Isolate the dist
  354. string::size_type Slash = strlen("dists/");
  355. string::size_type Slash2 = Path.find('/',Slash + 1);
  356. if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
  357. return;
  358. string Dist = string(Path,Slash,Slash2 - Slash);
  359. // Isolate the component
  360. Slash = Slash2;
  361. for (unsigned I = 0; I != 10; I++)
  362. {
  363. Slash = Path.find('/',Slash+1);
  364. if (Slash == string::npos || Slash + 2 >= Path.length())
  365. return;
  366. string Comp = string(Path,Slash2+1,Slash - Slash2-1);
  367. // Verify the trailing binary- bit
  368. string::size_type BinSlash = Path.find('/',Slash + 1);
  369. if (Slash == string::npos)
  370. return;
  371. string Binary = string(Path,Slash+1,BinSlash - Slash-1);
  372. if (Binary != S && Binary != "source")
  373. continue;
  374. Path = Dist + ' ' + Comp;
  375. return;
  376. }
  377. }
  378. /*}}}*/
  379. // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
  380. // ---------------------------------------------------------------------
  381. /* */
  382. bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth)
  383. {
  384. string::size_type I = 0;
  385. do
  386. {
  387. I = Path.find('/',I+1);
  388. Depth--;
  389. }
  390. while (I != string::npos && Depth != 0);
  391. if (I == string::npos)
  392. return false;
  393. To = string(Path,0,I+1);
  394. return true;
  395. }
  396. /*}}}*/
  397. // PackageCopy::GetFile - Get the file information from the section /*{{{*/
  398. // ---------------------------------------------------------------------
  399. /* */
  400. bool PackageCopy::GetFile(string &File,unsigned long &Size)
  401. {
  402. File = Section->FindS("Filename");
  403. Size = Section->FindI("Size");
  404. if (File.empty() || Size == 0)
  405. return _error->Error("Cannot find filename or size tag");
  406. return true;
  407. }
  408. /*}}}*/
  409. // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  410. // ---------------------------------------------------------------------
  411. /* */
  412. bool PackageCopy::RewriteEntry(FILE *Target,string File)
  413. {
  414. TFRewriteData Changes[] = {{"Filename",File.c_str()},
  415. {}};
  416. if (TFRewrite(Target,*Section,TFRewritePackageOrder,Changes) == false)
  417. return false;
  418. fputc('\n',Target);
  419. return true;
  420. }
  421. /*}}}*/
  422. // SourceCopy::GetFile - Get the file information from the section /*{{{*/
  423. // ---------------------------------------------------------------------
  424. /* */
  425. bool SourceCopy::GetFile(string &File,unsigned long &Size)
  426. {
  427. string Files = Section->FindS("Files");
  428. if (Files.empty() == true)
  429. return false;
  430. // Stash the / terminated directory prefix
  431. string Base = Section->FindS("Directory");
  432. if (Base.empty() == false && Base[Base.length()-1] != '/')
  433. Base += '/';
  434. // Read the first file triplet
  435. const char *C = Files.c_str();
  436. string sSize;
  437. string MD5Hash;
  438. // Parse each of the elements
  439. if (ParseQuoteWord(C,MD5Hash) == false ||
  440. ParseQuoteWord(C,sSize) == false ||
  441. ParseQuoteWord(C,File) == false)
  442. return _error->Error("Error parsing file record");
  443. // Parse the size and append the directory
  444. Size = atoi(sSize.c_str());
  445. File = Base + File;
  446. return true;
  447. }
  448. /*}}}*/
  449. // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  450. // ---------------------------------------------------------------------
  451. /* */
  452. bool SourceCopy::RewriteEntry(FILE *Target,string File)
  453. {
  454. string Dir(File,0,File.rfind('/'));
  455. TFRewriteData Changes[] = {{"Directory",Dir.c_str()},
  456. {}};
  457. if (TFRewrite(Target,*Section,TFRewriteSourceOrder,Changes) == false)
  458. return false;
  459. fputc('\n',Target);
  460. return true;
  461. }
  462. /*}}}*/