apt-cdrom.cc 29 KB

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