apt-cdrom.cc 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: apt-cdrom.cc,v 1.26 1999/07/03 03:10:35 jgg Exp $
  4. /* ######################################################################
  5. APT CDROM - Tool for handling APT's CDROM database.
  6. Currently the only option is 'add' which will take the current CD
  7. in the drive and add it into the database.
  8. ##################################################################### */
  9. /*}}}*/
  10. // Include Files /*{{{*/
  11. #include <apt-pkg/cmndline.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/init.h>
  14. #include <apt-pkg/fileutl.h>
  15. #include <apt-pkg/progress.h>
  16. #include <apt-pkg/tagfile.h>
  17. #include <apt-pkg/cdromutl.h>
  18. #include <apt-pkg/strutl.h>
  19. #include <config.h>
  20. #include <iostream>
  21. #include <fstream>
  22. #include <vector>
  23. #include <algorithm>
  24. #include <sys/stat.h>
  25. #include <fcntl.h>
  26. #include <dirent.h>
  27. #include <unistd.h>
  28. #include <stdio.h>
  29. /*}}}*/
  30. // FindPackages - Find the package files on the CDROM /*{{{*/
  31. // ---------------------------------------------------------------------
  32. /* We look over the cdrom for package files. This is a recursive
  33. search that short circuits when it his a package file in the dir.
  34. This speeds it up greatly as the majority of the size is in the
  35. binary-* sub dirs. */
  36. bool FindPackages(string CD,vector<string> &List,string &InfoDir,
  37. unsigned int Depth = 0)
  38. {
  39. static ino_t Inodes[9];
  40. if (Depth >= 7)
  41. return true;
  42. if (CD[CD.length()-1] != '/')
  43. CD += '/';
  44. if (chdir(CD.c_str()) != 0)
  45. return _error->Errno("chdir","Unable to change to %s",CD.c_str());
  46. // Look for a .disk subdirectory
  47. struct stat Buf;
  48. if (stat(".disk",&Buf) == 0)
  49. {
  50. if (InfoDir.empty() == true)
  51. InfoDir = CD + ".disk/";
  52. }
  53. /* Aha! We found some package files. We assume that everything under
  54. this dir is controlled by those package files so we don't look down
  55. anymore */
  56. if (stat("Packages",&Buf) == 0)
  57. {
  58. List.push_back(CD);
  59. // Continue down if thorough is given
  60. if (_config->FindB("APT::CDROM::Thorough",false) == false)
  61. return true;
  62. }
  63. DIR *D = opendir(".");
  64. if (D == 0)
  65. return _error->Errno("opendir","Unable to read %s",CD.c_str());
  66. // Run over the directory
  67. for (struct dirent *Dir = readdir(D); Dir != 0; Dir = readdir(D))
  68. {
  69. // Skip some files..
  70. if (strcmp(Dir->d_name,".") == 0 ||
  71. strcmp(Dir->d_name,"..") == 0 ||
  72. strcmp(Dir->d_name,"source") == 0 ||
  73. strcmp(Dir->d_name,"experimental") == 0 ||
  74. strcmp(Dir->d_name,"binary-all") == 0)
  75. continue;
  76. // See if the name is a sub directory
  77. struct stat Buf;
  78. if (stat(Dir->d_name,&Buf) != 0)
  79. continue;
  80. if (S_ISDIR(Buf.st_mode) == 0)
  81. continue;
  82. unsigned int I;
  83. for (I = 0; I != Depth; I++)
  84. if (Inodes[I] == Buf.st_ino)
  85. break;
  86. if (I != Depth)
  87. continue;
  88. // Store the inodes weve seen
  89. Inodes[Depth] = Buf.st_ino;
  90. // Descend
  91. if (FindPackages(CD + Dir->d_name,List,InfoDir,Depth+1) == false)
  92. break;
  93. if (chdir(CD.c_str()) != 0)
  94. return _error->Errno("chdir","Unable to change to ",CD.c_str());
  95. };
  96. closedir(D);
  97. return !_error->PendingError();
  98. }
  99. /*}}}*/
  100. // DropBinaryArch - Dump dirs with a string like /binary-<foo>/ /*{{{*/
  101. // ---------------------------------------------------------------------
  102. /* Here we drop everything that is not this machines arch */
  103. bool DropBinaryArch(vector<string> &List)
  104. {
  105. char S[300];
  106. sprintf(S,"/binary-%s/",_config->Find("Apt::Architecture").c_str());
  107. for (unsigned int I = 0; I < List.size(); I++)
  108. {
  109. const char *Str = List[I].c_str();
  110. const char *Res;
  111. if ((Res = strstr(Str,"/binary-")) == 0)
  112. continue;
  113. // Weird, remove it.
  114. if (strlen(Res) < strlen(S))
  115. {
  116. List.erase(List.begin() + I);
  117. I--;
  118. continue;
  119. }
  120. // See if it is our arch
  121. if (stringcmp(Res,Res + strlen(S),S) == 0)
  122. continue;
  123. // Erase it
  124. List.erase(List.begin() + I);
  125. I--;
  126. }
  127. return true;
  128. }
  129. /*}}}*/
  130. // Score - We compute a 'score' for a path /*{{{*/
  131. // ---------------------------------------------------------------------
  132. /* Paths are scored based on how close they come to what I consider
  133. normal. That is ones that have 'dist' 'stable' 'frozen' will score
  134. higher than ones without. */
  135. int Score(string Path)
  136. {
  137. int Res = 0;
  138. if (Path.find("stable/") != string::npos)
  139. Res += 2;
  140. if (Path.find("/binary-") != string::npos)
  141. Res += 2;
  142. if (Path.find("frozen/") != string::npos)
  143. Res += 2;
  144. if (Path.find("/dists/") != string::npos)
  145. Res += 4;
  146. if (Path.find("/main/") != string::npos)
  147. Res += 2;
  148. if (Path.find("/contrib/") != string::npos)
  149. Res += 2;
  150. if (Path.find("/non-free/") != string::npos)
  151. Res += 2;
  152. if (Path.find("/non-US/") != string::npos)
  153. Res += 2;
  154. return Res;
  155. }
  156. /*}}}*/
  157. // DropRepeats - Drop repeated files resulting from symlinks /*{{{*/
  158. // ---------------------------------------------------------------------
  159. /* Here we go and stat every file that we found and strip dup inodes. */
  160. bool DropRepeats(vector<string> &List)
  161. {
  162. // Get a list of all the inodes
  163. ino_t *Inodes = new ino_t[List.size()];
  164. for (unsigned int I = 0; I != List.size(); I++)
  165. {
  166. struct stat Buf;
  167. if (stat((List[I] + "Packages").c_str(),&Buf) != 0)
  168. _error->Errno("stat","Failed to stat %sPackages",List[I].c_str());
  169. Inodes[I] = Buf.st_ino;
  170. }
  171. if (_error->PendingError() == true)
  172. return false;
  173. // Look for dups
  174. for (unsigned int I = 0; I != List.size(); I++)
  175. {
  176. for (unsigned int J = I+1; J < List.size(); J++)
  177. {
  178. // No match
  179. if (Inodes[J] != Inodes[I])
  180. continue;
  181. // We score the two paths.. and erase one
  182. int ScoreA = Score(List[I]);
  183. int ScoreB = Score(List[J]);
  184. if (ScoreA < ScoreB)
  185. {
  186. List[I] = string();
  187. break;
  188. }
  189. List[J] = string();
  190. }
  191. }
  192. // Wipe erased entries
  193. for (unsigned int I = 0; I < List.size();)
  194. {
  195. if (List[I].empty() == false)
  196. I++;
  197. else
  198. List.erase(List.begin()+I);
  199. }
  200. return true;
  201. }
  202. /*}}}*/
  203. // ConvertToSourceList - Convert a Path to a sourcelist entry /*{{{*/
  204. // ---------------------------------------------------------------------
  205. /* We look for things in dists/ notation and convert them to
  206. <dist> <component> form otherwise it is left alone. This also strips
  207. the CD path. */
  208. void ConvertToSourceList(string CD,string &Path)
  209. {
  210. char S[300];
  211. sprintf(S,"binary-%s",_config->Find("Apt::Architecture").c_str());
  212. // Strip the cdrom base path
  213. Path = string(Path,CD.length());
  214. if (Path.empty() == true)
  215. Path = "/";
  216. // Too short to be a dists/ type
  217. if (Path.length() < strlen("dists/"))
  218. return;
  219. // Not a dists type.
  220. if (stringcmp(Path.begin(),Path.begin()+strlen("dists/"),"dists/") != 0)
  221. return;
  222. // Isolate the dist
  223. string::size_type Slash = strlen("dists/");
  224. string::size_type Slash2 = Path.find('/',Slash + 1);
  225. if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
  226. return;
  227. string Dist = string(Path,Slash,Slash2 - Slash);
  228. // Isolate the component
  229. Slash = Path.find('/',Slash2+1);
  230. if (Slash == string::npos || Slash + 2 >= Path.length())
  231. return;
  232. string Comp = string(Path,Slash2+1,Slash - Slash2-1);
  233. // Verify the trailing binar - bit
  234. Slash2 = Path.find('/',Slash + 1);
  235. if (Slash == string::npos)
  236. return;
  237. string Binary = string(Path,Slash+1,Slash2 - Slash-1);
  238. if (Binary != S)
  239. return;
  240. Path = Dist + ' ' + Comp;
  241. }
  242. /*}}}*/
  243. // GrabFirst - Return the first Depth path components /*{{{*/
  244. // ---------------------------------------------------------------------
  245. /* */
  246. bool GrabFirst(string Path,string &To,unsigned int Depth)
  247. {
  248. string::size_type I = 0;
  249. do
  250. {
  251. I = Path.find('/',I+1);
  252. Depth--;
  253. }
  254. while (I != string::npos && Depth != 0);
  255. if (I == string::npos)
  256. return false;
  257. To = string(Path,0,I+1);
  258. return true;
  259. }
  260. /*}}}*/
  261. // ChopDirs - Chop off the leading directory components /*{{{*/
  262. // ---------------------------------------------------------------------
  263. /* */
  264. string ChopDirs(string Path,unsigned int Depth)
  265. {
  266. string::size_type I = 0;
  267. do
  268. {
  269. I = Path.find('/',I+1);
  270. Depth--;
  271. }
  272. while (I != string::npos && Depth != 0);
  273. if (I == string::npos)
  274. return string();
  275. return string(Path,I+1);
  276. }
  277. /*}}}*/
  278. // ReconstructPrefix - Fix strange prefixing /*{{{*/
  279. // ---------------------------------------------------------------------
  280. /* This prepends dir components from the path to the package files to
  281. the path to the deb until it is found */
  282. bool ReconstructPrefix(string &Prefix,string OrigPath,string CD,
  283. string File)
  284. {
  285. bool Debug = _config->FindB("Debug::aptcdrom",false);
  286. unsigned int Depth = 1;
  287. string MyPrefix = Prefix;
  288. while (1)
  289. {
  290. struct stat Buf;
  291. if (stat(string(CD + MyPrefix + File).c_str(),&Buf) != 0)
  292. {
  293. if (Debug == true)
  294. cout << "Failed, " << CD + MyPrefix + File << endl;
  295. if (GrabFirst(OrigPath,MyPrefix,Depth++) == true)
  296. continue;
  297. return false;
  298. }
  299. else
  300. {
  301. Prefix = MyPrefix;
  302. return true;
  303. }
  304. }
  305. return false;
  306. }
  307. /*}}}*/
  308. // ReconstructChop - Fixes bad source paths /*{{{*/
  309. // ---------------------------------------------------------------------
  310. /* This removes path components from the filename and prepends the location
  311. of the package files until a file is found */
  312. bool ReconstructChop(unsigned long &Chop,string Dir,string File)
  313. {
  314. // Attempt to reconstruct the filename
  315. unsigned long Depth = 0;
  316. while (1)
  317. {
  318. struct stat Buf;
  319. if (stat(string(Dir + File).c_str(),&Buf) != 0)
  320. {
  321. File = ChopDirs(File,1);
  322. Depth++;
  323. if (File.empty() == false)
  324. continue;
  325. return false;
  326. }
  327. else
  328. {
  329. Chop = Depth;
  330. return true;
  331. }
  332. }
  333. return false;
  334. }
  335. /*}}}*/
  336. // CopyPackages - Copy the package files from the CD /*{{{*/
  337. // ---------------------------------------------------------------------
  338. /* */
  339. bool CopyPackages(string CDROM,string Name,vector<string> &List)
  340. {
  341. OpTextProgress Progress;
  342. bool NoStat = _config->FindB("APT::CDROM::Fast",false);
  343. bool Debug = _config->FindB("Debug::aptcdrom",false);
  344. // Prepare the progress indicator
  345. unsigned long TotalSize = 0;
  346. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  347. {
  348. struct stat Buf;
  349. if (stat(string(*I + "Packages").c_str(),&Buf) != 0)
  350. return _error->Errno("stat","Stat failed for %s",
  351. string(*I + "Packages").c_str());
  352. TotalSize += Buf.st_size;
  353. }
  354. unsigned long CurrentSize = 0;
  355. unsigned int NotFound = 0;
  356. unsigned int WrongSize = 0;
  357. unsigned int Packages = 0;
  358. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  359. {
  360. string OrigPath = string(*I,CDROM.length());
  361. // Open the package file
  362. FileFd Pkg(*I + "Packages",FileFd::ReadOnly);
  363. pkgTagFile Parser(Pkg);
  364. if (_error->PendingError() == true)
  365. return false;
  366. // Open the output file
  367. char S[400];
  368. sprintf(S,"cdrom:%s/%sPackages",Name.c_str(),(*I).c_str() + CDROM.length());
  369. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  370. TargetF += URItoFileName(S);
  371. if (_config->FindB("APT::CDROM::NoAct",false) == true)
  372. TargetF = "/dev/null";
  373. FileFd Target(TargetF,FileFd::WriteEmpty);
  374. if (_error->PendingError() == true)
  375. return false;
  376. // Setup the progress meter
  377. Progress.OverallProgress(CurrentSize,TotalSize,Pkg.Size(),
  378. "Reading Package Lists");
  379. // Parse
  380. Progress.SubProgress(Pkg.Size());
  381. pkgTagSection Section;
  382. string Prefix;
  383. unsigned long Hits = 0;
  384. unsigned long Chop = 0;
  385. while (Parser.Step(Section) == true)
  386. {
  387. Progress.Progress(Parser.Offset());
  388. string File = Section.FindS("Filename");
  389. unsigned long Size = Section.FindI("Size");
  390. if (File.empty() || Size == 0)
  391. return _error->Error("Cannot find filename or size tag");
  392. if (Chop != 0)
  393. File = OrigPath + ChopDirs(File,Chop);
  394. // See if the file exists
  395. bool Mangled = false;
  396. if (NoStat == false || Hits < 10)
  397. {
  398. // Attempt to fix broken structure
  399. if (Hits == 0)
  400. {
  401. if (ReconstructPrefix(Prefix,OrigPath,CDROM,File) == false &&
  402. ReconstructChop(Chop,*I,File) == false)
  403. {
  404. if (Debug == true)
  405. clog << "Missed: " << File << endl;
  406. NotFound++;
  407. continue;
  408. }
  409. if (Chop != 0)
  410. File = OrigPath + ChopDirs(File,Chop);
  411. }
  412. // Get the size
  413. struct stat Buf;
  414. if (stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0 ||
  415. Buf.st_size == 0)
  416. {
  417. // Attempt to fix busted symlink support for one instance
  418. string OrigFile = File;
  419. string::size_type Start = File.find("binary-");
  420. string::size_type End = File.find("/",Start+3);
  421. if (Start != string::npos && End != string::npos)
  422. {
  423. File.replace(Start,End-Start,"binary-all");
  424. Mangled = true;
  425. }
  426. if (Mangled == false ||
  427. stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0)
  428. {
  429. if (Debug == true)
  430. clog << "Missed(2): " << OrigFile << endl;
  431. NotFound++;
  432. continue;
  433. }
  434. }
  435. // Size match
  436. if ((unsigned)Buf.st_size != Size)
  437. {
  438. if (Debug == true)
  439. clog << "Wrong Size: " << File << endl;
  440. WrongSize++;
  441. continue;
  442. }
  443. }
  444. Packages++;
  445. Hits++;
  446. // Copy it to the target package file
  447. const char *Start;
  448. const char *Stop;
  449. if (Chop != 0 || Mangled == true)
  450. {
  451. // Mangle the output filename
  452. const char *Filename;
  453. Section.Find("Filename",Filename,Stop);
  454. /* We need to rewrite the filename field so we emit
  455. all fields except the filename file and rewrite that one */
  456. for (unsigned int I = 0; I != Section.Count(); I++)
  457. {
  458. Section.Get(Start,Stop,I);
  459. if (Start <= Filename && Stop > Filename)
  460. {
  461. char S[500];
  462. sprintf(S,"Filename: %s\n",File.c_str());
  463. if (I + 1 == Section.Count())
  464. strcat(S,"\n");
  465. if (Target.Write(S,strlen(S)) == false)
  466. return false;
  467. }
  468. else
  469. {
  470. if (Target.Write(Start,Stop-Start) == false)
  471. return false;
  472. if (Stop[-1] != '\n')
  473. if (Target.Write("\n",1) == false)
  474. return false;
  475. }
  476. }
  477. if (Target.Write("\n",1) == false)
  478. return false;
  479. }
  480. else
  481. {
  482. Section.GetSection(Start,Stop);
  483. if (Target.Write(Start,Stop-Start) == false)
  484. return false;
  485. }
  486. }
  487. if (Debug == true)
  488. cout << " Processed by using Prefix '" << Prefix << "' and chop " << Chop << endl;
  489. if (_config->FindB("APT::CDROM::NoAct",false) == false)
  490. {
  491. // Move out of the partial directory
  492. Target.Close();
  493. string FinalF = _config->FindDir("Dir::State::lists");
  494. FinalF += URItoFileName(S);
  495. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  496. return _error->Errno("rename","Failed to rename");
  497. // Copy the release file
  498. sprintf(S,"cdrom:%s/%sRelease",Name.c_str(),(*I).c_str() + CDROM.length());
  499. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  500. TargetF += URItoFileName(S);
  501. if (FileExists(*I + "Release") == true)
  502. {
  503. FileFd Target(TargetF,FileFd::WriteEmpty);
  504. FileFd Rel(*I + "Release",FileFd::ReadOnly);
  505. if (_error->PendingError() == true)
  506. return false;
  507. if (CopyFile(Rel,Target) == false)
  508. return false;
  509. }
  510. else
  511. {
  512. // Empty release file
  513. FileFd Target(TargetF,FileFd::WriteEmpty);
  514. }
  515. // Rename the release file
  516. FinalF = _config->FindDir("Dir::State::lists");
  517. FinalF += URItoFileName(S);
  518. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  519. return _error->Errno("rename","Failed to rename");
  520. }
  521. /* Mangle the source to be in the proper notation with
  522. prefix dist [component] */
  523. *I = string(*I,Prefix.length());
  524. ConvertToSourceList(CDROM,*I);
  525. *I = Prefix + ' ' + *I;
  526. CurrentSize += Pkg.Size();
  527. }
  528. Progress.Done();
  529. // Some stats
  530. cout << "Wrote " << Packages << " package records" ;
  531. if (NotFound != 0)
  532. cout << " with " << NotFound << " missing files";
  533. if (NotFound != 0 && WrongSize != 0)
  534. cout << " and";
  535. if (WrongSize != 0)
  536. cout << " with " << WrongSize << " mismatched files";
  537. cout << '.' << endl;
  538. if (Packages == 0)
  539. return _error->Error("No valid package records were found.");
  540. if (NotFound + WrongSize > 10)
  541. cout << "Alot of package entries were discarded, perhaps this CD is funny?" << endl;
  542. return true;
  543. }
  544. /*}}}*/
  545. // ReduceSourceList - Takes the path list and reduces it /*{{{*/
  546. // ---------------------------------------------------------------------
  547. /* This takes the list of source list expressed entires and collects
  548. similar ones to form a single entry for each dist */
  549. bool ReduceSourcelist(string CD,vector<string> &List)
  550. {
  551. sort(List.begin(),List.end());
  552. // Collect similar entries
  553. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  554. {
  555. // Find a space..
  556. string::size_type Space = (*I).find(' ');
  557. if (Space == string::npos)
  558. continue;
  559. string::size_type SSpace = (*I).find(' ',Space + 1);
  560. if (SSpace == string::npos)
  561. continue;
  562. string Word1 = string(*I,Space,SSpace-Space);
  563. for (vector<string>::iterator J = List.begin(); J != I; J++)
  564. {
  565. // Find a space..
  566. string::size_type Space2 = (*J).find(' ');
  567. if (Space2 == string::npos)
  568. continue;
  569. string::size_type SSpace2 = (*J).find(' ',Space2 + 1);
  570. if (SSpace2 == string::npos)
  571. continue;
  572. if (string(*J,Space2,SSpace2-Space2) != Word1)
  573. continue;
  574. *J += string(*I,SSpace);
  575. *I = string();
  576. }
  577. }
  578. // Wipe erased entries
  579. for (unsigned int I = 0; I < List.size();)
  580. {
  581. if (List[I].empty() == false)
  582. I++;
  583. else
  584. List.erase(List.begin()+I);
  585. }
  586. }
  587. /*}}}*/
  588. // WriteDatabase - Write the CDROM Database file /*{{{*/
  589. // ---------------------------------------------------------------------
  590. /* We rewrite the configuration class associated with the cdrom database. */
  591. bool WriteDatabase(Configuration &Cnf)
  592. {
  593. string DFile = _config->FindFile("Dir::State::cdroms");
  594. string NewFile = DFile + ".new";
  595. unlink(NewFile.c_str());
  596. ofstream Out(NewFile.c_str());
  597. if (!Out)
  598. return _error->Errno("ofstream::ofstream",
  599. "Failed to open %s.new",DFile.c_str());
  600. /* Write out all of the configuration directives by walking the
  601. configuration tree */
  602. const Configuration::Item *Top = Cnf.Tree(0);
  603. for (; Top != 0;)
  604. {
  605. // Print the config entry
  606. if (Top->Value.empty() == false)
  607. Out << Top->FullTag() + " \"" << Top->Value << "\";" << endl;
  608. if (Top->Child != 0)
  609. {
  610. Top = Top->Child;
  611. continue;
  612. }
  613. while (Top != 0 && Top->Next == 0)
  614. Top = Top->Parent;
  615. if (Top != 0)
  616. Top = Top->Next;
  617. }
  618. Out.close();
  619. rename(DFile.c_str(),string(DFile + '~').c_str());
  620. if (rename(NewFile.c_str(),DFile.c_str()) != 0)
  621. return _error->Errno("rename","Failed to rename %s.new to %s",
  622. DFile.c_str(),DFile.c_str());
  623. return true;
  624. }
  625. /*}}}*/
  626. // WriteSourceList - Write an updated sourcelist /*{{{*/
  627. // ---------------------------------------------------------------------
  628. /* This reads the old source list and copies it into the new one. It
  629. appends the new CDROM entires just after the first block of comments.
  630. This places them first in the file. It also removes any old entries
  631. that were the same. */
  632. bool WriteSourceList(string Name,vector<string> &List)
  633. {
  634. string File = _config->FindFile("Dir::Etc::sourcelist");
  635. // Open the stream for reading
  636. ifstream F(File.c_str(),ios::in | ios::nocreate);
  637. if (!F != 0)
  638. return _error->Errno("ifstream::ifstream","Opening %s",File.c_str());
  639. string NewFile = File + ".new";
  640. unlink(NewFile.c_str());
  641. ofstream Out(NewFile.c_str());
  642. if (!Out)
  643. return _error->Errno("ofstream::ofstream",
  644. "Failed to open %s.new",File.c_str());
  645. // Create a short uri without the path
  646. string ShortURI = "cdrom:" + Name + "/";
  647. char Buffer[300];
  648. int CurLine = 0;
  649. bool First = true;
  650. while (F.eof() == false)
  651. {
  652. F.getline(Buffer,sizeof(Buffer));
  653. CurLine++;
  654. _strtabexpand(Buffer,sizeof(Buffer));
  655. _strstrip(Buffer);
  656. // Comment or blank
  657. if (Buffer[0] == '#' || Buffer[0] == 0)
  658. {
  659. Out << Buffer << endl;
  660. continue;
  661. }
  662. if (First == true)
  663. {
  664. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  665. {
  666. string::size_type Space = (*I).find(' ');
  667. if (Space == string::npos)
  668. return _error->Error("Internal error");
  669. Out << "deb \"cdrom:" << Name << "/" << string(*I,0,Space) <<
  670. "\" " << string(*I,Space+1) << endl;
  671. }
  672. }
  673. First = false;
  674. // Grok it
  675. string Type;
  676. string URI;
  677. char *C = Buffer;
  678. if (ParseQuoteWord(C,Type) == false ||
  679. ParseQuoteWord(C,URI) == false)
  680. {
  681. Out << Buffer << endl;
  682. continue;
  683. }
  684. // Emit lines like this one
  685. if (Type != "deb" || string(URI,0,ShortURI.length()) != ShortURI)
  686. {
  687. Out << Buffer << endl;
  688. continue;
  689. }
  690. }
  691. // Just in case the file was empty
  692. if (First == true)
  693. {
  694. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  695. {
  696. string::size_type Space = (*I).find(' ');
  697. if (Space == string::npos)
  698. return _error->Error("Internal error");
  699. Out << "deb \"cdrom:" << Name << "/" << string(*I,0,Space) <<
  700. "\" " << string(*I,Space+1) << endl;
  701. }
  702. }
  703. Out.close();
  704. rename(File.c_str(),string(File + '~').c_str());
  705. if (rename(NewFile.c_str(),File.c_str()) != 0)
  706. return _error->Errno("rename","Failed to rename %s.new to %s",
  707. File.c_str(),File.c_str());
  708. return true;
  709. }
  710. /*}}}*/
  711. // Prompt - Simple prompt /*{{{*/
  712. // ---------------------------------------------------------------------
  713. /* */
  714. void Prompt(const char *Text)
  715. {
  716. char C;
  717. cout << Text << ' ' << flush;
  718. read(STDIN_FILENO,&C,1);
  719. if (C != '\n')
  720. cout << endl;
  721. }
  722. /*}}}*/
  723. // PromptLine - Prompt for an input line /*{{{*/
  724. // ---------------------------------------------------------------------
  725. /* */
  726. string PromptLine(const char *Text)
  727. {
  728. cout << Text << ':' << endl;
  729. string Res;
  730. getline(cin,Res);
  731. return Res;
  732. }
  733. /*}}}*/
  734. // DoAdd - Add a new CDROM /*{{{*/
  735. // ---------------------------------------------------------------------
  736. /* This does the main add bit.. We show some status and things. The
  737. sequence is to mount/umount the CD, Ident it then scan it for package
  738. files and reduce that list. Then we copy over the package files and
  739. verify them. Then rewrite the database files */
  740. bool DoAdd(CommandLine &)
  741. {
  742. // Startup
  743. string CDROM = _config->FindDir("Acquire::cdrom::mount","/cdrom/");
  744. if (CDROM[0] == '.')
  745. CDROM= SafeGetCWD() + '/' + CDROM;
  746. cout << "Using CD-ROM mount point " << CDROM << endl;
  747. // Read the database
  748. Configuration Database;
  749. string DFile = _config->FindFile("Dir::State::cdroms");
  750. if (FileExists(DFile) == true)
  751. {
  752. if (ReadConfigFile(Database,DFile) == false)
  753. return _error->Error("Unable to read the cdrom database %s",
  754. DFile.c_str());
  755. }
  756. // Unmount the CD and get the user to put in the one they want
  757. if (_config->FindB("APT::CDROM::NoMount",false) == false)
  758. {
  759. cout << "Unmounting CD-ROM" << endl;
  760. UnmountCdrom(CDROM);
  761. // Mount the new CDROM
  762. Prompt("Please insert a Disc in the drive and press enter");
  763. cout << "Mounting CD-ROM" << endl;
  764. if (MountCdrom(CDROM) == false)
  765. return _error->Error("Failed to mount the cdrom.");
  766. }
  767. // Hash the CD to get an ID
  768. cout << "Identifying.. " << flush;
  769. string ID;
  770. if (IdentCdrom(CDROM,ID) == false)
  771. {
  772. cout << endl;
  773. return false;
  774. }
  775. cout << '[' << ID << ']' << endl;
  776. cout << "Scanning Disc for index files.. " << flush;
  777. // Get the CD structure
  778. vector<string> List;
  779. string StartDir = SafeGetCWD();
  780. string InfoDir;
  781. if (FindPackages(CDROM,List,InfoDir) == false)
  782. {
  783. cout << endl;
  784. return false;
  785. }
  786. chdir(StartDir.c_str());
  787. if (_config->FindB("Debug::aptcdrom",false) == true)
  788. {
  789. cout << "I found:" << endl;
  790. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  791. {
  792. cout << *I << endl;
  793. }
  794. }
  795. // Fix up the list
  796. DropBinaryArch(List);
  797. DropRepeats(List);
  798. cout << "Found " << List.size() << " package index files." << endl;
  799. if (List.size() == 0)
  800. return _error->Error("Unable to locate any package files, perhaps this is not a Debian Disc");
  801. // Check if the CD is in the database
  802. string Name;
  803. if (Database.Exists("CD::" + ID) == false ||
  804. _config->FindB("APT::CDROM::Rename",false) == true)
  805. {
  806. // Try to use the CDs label if at all possible
  807. if (InfoDir.empty() == false &&
  808. FileExists(InfoDir + "/info") == true)
  809. {
  810. ifstream F(string(InfoDir + "/info").c_str());
  811. if (!F == 0)
  812. getline(F,Name);
  813. if (Name.empty() == false)
  814. {
  815. cout << "Found label '" << Name << "'" << endl;
  816. Database.Set("CD::" + ID + "::Label",Name);
  817. }
  818. }
  819. if (_config->FindB("APT::CDROM::Rename",false) == true ||
  820. Name.empty() == true)
  821. {
  822. cout << "Please provide a name for this Disc, such as 'Debian 2.1r1 Disk 1'";
  823. while (1)
  824. {
  825. Name = PromptLine("");
  826. if (Name.empty() == false &&
  827. Name.find('"') == string::npos &&
  828. Name.find(':') == string::npos &&
  829. Name.find('/') == string::npos)
  830. break;
  831. cout << "That is not a valid name, try again " << endl;
  832. }
  833. }
  834. }
  835. else
  836. Name = Database.Find("CD::" + ID);
  837. string::iterator J = Name.begin();
  838. for (; J != Name.end(); J++)
  839. if (*J == '/' || *J == '"' || *J == ':')
  840. *J = '_';
  841. Database.Set("CD::" + ID,Name);
  842. cout << "This Disc is called '" << Name << "'" << endl;
  843. // Copy the package files to the state directory
  844. if (CopyPackages(CDROM,Name,List) == false)
  845. return false;
  846. ReduceSourcelist(CDROM,List);
  847. // Write the database and sourcelist
  848. if (_config->FindB("APT::cdrom::NoAct",false) == false)
  849. {
  850. if (WriteDatabase(Database) == false)
  851. return false;
  852. cout << "Writing new source list" << endl;
  853. if (WriteSourceList(Name,List) == false)
  854. return false;
  855. }
  856. // Print the sourcelist entries
  857. cout << "Source List entries for this Disc are:" << endl;
  858. for (vector<string>::iterator I = List.begin(); I != List.end(); I++)
  859. {
  860. string::size_type Space = (*I).find(' ');
  861. if (Space == string::npos)
  862. return _error->Error("Internal error");
  863. cout << "deb \"cdrom:" << Name << "/" << string(*I,0,Space) <<
  864. "\" " << string(*I,Space+1) << endl;
  865. }
  866. cout << "Repeat this process for the rest of the CDs in your set." << endl;
  867. return true;
  868. }
  869. /*}}}*/
  870. // ShowHelp - Show the help screen /*{{{*/
  871. // ---------------------------------------------------------------------
  872. /* */
  873. int ShowHelp()
  874. {
  875. cout << PACKAGE << ' ' << VERSION << " for " << ARCHITECTURE <<
  876. " compiled on " << __DATE__ << " " << __TIME__ << endl;
  877. if (_config->FindB("version") == true)
  878. return 100;
  879. cout << "Usage: apt-cdrom [options] command" << endl;
  880. cout << endl;
  881. cout << "apt-cdrom is a tool to add CDROM's to APT's source list. The " << endl;
  882. cout << "CDROM mount point and device information is taken from apt.conf" << endl;
  883. cout << "and /etc/fstab." << endl;
  884. cout << endl;
  885. cout << "Commands:" << endl;
  886. cout << " add - Add a CDROM" << endl;
  887. cout << endl;
  888. cout << "Options:" << endl;
  889. cout << " -h This help text" << endl;
  890. cout << " -d CD-ROM mount point" << endl;
  891. cout << " -r Rename a recognized CD-ROM" << endl;
  892. cout << " -m No mounting" << endl;
  893. cout << " -f Fast mode, don't check package files" << endl;
  894. cout << " -a Thorough scan mode" << endl;
  895. cout << " -c=? Read this configuration file" << endl;
  896. cout << " -o=? Set an arbitary configuration option, eg -o dir::cache=/tmp" << endl;
  897. cout << "See fstab(5)" << endl;
  898. return 100;
  899. }
  900. /*}}}*/
  901. int main(int argc,const char *argv[])
  902. {
  903. CommandLine::Args Args[] = {
  904. {'h',"help","help",0},
  905. {'v',"version","version",0},
  906. {'d',"cdrom","Acquire::cdrom::mount",CommandLine::HasArg},
  907. {'r',"rename","APT::CDROM::Rename",0},
  908. {'m',"no-mount","APT::CDROM::NoMount",0},
  909. {'f',"fast","APT::CDROM::Fast",0},
  910. {'n',"just-print","APT::CDROM::NoAct",0},
  911. {'n',"recon","APT::CDROM::NoAct",0},
  912. {'n',"no-act","APT::CDROM::NoAct",0},
  913. {'a',"thorough","APT::CDROM::Thorough",0},
  914. {'c',"config-file",0,CommandLine::ConfigFile},
  915. {'o',"option",0,CommandLine::ArbItem},
  916. {0,0,0,0}};
  917. CommandLine::Dispatch Cmds[] = {
  918. {"add",&DoAdd},
  919. {0,0}};
  920. // Parse the command line and initialize the package library
  921. CommandLine CmdL(Args,_config);
  922. if (pkgInitialize(*_config) == false ||
  923. CmdL.Parse(argc,argv) == false)
  924. {
  925. _error->DumpErrors();
  926. return 100;
  927. }
  928. // See if the help should be shown
  929. if (_config->FindB("help") == true ||
  930. CmdL.FileSize() == 0)
  931. return ShowHelp();
  932. // Deal with stdout not being a tty
  933. if (ttyname(STDOUT_FILENO) == 0 && _config->FindI("quiet",0) < 1)
  934. _config->Set("quiet","1");
  935. // Match the operation
  936. CmdL.DispatchArg(Cmds);
  937. // Print any errors or warnings found during parsing
  938. if (_error->empty() == false)
  939. {
  940. bool Errors = _error->PendingError();
  941. _error->DumpErrors();
  942. return Errors == true?100:0;
  943. }
  944. return 0;
  945. }