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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. * Copyright 2024 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. int max_idx,
  29. GError **err)
  30. {
  31. int 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 rspamd_sqlite3_run_prstmt(rspamd_mempool_t *pool, sqlite3 *db, GArray *stmts,
  52. int idx, ...)
  53. {
  54. int retcode;
  55. va_list ap;
  56. sqlite3_stmt *stmt;
  57. int i, rowid, nargs, j;
  58. int64_t len;
  59. gpointer p;
  60. struct rspamd_sqlite3_prstmt *nst;
  61. const char *argtypes;
  62. if (idx < 0 || idx >= (int) stmts->len) {
  63. return -1;
  64. }
  65. nst = &g_array_index(stmts, struct rspamd_sqlite3_prstmt, idx);
  66. stmt = nst->stmt;
  67. g_assert(nst != NULL);
  68. msg_debug_pool("executing `%s`", nst->sql);
  69. argtypes = nst->args;
  70. sqlite3_clear_bindings(stmt);
  71. sqlite3_reset(stmt);
  72. va_start(ap, idx);
  73. nargs = 1;
  74. for (i = 0, rowid = 1; argtypes[i] != '\0'; i++) {
  75. switch (argtypes[i]) {
  76. case 'T':
  77. for (j = 0; j < nargs; j++, rowid++) {
  78. sqlite3_bind_text(stmt, rowid, va_arg(ap, const char *), -1,
  79. SQLITE_STATIC);
  80. }
  81. nargs = 1;
  82. break;
  83. case 'V':
  84. case 'B':
  85. for (j = 0; j < nargs; j++, rowid++) {
  86. len = va_arg(ap, int64_t);
  87. sqlite3_bind_text(stmt, rowid, va_arg(ap, const char *), len,
  88. SQLITE_STATIC);
  89. }
  90. nargs = 1;
  91. break;
  92. case 'I':
  93. for (j = 0; j < nargs; j++, rowid++) {
  94. sqlite3_bind_int64(stmt, rowid, va_arg(ap, int64_t));
  95. }
  96. nargs = 1;
  97. break;
  98. case 'S':
  99. for (j = 0; j < nargs; j++, rowid++) {
  100. sqlite3_bind_int(stmt, rowid, va_arg(ap, int));
  101. }
  102. nargs = 1;
  103. break;
  104. case '*':
  105. nargs = va_arg(ap, int);
  106. break;
  107. }
  108. }
  109. retcode = sqlite3_step(stmt);
  110. if (retcode == nst->result) {
  111. argtypes = nst->ret;
  112. for (i = 0; argtypes != NULL && argtypes[i] != '\0'; i++) {
  113. switch (argtypes[i]) {
  114. case 'T':
  115. *va_arg(ap, char **) = g_strdup(sqlite3_column_text(stmt, i));
  116. break;
  117. case 'I':
  118. *va_arg(ap, int64_t *) = sqlite3_column_int64(stmt, i);
  119. break;
  120. case 'S':
  121. *va_arg(ap, int *) = sqlite3_column_int(stmt, i);
  122. break;
  123. case 'L':
  124. *va_arg(ap, int64_t *) = sqlite3_last_insert_rowid(db);
  125. break;
  126. case 'B':
  127. len = sqlite3_column_bytes(stmt, i);
  128. g_assert(len >= 0);
  129. p = g_malloc(len);
  130. memcpy(p, sqlite3_column_blob(stmt, i), len);
  131. *va_arg(ap, int64_t *) = len;
  132. *va_arg(ap, gpointer *) = p;
  133. break;
  134. }
  135. }
  136. if (!(nst->flags & RSPAMD_SQLITE3_STMT_MULTIPLE)) {
  137. sqlite3_clear_bindings(stmt);
  138. sqlite3_reset(stmt);
  139. }
  140. va_end(ap);
  141. return SQLITE_OK;
  142. }
  143. else if (retcode != SQLITE_DONE && retcode != SQLITE_OK && retcode != SQLITE_ROW) {
  144. msg_warn_pool("failed to execute query %s: %d, %s", nst->sql,
  145. retcode, sqlite3_errmsg(db));
  146. }
  147. if (!(nst->flags & RSPAMD_SQLITE3_STMT_MULTIPLE)) {
  148. sqlite3_clear_bindings(stmt);
  149. sqlite3_reset(stmt);
  150. }
  151. va_end(ap);
  152. return retcode;
  153. }
  154. void rspamd_sqlite3_close_prstmt(sqlite3 *db, GArray *stmts)
  155. {
  156. unsigned int i;
  157. struct rspamd_sqlite3_prstmt *nst;
  158. for (i = 0; i < stmts->len; i++) {
  159. nst = &g_array_index(stmts, struct rspamd_sqlite3_prstmt, i);
  160. if (nst->stmt != NULL) {
  161. sqlite3_finalize(nst->stmt);
  162. }
  163. }
  164. g_array_free(stmts, TRUE);
  165. return;
  166. }
  167. static gboolean
  168. rspamd_sqlite3_wait(rspamd_mempool_t *pool, const char *lock)
  169. {
  170. int fd;
  171. pid_t pid;
  172. gssize r;
  173. struct timespec sleep_ts = {
  174. .tv_sec = 0,
  175. .tv_nsec = 1000000};
  176. while ((fd = open(lock, O_WRONLY | O_CREAT | O_EXCL, 00600)) == -1) {
  177. if (errno != EBUSY && errno != EEXIST) {
  178. msg_err_pool_check("cannot open lock file %s: %s", lock,
  179. strerror(errno));
  180. return FALSE;
  181. }
  182. fd = open(lock, O_RDONLY);
  183. if (fd == -1) {
  184. msg_err_pool_check("cannot open lock file %s: %s", lock,
  185. strerror(errno));
  186. return FALSE;
  187. }
  188. r = read(fd, &pid, sizeof(pid));
  189. if (r != sizeof(pid)) {
  190. msg_warn_pool_check("stale lock file %s, removing", lock);
  191. unlink(lock);
  192. close(fd);
  193. return TRUE;
  194. }
  195. /* Now check for process existence */
  196. if (pid == getpid()) {
  197. msg_warn_pool_check("lock file %s, belongs to me, removing", lock);
  198. unlink(lock);
  199. close(fd);
  200. return TRUE;
  201. }
  202. else if (kill(pid, 0) == -1) {
  203. if (errno == ESRCH) {
  204. /* Process is already dead */
  205. msg_warn_pool_check("stale lock file %s from pid: %P, removing",
  206. lock, pid);
  207. unlink(lock);
  208. close(fd);
  209. return TRUE;
  210. }
  211. }
  212. close(fd);
  213. if (nanosleep(&sleep_ts, NULL) == -1 && errno != EINTR) {
  214. msg_err_pool_check("cannot sleep open lock file %s: %s", lock,
  215. strerror(errno));
  216. return FALSE;
  217. }
  218. }
  219. unlink(lock);
  220. close(fd);
  221. return TRUE;
  222. }
  223. #define RSPAMD_SQLITE_MMAP_LIMIT 268435456
  224. #define RSPAMD_SQLITE_CACHE_SIZE 262144
  225. sqlite3 *
  226. rspamd_sqlite3_open_or_create(rspamd_mempool_t *pool, const char *path, const char *create_sql, unsigned int version, GError **err)
  227. {
  228. sqlite3 *sqlite;
  229. int rc, flags, lock_fd;
  230. char lock_path[PATH_MAX], dbdir[PATH_MAX], *pdir;
  231. static const char sqlite_wal[] =
  232. "PRAGMA journal_mode=\"wal\";"
  233. "PRAGMA wal_autocheckpoint = 16;"
  234. "PRAGMA journal_size_limit = 1536;",
  235. exclusive_lock_sql[] = "PRAGMA locking_mode=\"exclusive\";",
  236. fsync_sql[] = "PRAGMA synchronous=\"NORMAL\";",
  237. foreign_keys[] = "PRAGMA foreign_keys=\"ON\";",
  238. #if defined(__LP64__) || defined(_LP64)
  239. enable_mmap[] = "PRAGMA mmap_size=" G_STRINGIFY(RSPAMD_SQLITE_MMAP_LIMIT) ";",
  240. #endif
  241. other_pragmas[] = "PRAGMA read_uncommitted=\"ON\";"
  242. "PRAGMA cache_size=" G_STRINGIFY(RSPAMD_SQLITE_CACHE_SIZE) ";",
  243. db_version[] = "PRAGMA user_version;";
  244. gboolean create = FALSE, has_lock = FALSE;
  245. flags = SQLITE_OPEN_READWRITE;
  246. #ifdef SQLITE_OPEN_SHAREDCACHE
  247. flags |= SQLITE_OPEN_SHAREDCACHE;
  248. #endif
  249. #ifdef SQLITE_OPEN_WAL
  250. flags |= SQLITE_OPEN_WAL;
  251. #endif
  252. rspamd_strlcpy(dbdir, path, sizeof(dbdir));
  253. pdir = dirname(dbdir);
  254. if (access(pdir, W_OK) == -1) {
  255. g_set_error(err, rspamd_sqlite3_quark(),
  256. errno, "cannot open sqlite directory %s: %s",
  257. pdir, strerror(errno));
  258. return NULL;
  259. }
  260. rspamd_snprintf(lock_path, sizeof(lock_path), "%s.lock", path);
  261. if (access(path, R_OK) == -1) {
  262. flags |= SQLITE_OPEN_CREATE;
  263. create = TRUE;
  264. }
  265. rspamd_snprintf(lock_path, sizeof(lock_path), "%s.lock", path);
  266. lock_fd = open(lock_path, O_WRONLY | O_CREAT | O_EXCL, 00600);
  267. if (lock_fd == -1) {
  268. if (errno == EEXIST || errno == EBUSY) {
  269. msg_debug_pool_check("checking %s to wait for db being initialized", lock_path);
  270. if (!rspamd_sqlite3_wait(pool, lock_path)) {
  271. g_set_error(err, rspamd_sqlite3_quark(),
  272. errno, "cannot create sqlite file %s: %s",
  273. path, strerror(errno));
  274. return NULL;
  275. }
  276. /* At this point we have database created */
  277. create = FALSE;
  278. has_lock = FALSE;
  279. }
  280. else {
  281. g_set_error(err, rspamd_sqlite3_quark(),
  282. errno, "cannot lock sqlite file %s: %s",
  283. path, strerror(errno));
  284. }
  285. }
  286. else {
  287. pid_t myself = getpid();
  288. msg_debug_pool_check("locking %s to block other processes", lock_path);
  289. (void) write(lock_fd, &myself, sizeof(myself));
  290. g_assert(rspamd_file_lock(lock_fd, FALSE));
  291. has_lock = TRUE;
  292. }
  293. if ((rc = sqlite3_open_v2(path, &sqlite,
  294. flags, NULL)) != SQLITE_OK) {
  295. #if SQLITE_VERSION_NUMBER >= 3008000
  296. g_set_error(err, rspamd_sqlite3_quark(),
  297. rc, "cannot open sqlite db %s: %s",
  298. path, sqlite3_errstr(rc));
  299. #else
  300. g_set_error(err, rspamd_sqlite3_quark(),
  301. rc, "cannot open sqlite db %s: %d",
  302. path, rc);
  303. #endif
  304. if (has_lock && lock_fd != -1) {
  305. msg_debug_pool_check("removing lock from %s", lock_path);
  306. rspamd_file_unlock(lock_fd, FALSE);
  307. unlink(lock_path);
  308. close(lock_fd);
  309. }
  310. return NULL;
  311. }
  312. if (create && has_lock) {
  313. while ((rc = sqlite3_exec(sqlite, sqlite_wal, NULL, NULL, NULL)) != SQLITE_OK) {
  314. if (rc == SQLITE_BUSY) {
  315. struct timespec sleep_ts = {
  316. .tv_sec = 0,
  317. .tv_nsec = 1000000};
  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. nanosleep(&sleep_ts, NULL);
  336. continue;
  337. }
  338. g_set_error(err, rspamd_sqlite3_quark(),
  339. -1, "cannot execute create sql `%s`: %s",
  340. create_sql, sqlite3_errmsg(sqlite));
  341. sqlite3_close(sqlite);
  342. rspamd_file_unlock(lock_fd, FALSE);
  343. unlink(lock_path);
  344. if (lock_fd != -1) {
  345. close(lock_fd);
  346. }
  347. return NULL;
  348. }
  349. }
  350. sqlite3_close(sqlite);
  351. /* Reopen in normal mode */
  352. msg_debug_pool_check("reopening %s in normal mode", path);
  353. flags &= ~SQLITE_OPEN_CREATE;
  354. if ((rc = sqlite3_open_v2(path, &sqlite,
  355. flags, NULL)) != SQLITE_OK) {
  356. #if SQLITE_VERSION_NUMBER >= 3008000
  357. g_set_error(err, rspamd_sqlite3_quark(),
  358. rc, "cannot open sqlite db after creation %s: %s",
  359. path, sqlite3_errstr(rc));
  360. #else
  361. g_set_error(err, rspamd_sqlite3_quark(),
  362. rc, "cannot open sqlite db after creation %s: %d",
  363. path, rc);
  364. #endif
  365. rspamd_file_unlock(lock_fd, FALSE);
  366. unlink(lock_path);
  367. if (lock_fd != -1) {
  368. close(lock_fd);
  369. }
  370. return NULL;
  371. }
  372. }
  373. else if (has_lock && version > 0) {
  374. /* Check user version */
  375. sqlite3_stmt *stmt = NULL;
  376. uint32_t db_ver;
  377. GString *new_ver_sql;
  378. if (sqlite3_prepare(sqlite, db_version, -1, &stmt, NULL) != SQLITE_OK) {
  379. msg_warn_pool_check("Cannot get user version pragma: %s",
  380. sqlite3_errmsg(sqlite));
  381. }
  382. else {
  383. if (sqlite3_step(stmt) != SQLITE_ROW) {
  384. msg_warn_pool_check("Cannot get user version pragma, step failed: %s",
  385. sqlite3_errmsg(sqlite));
  386. sqlite3_finalize(stmt);
  387. }
  388. else {
  389. db_ver = sqlite3_column_int(stmt, 0);
  390. sqlite3_reset(stmt);
  391. sqlite3_finalize(stmt);
  392. if (version > db_ver) {
  393. msg_warn_pool_check("Database version %ud is less than "
  394. "desired version %ud, run create script",
  395. 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) != SQLITE_OK) {
  414. g_set_error(err, rspamd_sqlite3_quark(),
  415. -1, "cannot execute update version sql `%s`: %s",
  416. new_ver_sql->str, sqlite3_errmsg(sqlite));
  417. sqlite3_close(sqlite);
  418. rspamd_file_unlock(lock_fd, FALSE);
  419. unlink(lock_path);
  420. if (lock_fd != -1) {
  421. close(lock_fd);
  422. }
  423. g_string_free(new_ver_sql, TRUE);
  424. return NULL;
  425. }
  426. g_string_free(new_ver_sql, TRUE);
  427. }
  428. else if (db_ver > version) {
  429. msg_warn_pool_check("Database version %ud is more than "
  430. "desired version %ud, this could cause"
  431. " unexpected behaviour",
  432. 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. nanosleep(&sleep_ts, NULL);
  444. continue;
  445. }
  446. msg_warn_pool_check("WAL mode is not supported (%s), locking issues might occur",
  447. sqlite3_errmsg(sqlite));
  448. break;
  449. }
  450. if (sqlite3_exec(sqlite, fsync_sql, NULL, NULL, NULL) != SQLITE_OK) {
  451. msg_warn_pool_check("cannot set synchronous: %s",
  452. sqlite3_errmsg(sqlite));
  453. }
  454. if ((rc = sqlite3_exec(sqlite, foreign_keys, NULL, NULL, NULL)) !=
  455. SQLITE_OK) {
  456. msg_warn_pool_check("cannot enable foreign keys: %s",
  457. sqlite3_errmsg(sqlite));
  458. }
  459. #if defined(__LP64__) || defined(_LP64)
  460. if ((rc = sqlite3_exec(sqlite, enable_mmap, NULL, NULL, NULL)) != SQLITE_OK) {
  461. msg_warn_pool_check("cannot enable mmap: %s",
  462. sqlite3_errmsg(sqlite));
  463. }
  464. #endif
  465. if ((rc = sqlite3_exec(sqlite, other_pragmas, NULL, NULL, NULL)) !=
  466. SQLITE_OK) {
  467. msg_warn_pool_check("cannot execute tuning pragmas: %s",
  468. sqlite3_errmsg(sqlite));
  469. }
  470. if (has_lock && lock_fd != -1) {
  471. msg_debug_pool_check("removing lock from %s", lock_path);
  472. rspamd_file_unlock(lock_fd, FALSE);
  473. unlink(lock_path);
  474. close(lock_fd);
  475. }
  476. return sqlite;
  477. }
  478. gboolean
  479. rspamd_sqlite3_sync(sqlite3 *db, int *wal_frames, int *wal_checkpoints)
  480. {
  481. int wf = 0, wc = 0, mode;
  482. #ifdef SQLITE_OPEN_WAL
  483. #ifdef SQLITE_CHECKPOINT_TRUNCATE
  484. mode = SQLITE_CHECKPOINT_TRUNCATE;
  485. #elif defined(SQLITE_CHECKPOINT_RESTART)
  486. mode = SQLITE_CHECKPOINT_RESTART;
  487. #elif defined(SQLITE_CHECKPOINT_FULL)
  488. mode = SQLITE_CHECKPOINT_FULL;
  489. #endif
  490. /* Perform wal checkpoint (might be long) */
  491. if (sqlite3_wal_checkpoint_v2(db,
  492. NULL,
  493. mode,
  494. &wf,
  495. &wc) != SQLITE_OK) {
  496. return FALSE;
  497. }
  498. #endif
  499. if (wal_frames) {
  500. *wal_frames = wf;
  501. }
  502. if (wal_checkpoints) {
  503. *wal_checkpoints = wc;
  504. }
  505. return TRUE;
  506. }