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.

sqlite_utils.c 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "libserver/logger.h"
  18. #include "libutil/sqlite_utils.h"
  19. #include "unix-std.h"
  20. static GQuark
  21. rspamd_sqlite3_quark (void)
  22. {
  23. return g_quark_from_static_string ("rspamd-sqlite3");
  24. }
  25. GArray*
  26. rspamd_sqlite3_init_prstmt (sqlite3 *db,
  27. struct rspamd_sqlite3_prstmt *init_stmt,
  28. gint max_idx,
  29. GError **err)
  30. {
  31. gint i;
  32. GArray *res;
  33. struct rspamd_sqlite3_prstmt *nst;
  34. res = g_array_sized_new (FALSE, TRUE, sizeof (struct rspamd_sqlite3_prstmt),
  35. max_idx);
  36. g_array_set_size (res, max_idx);
  37. for (i = 0; i < max_idx; i ++) {
  38. nst = &g_array_index (res, struct rspamd_sqlite3_prstmt, i);
  39. memcpy (nst, &init_stmt[i], sizeof (*nst));
  40. if (sqlite3_prepare_v2 (db, init_stmt[i].sql, -1,
  41. &nst->stmt, NULL) != SQLITE_OK) {
  42. g_set_error (err, rspamd_sqlite3_quark (),
  43. -1, "Cannot initialize prepared sql `%s`: %s",
  44. nst->sql, sqlite3_errmsg (db));
  45. rspamd_sqlite3_close_prstmt (db, res);
  46. return NULL;
  47. }
  48. }
  49. return res;
  50. }
  51. int
  52. rspamd_sqlite3_run_prstmt (rspamd_mempool_t *pool, sqlite3 *db, GArray *stmts,
  53. gint idx, ...)
  54. {
  55. gint retcode;
  56. va_list ap;
  57. sqlite3_stmt *stmt;
  58. gint i, rowid, nargs, j;
  59. gint64 len;
  60. gpointer p;
  61. struct rspamd_sqlite3_prstmt *nst;
  62. const char *argtypes;
  63. if (idx < 0 || idx >= (gint)stmts->len) {
  64. return -1;
  65. }
  66. nst = &g_array_index (stmts, struct rspamd_sqlite3_prstmt, idx);
  67. stmt = nst->stmt;
  68. g_assert (nst != NULL);
  69. msg_debug_pool ("executing `%s`", nst->sql);
  70. argtypes = nst->args;
  71. sqlite3_clear_bindings (stmt);
  72. sqlite3_reset (stmt);
  73. va_start (ap, idx);
  74. nargs = 1;
  75. for (i = 0, rowid = 1; argtypes[i] != '\0'; i ++) {
  76. switch (argtypes[i]) {
  77. case 'T':
  78. for (j = 0; j < nargs; j ++, rowid ++) {
  79. sqlite3_bind_text (stmt, rowid, va_arg (ap, const char*), -1,
  80. SQLITE_STATIC);
  81. }
  82. nargs = 1;
  83. break;
  84. case 'V':
  85. case 'B':
  86. for (j = 0; j < nargs; j ++, rowid ++) {
  87. len = va_arg (ap, gint64);
  88. sqlite3_bind_text (stmt, rowid, va_arg (ap, const char*), len,
  89. SQLITE_STATIC);
  90. }
  91. nargs = 1;
  92. break;
  93. case 'I':
  94. for (j = 0; j < nargs; j ++, rowid ++) {
  95. sqlite3_bind_int64 (stmt, rowid, va_arg (ap, gint64));
  96. }
  97. nargs = 1;
  98. break;
  99. case 'S':
  100. for (j = 0; j < nargs; j ++, rowid ++) {
  101. sqlite3_bind_int (stmt, rowid, va_arg (ap, gint));
  102. }
  103. nargs = 1;
  104. break;
  105. case '*':
  106. nargs = va_arg (ap, gint);
  107. break;
  108. }
  109. }
  110. retcode = sqlite3_step (stmt);
  111. if (retcode == nst->result) {
  112. argtypes = nst->ret;
  113. for (i = 0; argtypes != NULL && argtypes[i] != '\0'; i ++) {
  114. switch (argtypes[i]) {
  115. case 'T':
  116. *va_arg (ap, char**) = g_strdup (sqlite3_column_text (stmt, i));
  117. break;
  118. case 'I':
  119. *va_arg (ap, gint64*) = sqlite3_column_int64 (stmt, i);
  120. break;
  121. case 'S':
  122. *va_arg (ap, int*) = sqlite3_column_int (stmt, i);
  123. break;
  124. case 'L':
  125. *va_arg (ap, gint64*) = sqlite3_last_insert_rowid (db);
  126. break;
  127. case 'B':
  128. len = sqlite3_column_bytes (stmt, i);
  129. g_assert (len >= 0);
  130. p = g_malloc (len);
  131. memcpy (p, sqlite3_column_blob (stmt, i), len);
  132. *va_arg (ap, gint64*) = len;
  133. *va_arg (ap, gpointer*) = p;
  134. break;
  135. }
  136. }
  137. if (!(nst->flags & RSPAMD_SQLITE3_STMT_MULTIPLE)) {
  138. sqlite3_clear_bindings (stmt);
  139. sqlite3_reset (stmt);
  140. }
  141. va_end (ap);
  142. return SQLITE_OK;
  143. }
  144. else if (retcode != SQLITE_DONE && retcode != SQLITE_OK && retcode != SQLITE_ROW) {
  145. msg_warn_pool ("failed to execute query %s: %d, %s", nst->sql,
  146. retcode, sqlite3_errmsg (db));
  147. }
  148. if (!(nst->flags & RSPAMD_SQLITE3_STMT_MULTIPLE)) {
  149. sqlite3_clear_bindings (stmt);
  150. sqlite3_reset (stmt);
  151. }
  152. va_end (ap);
  153. return retcode;
  154. }
  155. void
  156. rspamd_sqlite3_close_prstmt (sqlite3 *db, GArray *stmts)
  157. {
  158. guint i;
  159. struct rspamd_sqlite3_prstmt *nst;
  160. for (i = 0; i < stmts->len; i++) {
  161. nst = &g_array_index (stmts, struct rspamd_sqlite3_prstmt, i);
  162. if (nst->stmt != NULL) {
  163. sqlite3_finalize (nst->stmt);
  164. }
  165. }
  166. g_array_free (stmts, TRUE);
  167. return;
  168. }
  169. static gboolean
  170. rspamd_sqlite3_wait (rspamd_mempool_t *pool, const gchar *lock)
  171. {
  172. gint fd;
  173. pid_t pid;
  174. gssize r;
  175. struct timespec sleep_ts = {
  176. .tv_sec = 0,
  177. .tv_nsec = 1000000
  178. };
  179. while ((fd = open (lock, O_WRONLY|O_CREAT|O_EXCL, 00600)) == -1) {
  180. if (errno != EBUSY && errno != EEXIST) {
  181. msg_err_pool_check ("cannot open lock file %s: %s", lock,
  182. strerror (errno));
  183. return FALSE;
  184. }
  185. fd = open (lock, O_RDONLY);
  186. if (fd == -1) {
  187. msg_err_pool_check ("cannot open lock file %s: %s", lock,
  188. strerror (errno));
  189. return FALSE;
  190. }
  191. r = read (fd, &pid, sizeof (pid));
  192. if (r != sizeof (pid)) {
  193. msg_warn_pool_check ("stale lock file %s, removing", lock);
  194. unlink (lock);
  195. close (fd);
  196. return TRUE;
  197. }
  198. /* Now check for process existence */
  199. if (pid == getpid ()) {
  200. msg_warn_pool_check ("lock file %s, belongs to me, removing", lock);
  201. unlink (lock);
  202. close (fd);
  203. return TRUE;
  204. }
  205. else if (kill (pid, 0) == -1) {
  206. if (errno == ESRCH) {
  207. /* Process is already dead */
  208. msg_warn_pool_check ("stale lock file %s from pid: %P, removing",
  209. lock, pid);
  210. unlink (lock);
  211. close (fd);
  212. return TRUE;
  213. }
  214. }
  215. close (fd);
  216. if (nanosleep (&sleep_ts, NULL) == -1 && errno != EINTR) {
  217. msg_err_pool_check ("cannot sleep open lock file %s: %s", lock,
  218. strerror (errno));
  219. return FALSE;
  220. }
  221. }
  222. unlink (lock);
  223. close (fd);
  224. return TRUE;
  225. }
  226. #define RSPAMD_SQLITE_MMAP_LIMIT 268435456
  227. #define RSPAMD_SQLITE_CACHE_SIZE 262144
  228. sqlite3 *
  229. rspamd_sqlite3_open_or_create (rspamd_mempool_t *pool, const gchar *path, const
  230. gchar *create_sql, guint version, GError **err)
  231. {
  232. sqlite3 *sqlite;
  233. gint rc, flags, lock_fd;
  234. gchar lock_path[PATH_MAX], dbdir[PATH_MAX], *pdir;
  235. static const char sqlite_wal[] =
  236. "PRAGMA journal_mode=\"wal\";"
  237. "PRAGMA wal_autocheckpoint = 16;"
  238. "PRAGMA journal_size_limit = 1536;",
  239. exclusive_lock_sql[] = "PRAGMA locking_mode=\"exclusive\";",
  240. fsync_sql[] = "PRAGMA synchronous=\"NORMAL\";",
  241. foreign_keys[] = "PRAGMA foreign_keys=\"ON\";",
  242. #if defined(__LP64__) || defined(_LP64)
  243. enable_mmap[] = "PRAGMA mmap_size="
  244. G_STRINGIFY(RSPAMD_SQLITE_MMAP_LIMIT) ";",
  245. #endif
  246. other_pragmas[] = "PRAGMA read_uncommitted=\"ON\";"
  247. "PRAGMA cache_size="
  248. G_STRINGIFY(RSPAMD_SQLITE_CACHE_SIZE) ";",
  249. db_version[] = "PRAGMA user_version;";
  250. gboolean create = FALSE, has_lock = FALSE;
  251. flags = SQLITE_OPEN_READWRITE;
  252. #ifdef SQLITE_OPEN_SHAREDCACHE
  253. flags |= SQLITE_OPEN_SHAREDCACHE;
  254. #endif
  255. #ifdef SQLITE_OPEN_WAL
  256. flags |= SQLITE_OPEN_WAL;
  257. #endif
  258. rspamd_strlcpy (dbdir, path, sizeof (dbdir));
  259. pdir = dirname (dbdir);
  260. if (access (pdir, W_OK) == -1) {
  261. g_set_error (err, rspamd_sqlite3_quark (),
  262. errno, "cannot open sqlite directory %s: %s",
  263. pdir, strerror (errno));
  264. return NULL;
  265. }
  266. rspamd_snprintf (lock_path, sizeof (lock_path), "%s.lock", path);
  267. if (access (path, R_OK) == -1) {
  268. flags |= SQLITE_OPEN_CREATE;
  269. create = TRUE;
  270. }
  271. rspamd_snprintf (lock_path, sizeof (lock_path), "%s.lock", path);
  272. lock_fd = open (lock_path, O_WRONLY|O_CREAT|O_EXCL, 00600);
  273. if (lock_fd == -1) {
  274. if (errno == EEXIST || errno == EBUSY) {
  275. msg_debug_pool_check ("checking %s to wait for db being initialized", lock_path);
  276. if (!rspamd_sqlite3_wait(pool, lock_path)) {
  277. g_set_error(err, rspamd_sqlite3_quark(),
  278. errno, "cannot create sqlite file %s: %s",
  279. path, strerror(errno));
  280. return NULL;
  281. }
  282. /* At this point we have database created */
  283. create = FALSE;
  284. has_lock = FALSE;
  285. }
  286. else {
  287. g_set_error(err, rspamd_sqlite3_quark(),
  288. errno, "cannot lock sqlite file %s: %s",
  289. path, strerror(errno));
  290. }
  291. }
  292. else {
  293. pid_t myself = getpid ();
  294. msg_debug_pool_check ("locking %s to block other processes", lock_path);
  295. (void)write (lock_fd, &myself, sizeof (myself));
  296. g_assert (rspamd_file_lock (lock_fd, FALSE));
  297. has_lock = TRUE;
  298. }
  299. if ((rc = sqlite3_open_v2 (path, &sqlite,
  300. flags, NULL)) != SQLITE_OK) {
  301. #if SQLITE_VERSION_NUMBER >= 3008000
  302. g_set_error (err, rspamd_sqlite3_quark (),
  303. rc, "cannot open sqlite db %s: %s",
  304. path, sqlite3_errstr (rc));
  305. #else
  306. g_set_error (err, rspamd_sqlite3_quark (),
  307. rc, "cannot open sqlite db %s: %d",
  308. path, rc);
  309. #endif
  310. if (has_lock && lock_fd != -1) {
  311. msg_debug_pool_check ("removing lock from %s", lock_path);
  312. rspamd_file_unlock (lock_fd, FALSE);
  313. unlink (lock_path);
  314. close (lock_fd);
  315. }
  316. return NULL;
  317. }
  318. if (create && has_lock) {
  319. while ((rc = sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL)) != SQLITE_OK) {
  320. if (rc == SQLITE_BUSY) {
  321. struct timespec sleep_ts = {
  322. .tv_sec = 0,
  323. .tv_nsec = 1000000
  324. };
  325. nanosleep (&sleep_ts, NULL);
  326. continue;
  327. }
  328. msg_warn_pool_check ("WAL mode is not supported (%s), locking issues might occur",
  329. sqlite3_errmsg (sqlite));
  330. break;
  331. }
  332. if (sqlite3_exec (sqlite, exclusive_lock_sql, NULL, NULL, NULL) != SQLITE_OK) {
  333. msg_warn_pool_check ("cannot exclusively lock database to create schema: %s",
  334. sqlite3_errmsg (sqlite));
  335. }
  336. if (create_sql) {
  337. while ((rc = sqlite3_exec (sqlite, create_sql, NULL, NULL, NULL)) != SQLITE_OK) {
  338. if (rc == SQLITE_BUSY) {
  339. struct timespec sleep_ts = {
  340. .tv_sec = 0,
  341. .tv_nsec = 1000000
  342. };
  343. nanosleep (&sleep_ts, NULL);
  344. continue;
  345. }
  346. g_set_error (err, rspamd_sqlite3_quark (),
  347. -1, "cannot execute create sql `%s`: %s",
  348. create_sql, sqlite3_errmsg (sqlite));
  349. sqlite3_close (sqlite);
  350. rspamd_file_unlock (lock_fd, FALSE);
  351. unlink (lock_path);
  352. if (lock_fd != -1) {
  353. close (lock_fd);
  354. }
  355. return NULL;
  356. }
  357. }
  358. sqlite3_close (sqlite);
  359. /* Reopen in normal mode */
  360. msg_debug_pool_check ("reopening %s in normal mode", path);
  361. flags &= ~SQLITE_OPEN_CREATE;
  362. if ((rc = sqlite3_open_v2 (path, &sqlite,
  363. flags, NULL)) != SQLITE_OK) {
  364. #if SQLITE_VERSION_NUMBER >= 3008000
  365. g_set_error (err, rspamd_sqlite3_quark (),
  366. rc, "cannot open sqlite db after creation %s: %s",
  367. path, sqlite3_errstr (rc));
  368. #else
  369. g_set_error (err, rspamd_sqlite3_quark (),
  370. rc, "cannot open sqlite db after creation %s: %d",
  371. path, rc);
  372. #endif
  373. rspamd_file_unlock (lock_fd, FALSE);
  374. unlink (lock_path);
  375. if (lock_fd != -1) {
  376. close (lock_fd);
  377. }
  378. return NULL;
  379. }
  380. }
  381. else if (has_lock && version > 0) {
  382. /* Check user version */
  383. sqlite3_stmt *stmt = NULL;
  384. guint32 db_ver;
  385. GString *new_ver_sql;
  386. if (sqlite3_prepare (sqlite, db_version, -1, &stmt, NULL) != SQLITE_OK) {
  387. msg_warn_pool_check ("Cannot get user version pragma: %s",
  388. sqlite3_errmsg (sqlite));
  389. }
  390. else {
  391. if (sqlite3_step (stmt) != SQLITE_ROW) {
  392. msg_warn_pool_check ("Cannot get user version pragma, step failed: %s",
  393. sqlite3_errmsg (sqlite));
  394. sqlite3_finalize (stmt);
  395. }
  396. else {
  397. db_ver = sqlite3_column_int (stmt, 0);
  398. sqlite3_reset (stmt);
  399. sqlite3_finalize (stmt);
  400. if (version > db_ver) {
  401. msg_warn_pool_check ("Database version %ud is less than "
  402. "desired version %ud, run create script", db_ver,
  403. version);
  404. if (create_sql) {
  405. if (sqlite3_exec (sqlite, create_sql, NULL, NULL, NULL) != SQLITE_OK) {
  406. g_set_error (err, rspamd_sqlite3_quark (),
  407. -1, "cannot execute create sql `%s`: %s",
  408. create_sql, sqlite3_errmsg (sqlite));
  409. sqlite3_close (sqlite);
  410. rspamd_file_unlock (lock_fd, FALSE);
  411. unlink (lock_path);
  412. if (lock_fd != -1) {
  413. close (lock_fd);
  414. }
  415. return NULL;
  416. }
  417. }
  418. new_ver_sql = g_string_new ("PRAGMA user_version=");
  419. rspamd_printf_gstring (new_ver_sql, "%ud", version);
  420. if (sqlite3_exec (sqlite, new_ver_sql->str, NULL, NULL, NULL)
  421. != SQLITE_OK) {
  422. g_set_error (err, rspamd_sqlite3_quark (),
  423. -1, "cannot execute update version sql `%s`: %s",
  424. new_ver_sql->str, sqlite3_errmsg (sqlite));
  425. sqlite3_close (sqlite);
  426. rspamd_file_unlock (lock_fd, FALSE);
  427. unlink (lock_path);
  428. if (lock_fd != -1) {
  429. close (lock_fd);
  430. }
  431. g_string_free (new_ver_sql, TRUE);
  432. return NULL;
  433. }
  434. g_string_free (new_ver_sql, TRUE);
  435. }
  436. else if (db_ver > version) {
  437. msg_warn_pool_check ("Database version %ud is more than "
  438. "desired version %ud, this could cause"
  439. " unexpected behaviour", db_ver,
  440. version);
  441. }
  442. }
  443. }
  444. }
  445. while ((rc = sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL)) != SQLITE_OK) {
  446. if (rc == SQLITE_BUSY) {
  447. struct timespec sleep_ts = {
  448. .tv_sec = 0,
  449. .tv_nsec = 1000000
  450. };
  451. nanosleep (&sleep_ts, NULL);
  452. continue;
  453. }
  454. msg_warn_pool_check ("WAL mode is not supported (%s), locking issues might occur",
  455. sqlite3_errmsg (sqlite));
  456. break;
  457. }
  458. if (sqlite3_exec (sqlite, fsync_sql, NULL, NULL, NULL) != SQLITE_OK) {
  459. msg_warn_pool_check ("cannot set synchronous: %s",
  460. sqlite3_errmsg (sqlite));
  461. }
  462. if ((rc = sqlite3_exec (sqlite, foreign_keys, NULL, NULL, NULL)) !=
  463. SQLITE_OK) {
  464. msg_warn_pool_check ("cannot enable foreign keys: %s",
  465. sqlite3_errmsg (sqlite));
  466. }
  467. #if defined(__LP64__) || defined(_LP64)
  468. if ((rc = sqlite3_exec (sqlite, enable_mmap, NULL, NULL, NULL)) != SQLITE_OK) {
  469. msg_warn_pool_check ("cannot enable mmap: %s",
  470. sqlite3_errmsg (sqlite));
  471. }
  472. #endif
  473. if ((rc = sqlite3_exec (sqlite, other_pragmas, NULL, NULL, NULL)) !=
  474. SQLITE_OK) {
  475. msg_warn_pool_check ("cannot execute tuning pragmas: %s",
  476. sqlite3_errmsg (sqlite));
  477. }
  478. if (has_lock && lock_fd != -1) {
  479. msg_debug_pool_check ("removing lock from %s", lock_path);
  480. rspamd_file_unlock (lock_fd, FALSE);
  481. unlink (lock_path);
  482. close (lock_fd);
  483. }
  484. return sqlite;
  485. }
  486. gboolean
  487. rspamd_sqlite3_sync (sqlite3 *db, gint *wal_frames, gint *wal_checkpoints)
  488. {
  489. gint wf = 0, wc = 0, mode;
  490. #ifdef SQLITE_OPEN_WAL
  491. #ifdef SQLITE_CHECKPOINT_TRUNCATE
  492. mode = SQLITE_CHECKPOINT_TRUNCATE;
  493. #elif defined(SQLITE_CHECKPOINT_RESTART)
  494. mode = SQLITE_CHECKPOINT_RESTART;
  495. #elif defined(SQLITE_CHECKPOINT_FULL)
  496. mode = SQLITE_CHECKPOINT_FULL;
  497. #endif
  498. /* Perform wal checkpoint (might be long) */
  499. if (sqlite3_wal_checkpoint_v2 (db,
  500. NULL,
  501. mode,
  502. &wf,
  503. &wc) != SQLITE_OK) {
  504. return FALSE;
  505. }
  506. #endif
  507. if (wal_frames) {
  508. *wal_frames = wf;
  509. }
  510. if (wal_checkpoints) {
  511. *wal_checkpoints = wc;
  512. }
  513. return TRUE;
  514. }