cachedb.cc 14 KB

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