cachedb.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: cachedb.cc,v 1.7 2004/05/08 19:41:01 mdz Exp $
  4. /* ######################################################################
  5. CacheDB
  6. Simple uniform interface to a cache database.
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include <config.h>
  11. #include <apt-pkg/error.h>
  12. #include <apt-pkg/md5.h>
  13. #include <apt-pkg/sha1.h>
  14. #include <apt-pkg/sha2.h>
  15. #include <apt-pkg/strutl.h>
  16. #include <apt-pkg/configuration.h>
  17. #include <apt-pkg/fileutl.h>
  18. #include <apt-pkg/debfile.h>
  19. #include <apt-pkg/gpgv.h>
  20. #include <apt-pkg/hashes.h>
  21. #include <netinet/in.h> // htonl, etc
  22. #include <ctype.h>
  23. #include <stddef.h>
  24. #include <sys/stat.h>
  25. #include <strings.h>
  26. #include "cachedb.h"
  27. #include <apti18n.h>
  28. /*}}}*/
  29. CacheDB::CacheDB(std::string const &DB)
  30. : Dbp(0), Fd(NULL), DebFile(0)
  31. {
  32. TmpKey[0]='\0';
  33. ReadyDB(DB);
  34. }
  35. CacheDB::~CacheDB()
  36. {
  37. ReadyDB();
  38. delete DebFile;
  39. CloseFile();
  40. }
  41. // CacheDB::ReadyDB - Ready the DB2 /*{{{*/
  42. // ---------------------------------------------------------------------
  43. /* This opens the DB2 file for caching package information */
  44. bool CacheDB::ReadyDB(std::string const &DB)
  45. {
  46. int err;
  47. ReadOnly = _config->FindB("APT::FTPArchive::ReadOnlyDB",false);
  48. // Close the old DB
  49. if (Dbp != 0)
  50. Dbp->close(Dbp,0);
  51. /* Check if the DB was disabled while running and deal with a
  52. corrupted DB */
  53. if (DBFailed() == true)
  54. {
  55. _error->Warning(_("DB was corrupted, file renamed to %s.old"),DBFile.c_str());
  56. rename(DBFile.c_str(),(DBFile+".old").c_str());
  57. }
  58. DBLoaded = false;
  59. Dbp = 0;
  60. DBFile = std::string();
  61. if (DB.empty())
  62. return true;
  63. db_create(&Dbp, NULL, 0);
  64. if ((err = Dbp->open(Dbp, NULL, DB.c_str(), NULL, DB_BTREE,
  65. (ReadOnly?DB_RDONLY:DB_CREATE),
  66. 0644)) != 0)
  67. {
  68. if (err == DB_OLD_VERSION)
  69. {
  70. _error->Warning(_("DB is old, attempting to upgrade %s"),DBFile.c_str());
  71. err = Dbp->upgrade(Dbp, DB.c_str(), 0);
  72. if (!err)
  73. err = Dbp->open(Dbp, NULL, DB.c_str(), NULL, DB_HASH,
  74. (ReadOnly?DB_RDONLY:DB_CREATE), 0644);
  75. }
  76. // the database format has changed from DB_HASH to DB_BTREE in
  77. // apt 0.6.44
  78. if (err == EINVAL)
  79. {
  80. _error->Error(_("DB format is invalid. If you upgraded from an older version of apt, please remove and re-create the database."));
  81. }
  82. if (err)
  83. {
  84. Dbp = 0;
  85. return _error->Error(_("Unable to open DB file %s: %s"),DB.c_str(), db_strerror(err));
  86. }
  87. }
  88. DBFile = DB;
  89. DBLoaded = true;
  90. return true;
  91. }
  92. /*}}}*/
  93. // CacheDB::OpenFile - Open the file /*{{{*/
  94. // ---------------------------------------------------------------------
  95. /* */
  96. bool CacheDB::OpenFile()
  97. {
  98. // always close existing file first
  99. CloseFile();
  100. // open a new file
  101. Fd = new FileFd(FileName,FileFd::ReadOnly);
  102. if (_error->PendingError() == true)
  103. {
  104. CloseFile();
  105. return false;
  106. }
  107. return true;
  108. }
  109. /*}}}*/
  110. // CacheDB::CloseFile - Close the file /*{{{*/
  111. void CacheDB::CloseFile()
  112. {
  113. if(Fd != NULL)
  114. {
  115. delete Fd;
  116. Fd = NULL;
  117. }
  118. }
  119. /*}}}*/
  120. // CacheDB::OpenDebFile - Open a debfile /*{{{*/
  121. bool CacheDB::OpenDebFile()
  122. {
  123. // always close existing file first
  124. CloseDebFile();
  125. // first open the fd, then pass it to the debDebFile
  126. if(OpenFile() == false)
  127. return false;
  128. DebFile = new debDebFile(*Fd);
  129. if (_error->PendingError() == true)
  130. return false;
  131. return true;
  132. }
  133. /*}}}*/
  134. // CacheDB::CloseDebFile - Close a debfile again /*{{{*/
  135. void CacheDB::CloseDebFile()
  136. {
  137. CloseFile();
  138. if(DebFile != NULL)
  139. {
  140. delete DebFile;
  141. DebFile = NULL;
  142. }
  143. }
  144. /*}}}*/
  145. // CacheDB::GetFileStat - Get stats from the file /*{{{*/
  146. // ---------------------------------------------------------------------
  147. /* This gets the size from the database if it's there. If we need
  148. * to look at the file, also get the mtime from the file. */
  149. bool CacheDB::GetFileStat(bool const &doStat)
  150. {
  151. if ((CurStat.Flags & FlSize) == FlSize && doStat == false)
  152. return true;
  153. /* Get it from the file. */
  154. if (OpenFile() == false)
  155. return false;
  156. // Stat the file
  157. struct stat St;
  158. if (fstat(Fd->Fd(),&St) != 0)
  159. {
  160. CloseFile();
  161. return _error->Errno("fstat",
  162. _("Failed to stat %s"),FileName.c_str());
  163. }
  164. CurStat.FileSize = St.st_size;
  165. CurStat.mtime = htonl(St.st_mtime);
  166. CurStat.Flags |= FlSize;
  167. return true;
  168. }
  169. /*}}}*/
  170. // CacheDB::GetCurStatCompatOldFormat /*{{{*/
  171. // ---------------------------------------------------------------------
  172. /* Read the old (32bit FileSize) StateStore format from disk */
  173. bool CacheDB::GetCurStatCompatOldFormat()
  174. {
  175. InitQueryStats();
  176. Data.data = &CurStatOldFormat;
  177. Data.flags = DB_DBT_USERMEM;
  178. Data.ulen = sizeof(CurStatOldFormat);
  179. if (Get() == false)
  180. {
  181. CurStat.Flags = 0;
  182. } else {
  183. CurStat.Flags = CurStatOldFormat.Flags;
  184. CurStat.mtime = CurStatOldFormat.mtime;
  185. CurStat.FileSize = CurStatOldFormat.FileSize;
  186. memcpy(CurStat.MD5, CurStatOldFormat.MD5, sizeof(CurStat.MD5));
  187. memcpy(CurStat.SHA1, CurStatOldFormat.SHA1, sizeof(CurStat.SHA1));
  188. memcpy(CurStat.SHA256, CurStatOldFormat.SHA256, sizeof(CurStat.SHA256));
  189. }
  190. return true;
  191. }
  192. /*}}}*/
  193. // CacheDB::GetCurStatCompatOldFormat /*{{{*/
  194. // ---------------------------------------------------------------------
  195. /* Read the new (64bit FileSize) StateStore format from disk */
  196. bool CacheDB::GetCurStatCompatNewFormat()
  197. {
  198. InitQueryStats();
  199. Data.data = &CurStat;
  200. Data.flags = DB_DBT_USERMEM;
  201. Data.ulen = sizeof(CurStat);
  202. if (Get() == false)
  203. {
  204. CurStat.Flags = 0;
  205. }
  206. return true;
  207. }
  208. /*}}}*/
  209. // CacheDB::GetCurStat - Set the CurStat variable. /*{{{*/
  210. // ---------------------------------------------------------------------
  211. /* Sets the CurStat variable. Either to 0 if no database is used
  212. * or to the value in the database if one is used */
  213. bool CacheDB::GetCurStat()
  214. {
  215. memset(&CurStat,0,sizeof(CurStat));
  216. if (DBLoaded)
  217. {
  218. // do a first query to just get the size of the data on disk
  219. InitQueryStats();
  220. Data.data = &CurStat;
  221. Data.flags = DB_DBT_USERMEM;
  222. Data.ulen = 0;
  223. Get();
  224. if (Data.size == 0)
  225. {
  226. // nothing needs to be done, we just have not data for this deb
  227. }
  228. // check if the record is written in the old format (32bit filesize)
  229. else if(Data.size == sizeof(CurStatOldFormat))
  230. {
  231. GetCurStatCompatOldFormat();
  232. }
  233. else if(Data.size == sizeof(CurStat))
  234. {
  235. GetCurStatCompatNewFormat();
  236. } else {
  237. return _error->Error("Cache record size mismatch (%ul)", Data.size);
  238. }
  239. CurStat.Flags = ntohl(CurStat.Flags);
  240. CurStat.FileSize = ntohl(CurStat.FileSize);
  241. }
  242. return true;
  243. }
  244. /*}}}*/
  245. // CacheDB::GetFileInfo - Get all the info about the file /*{{{*/
  246. // ---------------------------------------------------------------------
  247. bool CacheDB::GetFileInfo(std::string const &FileName, bool const &DoControl, bool const &DoContents,
  248. bool const &GenContentsOnly, bool const DoSource, unsigned int const DoHashes,
  249. bool const &checkMtime)
  250. {
  251. this->FileName = FileName;
  252. if (GetCurStat() == false)
  253. return false;
  254. OldStat = CurStat;
  255. if (GetFileStat(checkMtime) == false)
  256. return false;
  257. /* if mtime changed, update CurStat from disk */
  258. if (checkMtime == true && OldStat.mtime != CurStat.mtime)
  259. CurStat.Flags = FlSize;
  260. Stats.Bytes += CurStat.FileSize;
  261. ++Stats.Packages;
  262. if ((DoControl && LoadControl() == false)
  263. || (DoContents && LoadContents(GenContentsOnly) == false)
  264. || (DoSource && LoadSource() == false)
  265. || (DoHashes != 0 && GetHashes(false, DoHashes) == false)
  266. )
  267. {
  268. return false;
  269. }
  270. return true;
  271. }
  272. /*}}}*/
  273. bool CacheDB::LoadSource() /*{{{*/
  274. {
  275. // Try to read the control information out of the DB.
  276. if ((CurStat.Flags & FlSource) == FlSource)
  277. {
  278. // Lookup the control information
  279. InitQuerySource();
  280. if (Get() == true && Dsc.TakeDsc(Data.data, Data.size) == true)
  281. {
  282. return true;
  283. }
  284. CurStat.Flags &= ~FlSource;
  285. }
  286. if (OpenFile() == false)
  287. return false;
  288. Stats.Misses++;
  289. if (Dsc.Read(FileName) == false)
  290. return false;
  291. if (Dsc.Length == 0)
  292. return _error->Error(_("Failed to read .dsc"));
  293. // Write back the control information
  294. InitQuerySource();
  295. if (Put(Dsc.Data.c_str(), Dsc.Length) == true)
  296. CurStat.Flags |= FlSource;
  297. return true;
  298. }
  299. /*}}}*/
  300. // CacheDB::LoadControl - Load Control information /*{{{*/
  301. // ---------------------------------------------------------------------
  302. /* */
  303. bool CacheDB::LoadControl()
  304. {
  305. // Try to read the control information out of the DB.
  306. if ((CurStat.Flags & FlControl) == FlControl)
  307. {
  308. // Lookup the control information
  309. InitQueryControl();
  310. if (Get() == true && Control.TakeControl(Data.data,Data.size) == true)
  311. return true;
  312. CurStat.Flags &= ~FlControl;
  313. }
  314. if(OpenDebFile() == false)
  315. return false;
  316. Stats.Misses++;
  317. if (Control.Read(*DebFile) == false)
  318. return false;
  319. if (Control.Control == 0)
  320. return _error->Error(_("Archive has no control record"));
  321. // Write back the control information
  322. InitQueryControl();
  323. if (Put(Control.Control,Control.Length) == true)
  324. CurStat.Flags |= FlControl;
  325. return true;
  326. }
  327. /*}}}*/
  328. // CacheDB::LoadContents - Load the File Listing /*{{{*/
  329. // ---------------------------------------------------------------------
  330. /* */
  331. bool CacheDB::LoadContents(bool const &GenOnly)
  332. {
  333. // Try to read the control information out of the DB.
  334. if ((CurStat.Flags & FlContents) == FlContents)
  335. {
  336. if (GenOnly == true)
  337. return true;
  338. // Lookup the contents information
  339. InitQueryContent();
  340. if (Get() == true)
  341. {
  342. if (Contents.TakeContents(Data.data,Data.size) == true)
  343. return true;
  344. }
  345. CurStat.Flags &= ~FlContents;
  346. }
  347. if(OpenDebFile() == false)
  348. return false;
  349. Stats.Misses++;
  350. if (Contents.Read(*DebFile) == false)
  351. return false;
  352. // Write back the control information
  353. InitQueryContent();
  354. if (Put(Contents.Data,Contents.CurSize) == true)
  355. CurStat.Flags |= FlContents;
  356. return true;
  357. }
  358. /*}}}*/
  359. // CacheDB::GetHashes - Get the hashs /*{{{*/
  360. static std::string bytes2hex(uint8_t *bytes, size_t length) {
  361. char buf[3];
  362. std::string space;
  363. space.reserve(length*2 + 1);
  364. for (size_t i = 0; i < length; i++) {
  365. snprintf(buf, sizeof(buf), "%02x", bytes[i]);
  366. space.append(buf);
  367. }
  368. return space;
  369. }
  370. static inline unsigned char xdig2num(char const &dig) {
  371. if (isdigit(dig)) return dig - '0';
  372. if ('a' <= dig && dig <= 'f') return dig - 'a' + 10;
  373. if ('A' <= dig && dig <= 'F') return dig - 'A' + 10;
  374. return 0;
  375. }
  376. static void hex2bytes(uint8_t *bytes, const char *hex, int length) {
  377. while (length-- > 0) {
  378. *bytes = 0;
  379. if (isxdigit(hex[0]) && isxdigit(hex[1])) {
  380. *bytes = xdig2num(hex[0]) * 16 + xdig2num(hex[1]);
  381. hex += 2;
  382. }
  383. bytes++;
  384. }
  385. }
  386. bool CacheDB::GetHashes(bool const GenOnly, unsigned int const DoHashes)
  387. {
  388. unsigned int FlHashes = DoHashes & (Hashes::MD5SUM | Hashes::SHA1SUM | Hashes::SHA256SUM | Hashes::SHA512SUM);
  389. HashesList.clear();
  390. if (FlHashes != 0)
  391. {
  392. if (OpenFile() == false)
  393. return false;
  394. Hashes hashes(FlHashes);
  395. if (Fd->Seek(0) == false || hashes.AddFD(*Fd, CurStat.FileSize) == false)
  396. return false;
  397. HashStringList hl = hashes.GetHashStringList();
  398. for (HashStringList::const_iterator hs = hl.begin(); hs != hl.end(); ++hs)
  399. {
  400. HashesList.push_back(*hs);
  401. if (strcasecmp(hs->HashType().c_str(), "SHA512") == 0)
  402. {
  403. Stats.SHA512Bytes += CurStat.FileSize;
  404. hex2bytes(CurStat.SHA512, hs->HashValue().data(), sizeof(CurStat.SHA512));
  405. CurStat.Flags |= FlSHA512;
  406. }
  407. else if (strcasecmp(hs->HashType().c_str(), "SHA256") == 0)
  408. {
  409. Stats.SHA256Bytes += CurStat.FileSize;
  410. hex2bytes(CurStat.SHA256, hs->HashValue().data(), sizeof(CurStat.SHA256));
  411. CurStat.Flags |= FlSHA256;
  412. }
  413. else if (strcasecmp(hs->HashType().c_str(), "SHA1") == 0)
  414. {
  415. Stats.SHA1Bytes += CurStat.FileSize;
  416. hex2bytes(CurStat.SHA1, hs->HashValue().data(), sizeof(CurStat.SHA1));
  417. CurStat.Flags |= FlSHA1;
  418. }
  419. else if (strcasecmp(hs->HashType().c_str(), "MD5Sum") == 0)
  420. {
  421. Stats.MD5Bytes += CurStat.FileSize;
  422. hex2bytes(CurStat.MD5, hs->HashValue().data(), sizeof(CurStat.MD5));
  423. CurStat.Flags |= FlMD5;
  424. }
  425. else if (strcasecmp(hs->HashType().c_str(), "Checksum-FileSize") == 0)
  426. {
  427. // we store it in a different field already
  428. }
  429. else
  430. return _error->Error("Got unknown unrequested hashtype %s", hs->HashType().c_str());
  431. }
  432. }
  433. if (GenOnly == true)
  434. return true;
  435. bool ret = true;
  436. #define PUSH_BACK_HASH(FLAG, TYPE, VALUE) \
  437. if ((CurStat.Flags & FLAG) == FLAG) \
  438. ret &= HashesList.push_back(HashString(TYPE, bytes2hex(VALUE, sizeof(VALUE))));
  439. PUSH_BACK_HASH(FlMD5, "MD5Sum", CurStat.MD5);
  440. PUSH_BACK_HASH(FlSHA1, "SHA1", CurStat.SHA1);
  441. PUSH_BACK_HASH(FlSHA256, "SHA256", CurStat.SHA256);
  442. PUSH_BACK_HASH(FlSHA512, "SHA512", CurStat.SHA512);
  443. return ret;
  444. }
  445. /*}}}*/
  446. // CacheDB::Finish - Write back the cache structure /*{{{*/
  447. // ---------------------------------------------------------------------
  448. /* */
  449. bool CacheDB::Finish()
  450. {
  451. // Optimize away some writes.
  452. if (CurStat.Flags == OldStat.Flags &&
  453. CurStat.mtime == OldStat.mtime)
  454. return true;
  455. // Write the stat information
  456. CurStat.Flags = htonl(CurStat.Flags);
  457. CurStat.FileSize = htonl(CurStat.FileSize);
  458. InitQueryStats();
  459. Put(&CurStat,sizeof(CurStat));
  460. CurStat.Flags = ntohl(CurStat.Flags);
  461. CurStat.FileSize = ntohl(CurStat.FileSize);
  462. return true;
  463. }
  464. /*}}}*/
  465. // CacheDB::Clean - Clean the Database /*{{{*/
  466. // ---------------------------------------------------------------------
  467. /* Tidy the database by removing files that no longer exist at all. */
  468. bool CacheDB::Clean()
  469. {
  470. if (DBLoaded == false)
  471. return true;
  472. /* I'm not sure what VERSION_MINOR should be here.. 2.4.14 certainly
  473. needs the lower one and 2.7.7 needs the upper.. */
  474. DBC *Cursor;
  475. if ((errno = Dbp->cursor(Dbp, NULL, &Cursor, 0)) != 0)
  476. return _error->Error(_("Unable to get a cursor"));
  477. DBT Key;
  478. DBT Data;
  479. memset(&Key,0,sizeof(Key));
  480. memset(&Data,0,sizeof(Data));
  481. while ((errno = Cursor->c_get(Cursor,&Key,&Data,DB_NEXT)) == 0)
  482. {
  483. const char *Colon = (char*)memrchr(Key.data, ':', Key.size);
  484. if (Colon)
  485. {
  486. if (stringcmp(Colon + 1, (char *)Key.data+Key.size,"st") == 0 ||
  487. stringcmp(Colon + 1, (char *)Key.data+Key.size,"cl") == 0 ||
  488. stringcmp(Colon + 1, (char *)Key.data+Key.size,"cs") == 0 ||
  489. stringcmp(Colon + 1, (char *)Key.data+Key.size,"cn") == 0)
  490. {
  491. std::string FileName = std::string((const char *)Key.data,Colon);
  492. if (FileExists(FileName) == true) {
  493. continue;
  494. }
  495. }
  496. }
  497. Cursor->c_del(Cursor,0);
  498. }
  499. int res = Dbp->compact(Dbp, NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
  500. if (res < 0)
  501. _error->Warning("compact failed with result %i", res);
  502. if(_config->FindB("Debug::APT::FTPArchive::Clean", false) == true)
  503. Dbp->stat_print(Dbp, 0);
  504. return true;
  505. }
  506. /*}}}*/