apt-cdrom.cc 28 KB

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