indexcopy.cc 15 KB

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