dpkgdb.cc 15 KB

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