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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 && (errno == EEXIST || errno == EBUSY)) {
  274. msg_debug_pool_check ("checking %s to wait for db being initialized", lock_path);
  275. if (!rspamd_sqlite3_wait (pool, lock_path)) {
  276. g_set_error (err, rspamd_sqlite3_quark (),
  277. errno, "cannot create sqlite file %s: %s",
  278. path, strerror (errno));
  279. return NULL;
  280. }
  281. /* At this point we have database created */
  282. create = FALSE;
  283. has_lock = FALSE;
  284. }
  285. else {
  286. pid_t myself = getpid ();
  287. msg_debug_pool_check ("locking %s to block other processes", lock_path);
  288. (void) !write (lock_fd, &myself, sizeof (myself));
  289. g_assert (rspamd_file_lock (lock_fd, FALSE));
  290. has_lock = TRUE;
  291. }
  292. if ((rc = sqlite3_open_v2 (path, &sqlite,
  293. flags, NULL)) != SQLITE_OK) {
  294. #if SQLITE_VERSION_NUMBER >= 3008000
  295. g_set_error (err, rspamd_sqlite3_quark (),
  296. rc, "cannot open sqlite db %s: %s",
  297. path, sqlite3_errstr (rc));
  298. #else
  299. g_set_error (err, rspamd_sqlite3_quark (),
  300. rc, "cannot open sqlite db %s: %d",
  301. path, rc);
  302. #endif
  303. if (has_lock && lock_fd != -1) {
  304. msg_debug_pool_check ("removing lock from %s", lock_path);
  305. rspamd_file_unlock (lock_fd, FALSE);
  306. unlink (lock_path);
  307. close (lock_fd);
  308. }
  309. return NULL;
  310. }
  311. if (create && has_lock) {
  312. while ((rc = sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL)) != SQLITE_OK) {
  313. if (rc == SQLITE_BUSY) {
  314. struct timespec sleep_ts = {
  315. .tv_sec = 0,
  316. .tv_nsec = 1000000
  317. };
  318. nanosleep (&sleep_ts, NULL);
  319. continue;
  320. }
  321. msg_warn_pool_check ("WAL mode is not supported (%s), locking issues might occur",
  322. sqlite3_errmsg (sqlite));
  323. break;
  324. }
  325. if (sqlite3_exec (sqlite, exclusive_lock_sql, NULL, NULL, NULL) != SQLITE_OK) {
  326. msg_warn_pool_check ("cannot exclusively lock database to create schema: %s",
  327. sqlite3_errmsg (sqlite));
  328. }
  329. if (create_sql) {
  330. while ((rc = sqlite3_exec (sqlite, create_sql, NULL, NULL, NULL)) != SQLITE_OK) {
  331. if (rc == SQLITE_BUSY) {
  332. struct timespec sleep_ts = {
  333. .tv_sec = 0,
  334. .tv_nsec = 1000000
  335. };
  336. nanosleep (&sleep_ts, NULL);
  337. continue;
  338. }
  339. g_set_error (err, rspamd_sqlite3_quark (),
  340. -1, "cannot execute create sql `%s`: %s",
  341. create_sql, sqlite3_errmsg (sqlite));
  342. sqlite3_close (sqlite);
  343. rspamd_file_unlock (lock_fd, FALSE);
  344. unlink (lock_path);
  345. if (lock_fd != -1) {
  346. close (lock_fd);
  347. }
  348. return NULL;
  349. }
  350. }
  351. sqlite3_close (sqlite);
  352. /* Reopen in normal mode */
  353. msg_debug_pool_check ("reopening %s in normal mode", path);
  354. flags &= ~SQLITE_OPEN_CREATE;
  355. if ((rc = sqlite3_open_v2 (path, &sqlite,
  356. flags, NULL)) != SQLITE_OK) {
  357. #if SQLITE_VERSION_NUMBER >= 3008000
  358. g_set_error (err, rspamd_sqlite3_quark (),
  359. rc, "cannot open sqlite db after creation %s: %s",
  360. path, sqlite3_errstr (rc));
  361. #else
  362. g_set_error (err, rspamd_sqlite3_quark (),
  363. rc, "cannot open sqlite db after creation %s: %d",
  364. path, rc);
  365. #endif
  366. rspamd_file_unlock (lock_fd, FALSE);
  367. unlink (lock_path);
  368. if (lock_fd != -1) {
  369. close (lock_fd);
  370. }
  371. return NULL;
  372. }
  373. }
  374. else if (has_lock && version > 0) {
  375. /* Check user version */
  376. sqlite3_stmt *stmt = NULL;
  377. guint32 db_ver;
  378. GString *new_ver_sql;
  379. if (sqlite3_prepare (sqlite, db_version, -1, &stmt, NULL) != SQLITE_OK) {
  380. msg_warn_pool_check ("Cannot get user version pragma: %s",
  381. sqlite3_errmsg (sqlite));
  382. }
  383. else {
  384. if (sqlite3_step (stmt) != SQLITE_ROW) {
  385. msg_warn_pool_check ("Cannot get user version pragma, step failed: %s",
  386. sqlite3_errmsg (sqlite));
  387. sqlite3_finalize (stmt);
  388. }
  389. else {
  390. db_ver = sqlite3_column_int (stmt, 0);
  391. sqlite3_reset (stmt);
  392. sqlite3_finalize (stmt);
  393. if (version > db_ver) {
  394. msg_warn_pool_check ("Database version %ud is less than "
  395. "desired version %ud, run create script", db_ver,
  396. version);
  397. if (create_sql) {
  398. if (sqlite3_exec (sqlite, create_sql, NULL, NULL, NULL) != SQLITE_OK) {
  399. g_set_error (err, rspamd_sqlite3_quark (),
  400. -1, "cannot execute create sql `%s`: %s",
  401. create_sql, sqlite3_errmsg (sqlite));
  402. sqlite3_close (sqlite);
  403. rspamd_file_unlock (lock_fd, FALSE);
  404. unlink (lock_path);
  405. if (lock_fd != -1) {
  406. close (lock_fd);
  407. }
  408. return NULL;
  409. }
  410. }
  411. new_ver_sql = g_string_new ("PRAGMA user_version=");
  412. rspamd_printf_gstring (new_ver_sql, "%ud", version);
  413. if (sqlite3_exec (sqlite, new_ver_sql->str, NULL, NULL, NULL)
  414. != SQLITE_OK) {
  415. g_set_error (err, rspamd_sqlite3_quark (),
  416. -1, "cannot execute update version sql `%s`: %s",
  417. new_ver_sql->str, sqlite3_errmsg (sqlite));
  418. sqlite3_close (sqlite);
  419. rspamd_file_unlock (lock_fd, FALSE);
  420. unlink (lock_path);
  421. if (lock_fd != -1) {
  422. close (lock_fd);
  423. }
  424. g_string_free (new_ver_sql, TRUE);
  425. return NULL;
  426. }
  427. g_string_free (new_ver_sql, TRUE);
  428. }
  429. else if (db_ver > version) {
  430. msg_warn_pool_check ("Database version %ud is more than "
  431. "desired version %ud, this could cause"
  432. " unexpected behaviour", db_ver,
  433. version);
  434. }
  435. }
  436. }
  437. }
  438. while ((rc = sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL)) != SQLITE_OK) {
  439. if (rc == SQLITE_BUSY) {
  440. struct timespec sleep_ts = {
  441. .tv_sec = 0,
  442. .tv_nsec = 1000000
  443. };
  444. nanosleep (&sleep_ts, NULL);
  445. continue;
  446. }
  447. msg_warn_pool_check ("WAL mode is not supported (%s), locking issues might occur",
  448. sqlite3_errmsg (sqlite));
  449. break;
  450. }
  451. if (sqlite3_exec (sqlite, fsync_sql, NULL, NULL, NULL) != SQLITE_OK) {
  452. msg_warn_pool_check ("cannot set synchronous: %s",
  453. sqlite3_errmsg (sqlite));
  454. }
  455. if ((rc = sqlite3_exec (sqlite, foreign_keys, NULL, NULL, NULL)) !=
  456. SQLITE_OK) {
  457. msg_warn_pool_check ("cannot enable foreign keys: %s",
  458. sqlite3_errmsg (sqlite));
  459. }
  460. #if defined(__LP64__) || defined(_LP64)
  461. if ((rc = sqlite3_exec (sqlite, enable_mmap, NULL, NULL, NULL)) != SQLITE_OK) {
  462. msg_warn_pool_check ("cannot enable mmap: %s",
  463. sqlite3_errmsg (sqlite));
  464. }
  465. #endif
  466. if ((rc = sqlite3_exec (sqlite, other_pragmas, NULL, NULL, NULL)) !=
  467. SQLITE_OK) {
  468. msg_warn_pool_check ("cannot execute tuning pragmas: %s",
  469. sqlite3_errmsg (sqlite));
  470. }
  471. if (has_lock && lock_fd != -1) {
  472. msg_debug_pool_check ("removing lock from %s", lock_path);
  473. rspamd_file_unlock (lock_fd, FALSE);
  474. unlink (lock_path);
  475. close (lock_fd);
  476. }
  477. return sqlite;
  478. }
  479. gboolean
  480. rspamd_sqlite3_sync (sqlite3 *db, gint *wal_frames, gint *wal_checkpoints)
  481. {
  482. gint wf = 0, wc = 0, mode;
  483. #ifdef SQLITE_OPEN_WAL
  484. #ifdef SQLITE_CHECKPOINT_TRUNCATE
  485. mode = SQLITE_CHECKPOINT_TRUNCATE;
  486. #elif defined(SQLITE_CHECKPOINT_RESTART)
  487. mode = SQLITE_CHECKPOINT_RESTART;
  488. #elif defined(SQLITE_CHECKPOINT_FULL)
  489. mode = SQLITE_CHECKPOINT_FULL;
  490. #endif
  491. /* Perform wal checkpoint (might be long) */
  492. if (sqlite3_wal_checkpoint_v2 (db,
  493. NULL,
  494. mode,
  495. &wf,
  496. &wc) != SQLITE_OK) {
  497. return FALSE;
  498. }
  499. #endif
  500. if (wal_frames) {
  501. *wal_frames = wf;
  502. }
  503. if (wal_checkpoints) {
  504. *wal_checkpoints = wc;
  505. }
  506. return TRUE;
  507. }