dpkgdb.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: dpkgdb.cc,v 1.5 2002/03/26 07:38:58 jgg Exp $
  4. /* ######################################################################
  5. DPKGv1 Database Implemenation
  6. This class provides parsers and other implementations for the DPKGv1
  7. database. It reads the diversion file, the list files and the status
  8. file to build both the list of currently installed files and the
  9. currently installed package list.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #ifdef __GNUG__
  14. #pragma implementation "apt-pkg/dpkgdb.h"
  15. #endif
  16. #include <apt-pkg/dpkgdb.h>
  17. #include <apt-pkg/configuration.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/progress.h>
  20. #include <apt-pkg/tagfile.h>
  21. #include <apt-pkg/strutl.h>
  22. #include <stdio.h>
  23. #include <errno.h>
  24. #include <sys/stat.h>
  25. #include <sys/mman.h>
  26. #include <fcntl.h>
  27. #include <unistd.h>
  28. #include <ctype.h>
  29. #include <iostream>
  30. /*}}}*/
  31. // EraseDir - Erase A Directory /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* This is necessary to create a new empty sub directory. The caller should
  34. invoke mkdir after this with the proper permissions and check for
  35. error. Maybe stick this in fileutils */
  36. static bool EraseDir(const char *Dir)
  37. {
  38. // First we try a simple RM
  39. if (rmdir(Dir) == 0 ||
  40. errno == ENOENT)
  41. return true;
  42. // A file? Easy enough..
  43. if (errno == ENOTDIR)
  44. {
  45. if (unlink(Dir) != 0)
  46. return _error->Errno("unlink","Failed to remove %s",Dir);
  47. return true;
  48. }
  49. // Should not happen
  50. if (errno != ENOTEMPTY)
  51. return _error->Errno("rmdir","Failed to remove %s",Dir);
  52. // Purge it using rm
  53. int Pid = ExecFork();
  54. // Spawn the subprocess
  55. if (Pid == 0)
  56. {
  57. execlp(_config->Find("Dir::Bin::rm","/bin/rm").c_str(),
  58. "rm","-rf","--",Dir,0);
  59. _exit(100);
  60. }
  61. return ExecWait(Pid,_config->Find("dir::bin::rm","/bin/rm").c_str());
  62. }
  63. /*}}}*/
  64. // DpkgDB::debDpkgDB - Constructor /*{{{*/
  65. // ---------------------------------------------------------------------
  66. /* */
  67. debDpkgDB::debDpkgDB() : CacheMap(0), FileMap(0)
  68. {
  69. AdminDir = flNotFile(_config->Find("Dir::State::status"));
  70. DiverInode = 0;
  71. DiverTime = 0;
  72. }
  73. /*}}}*/
  74. // DpkgDB::~debDpkgDB - Destructor /*{{{*/
  75. // ---------------------------------------------------------------------
  76. /* */
  77. debDpkgDB::~debDpkgDB()
  78. {
  79. delete Cache;
  80. Cache = 0;
  81. delete CacheMap;
  82. CacheMap = 0;
  83. delete FList;
  84. FList = 0;
  85. delete FileMap;
  86. FileMap = 0;
  87. }
  88. /*}}}*/
  89. // DpkgDB::InitMetaTmp - Get the temp dir for meta information /*{{{*/
  90. // ---------------------------------------------------------------------
  91. /* This creats+empties the meta temporary directory /var/lib/dpkg/tmp.ci
  92. Only one package at a time can be using the returned meta directory. */
  93. bool debDpkgDB::InitMetaTmp(string &Dir)
  94. {
  95. string Tmp = AdminDir + "tmp.ci/";
  96. if (EraseDir(Tmp.c_str()) == false)
  97. return _error->Error("Unable to create %s",Tmp.c_str());
  98. if (mkdir(Tmp.c_str(),0755) != 0)
  99. return _error->Errno("mkdir","Unable to create %s",Tmp.c_str());
  100. // Verify it is on the same filesystem as the main info directory
  101. dev_t Dev;
  102. struct stat St;
  103. if (stat((AdminDir + "info").c_str(),&St) != 0)
  104. return _error->Errno("stat","Failed to stat %sinfo",AdminDir.c_str());
  105. Dev = St.st_dev;
  106. if (stat(Tmp.c_str(),&St) != 0)
  107. return _error->Errno("stat","Failed to stat %s",Tmp.c_str());
  108. if (Dev != St.st_dev)
  109. return _error->Error("The info and temp directories need to be on the same filesystem");
  110. // Done
  111. Dir = Tmp;
  112. return true;
  113. }
  114. /*}}}*/
  115. // DpkgDB::ReadyPkgCache - Prepare the cache with the current status /*{{{*/
  116. // ---------------------------------------------------------------------
  117. /* This reads in the status file into an empty cache. This really needs
  118. to be somehow unified with the high level APT notion of the Database
  119. directory, but there is no clear way on how to do that yet. */
  120. bool debDpkgDB::ReadyPkgCache(OpProgress &Progress)
  121. {
  122. if (Cache != 0)
  123. {
  124. Progress.OverallProgress(1,1,1,"Reading Package Lists");
  125. return true;
  126. }
  127. if (CacheMap != 0)
  128. {
  129. delete CacheMap;
  130. CacheMap = 0;
  131. }
  132. if (pkgMakeOnlyStatusCache(Progress,&CacheMap) == false)
  133. return false;
  134. Cache->DropProgress();
  135. return true;
  136. }
  137. /*}}}*/
  138. // DpkgDB::ReadFList - Read the File Listings in /*{{{*/
  139. // ---------------------------------------------------------------------
  140. /* This reads the file listing in from the state directory. This is a
  141. performance critical routine, as it needs to parse about 50k lines of
  142. text spread over a hundred or more files. For an initial cold start
  143. most of the time is spent in reading file inodes and so on, not
  144. actually parsing. */
  145. bool debDpkgDB::ReadFList(OpProgress &Progress)
  146. {
  147. // Count the number of packages we need to read information for
  148. unsigned long Total = 0;
  149. pkgCache &Cache = this->Cache->GetCache();
  150. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
  151. {
  152. // Only not installed packages have no files.
  153. if (I->CurrentState == pkgCache::State::NotInstalled)
  154. continue;
  155. Total++;
  156. }
  157. /* Switch into the admin dir, this prevents useless lookups for the
  158. path components */
  159. string Cwd = SafeGetCWD();
  160. if (chdir((AdminDir + "info/").c_str()) != 0)
  161. return _error->Errno("chdir","Failed to change to the admin dir %sinfo",AdminDir.c_str());
  162. // Allocate a buffer. Anything larger than this buffer will be mmaped
  163. unsigned long BufSize = 32*1024;
  164. char *Buffer = new char[BufSize];
  165. // Begin Loading them
  166. unsigned long Count = 0;
  167. char Name[300];
  168. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
  169. {
  170. /* Only not installed packages have no files. ConfFile packages have
  171. file lists but we don't want to read them in */
  172. if (I->CurrentState == pkgCache::State::NotInstalled ||
  173. I->CurrentState == pkgCache::State::ConfigFiles)
  174. continue;
  175. // Fetch a package handle to associate with the file
  176. pkgFLCache::PkgIterator FlPkg = FList->GetPkg(I.Name(),0,true);
  177. if (FlPkg.end() == true)
  178. {
  179. _error->Error("Internal Error getting a Package Name");
  180. break;
  181. }
  182. Progress.OverallProgress(Count,Total,1,"Reading File Listing");
  183. // Open the list file
  184. snprintf(Name,sizeof(Name),"%s.list",I.Name());
  185. int Fd = open(Name,O_RDONLY);
  186. /* Okay this is very strange and bad.. Best thing is to bail and
  187. instruct the user to look into it. */
  188. struct stat Stat;
  189. if (Fd == -1 || fstat(Fd,&Stat) != 0)
  190. {
  191. _error->Errno("open","Failed to open the list file '%sinfo/%s'. If you "
  192. "cannot restore this file then make it empty "
  193. "and immediately re-install the same version of the package!",
  194. AdminDir.c_str(),Name);
  195. break;
  196. }
  197. // Set File to be a memory buffer containing the whole file
  198. char *File;
  199. if ((unsigned)Stat.st_size < BufSize)
  200. {
  201. if (read(Fd,Buffer,Stat.st_size) != Stat.st_size)
  202. {
  203. _error->Errno("read","Failed reading the list file %sinfo/%s",
  204. AdminDir.c_str(),Name);
  205. close(Fd);
  206. break;
  207. }
  208. File = Buffer;
  209. }
  210. else
  211. {
  212. // Use mmap
  213. File = (char *)mmap(0,Stat.st_size,PROT_READ,MAP_PRIVATE,Fd,0);
  214. if (File == (char *)(-1))
  215. {
  216. _error->Errno("mmap","Failed reading the list file %sinfo/%s",
  217. AdminDir.c_str(),Name);
  218. close(Fd);
  219. break;
  220. }
  221. }
  222. // Parse it
  223. const char *Start = File;
  224. const char *End = File;
  225. const char *Finish = File + Stat.st_size;
  226. for (; End < Finish; End++)
  227. {
  228. // Not an end of line
  229. if (*End != '\n' && End + 1 < Finish)
  230. continue;
  231. // Skip blank lines
  232. if (End - Start > 1)
  233. {
  234. pkgFLCache::NodeIterator Node = FList->GetNode(Start,End,
  235. FlPkg.Offset(),true,false);
  236. if (Node.end() == true)
  237. {
  238. _error->Error("Internal Error getting a Node");
  239. break;
  240. }
  241. }
  242. // Skip past the end of line
  243. for (; *End == '\n' && End < Finish; End++);
  244. Start = End;
  245. }
  246. close(Fd);
  247. if ((unsigned)Stat.st_size >= BufSize)
  248. munmap((caddr_t)File,Stat.st_size);
  249. // Failed
  250. if (End < Finish)
  251. break;
  252. Count++;
  253. }
  254. delete [] Buffer;
  255. if (chdir(Cwd.c_str()) != 0)
  256. chdir("/");
  257. return !_error->PendingError();
  258. }
  259. /*}}}*/
  260. // DpkgDB::ReadDiversions - Load the diversions file /*{{{*/
  261. // ---------------------------------------------------------------------
  262. /* Read the diversion file in from disk. This is usually invoked by
  263. LoadChanges before performing an operation that uses the FLCache. */
  264. bool debDpkgDB::ReadDiversions()
  265. {
  266. struct stat Stat;
  267. if (stat((AdminDir + "diversions").c_str(),&Stat) != 0)
  268. return true;
  269. if (_error->PendingError() == true)
  270. return false;
  271. FILE *Fd = fopen((AdminDir + "diversions").c_str(),"r");
  272. if (Fd == 0)
  273. return _error->Errno("fopen","Failed to open the diversions file %sdiversions",AdminDir.c_str());
  274. FList->BeginDiverLoad();
  275. while (1)
  276. {
  277. char From[300];
  278. char To[300];
  279. char Package[100];
  280. // Read the three lines in
  281. if (fgets(From,sizeof(From),Fd) == 0)
  282. break;
  283. if (fgets(To,sizeof(To),Fd) == 0 ||
  284. fgets(Package,sizeof(Package),Fd) == 0)
  285. {
  286. _error->Error("The diversion file is corrupted");
  287. break;
  288. }
  289. // Strip the \ns
  290. unsigned long Len = strlen(From);
  291. if (Len < 2 || From[Len-1] != '\n')
  292. _error->Error("Invalid line in the diversion file: %s",From);
  293. else
  294. From[Len-1] = 0;
  295. Len = strlen(To);
  296. if (Len < 2 || To[Len-1] != '\n')
  297. _error->Error("Invalid line in the diversion file: %s",To);
  298. else
  299. To[Len-1] = 0;
  300. Len = strlen(Package);
  301. if (Len < 2 || Package[Len-1] != '\n')
  302. _error->Error("Invalid line in the diversion file: %s",Package);
  303. else
  304. Package[Len-1] = 0;
  305. // Make sure the lines were parsed OK
  306. if (_error->PendingError() == true)
  307. break;
  308. // Fetch a package
  309. if (strcmp(Package,":") == 0)
  310. Package[0] = 0;
  311. pkgFLCache::PkgIterator FlPkg = FList->GetPkg(Package,0,true);
  312. if (FlPkg.end() == true)
  313. {
  314. _error->Error("Internal Error getting a Package Name");
  315. break;
  316. }
  317. // Install the diversion
  318. if (FList->AddDiversion(FlPkg,From,To) == false)
  319. {
  320. _error->Error("Internal Error adding a diversion");
  321. break;
  322. }
  323. }
  324. if (_error->PendingError() == false)
  325. FList->FinishDiverLoad();
  326. DiverInode = Stat.st_ino;
  327. DiverTime = Stat.st_mtime;
  328. fclose(Fd);
  329. return !_error->PendingError();
  330. }
  331. /*}}}*/
  332. // DpkgDB::ReadFileList - Read the file listing /*{{{*/
  333. // ---------------------------------------------------------------------
  334. /* Read in the file listing. The file listing is created from three
  335. sources, *.list, Conffile sections and the Diversion table. */
  336. bool debDpkgDB::ReadyFileList(OpProgress &Progress)
  337. {
  338. if (Cache == 0)
  339. return _error->Error("The pkg cache must be initialize first");
  340. if (FList != 0)
  341. {
  342. Progress.OverallProgress(1,1,1,"Reading File List");
  343. return true;
  344. }
  345. // Create the cache and read in the file listing
  346. FileMap = new DynamicMMap(MMap::Public);
  347. FList = new pkgFLCache(*FileMap);
  348. if (_error->PendingError() == true ||
  349. ReadFList(Progress) == false ||
  350. ReadConfFiles() == false ||
  351. ReadDiversions() == false)
  352. {
  353. delete FList;
  354. delete FileMap;
  355. FileMap = 0;
  356. FList = 0;
  357. return false;
  358. }
  359. cout << "Node: " << FList->HeaderP->NodeCount << ',' << FList->HeaderP->UniqNodes << endl;
  360. cout << "Dir: " << FList->HeaderP->DirCount << endl;
  361. cout << "Package: " << FList->HeaderP->PackageCount << endl;
  362. cout << "HashSize: " << FList->HeaderP->HashSize << endl;
  363. cout << "Size: " << FileMap->Size() << endl;
  364. cout << endl;
  365. return true;
  366. }
  367. /*}}}*/
  368. // DpkgDB::ReadConfFiles - Read the conf file sections from the s-file /*{{{*/
  369. // ---------------------------------------------------------------------
  370. /* Reading the conf files is done by reparsing the status file. This is
  371. actually rather fast so it is no big deal. */
  372. bool debDpkgDB::ReadConfFiles()
  373. {
  374. FileFd File(_config->FindFile("Dir::State::status"),FileFd::ReadOnly);
  375. pkgTagFile Tags(&File);
  376. if (_error->PendingError() == true)
  377. return false;
  378. pkgTagSection Section;
  379. while (1)
  380. {
  381. // Skip to the next section
  382. unsigned long Offset = Tags.Offset();
  383. if (Tags.Step(Section) == false)
  384. break;
  385. // Parse the line
  386. const char *Start;
  387. const char *Stop;
  388. if (Section.Find("Conffiles",Start,Stop) == false)
  389. continue;
  390. const char *PkgStart;
  391. const char *PkgEnd;
  392. if (Section.Find("Package",PkgStart,PkgEnd) == false)
  393. return _error->Error("Failed to find a Package: Header, offset %lu",Offset);
  394. // Snag a package record for it
  395. pkgFLCache::PkgIterator FlPkg = FList->GetPkg(PkgStart,PkgEnd,true);
  396. if (FlPkg.end() == true)
  397. return _error->Error("Internal Error getting a Package Name");
  398. // Parse the conf file lines
  399. while (1)
  400. {
  401. for (; isspace(*Start) != 0 && Start < Stop; Start++);
  402. if (Start == Stop)
  403. break;
  404. // Split it into words
  405. const char *End = Start;
  406. for (; isspace(*End) == 0 && End < Stop; End++);
  407. const char *StartMd5 = End;
  408. for (; isspace(*StartMd5) != 0 && StartMd5 < Stop; StartMd5++);
  409. const char *EndMd5 = StartMd5;
  410. for (; isspace(*EndMd5) == 0 && EndMd5 < Stop; EndMd5++);
  411. if (StartMd5 == EndMd5 || Start == End)
  412. return _error->Error("Bad ConfFile section in the status file. Offset %lu",Offset);
  413. // Insert a new entry
  414. unsigned char MD5[16];
  415. if (Hex2Num(string(StartMd5,EndMd5-StartMd5),MD5,16) == false)
  416. return _error->Error("Error parsing MD5. Offset %lu",Offset);
  417. if (FList->AddConfFile(Start,End,FlPkg,MD5) == false)
  418. return false;
  419. Start = EndMd5;
  420. }
  421. }
  422. return true;
  423. }
  424. /*}}}*/
  425. // DpkgDB::LoadChanges - Read in any changed state files /*{{{*/
  426. // ---------------------------------------------------------------------
  427. /* The only file in the dpkg system that can change while packages are
  428. unpacking is the diversions file. */
  429. bool debDpkgDB::LoadChanges()
  430. {
  431. struct stat Stat;
  432. if (stat((AdminDir + "diversions").c_str(),&Stat) != 0)
  433. return true;
  434. if (DiverInode == Stat.st_ino && DiverTime == Stat.st_mtime)
  435. return true;
  436. return ReadDiversions();
  437. }
  438. /*}}}*/