misc: a few portability tweaks
[rb-79.git] / db-sqlite3.c
blob1201eaec5b1860aad8b7b5f3aec6c2d4817ccf95
1 /*
2 * Copyright (c) 2017-2018, De Rais <derais@cock.li>
4 * Permission to use, copy, modify, and/or distribute this software for
5 * any purpose with or without fee is hereby granted, provided that the
6 * above copyright notice and this permission notice appear in all
7 * copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
10 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
11 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
12 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
13 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
14 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
15 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16 * PERFORMANCE OF THIS SOFTWARE.
18 #include <limits.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <time.h>
25 #include <sqlite3.h>
27 #include "macros.h"
28 #include "rb79.h"
30 #define TRY_BIND_T(s, db, i, v) \
31 do { \
32 if ((sqlite3_bind_text((s), \
33 sqlite3_bind_parameter_index((s), (i)), \
34 (v), -1, SQLITE_STATIC)) \
35 != SQLITE_OK) { \
36 ERROR_MESSAGE("sqlite3_bind_text(): cannot bind " \
37 "%s := \"%s\": %s", \
38 (i), (v), \
39 sqlite3_errmsg(db)); \
40 goto done; \
41 } \
42 } while (0)
44 #define TRY_BIND_I(s, db, i, v) \
45 do { \
46 if ((sret = sqlite3_bind_int64((s), \
47 sqlite3_bind_parameter_index((s), \
48 (i)), \
49 (sqlite3_int64) (v))) != \
50 SQLITE_OK) { \
51 ERROR_MESSAGE("sqlite3_bind_int64(): cannot bind " \
52 "%s := %lld: %s", \
53 (i), ((long long int) (v)), \
54 sqlite3_errmsg(db)); \
55 goto done; \
56 } \
57 } while (0)
59 #define TRY_MAKE_STATEMENT_ARRAY(name) \
60 do { \
61 if (!(board_ ## name ## _stmt = \
62 calloc(conf->boards_num, \
63 sizeof *board_ ## name ## _stmt))) \
64 { \
65 PERROR_MESSAGE("calloc"); \
66 goto done; \
67 } \
68 } while (0)
70 #define TRY_PREPARE_FOR_BOARD(j, name) \
71 do { \
72 if (sqlite3_prepare_v2(board_dbs[j], \
73 board_ ## name ## _txt, -1, \
74 &board_ ## name ## _stmt[j], \
75 0) != SQLITE_OK) { \
76 ERROR_MESSAGE("Preparing statement failed: %s", \
77 sqlite3_errmsg(board_dbs[j])); \
78 goto done; \
79 } \
80 } while (0)
82 #define FINALIZE_FOR_BOARD(j, name) \
83 do { \
84 if (board_ ## name ## _stmt) { \
85 sqlite3_finalize(board_ ## name ## _stmt[j]); \
86 board_ ## name ## _stmt[j] = 0; \
87 } \
88 } while (0)
90 #define CLEAN_UP_STATEMENT_ARRAY(name) \
91 do { \
92 free(board_ ## name ## _stmt); \
93 board_ ## name ## _stmt = 0; \
94 } while (0);
96 #define EXFILTRATE_TEXT(s, n, str, len) \
97 do { \
98 char *tmp = (char *) sqlite3_column_text(s, n); \
99 if (tmp) { \
100 str = strdup(tmp); \
101 len = sqlite3_column_bytes(s, n); \
103 else { \
104 str = 0; \
105 len = 0; \
107 } while (0)
109 /* Preparing DBs */
110 static const char *make_comment_table =
111 "create table if not exists comments \n" /* */
112 " (id integer primary key autoincrement,\n" /* */
113 " thread_closed integer default 0, \n" /* */
114 " thread_full integer default 0, \n" /* */
115 " thread_stickied integer default 0, \n" /* */
116 " thread_last_reply integer default 0, \n" /* */
117 " thread_bumpable integer default 1, \n" /* */
118 " in_thread integer default 0, \n" /* */
119 " ip text default '0.0.0.0', \n" /* */
120 " date integer default 0, \n" /* */
121 " name text default 'Anonymous', \n" /* */
122 " tripcode text default '', \n" /* */
123 " email text default '', \n" /* */
124 " comment text default '', \n" /* */
125 " subject text default '', \n" /* */
126 " users_filename text default '', \n" /* */
127 " system_full_path text default '', \n" /* */
128 " system_thumb_path text default '', \n" /* */
129 " file_info text default '' \n" /* */
130 " );"; /* */
131 static const char *make_ban_table =
132 "create table if not exists bans \n" /* */
133 " (id integer primary key autoincrement,\n" /* */
134 " ip_start text default '', \n" /* */
135 " ip_end text default '', \n" /* */
136 " date_start integer default 0, \n" /* */
137 " date_end integer default 0, \n" /* */
138 " reason text default 'No reason given' \n" /* */
139 " );"; /* */
140 static const char *make_cooldown_table =
141 "create table if not exists cooldowns \n" /* */
142 " (ip text primary key, \n" /* */
143 " cooldown_expiry integer default 0 \n" /* */
144 " );"; /* */
145 /* Are you banned globally? */
146 static const char *global_check_ban_txt =
147 "select date_end, reason from bans \n" /* */
148 " where @ip between ip_start and ip_end \n" /* */
149 " and date_end > @now; \n"; /* */
150 static sqlite3_stmt *global_check_ban_stmt;
152 /* Create a global ban */
153 static const char *global_insert_ban_txt =
154 "insert into bans ( ip_start, \n" /* */
155 " ip_end, \n" /* */
156 " date_start, \n" /* */
157 " date_end, \n" /* */
158 " reason) \n" /* */
159 " values (@ip_start, \n" /* */
160 " @ip_end, \n" /* */
161 " @date_start, \n" /* */
162 " @date_end, \n" /* */
163 " @reason); \n"; /* */
164 static sqlite3_stmt *global_insert_ban_stmt;
166 /* Are you banned? */
167 static const char *board_check_ban_txt =
168 "select date_end, reason from bans \n" /* */
169 " where @ip between ip_start and ip_end \n" /* */
170 " and date_end > @now; \n"; /* */
171 static sqlite3_stmt **board_check_ban_stmt;
173 /* When was your last post? */
174 static const char *board_check_cooldown_txt =
175 "select cooldown_expiry from cooldowns \n" /* */
176 "where ip is @ip;";
177 static sqlite3_stmt **board_check_cooldown_stmt;
179 /* That thread, uhh, exists, right? */
180 static const char *board_check_thread_exists_txt =
181 "select thread_closed, thread_full from comments \n" /* */
182 "where id is @thread; \n";
183 static sqlite3_stmt **board_check_thread_exists_stmt;
185 /* How many replies are in this thread? */
186 static const char *board_count_posts_txt =
187 "select count(*) from comments \n" /* */
188 "where coalesce(in_thread, id) is @thread; \n";
189 static sqlite3_stmt **board_count_posts_stmt;
191 /* Delete a thread */
192 static const char *board_delete_thread_txt =
193 "delete from comments where coalesce(in_thread, id) is @thread;";
194 static sqlite3_stmt **board_delete_thread_stmt;
196 /* Delete a post */
197 static const char *board_delete_post_txt =
198 "delete from comments where id is @id;";
199 static sqlite3_stmt **board_delete_post_stmt;
201 /* Get the thread for a post */
202 static const char *board_find_containing_thread_txt =
203 "select coalesce(in_thread, id) from comments \n" /* */
204 "where id is @id order by id; \n";
205 static sqlite3_stmt **board_find_containing_thread_stmt;
207 /* Get the subject of a thread */
208 static const char *board_get_subject_txt =
209 "select subject from comments where id is @thread;";
210 static sqlite3_stmt **board_get_subject_stmt;
212 /* Get the contents of a thread */
213 static const char *board_get_thread_contents_txt =
214 "select id, date, name, subject, email, \n" /* */
215 " tripcode, comment, users_filename, \n" /* */
216 " system_full_path, system_thumb_path, \n" /* */
217 " file_info, ip, thread_closed, \n" /* */
218 " thread_stickied from comments \n" /* */
219 "where coalesce(in_thread, id) is @thread;\n"; /* */
220 static sqlite3_stmt **board_get_thread_contents_stmt;
222 /* Get enough of a thread to write a summary on a board page */
223 static const char *board_get_thread_summary_txt =
224 "select id, date, name, subject, email, \n" /* */
225 " tripcode, comment, users_filename, \n" /* */
226 " system_full_path, system_thumb_path, \n" /* */
227 " file_info, ip, thread_closed, \n" /* */
228 " thread_stickied from comments where \n" /* */
229 " coalesce(in_thread, id) is @thread \n" /* */
230 " and (id in ( \n" /* */
231 " select id from comments where \n" /* */
232 " id is @thread or \n" /* */
233 " in_thread is @thread \n" /* */
234 " order by id desc limit 3 \n" /* */
235 " ) or id is @thread) order by id asc;\n"; /* */
236 static sqlite3_stmt **board_get_thread_summary_stmt;
238 /* Get the contents of a post */
239 static const char *board_get_post_contents_txt =
240 "select id, date, name, subject, email, \n" /* */
241 " tripcode, comment, users_filename, \n" /* */
242 " system_full_path, system_thumb_path, \n" /* */
243 " file_info, ip, in_thread, \n" /* */
244 " thread_closed, thread_stickied \n" /* */
245 " from comments \n" /* */
246 "where id is @post; \n"; /* */
247 static sqlite3_stmt **board_get_post_contents_stmt;
249 /* Create a global ban */
250 static const char *board_insert_ban_txt =
251 "insert into bans ( ip_start, \n" /* */
252 " ip_end, \n" /* */
253 " date_start, \n" /* */
254 " date_end, \n" /* */
255 " reason) \n" /* */
256 " values (@ip_start, \n" /* */
257 " @ip_end, \n" /* */
258 " @date_start, \n" /* */
259 " @date_end, \n" /* */
260 " @reason); \n"; /* */
261 static sqlite3_stmt **board_insert_ban_stmt;
263 /* Make a post/thread/whatever */
264 static const char *board_insert_comment_txt =
265 "insert into comments ( ip, \n" /* */
266 " date, \n" /* */
267 " thread_last_reply,\n" /* */
268 " in_thread, \n" /* */
269 " name, \n" /* */
270 " tripcode, \n" /* */
271 " email, \n" /* */
272 " subject, \n" /* */
273 " comment, \n" /* */
274 " users_filename, \n" /* */
275 " system_full_path, \n" /* */
276 " system_thumb_path \n" /* */
277 " ) \n" /* */
278 " values (@ip, \n" /* */
279 " @date, \n" /* */
280 " @date, \n" /* */
281 " @in_thread, \n" /* */
282 " @name, \n" /* */
283 " @tripcode, \n" /* */
284 " @email, \n" /* */
285 " @subject, \n" /* */
286 " @comment, \n" /* */
287 " @users_filename, \n" /* */
288 " @system_full_path, \n" /* */
289 " @system_thumb_path \n" /* */
290 " ); \n"; /* */
291 static sqlite3_stmt **board_insert_comment_stmt;
293 /* Insert comment part II: adjust the thread */
294 static const char *board_insert_comment_II_txt =
295 "update comments set \n" /* */
296 " thread_last_reply = \n" /* */
297 " (case when @should_bump is 1 and \n" /* */
298 " thread_bumpable is 1 then \n" /* */
299 " @date \n" /* */
300 " else \n" /* */
301 " thread_last_reply \n" /* */
302 " end), \n" /* */
303 " \n" /* */
304 " thread_bumpable = \n" /* */
305 " (case when (select count(*) \n" /* */
306 " from comments \n" /* */
307 " where in_thread is @in_thread) \n" /* */
308 " >= 300 then \n" /* */
309 " 0 \n" /* */
310 " else \n" /* */
311 " thread_bumpable \n" /* */
312 " end), \n" /* */
313 " \n" /* */
314 " thread_full = \n" /* */
315 " (case when (select count(*) \n" /* */
316 " from comments \n" /* */
317 " where in_thread is @in_thread) \n" /* */
318 " >= 500 then \n" /* */
319 " 0 \n" /* */
320 " else \n" /* */
321 " thread_full \n" /* */
322 " end) \n" /* */
323 " where id is @in_thread; \n"; /* */
324 static sqlite3_stmt **board_insert_comment_II_stmt;
326 /* Find all threads on this board */
327 static const char *board_list_threads_txt =
328 "select id from comments where in_thread is NULL\n" /* */
329 "order by thread_stickied desc, \n" /* */
330 " thread_last_reply desc; \n"; /* */
331 static sqlite3_stmt **board_list_threads_stmt;
333 /* Cooldown */
334 static const char *board_set_cooldown_txt =
335 "insert or replace into cooldowns (ip, \n" /* */
336 " cooldown_expiry) \n" /* */
337 "values (@ip, @cooldown_expiry); "; /* */
338 static sqlite3_stmt **board_set_cooldown_stmt;
340 /* Change the sorts of things that moderation needs */
341 static const char *board_update_by_moderation_txt =
342 "update comments set \n" /* */
343 " comment = @comment, \n" /* */
344 " thread_stickied = @thread_stickied, \n" /* */
345 " thread_closed = @thread_closed \n" /* */
346 " where id is @id; \n"; /* */
347 static sqlite3_stmt **board_update_by_moderation_stmt;
349 /* Update the file_info field for a post (after creation) */
350 static const char *board_update_file_info_txt =
351 "update comments set \n" /* */
352 " file_info = @file_info, \n" /* */
353 " system_full_path = @system_full_path, \n" /* */
354 " system_thumb_path = @system_thumb_path \n" /* */
355 " where id is @id; \n"; /* */
356 static sqlite3_stmt **board_update_file_info_stmt;
358 /* Get the last few posts on this board for /recent/ purposes */
359 static const char *board_get_recent_posts_txt =
360 "select id, date, name, subject, email, \n" /* */
361 " tripcode, comment, users_filename, \n" /* */
362 " system_full_path, system_thumb_path, \n" /* */
363 " file_info, ip, in_thread \n" /* */
364 "from comments order by date desc limit 10; \n"; /* */
365 static sqlite3_stmt **board_get_recent_posts_stmt;
367 /* Our connections */
368 static sqlite3 **board_dbs = 0;
369 static size_t num_connected_db = 0;
370 static sqlite3 *global_db = 0;
372 /* Global configuration */
373 const struct configuration *conf;
375 /* Clean the internals of a prepared_post */
376 static void clean_prepared_post(struct prepared_post *p)
378 free(p->name);
379 free(p->subject);
380 free(p->email);
381 free(p->tripcode);
382 free(p->comment);
383 free(p->file_name);
384 free(p->system_full_path);
385 free(p->system_thumb_path);
386 free(p->file_info);
387 free(p->ip);
388 *p = (struct prepared_post) { 0 };
392 * Make sure we can connect to the DBs and that they're in working order
394 * Preconditions:
396 * - setup_dbs() was not invoked more recently than clean_dbs().
398 * Postconditions (success):
400 * - Any other function in this file may be safely called.
402 int setup_dbs(const struct configuration *in_conf)
404 int ret = -1;
405 int sret = 0;
406 size_t len = 0;
407 char *path = 0;
408 char *error_message = 0;
410 conf = in_conf;
412 /* Memory for all our board-specific things */
413 if (!(board_dbs = calloc(conf->boards_num, sizeof *board_dbs))) {
414 PERROR_MESSAGE("calloc");
415 goto done;
418 TRY_MAKE_STATEMENT_ARRAY(check_ban);
419 TRY_MAKE_STATEMENT_ARRAY(check_cooldown);
420 TRY_MAKE_STATEMENT_ARRAY(check_thread_exists);
421 TRY_MAKE_STATEMENT_ARRAY(count_posts);
422 TRY_MAKE_STATEMENT_ARRAY(delete_thread);
423 TRY_MAKE_STATEMENT_ARRAY(delete_post);
424 TRY_MAKE_STATEMENT_ARRAY(find_containing_thread);
425 TRY_MAKE_STATEMENT_ARRAY(get_subject);
426 TRY_MAKE_STATEMENT_ARRAY(get_thread_contents);
427 TRY_MAKE_STATEMENT_ARRAY(get_thread_summary);
428 TRY_MAKE_STATEMENT_ARRAY(get_post_contents);
429 TRY_MAKE_STATEMENT_ARRAY(insert_ban);
430 TRY_MAKE_STATEMENT_ARRAY(insert_comment);
431 TRY_MAKE_STATEMENT_ARRAY(insert_comment_II);
432 TRY_MAKE_STATEMENT_ARRAY(list_threads);
433 TRY_MAKE_STATEMENT_ARRAY(set_cooldown);
434 TRY_MAKE_STATEMENT_ARRAY(update_by_moderation);
435 TRY_MAKE_STATEMENT_ARRAY(update_file_info);
436 TRY_MAKE_STATEMENT_ARRAY(get_recent_posts);
438 /* Turn on global connection */
439 len = snprintf(0, 0, "%s/global.db", conf->work_path);
441 if (len + 1 < len) {
442 ERROR_MESSAGE("overflow");
443 goto done;
446 if (!(path = malloc(len + 1))) {
447 PERROR_MESSAGE("malloc");
448 goto done;
451 sprintf(path, "%s/global.db", conf->work_path);
453 if ((sret = sqlite3_open(path, &global_db)) != SQLITE_OK) {
454 ERROR_MESSAGE("Cannot open or create database %s: %s", path,
455 sqlite3_errstr(sret));
456 goto done;
459 /* Set up global table (only bans) */
460 if (sqlite3_exec(global_db, make_ban_table, 0, 0, &error_message) !=
461 SQLITE_OK) {
462 ERROR_MESSAGE("Cannot set up ban table in database %s: %s",
463 path, error_message);
464 goto done;
467 /* Global statments (only ban creation/checking) */
468 if (sqlite3_prepare_v2(global_db, global_check_ban_txt, -1,
469 &global_check_ban_stmt, 0) != SQLITE_OK) {
470 ERROR_MESSAGE("Preparing statement failed: %s", sqlite3_errmsg(
471 global_db));
472 goto done;
475 if (sqlite3_prepare_v2(global_db, global_insert_ban_txt, -1,
476 &global_insert_ban_stmt, 0) != SQLITE_OK) {
477 ERROR_MESSAGE("Preparing statement failed: %s", sqlite3_errmsg(
478 global_db));
479 goto done;
482 /* Board specific stuff */
483 for (size_t j = 0; j < conf->boards_num; ++j) {
484 free(path);
485 path = 0;
486 len = snprintf(0, 0, "%s/board_%s.db", conf->work_path,
487 conf->boards[j].name);
489 if (len + 1 < len) {
490 ERROR_MESSAGE("overflow");
491 goto done;
494 if (!(path = malloc(len + 1))) {
495 PERROR_MESSAGE("malloc");
496 goto done;
499 sprintf(path, "%s/board_%s.db", conf->work_path,
500 conf->boards[j].name);
502 /* Turn on board */
503 if ((sret = sqlite3_open(path, &board_dbs[j])) != SQLITE_OK) {
504 ERROR_MESSAGE("Cannot open or create database %s: %s",
505 path, sqlite3_errstr(sret));
506 goto done;
509 num_connected_db++;
511 /* Set up tables */
512 if (sqlite3_exec(board_dbs[j], make_comment_table, 0, 0,
513 &error_message) != SQLITE_OK) {
514 ERROR_MESSAGE(
515 "Cannot set up comment table in database %s: %s",
516 path,
517 error_message);
518 goto done;
521 if (sqlite3_exec(board_dbs[j], make_ban_table, 0, 0,
522 &error_message) != SQLITE_OK) {
523 ERROR_MESSAGE(
524 "Cannot set up ban table in database %s: %s",
525 path,
526 error_message);
527 goto done;
530 if (sqlite3_exec(board_dbs[j], make_cooldown_table, 0, 0,
531 &error_message) != SQLITE_OK) {
532 ERROR_MESSAGE(
533 "Cannot set up cooldown table in database %s: %s",
534 path,
535 error_message);
536 goto done;
539 free(path);
540 path = 0;
542 /* Set up statements */
543 TRY_PREPARE_FOR_BOARD(j, check_ban);
544 TRY_PREPARE_FOR_BOARD(j, check_cooldown);
545 TRY_PREPARE_FOR_BOARD(j, check_thread_exists);
546 TRY_PREPARE_FOR_BOARD(j, count_posts);
547 TRY_PREPARE_FOR_BOARD(j, delete_thread);
548 TRY_PREPARE_FOR_BOARD(j, delete_post);
549 TRY_PREPARE_FOR_BOARD(j, find_containing_thread);
550 TRY_PREPARE_FOR_BOARD(j, get_subject);
551 TRY_PREPARE_FOR_BOARD(j, get_thread_contents);
552 TRY_PREPARE_FOR_BOARD(j, get_thread_summary);
553 TRY_PREPARE_FOR_BOARD(j, get_post_contents);
554 TRY_PREPARE_FOR_BOARD(j, insert_ban);
555 TRY_PREPARE_FOR_BOARD(j, insert_comment);
556 TRY_PREPARE_FOR_BOARD(j, insert_comment_II);
557 TRY_PREPARE_FOR_BOARD(j, list_threads);
558 TRY_PREPARE_FOR_BOARD(j, set_cooldown);
559 TRY_PREPARE_FOR_BOARD(j, update_by_moderation);
560 TRY_PREPARE_FOR_BOARD(j, update_file_info);
561 TRY_PREPARE_FOR_BOARD(j, get_recent_posts);
564 ret = 0;
565 done:
567 if (error_message) {
568 sqlite3_free(error_message);
571 free(path);
573 return ret;
577 * Construct something suitable for use in <a>
579 * Preconditions:
581 * - setup_dbs() has been invoked more recently than clean_dbs().
583 * - board is a sequence of ASCII characters of length board_len
584 * that represents a board.
586 * - Board directories are located at "/", so that "/".board."/res/"
587 * is where thread pages live.
589 * - post is a sequence of ASCII digits of length post_len.
591 * - out, out_len, and found are not 0.
593 * - Overwriting *out shall not cause a memory leak.
595 * Postconditions:
597 * - If the post doesn't exist, *found = 0.
599 * - Otherwise, *found is 1, and *out is a string like "/a/res/1235"
600 * of length *out_len, which can be used in a <a> element.
602 int db_construct_post_link(const char *board, size_t board_len, const
603 char *post, size_t post_len, int *found, char **out,
604 size_t *out_len)
606 int ret = -1;
607 int sret = 0;
608 size_t board_idx = (size_t) -1;
609 size_t in_thread = 0;
610 uintmax_t post_num = 0;
611 sqlite3_stmt *s = 0;
612 sqlite3 *db = 0;
613 size_t len = 0;
614 char *tmp = 0;
616 if (board_len > INT_MAX / 2) {
617 ERROR_MESSAGE("The board name \"%.*s...\" is way too long", 10,
618 board);
619 goto done;
623 * We can't call strtoll(post, 0, 0) because board might
624 * not be 0-terminated, it may point into internal PCRE2
625 * memory for example. It's simpler to recreate base 10
626 * strtoll than to malloc/copy/free a temp buffer.
628 for (size_t j = 0; j < post_len; ++j) {
629 post_num = 10 * post_num + (post[j] - '0');
632 for (size_t j = 0; j < num_connected_db; ++j) {
633 const struct board *b = &conf->boards[j];
635 if (strlen(b->name) == board_len &&
636 !strcmp(board, b->name)) {
637 board_idx = j;
638 break;
642 if (board_idx == (size_t) -1) {
643 ERROR_MESSAGE("Board \"%.*s\" doesn't exist", (int) board_len,
644 board);
645 goto done;
648 s = board_find_containing_thread_stmt[board_idx];
649 db = board_dbs[board_idx];
650 TRY_BIND_I(s, db, "@id", post_num);
651 sret = sqlite3_step(s);
653 switch (sret) {
654 case SQLITE_DONE:
655 *found = 0;
656 ret = 0;
657 goto done;
658 case SQLITE_ROW:
659 in_thread = sqlite3_column_int64(s, 0);
660 break;
661 default:
662 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
663 goto done;
664 break;
667 len = snprintf(0, 0, "/%.*s/res/%zu#post%ju", (int) board_len, board,
668 in_thread, post_num);
670 if (len + 1 < len) {
671 ERROR_MESSAGE("overflow");
672 goto done;
675 if (!(tmp = malloc(len + 1))) {
676 PERROR_MESSAGE("malloc");
677 goto done;
680 sprintf(tmp, "/%.*s/res/%zu#post%ju", (int) board_len, board, in_thread,
681 post_num);
682 *out = tmp;
683 *out_len = len;
684 *found = 1;
685 ret = 0;
686 done:
687 sqlite3_reset(s);
688 sqlite3_clear_bindings(s);
690 return ret;
694 * Ensure that there are not more than the proper number of threads
695 * lying around; report how many pages we need.
697 * Preconditions:
699 * - setup_dbs() has been invoked more recently than clean_dbs().
701 * - board_idx represents a board, AND THE LOCK IS HELD.
703 * - out_thread_ids, out_thread_id_num, and out_num_pages are not 0.
705 * - Overwriting *out_thread_ids shall not cause a memory leak.
707 * Postconditions (success):
709 * - There are num_pages * threads_per_page threads (rows with
710 * in_thread = 0) in the board's database.
712 * - If rows had to be deleted, all relevant reply rows were also
713 * deleted.
715 * - If rows had to be deleted, all files related to those rows
716 * (the thread page, the stored files for replies, etc.) have
717 * been deleted.
719 int db_cull_and_report_threads(size_t board_idx, uintmax_t **out_thread_ids,
720 size_t *out_thread_ids_num,
721 size_t *out_num_pages)
723 uintmax_t *to_delete = 0;
724 size_t to_delete_num = 0;
725 size_t to_delete_sz = 0;
726 uintmax_t total_threads_seen = 0;
727 uintmax_t threads_to_keep = 0;
728 int ret = -1;
729 int sret = 0;
730 sqlite3_stmt *s = board_list_threads_stmt[board_idx];
731 sqlite3 *db = board_dbs[board_idx];
732 uint_fast8_t exhausted = 0;
733 void *newmem = 0;
734 uintmax_t *thread_ids = 0;
735 const struct board *b = &conf->boards[board_idx];
737 threads_to_keep = b->num_pages * b->threads_per_page;
739 if (!(thread_ids = calloc(threads_to_keep, sizeof *thread_ids))) {
740 PERROR_MESSAGE("calloc");
741 goto done;
744 if (!(to_delete = malloc(sizeof *to_delete))) {
745 PERROR_MESSAGE("malloc");
746 goto done;
749 to_delete_sz = 1;
750 to_delete[0] = 0;
752 while (!exhausted) {
753 sret = sqlite3_step(s);
755 switch (sret) {
756 case SQLITE_DONE:
757 exhausted = 1;
758 break;
759 case SQLITE_ROW:
760 total_threads_seen++;
762 if (total_threads_seen > threads_to_keep) {
763 to_delete[to_delete_num] = sqlite3_column_int64(
764 s, 0);
766 if (to_delete_num + 1 >= to_delete_sz) {
767 if (to_delete_sz + 16 < to_delete_sz ||
768 ((to_delete_sz + 16) *
769 sizeof *to_delete) /
770 (to_delete_sz +
771 16) !=
772 sizeof *to_delete) {
773 ERROR_MESSAGE("overflow "
774 "(to_delete_sz = %zu)",
775 to_delete_sz);
776 goto done;
779 if (!(newmem = realloc(to_delete,
780 (to_delete_sz +
781 16) *
782 sizeof *to_delete)))
784 PERROR_MESSAGE("relloc");
785 goto done;
788 to_delete = newmem;
789 to_delete_sz += 16;
792 to_delete_num++;
793 } else {
794 thread_ids[total_threads_seen - 1] =
795 sqlite3_column_int64(s, 0);
798 break;
799 default:
800 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
801 goto done;
805 for (size_t j = 0; j < to_delete_num; ++j) {
806 db_remove_thread_and_files(board_idx, to_delete[j]);
809 *out_thread_ids = thread_ids;
810 *out_thread_ids_num = (total_threads_seen > threads_to_keep) ?
811 threads_to_keep : total_threads_seen;
812 *out_num_pages = 0;
814 if (*out_thread_ids_num) {
815 *out_num_pages = 1 + ((*out_thread_ids_num - 1) /
816 b->threads_per_page);
819 ret = 0;
820 done:
821 free(to_delete);
822 to_delete = 0;
823 sqlite3_reset(s);
824 sqlite3_clear_bindings(s);
826 return ret;
830 * Check whether a specific type of ban is active.
832 * Preconditions:
834 * - setup_dbs() has been invoked more recently than clean_dbs().
836 * - s is one of global_check_ban_stmt or a board_check_ban_stmt[j].
838 * - db corresponds to s.
840 * - ip is a string like "127.0.0.1"
842 * - out_is_banned, out_ban_until, out_ban_reason are not 0.
844 * - Overwriting *out_ban_until and *out_ban_reason shall not cause
845 * a memory leak.
847 * Postconditions (success):
849 * - *out_is_banned represents whether s returned a row for ip and
850 * row.
852 * - If *out_banned != 0, then *out_ban_until and *out_ban_reason
853 * are informative text strings (*out_ban_until is something
854 * like "2020-01-01T12:34:56" and *out_ban_reason is something
855 * like "having wrong opinions"). They are not 0.
857 static int check_ban_h(sqlite3_stmt *s, sqlite3 * db, const char *ip, time_t
858 now, int *out_is_banned, char **out_ban_until,
859 char **out_ban_reason)
861 int ret = -1;
862 int sret = 0;
863 size_t dummy_len = 0;
865 UNUSED(dummy_len);
866 TRY_BIND_T(s, db, "@ip", ip);
867 TRY_BIND_I(s, db, "@now", now);
868 sret = sqlite3_step(s);
870 switch (sret) {
871 case SQLITE_DONE:
873 /* No global ban */
874 break;
875 case SQLITE_ROW:
876 *out_is_banned = 1;
877 EXFILTRATE_TEXT(s, 1, *out_ban_reason, dummy_len);
879 if (!(*out_ban_until = util_iso8601_from_time_t(
880 (time_t) sqlite3_column_int64(s, 0)))) {
881 goto done;
884 ret = 0;
885 goto done;
886 default:
887 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
888 goto done;
891 ret = 0;
892 done:
893 sqlite3_reset(s);
894 sqlite3_clear_bindings(s);
896 return ret;
900 * Check whether any ban is active.
902 * Preconditions:
904 * - setup_dbs() has been invoked more recently than clean_dbs().
906 * - ip is a string like "127.0.0.1".
908 * - out_is_banned, out_ban_until, out_ban_reason are not 0.
910 * - Overwriting *out_ban_until and *out_ban_reason shall not cause
911 * a memory leak.
913 * - board_idx corresponds to a board.
915 * Postconditions (success):
917 * - *out_is_banned represents whether a row was found in the bans
918 * db, either globally or for board_idx, matching ip and now.
920 * - If *out_banned != 0, then *out_ban_until and *out_ban_reason
921 * are informative text strings (*out_ban_until is something
922 * like "2020-01-01T12:34:56" and *out_ban_reason is something
923 * like "having wrong opinions"). They are not 0.
925 int db_check_bans(const char *ip, size_t board_idx, time_t now,
926 int *out_is_banned, char **out_ban_until,
927 char **out_ban_reason)
929 int ret = -1;
931 /* First check global bans */
932 if (check_ban_h(global_check_ban_stmt, global_db, ip, now,
933 out_is_banned, out_ban_until, out_ban_reason) < 0) {
934 goto done;
937 if (*out_is_banned) {
938 ret = 0;
939 goto done;
942 /* Now board-specific */
943 if (check_ban_h(board_check_ban_stmt[board_idx], board_dbs[board_idx],
944 ip, now, out_is_banned, out_ban_until, out_ban_reason) <
945 0) {
946 goto done;
949 ret = 0;
950 done:
952 return ret;
956 * Check whether a cooldown is active.
958 * Preconditions:
960 * - setup_dbs() has been invoked more recently than clean_dbs().
962 * - ip is a string like "127.0.0.1".
964 * - out_is_cooled, out_cooldown_length are not 0.
966 * - Overwriting *out_cooldown_length shall not cause a memory
967 * leak.
969 * - board_idx corresponds to a board.
971 * Postconditions (success):
973 * - *out_is_cooled represents whether a row was found in the
974 * cooldowns table corresponding to board_idx.
976 * - If *out_is_cooled != 0, then *out_cooldown_length is a string
977 * like "20 seconds", corresponding to the cooldown row.
979 int db_check_cooldowns(const char *ip, size_t board_idx, time_t now,
980 int *out_is_cooled, char **out_cooldown_length)
982 int ret = -1;
983 int sret = 0;
984 time_t expiry = 0;
985 long diff = 0;
986 size_t len = 0;
987 sqlite3_stmt *s = board_check_cooldown_stmt[board_idx];
988 sqlite3 *db = board_dbs[board_idx];
990 TRY_BIND_T(s, db, "@ip", ip);
991 sret = sqlite3_step(s);
993 switch (sret) {
994 case SQLITE_DONE:
995 *out_is_cooled = 0;
996 break;
997 case SQLITE_ROW:
998 expiry = (time_t) sqlite3_column_int64(s, 0);
999 diff = (expiry > now) ? expiry - now : -1;
1001 if (diff > 0) {
1002 *out_is_cooled = 1;
1003 len = snprintf(0, 0, "%ld seconds", diff);
1005 if (len + 1 < len) {
1006 ERROR_MESSAGE("overflow");
1007 goto done;
1010 if (!(*out_cooldown_length = malloc(len + 1))) {
1011 PERROR_MESSAGE("malloc");
1012 goto done;
1015 sprintf(*out_cooldown_length, "%ld seconds", diff);
1018 ret = 0;
1019 goto done;
1020 default:
1021 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1022 goto done;
1025 ret = 0;
1026 done:
1027 sqlite3_reset(s);
1028 sqlite3_clear_bindings(s);
1030 return ret;
1034 * Check whether a thread exists, is full, is closed.
1036 * Preconditions:
1038 * - board_idx corresponds to a board.
1040 * - thread_dne, thread_closed, thread_full are not 0.
1042 static int check_thread(uintmax_t id, size_t board_idx, int *thread_dne,
1043 int *thread_closed, int *thread_full)
1045 int ret = -1;
1046 int sret = 0;
1047 sqlite3 *db = board_dbs[board_idx];
1048 sqlite3_stmt *s = board_check_thread_exists_stmt[board_idx];
1050 TRY_BIND_I(s, db, "@thread", id);
1051 sret = sqlite3_step(s);
1053 switch (sret) {
1054 case SQLITE_DONE:
1055 *thread_dne = 1;
1056 ret = 0;
1057 goto done;
1058 case SQLITE_ROW:
1059 *thread_closed = sqlite3_column_int(s, 0);
1060 *thread_full = sqlite3_column_int(s, 1);
1061 ret = 0;
1062 goto done;
1063 default:
1064 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1065 goto done;
1068 ret = 0;
1069 done:
1070 sqlite3_reset(s);
1071 sqlite3_clear_bindings(s);
1073 return ret;
1076 /* Get the subject of a thread.
1078 * Preconditions:
1080 * - setup_dbs() has been invoked more recently than clean_dbs().
1082 * - board_idx represents a board.
1084 * - thread is the id of a thread.
1086 * - out_subject and out_subject_len are not 0.
1088 * - overwriting *out_subject shall not cause a memory leak.
1090 * Postconditions (success):
1092 * - *out_subject is a string of length *out_subject_len, which
1093 * is the subject of the thread given by thread.
1095 * - The memory of *out_subject should be freed by the caller.
1097 int db_extract_subject(size_t board_idx, uintmax_t thread, char **out_subject,
1098 size_t *out_subject_len)
1100 int ret = -1;
1101 int sret = 0;
1102 sqlite3 *db = board_dbs[board_idx];
1103 sqlite3_stmt *s = board_get_subject_stmt[board_idx];
1105 TRY_BIND_I(s, db, "@thread", thread);
1106 sret = sqlite3_step(s);
1108 switch (sret) {
1109 case SQLITE_DONE:
1110 break;
1111 case SQLITE_ROW:
1112 EXFILTRATE_TEXT(s, 0, *out_subject, *out_subject_len);
1113 break;
1114 default:
1115 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1116 goto done;
1119 ret = 0;
1120 done:
1121 sqlite3_reset(s);
1122 sqlite3_clear_bindings(s);
1124 return ret;
1128 * Insert a ban, which may be either global or board-specific.
1130 * Preconditions:
1132 * - setup_dbs() has been invoked more recently than clean_dbs().
1134 * - Either global_ban is non-zero, or board_idx represents a board.
1136 * - first_ip and last_ip are "normalized" ip addresses, in the
1137 * sense of the output of util_normalize_ip(), not e.g. RFC 2373.
1139 * - message is a string.
1141 * Postconditions (success):
1143 * - Depending on global_ban and board_idx, a row in the bans table
1144 * of an appropriate database has been created, depending on the
1145 * input parameters in an obvious way.
1147 int db_insert_ban(uint_fast8_t global_ban, size_t board_idx, const
1148 char *first_ip, const char *last_ip, const char *message,
1149 time_t ban_start,
1150 time_t ban_expiry)
1152 int ret = -1;
1153 int sret = 0;
1154 sqlite3_stmt *s = 0;
1155 sqlite3 *db = 0;
1157 if (global_ban) {
1158 s = global_insert_ban_stmt;
1159 db = global_db;
1160 } else {
1161 s = board_insert_ban_stmt[board_idx];
1162 db = board_dbs[board_idx];
1165 TRY_BIND_T(s, db, "@ip_start", first_ip);
1166 TRY_BIND_T(s, db, "@ip_end", last_ip);
1167 TRY_BIND_I(s, db, "@date_start", ban_start);
1168 TRY_BIND_I(s, db, "@date_end", ban_expiry);
1169 TRY_BIND_T(s, db, "@reason", message);
1170 sret = sqlite3_step(s);
1172 switch (sret) {
1173 case SQLITE_DONE:
1174 break;
1175 default:
1176 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1177 goto done;
1180 ret = 0;
1181 done:
1182 sqlite3_reset(s);
1183 sqlite3_clear_bindings(s);
1185 return ret;
1189 * Insert a post, which may be a reply or a new thread. Some fields
1190 * (file_info) are not filled out - they are updated later, after
1191 * filesystem work has been completed.
1193 * Preconditions:
1195 * - setup_dbs() has been invoked more recently than clean_dbs().
1197 * - ip is a string like "127.0.0.1".
1199 * - f is not 0 if pc contains a file.
1201 * - The prepared_XYZ fields of pc are filled out.
1203 * - If this post is a reply, in_thread is the id of the thread's
1204 * OP.
1206 * - thread_dne, thread_closed, thread_full, post_id are not 0.
1208 * Postconditions (success):
1210 * - If the post couldn't be made because the thread doesn't exist,
1211 * *thread_dne is 1.
1213 * - Otherwise, if the post couldn't be made because the thread
1214 * is closed, *thread_closed = 1.
1216 * - Otherwise, if the post couldn't be made because the thread
1217 * is full, *thread_full = 1.
1219 * - Otherwise, the post was made, and the surrounding thread's
1220 * reply date, fullness, etc. have been updated (no actual HTML
1221 * regeneration, though).
1223 * - Furthermore, *post_id is the number of the inserted post.
1225 int db_insert_post(const char *ip, size_t in_thread, int cooldown, struct
1226 post_cmd *pc, int *thread_dne, int *thread_closed,
1227 int *thread_full,
1228 uintmax_t *post_id)
1230 int ret = -1;
1231 int sret = 0;
1232 sqlite3_stmt *s = board_insert_comment_stmt[pc->board_idx];
1233 sqlite3_stmt *s2 = board_insert_comment_II_stmt[pc->board_idx];
1234 sqlite3_stmt *s3 = board_set_cooldown_stmt[pc->board_idx];
1235 sqlite3 *db = board_dbs[pc->board_idx];
1237 TRY_BIND_T(s, db, "@ip", ip);
1238 TRY_BIND_I(s, db, "@date", pc->prepared.now);
1240 if (in_thread) {
1241 if (check_thread(in_thread, pc->board_idx, thread_dne,
1242 thread_closed, thread_full) < 0) {
1243 goto done;
1246 if (*thread_dne ||
1247 *thread_closed ||
1248 *thread_full) {
1249 ret = 0;
1250 goto done;
1253 TRY_BIND_I(s, db, "@in_thread", in_thread);
1254 TRY_BIND_I(s2, db, "@in_thread", in_thread);
1255 TRY_BIND_I(s2, db, "@date", pc->prepared.now);
1256 TRY_BIND_I(s2, db, "@should_bump", (!pc->prepared.email ||
1257 strcmp(pc->prepared.email,
1258 "sage")));
1261 TRY_BIND_T(s, db, "@name", pc->prepared.name);
1262 TRY_BIND_T(s, db, "@tripcode", pc->prepared.tripcode);
1263 TRY_BIND_T(s, db, "@email", pc->prepared.email);
1264 TRY_BIND_T(s, db, "@subject", pc->prepared.subject);
1265 TRY_BIND_T(s, db, "@comment", pc->prepared.comment);
1266 TRY_BIND_T(s, db, "@users_filename", pc->prepared.file_name);
1269 * It's highly probable that these are blank. At the current
1270 * time of writing, db_insert_post() is called before
1271 * install_files(), and the resulting row is fixed up
1272 * afterwards in db_update_file_info(). These are currently
1273 * left in for the hack-ish hooks for writing posts
1274 * programatically.
1276 TRY_BIND_T(s, db, "@system_full_path", pc->prepared.system_full_path);
1277 TRY_BIND_T(s, db, "@system_thumb_path", pc->prepared.system_thumb_path);
1278 sret = sqlite3_step(s);
1280 switch (sret) {
1281 case SQLITE_DONE:
1282 break;
1283 default:
1284 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1285 goto done;
1288 *post_id = sqlite3_last_insert_rowid(db);
1290 if (in_thread) {
1291 sret = sqlite3_step(s2);
1293 switch (sret) {
1294 case SQLITE_DONE:
1295 case SQLITE_ROW:
1296 break;
1297 default:
1298 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1299 goto done;
1303 TRY_BIND_T(s3, db, "@ip", ip);
1304 TRY_BIND_I(s3, db, "@cooldown_expiry", pc->prepared.now + cooldown);
1305 sret = sqlite3_step(s3);
1307 switch (sret) {
1308 case SQLITE_DONE:
1309 case SQLITE_ROW:
1310 break;
1311 default:
1312 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1313 goto done;
1316 ret = 0;
1317 done:
1318 sqlite3_reset(s);
1319 sqlite3_clear_bindings(s);
1320 sqlite3_reset(s2);
1321 sqlite3_clear_bindings(s2);
1322 sqlite3_reset(s3);
1323 sqlite3_clear_bindings(s3);
1325 return ret;
1329 * Check if a post is actually the OP of a thread.
1331 * Preconditions:
1333 * - setup_dbs() has been invoked more recently than clean_dbs().
1335 * - board_idx represents a board.
1337 * - post_id represents a post.
1339 * - out_is_op is not 0.
1341 * Postconditions (success):
1343 * - *out_is_op is either 1 (if the row with id = post_id has
1344 * in_thread NULL), or 0 (otherwise).
1346 int db_is_op(size_t board_idx, uintmax_t post_id, uint_fast8_t *out_is_op)
1348 int ret = -1;
1349 int sret = 0;
1350 sqlite3_stmt *s = board_get_post_contents_stmt[board_idx];
1351 sqlite3 *db = board_dbs[board_idx];
1353 TRY_BIND_I(s, db, "@post", post_id);
1354 sret = sqlite3_step(s);
1356 switch (sret) {
1357 case SQLITE_DONE:
1358 *out_is_op = 0;
1359 break;
1360 case SQLITE_ROW:
1361 *out_is_op = !sqlite3_column_int64(s, 12);
1362 break;
1363 default:
1364 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1365 goto done;
1368 ret = 0;
1369 done:
1370 sqlite3_reset(s);
1371 sqlite3_clear_bindings(s);
1373 return ret;
1377 * Perform minor adjustments to a post
1379 * Preconditions:
1381 * - setup_dbs() has been invoked more recently than clean_dbs().
1383 * - board_idx represents a board.
1385 * - post_id represents a post.
1387 * - moderator_comment is either 0 or a string.
1389 * - If change_sticky or change_close are not 0, then post_id
1390 * represents the OP of a thread.
1392 * Postconditions (success):
1394 * - If change_sticky, then the thread_stickied will be adjusted
1395 * to sticky_status.
1397 * - If change_close, then the thread_closed will be adjusted to
1398 * close_status.
1400 int db_moderate_post(size_t board_idx, uintmax_t post_id, const
1401 char *moderator_comment, uint_fast8_t change_sticky,
1402 uint_fast8_t sticky_status,
1403 uint_fast8_t change_close, uint_fast8_t close_status)
1405 int ret = -1;
1406 int sret = 0;
1407 sqlite3_stmt *s = board_get_post_contents_stmt[board_idx];
1408 sqlite3_stmt *s2 = board_update_by_moderation_stmt[board_idx];
1409 sqlite3 *db = board_dbs[board_idx];
1410 uint_fast8_t thread_stickied = 0;
1411 uint_fast8_t thread_closed = 0;
1412 char *comment = 0;
1413 size_t comment_len = 0;
1414 char *new_comment = 0;
1415 size_t new_comment_len = 0;
1417 TRY_BIND_I(s, db, "@post", post_id);
1418 sret = sqlite3_step(s);
1420 switch (sret) {
1421 case SQLITE_DONE:
1422 LOG("Board /%s/, post %ju does not exist",
1423 conf->boards[board_idx].name, post_id);
1424 goto done;
1425 case SQLITE_ROW:
1426 EXFILTRATE_TEXT(s, 6, comment, comment_len);
1427 thread_closed = !!sqlite3_column_int64(s, 13);
1428 thread_stickied = !!sqlite3_column_int64(s, 14);
1429 break;
1430 default:
1431 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1432 goto done;
1435 if (!moderator_comment) {
1436 TRY_BIND_T(s2, db, "@comment", comment);
1437 } else if (comment_len) {
1438 new_comment_len = snprintf(0, 0, "%s<br /><br />"
1439 "<span class=\"mod-text\">"
1440 "(%s)</span>", comment,
1441 moderator_comment);
1443 if (new_comment_len + 1 < new_comment_len) {
1444 ERROR_MESSAGE("overflow");
1445 goto done;
1448 if (!(new_comment = malloc(new_comment_len + 1))) {
1449 PERROR_MESSAGE("malloc");
1450 goto done;
1453 sprintf(new_comment, "%s<br /><br />"
1454 "<span class=\"mod-text\">(%s)</span>",
1455 comment,
1456 moderator_comment);
1457 TRY_BIND_T(s2, db, "@comment", new_comment);
1458 } else {
1459 new_comment_len = snprintf(0, 0, "<span class=\"mod-text\">"
1460 "(%s)</span>",
1461 moderator_comment);
1463 if (new_comment_len + 1 < new_comment_len) {
1464 ERROR_MESSAGE("overflow");
1465 goto done;
1468 if (!(new_comment = malloc(new_comment_len + 1))) {
1469 PERROR_MESSAGE("malloc");
1470 goto done;
1473 sprintf(new_comment, "<span class=\"mod-text\">(%s)</span>",
1474 moderator_comment);
1475 TRY_BIND_T(s2, db, "@comment", new_comment);
1478 if (change_sticky) {
1479 TRY_BIND_I(s2, db, "@thread_stickied", sticky_status);
1480 } else {
1481 TRY_BIND_I(s2, db, "@thread_stickied", thread_stickied);
1484 if (change_close) {
1485 TRY_BIND_I(s2, db, "@thread_closed", close_status);
1486 } else {
1487 TRY_BIND_I(s2, db, "@thread_closed", thread_closed);
1490 TRY_BIND_I(s2, db, "@id", post_id);
1491 sret = sqlite3_step(s2);
1493 switch (sret) {
1494 case SQLITE_DONE:
1495 break;
1496 default:
1497 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1498 goto done;
1501 ret = 0;
1502 done:
1503 free(comment);
1504 free(new_comment);
1505 sqlite3_reset(s);
1506 sqlite3_clear_bindings(s);
1508 return ret;
1512 * Delete all files related to a post, remove row from the
1513 * database.
1515 * Preconditions:
1517 * - setup_dbs() has been invoked more recently than clean_dbs().
1519 * - board_idx represents a board, AND THE LOCK IS HELD.
1521 * - post_id represents a post (a row with in_thread != NULL).
1523 * Postconditions (success):
1525 * - wt_remove_files() has been called on the relevant paths.
1527 * - The row for which id is thread_id has been removed
1528 * from the database.
1530 int db_remove_post_and_files(size_t board_idx, uintmax_t post_id)
1532 int ret = -1;
1533 int sret = 0;
1534 sqlite3_stmt *s = board_get_post_contents_stmt[board_idx];
1535 sqlite3_stmt *s2 = board_delete_post_stmt[board_idx];
1536 sqlite3 *db = board_dbs[board_idx];
1537 char *system_full_path = 0;
1538 size_t system_full_path_len = 0;
1539 char *system_thumb_path = 0;
1540 size_t system_thumb_path_len = 0;
1542 TRY_BIND_I(s, db, "@post", post_id);
1543 sret = sqlite3_step(s);
1545 switch (sret) {
1546 case SQLITE_DONE:
1547 LOG("Board /%s/, post %ju does not exist",
1548 conf->boards[board_idx].name, post_id);
1549 goto done;
1550 case SQLITE_ROW:
1551 EXFILTRATE_TEXT(s, 8, system_full_path, system_full_path_len);
1552 EXFILTRATE_TEXT(s, 9, system_thumb_path, system_thumb_path_len);
1553 wt_remove_files(system_full_path, system_full_path_len,
1554 system_thumb_path, system_thumb_path_len);
1555 break;
1556 default:
1557 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1558 goto done;
1561 TRY_BIND_I(s2, db, "@id", post_id);
1562 sret = sqlite3_step(s2);
1564 switch (sret) {
1565 case SQLITE_DONE:
1566 break;
1567 default:
1568 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1569 goto done;
1572 ret = 0;
1573 done:
1574 free(system_full_path);
1575 free(system_thumb_path);
1576 sqlite3_reset(s);
1577 sqlite3_reset(s2);
1578 sqlite3_clear_bindings(s);
1579 sqlite3_clear_bindings(s2);
1581 return ret;
1585 * Delete all files related to a thread, remove rows from the
1586 * database.
1588 * Preconditions:
1590 * - setup_dbs() has been invoked more recently than clean_dbs().
1592 * - board_idx represents a board, AND THE LOCK IS HELD.
1594 * - thread_id represents a thread (a row with in_thread = NULL).
1596 * Postconditions (success):
1598 * - For every post in the thread, wt_remove_files() has been
1599 * called on the relevant paths.
1601 * - wt_remove_thread_page() has been called on the relevant thread.
1603 * - Any row for which in_thread is thread_id has been removed
1604 * from the database.
1606 int db_remove_thread_and_files(size_t board_idx, uintmax_t thread_id)
1608 int ret = -1;
1609 int sret = 0;
1610 sqlite3_stmt *s = board_get_thread_contents_stmt[board_idx];
1611 sqlite3_stmt *s2 = board_delete_thread_stmt[board_idx];
1612 sqlite3 *db = board_dbs[board_idx];
1613 char *system_full_path = 0;
1614 size_t system_full_path_len = 0;
1615 char *system_thumb_path = 0;
1616 size_t system_thumb_path_len = 0;
1618 TRY_BIND_I(s, db, "@thread", thread_id);
1619 again:
1620 sret = sqlite3_step(s);
1622 switch (sret) {
1623 case SQLITE_DONE:
1624 LOG("Board /%s/, post %ju does not exist",
1625 conf->boards[board_idx].name, thread_id);
1626 goto done;
1627 case SQLITE_ROW:
1628 EXFILTRATE_TEXT(s, 8, system_full_path, system_full_path_len);
1629 EXFILTRATE_TEXT(s, 9, system_thumb_path, system_thumb_path_len);
1630 wt_remove_files(system_full_path, system_full_path_len,
1631 system_thumb_path, system_thumb_path_len);
1633 /* Clean up */
1634 free(system_full_path);
1635 free(system_thumb_path);
1636 system_full_path = 0;
1637 system_thumb_path = 0;
1638 goto again;
1639 default:
1640 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1641 goto done;
1644 if (wt_remove_thread_page(board_idx, thread_id) < 0) {
1645 goto done;
1648 TRY_BIND_I(s2, db, "@thread", thread_id);
1649 sret = sqlite3_step(s2);
1651 switch (sret) {
1652 case SQLITE_DONE:
1653 break;
1654 default:
1655 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1656 goto done;
1659 ret = 0;
1660 done:
1661 sqlite3_reset(s);
1662 sqlite3_reset(s2);
1663 sqlite3_clear_bindings(s);
1664 sqlite3_clear_bindings(s2);
1666 return ret;
1670 * Update the file_info field for a comment (as it isn't known at insert time)
1672 * Preconditions:
1674 * - setup_dbs() has been invoked more recently than clean_dbs().
1676 * - board_idx represents a board.
1678 * - post_id is the id of a row that exists in that board's comments.
1680 * - info is a string of length info_len.
1682 * Postconditions (success):
1684 * - `select file_info from comments where id is @post_id', on the
1685 * correct board, would return info.
1687 int db_update_file_info(size_t board_idx, uintmax_t post_id, const char *info,
1688 size_t info_len, const char *system_full_path, size_t
1689 system_full_path_len,
1690 const char *system_thumb_path, size_t
1691 system_thumb_path_len)
1693 int ret = -1;
1694 int sret = 0;
1695 sqlite3 *db = board_dbs[board_idx];
1696 sqlite3_stmt *s = board_update_file_info_stmt[board_idx];
1698 /* XXX: use this in TRY_BIND_T */
1699 UNUSED(info_len);
1700 UNUSED(system_full_path_len);
1701 UNUSED(system_thumb_path_len);
1702 TRY_BIND_I(s, db, "@id", post_id);
1703 TRY_BIND_T(s, db, "@file_info", info);
1704 TRY_BIND_T(s, db, "@system_full_path", system_full_path);
1705 TRY_BIND_T(s, db, "@system_thumb_path", system_thumb_path);
1706 sret = sqlite3_step(s);
1708 switch (sret) {
1709 case SQLITE_DONE:
1710 ret = 0;
1711 goto done;
1712 default:
1713 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1714 goto done;
1717 ret = 0;
1718 done:
1719 sqlite3_reset(s);
1720 sqlite3_clear_bindings(s);
1722 return ret;
1726 * The db side of write_thread(): pull all posts from a thread, and
1727 * call pw_function as appropriate (the abstraction is for the sake
1728 * of rb79-view-thread).
1730 * *pw_function had better be one of wt_write_post(),
1732 * Preconditions:
1734 * - setup_dbs() has been invoked more recently than clean_dbs().
1736 * - board_idx represents a board.
1738 * - thread is the id of a thread.
1740 * - f is an open filehandle that can be written to.
1742 * - *pw_function is something like wt_write_post().
1744 * Postconditions (success):
1746 * - The thread has, somehow, been written out to f. In practice,
1747 * this means wt_write_post() has been called on the rows that
1748 * correspond to thread.
1750 int db_writeback_posts_in_thread(size_t board_idx, uintmax_t thread, FILE *f,
1751 post_writeback pw_function)
1753 int ret = -1;
1754 int sret = 0;
1755 uint_fast8_t first_post = 1;
1756 struct prepared_post p = { 0 };
1757 sqlite3_stmt *s = board_get_thread_contents_stmt[board_idx];
1758 sqlite3 *db = board_dbs[board_idx];
1760 TRY_BIND_I(s, db, "@thread", thread);
1761 again:
1762 sret = sqlite3_step(s);
1764 switch (sret) {
1765 case SQLITE_DONE:
1766 ret = 0;
1767 goto done;
1768 break;
1769 case SQLITE_ROW:
1770 p = (struct prepared_post) { 0 };
1771 p.id = sqlite3_column_int64(s, 0);
1772 p.now = sqlite3_column_int64(s, 1);
1773 EXFILTRATE_TEXT(s, 2, p.name, p.name_len);
1774 EXFILTRATE_TEXT(s, 3, p.subject, p.subject_len);
1775 EXFILTRATE_TEXT(s, 4, p.email, p.email_len);
1776 EXFILTRATE_TEXT(s, 5, p.tripcode, p.tripcode_len);
1777 EXFILTRATE_TEXT(s, 6, p.comment, p.comment_len);
1778 EXFILTRATE_TEXT(s, 7, p.file_name, p.file_name_len);
1779 EXFILTRATE_TEXT(s, 8, p.system_full_path,
1780 p.system_full_path_len);
1781 EXFILTRATE_TEXT(s, 9, p.system_thumb_path,
1782 p.system_thumb_path_len);
1783 EXFILTRATE_TEXT(s, 10, p.file_info, p.file_info_len);
1784 EXFILTRATE_TEXT(s, 11, p.ip, p.ip_len);
1785 p.thread_closed = !!sqlite3_column_int64(s, 12);
1786 p.thread_stickied = !!sqlite3_column_int64(s, 13);
1788 if ((*pw_function)(&p, f, first_post, 0, 0, 0, 0, 0, 0) < 0) {
1789 goto done;
1792 first_post = 0;
1793 clean_prepared_post(&p);
1794 goto again;
1795 default:
1796 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1797 goto done;
1800 ret = 0;
1801 done:
1802 sqlite3_reset(s);
1803 sqlite3_clear_bindings(s);
1805 return ret;
1809 * The db side of write_recent_page(): pull recent posts from all
1810 * boards, sort, and call pw_function as appropriate.
1812 * *pw_function had better be one of wt_write_recent_post(),
1814 * Preconditions:
1816 * - setup_dbs() has been invoked more recently than clean_dbs().
1818 * - f is an open filehandle that can be written to.
1820 * - *pw_function is something like wt_write_recent_post().
1822 * Postconditions (success):
1824 * - The few most recent posts of the board have, somehow, been
1825 * written out to f. In practice, this means wt_write_recent_post()
1826 * has been called on the rows that correspond to thread.
1828 int db_writeback_recent_posts(FILE *f, post_writeback pw_function)
1830 int ret = -1;
1831 int sret = 0;
1832 struct prepared_post p[10];
1833 size_t on_board[10];
1834 uintmax_t in_thread[10];
1835 time_t now = 0;
1836 sqlite3_stmt *s = 0;
1837 sqlite3 *db = 0;
1839 for (size_t k = 0; k < 10; ++k) {
1840 p[k] = (struct prepared_post) { 0 };
1841 on_board[k] = (size_t) -1;
1844 for (size_t j = 0; j < conf->boards_num; ++j) {
1845 s = board_get_recent_posts_stmt[j];
1846 db = board_dbs[j];
1847 again:
1848 sret = sqlite3_step(s);
1850 switch (sret) {
1851 case SQLITE_DONE:
1852 break;
1853 case SQLITE_ROW:
1854 now = sqlite3_column_int64(s, 1);
1856 for (size_t k = 0; k < 10; ++k) {
1857 if (p[k].now >= now) {
1858 continue;
1861 clean_prepared_post(&p[9]);
1863 for (size_t l = 9; l >= k + 1; --l) {
1864 memcpy(&p[l], &p[l - 1], sizeof p[0]);
1865 on_board[l] = on_board[l - 1];
1866 in_thread[l] = in_thread[l - 1];
1869 on_board[k] = j;
1870 p[k].id = sqlite3_column_int64(s, 0);
1871 p[k].now = sqlite3_column_int64(s, 1);
1872 EXFILTRATE_TEXT(s, 2, p[k].name, p[k].name_len);
1873 EXFILTRATE_TEXT(s, 3, p[k].subject,
1874 p[k].subject_len);
1875 EXFILTRATE_TEXT(s, 4, p[k].email,
1876 p[k].email_len);
1877 EXFILTRATE_TEXT(s, 5, p[k].tripcode,
1878 p[k].tripcode_len);
1879 EXFILTRATE_TEXT(s, 6, p[k].comment,
1880 p[k].comment_len);
1881 EXFILTRATE_TEXT(s, 7, p[k].file_name,
1882 p[k].file_name_len);
1883 EXFILTRATE_TEXT(s, 8, p[k].system_full_path,
1884 p[k].system_full_path_len);
1885 EXFILTRATE_TEXT(s, 9, p[k].system_thumb_path,
1886 p[k].system_thumb_path_len);
1887 EXFILTRATE_TEXT(s, 10, p[k].file_info,
1888 p[k].file_info_len);
1889 EXFILTRATE_TEXT(s, 11, p[k].ip, p[k].ip_len);
1890 in_thread[k] = sqlite3_column_int64(s, 12);
1892 if (!in_thread[k]) {
1893 in_thread[k] = p[k].id;
1896 break;
1899 goto again;
1900 default:
1901 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1902 goto done;
1905 sqlite3_reset(s);
1908 for (size_t k = 0; k < 10; ++k) {
1909 const struct board *b = 0;
1911 if (on_board[k] >= conf->boards_num) {
1912 continue;
1915 b = &conf->boards[on_board[k]];
1917 if ((*pw_function)(&p[k], f, 0, 0, 1, b->name, in_thread[k], 0,
1918 !!k) < 0) {
1919 goto done;
1923 done:
1925 for (size_t k = 0; k < 10; ++k) {
1926 clean_prepared_post(&p[k]);
1929 return ret;
1933 * The db side of write_board(): pull enough posts from a thread
1934 * to create a summary for the board page.
1936 * Preconditions:
1938 * - setup_dbs() has been invoked more recently than clean_dbs().
1940 * - board_idx represents a board.
1942 * - thread_ids is an array of size (at least) thread_ids_num.
1944 * - each element of thread_ids represents a currently-active
1945 * thread, and the list is sorted by bump order (most recent
1946 * first).
1948 * - f is an open filehandle that can be written to.
1950 * Postconditions (success):
1952 * - Each of the thread_ids_num threads represented in thread_ids
1953 * has, somehow, been written out to f. In practice, this means
1954 * write_op_in_board() and write_post_in_board() have been called
1955 * on the rows that correspond to the OP and the last few posts
1956 * of a thread.
1958 int db_writeback_thread_summaries(size_t board_idx, uintmax_t *thread_ids,
1959 size_t thread_ids_num, FILE *f)
1961 int ret = -1;
1962 int sret = 0;
1963 uint_fast8_t first_post = 1;
1964 sqlite3_stmt *s = board_count_posts_stmt[board_idx];
1965 sqlite3_stmt *s2 = board_get_thread_summary_stmt[board_idx];
1966 sqlite3 *db = board_dbs[board_idx];
1967 struct prepared_post p = { 0 };
1969 for (size_t j = 0; j < thread_ids_num; ++j) {
1970 uintmax_t total_post_num = 0;
1971 uintmax_t thread_id = thread_ids[j];
1973 first_post = 1;
1974 sqlite3_reset(s);
1975 sqlite3_clear_bindings(s);
1976 TRY_BIND_I(s, db, "@thread", thread_id);
1977 sret = sqlite3_step(s);
1979 switch (sret) {
1980 case SQLITE_DONE:
1981 break;
1982 case SQLITE_ROW:
1983 total_post_num = sqlite3_column_int64(s, 0);
1984 break;
1985 default:
1986 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
1987 goto done;
1990 sqlite3_reset(s2);
1991 sqlite3_clear_bindings(s2);
1992 TRY_BIND_I(s2, db, "@thread", thread_id);
1993 again:
1994 sret = sqlite3_step(s2);
1996 switch (sret) {
1997 case SQLITE_DONE:
1998 break;
1999 case SQLITE_ROW:
2000 p = (struct prepared_post) { 0 };
2001 p.id = sqlite3_column_int64(s2, 0);
2002 p.now = sqlite3_column_int64(s2, 1);
2003 EXFILTRATE_TEXT(s2, 2, p.name, p.name_len);
2004 EXFILTRATE_TEXT(s2, 3, p.subject, p.subject_len);
2005 EXFILTRATE_TEXT(s2, 4, p.email, p.email_len);
2006 EXFILTRATE_TEXT(s2, 5, p.tripcode, p.tripcode_len);
2007 EXFILTRATE_TEXT(s2, 6, p.comment, p.comment_len);
2008 EXFILTRATE_TEXT(s2, 7, p.file_name, p.file_name_len);
2009 EXFILTRATE_TEXT(s2, 8, p.system_full_path,
2010 p.system_full_path_len);
2011 EXFILTRATE_TEXT(s2, 9, p.system_thumb_path,
2012 p.system_thumb_path_len);
2013 EXFILTRATE_TEXT(s2, 10, p.file_info, p.file_info_len);
2014 EXFILTRATE_TEXT(s2, 11, p.ip, p.ip_len);
2015 p.thread_closed = !!sqlite3_column_int64(s2, 12);
2016 p.thread_stickied = !!sqlite3_column_int64(s2, 13);
2017 wt_write_post(&p, f, first_post, 1, 0,
2018 conf->boards[board_idx].name, 0,
2019 total_post_num,
2020 first_post);
2021 first_post = 0;
2022 clean_prepared_post(&p);
2023 goto again;
2024 default:
2025 ERROR_MESSAGE("sqlite3_step(): %s", sqlite3_errmsg(db));
2026 break;
2030 ret = 0;
2031 done:
2032 sqlite3_reset(s);
2033 sqlite3_clear_bindings(s);
2035 return ret;
2039 * Clean up any memory from this file
2041 * Postconditions (success):
2043 * - Valgrind won't report any memory leaks from this file.
2045 * - setup_dbs() can be safely called again.
2047 int clean_dbs(void)
2049 /* Close board connections */
2050 for (size_t j = 0; j < num_connected_db; ++j) {
2051 FINALIZE_FOR_BOARD(j, check_ban);
2052 FINALIZE_FOR_BOARD(j, check_cooldown);
2053 FINALIZE_FOR_BOARD(j, check_thread_exists);
2054 FINALIZE_FOR_BOARD(j, count_posts);
2055 FINALIZE_FOR_BOARD(j, delete_thread);
2056 FINALIZE_FOR_BOARD(j, delete_post);
2057 FINALIZE_FOR_BOARD(j, find_containing_thread);
2058 FINALIZE_FOR_BOARD(j, get_subject);
2059 FINALIZE_FOR_BOARD(j, get_thread_contents);
2060 FINALIZE_FOR_BOARD(j, get_thread_summary);
2061 FINALIZE_FOR_BOARD(j, get_post_contents);
2062 FINALIZE_FOR_BOARD(j, insert_ban);
2063 FINALIZE_FOR_BOARD(j, insert_comment);
2064 FINALIZE_FOR_BOARD(j, insert_comment_II);
2065 FINALIZE_FOR_BOARD(j, list_threads);
2066 FINALIZE_FOR_BOARD(j, set_cooldown);
2067 FINALIZE_FOR_BOARD(j, update_by_moderation);
2068 FINALIZE_FOR_BOARD(j, update_file_info);
2069 FINALIZE_FOR_BOARD(j, get_recent_posts);
2071 if (board_dbs) {
2072 sqlite3_close(board_dbs[j]);
2075 board_dbs[j] = 0;
2078 free(board_dbs);
2079 board_dbs = 0;
2080 conf = 0;
2082 /* Clean up prepared board statements */
2083 CLEAN_UP_STATEMENT_ARRAY(check_ban);
2084 CLEAN_UP_STATEMENT_ARRAY(check_cooldown);
2085 CLEAN_UP_STATEMENT_ARRAY(check_thread_exists);
2086 CLEAN_UP_STATEMENT_ARRAY(count_posts);
2087 CLEAN_UP_STATEMENT_ARRAY(delete_thread);
2088 CLEAN_UP_STATEMENT_ARRAY(delete_post);
2089 CLEAN_UP_STATEMENT_ARRAY(find_containing_thread);
2090 CLEAN_UP_STATEMENT_ARRAY(get_subject);
2091 CLEAN_UP_STATEMENT_ARRAY(get_thread_contents);
2092 CLEAN_UP_STATEMENT_ARRAY(get_thread_summary);
2093 CLEAN_UP_STATEMENT_ARRAY(get_post_contents);
2094 CLEAN_UP_STATEMENT_ARRAY(insert_ban);
2095 CLEAN_UP_STATEMENT_ARRAY(insert_comment);
2096 CLEAN_UP_STATEMENT_ARRAY(insert_comment_II);
2097 CLEAN_UP_STATEMENT_ARRAY(list_threads);
2098 CLEAN_UP_STATEMENT_ARRAY(set_cooldown);
2099 CLEAN_UP_STATEMENT_ARRAY(update_by_moderation);
2100 CLEAN_UP_STATEMENT_ARRAY(update_file_info);
2101 CLEAN_UP_STATEMENT_ARRAY(get_recent_posts);
2103 /* Close global connection */
2104 sqlite3_finalize(global_check_ban_stmt);
2105 global_check_ban_stmt = 0;
2106 sqlite3_finalize(global_insert_ban_stmt);
2107 global_insert_ban_stmt = 0;
2109 if (global_db) {
2110 sqlite3_close(global_db);
2111 global_db = 0;
2114 return 0;