dpkgdb.cc 15 KB

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