apt-cdrom.cc 31 KB

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