You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

491 lines
15 KiB

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