summaryrefslogtreecommitdiff
path: root/src/core/storage_sql.c
blob: 4a5dc13f6f28ea78320f79fb2cd2580e18ce0e64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
#include "hybbx/storage.h"
#include "hybbx/auth.h"
#include "hybbx/config.h"
#include "hybbx/password.h"
#include "hybbx/security.h"
#include "hybbx/util.h"
#include "hybbx/log.h"
#include "storage_private.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#ifdef HYBBX_HAVE_SQLITE
#include <sqlite3.h>
#endif

#define HYBBX_SQL_DEFAULT_USER_DB "users.db"
#define HYBBX_SQL_DEFAULT_MAIL_DB "mail.db"

#ifndef HYBBX_HAVE_SQLITE

hybbx_result_t hybbx_storage_sql_open(hybbx_storage_t *storage)
{
    (void)storage;
    hybbx_log_warn("[storage] SQLite backend requested but hybbx was built without "
                   "libsqlite3 — use backend=flatfile or rebuild with sqlite3");
    return HYBBX_ERR_UNSUPPORTED;
}

void hybbx_storage_sql_close(hybbx_storage_t *storage)
{
    (void)storage;
}

hybbx_result_t hybbx_storage_sql_register_user(hybbx_storage_t *storage,
                                               const hybbx_user_registration_t *reg,
                                               hybbx_user_record_t *out)
{
    (void)storage;
    (void)reg;
    (void)out;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_find_user(hybbx_storage_t *storage,
                                           const char *username,
                                           hybbx_user_record_t *out)
{
    (void)storage;
    (void)username;
    (void)out;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_resolve_user(hybbx_storage_t *storage,
                                              const char *name,
                                              hybbx_user_record_t *out)
{
    (void)storage;
    (void)name;
    (void)out;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_count_level(hybbx_storage_t *storage,
                                             hybbx_user_level_t level,
                                             size_t *count)
{
    (void)storage;
    (void)level;
    (void)count;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_foreach_user(hybbx_storage_t *storage,
                                            hybbx_storage_user_fn fn,
                                            void *ctx)
{
    (void)storage;
    (void)fn;
    (void)ctx;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_update_user(hybbx_storage_t *storage,
                                             const hybbx_user_record_t *user)
{
    (void)storage;
    (void)user;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_delete_user(hybbx_storage_t *storage,
                                             uint64_t user_id)
{
    (void)storage;
    (void)user_id;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_session_begin(hybbx_storage_t *storage,
                                               const hybbx_user_record_t *user,
                                               const char *transport,
                                               hybbx_session_record_t *out)
{
    (void)storage;
    (void)user;
    (void)transport;
    (void)out;
    return HYBBX_ERR_UNSUPPORTED;
}

hybbx_result_t hybbx_storage_sql_session_end(hybbx_storage_t *storage,
                                             uint64_t session_id)
{
    (void)storage;
    (void)session_id;
    return HYBBX_ERR_UNSUPPORTED;
}

void hybbx_storage_sql_backup_files(const hybbx_storage_t *storage)
{
    (void)storage;
}

void hybbx_storage_sql_backup_tick(hybbx_storage_t *storage)
{
    (void)storage;
}

#else /* HYBBX_HAVE_SQLITE */

struct sql_state {
    sqlite3 *users_db;
    sqlite3 *mail_db;
    unsigned backup_tick;
};

static int sql_str_ieq(const char *a, const char *b)
{
    if (a == NULL || b == NULL) {
        return 0;
    }

    while (*a != '\0' && *b != '\0') {
        char ca = (char)(*a >= 'A' && *a <= 'Z' ? *a + 32 : *a);
        char cb = (char)(*b >= 'A' && *b <= 'Z' ? *b + 32 : *b);

        if (ca != cb) {
            return 0;
        }
        a++;
        b++;
    }

    return *a == '\0' && *b == '\0';
}

static int mkdir_p(const char *path)
{
    char buf[HYBBX_PATH_MAX];
    size_t len;
    size_t i;

    if (path == NULL || path[0] == '\0') {
        return -1;
    }

    len = strlen(path);
    if (len >= sizeof(buf)) {
        return -1;
    }

    memcpy(buf, path, len + 1);

    for (i = 1; i < len; i++) {
        if (buf[i] == '/') {
            buf[i] = '\0';
            if (mkdir(buf, 0755) != 0 && errno != EEXIST) {
                return -1;
            }
            buf[i] = '/';
        }
    }

    if (mkdir(buf, 0755) != 0 && errno != EEXIST) {
        return -1;
    }

    return 0;
}

static hybbx_result_t sql_exec(sqlite3 *db, const char *sql)
{
    char *err = NULL;
    int rc;

    if (db == NULL || sql == NULL) {
        return HYBBX_ERR_INVALID;
    }

    rc = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (rc != SQLITE_OK) {
        hybbx_log_warn("[storage] sqlite: %s",
                err != NULL ? err : sqlite3_errmsg(db));
        sqlite3_free(err);
        return HYBBX_ERR_IO;
    }

    return HYBBX_OK;
}

static hybbx_result_t sql_meta_get(sqlite3 *db, const char *key, uint64_t *value)
{
    sqlite3_stmt *stmt;
    int rc;

    *value = 0;

    rc = sqlite3_prepare_v2(db,
                            "SELECT value FROM meta WHERE key = ?1;",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) {
        *value = (uint64_t)sqlite3_column_int64(stmt, 0);
    }
    sqlite3_finalize(stmt);
    return HYBBX_OK;
}

static hybbx_result_t sql_meta_set(sqlite3 *db, const char *key, uint64_t value)
{
    sqlite3_stmt *stmt;
    int rc;

    rc = sqlite3_prepare_v2(db,
                            "INSERT INTO meta(key,value) VALUES(?1,?2) "
                            "ON CONFLICT(key) DO UPDATE SET value=?2;",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_text(stmt, 1, key, -1, SQLITE_STATIC);
    sqlite3_bind_int64(stmt, 2, (sqlite3_int64)value);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    return (rc == SQLITE_DONE) ? HYBBX_OK : HYBBX_ERR_IO;
}

static hybbx_result_t sql_meta_bump(sqlite3 *db, const char *key, uint64_t *value)
{
    hybbx_result_t rc;

    rc = sql_meta_get(db, key, value);
    if (rc != HYBBX_OK) {
        return rc;
    }

    (*value)++;
    return sql_meta_set(db, key, *value);
}

static hybbx_result_t sql_open_db(const char *path, sqlite3 **out_db)
{
    int rc;
    int existed = (access(path, F_OK) == 0);

    if (out_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    *out_db = NULL;
    rc = sqlite3_open(path, out_db);
    if (rc != SQLITE_OK) {
        hybbx_log_warn("[storage] cannot open '%s': %s",
                path, sqlite3_errmsg(*out_db));
        if (*out_db != NULL) {
            sqlite3_close(*out_db);
            *out_db = NULL;
        }
        return HYBBX_ERR_IO;
    }

    sqlite3_busy_timeout(*out_db, 5000);
    if (!existed) {
        hybbx_log_info("[storage] created new database %s", path);
    } else {
        hybbx_log_info("[storage] opened existing database %s", path);
    }

    return HYBBX_OK;
}

static hybbx_result_t sql_init_users_schema(sqlite3 *db)
{
    static const char *schema =
        "CREATE TABLE IF NOT EXISTS users ("
        "  id INTEGER PRIMARY KEY,"
        "  username TEXT NOT NULL UNIQUE,"
        "  nickname TEXT,"
        "  level INTEGER NOT NULL,"
        "  active INTEGER NOT NULL,"
        "  created_at INTEGER NOT NULL,"
        "  full_name TEXT,"
        "  country TEXT,"
        "  location TEXT,"
        "  email TEXT,"
        "  password TEXT NOT NULL,"
        "  last_login_at INTEGER"
        ");"
        "CREATE INDEX IF NOT EXISTS idx_users_nickname ON users(nickname);"
        "CREATE TABLE IF NOT EXISTS sessions ("
        "  session_id INTEGER PRIMARY KEY,"
        "  user_id INTEGER NOT NULL,"
        "  username TEXT,"
        "  transport TEXT,"
        "  remote TEXT,"
        "  connected_at INTEGER,"
        "  disconnected_at INTEGER,"
        "  active INTEGER"
        ");"
        "CREATE TABLE IF NOT EXISTS meta ("
        "  key TEXT PRIMARY KEY,"
        "  value INTEGER NOT NULL"
        ");";

    return sql_exec(db, schema);
}

static hybbx_result_t sql_init_mail_schema(sqlite3 *db)
{
    static const char *schema =
        "CREATE TABLE IF NOT EXISTS messages ("
        "  id INTEGER PRIMARY KEY,"
        "  owner TEXT NOT NULL,"
        "  from_user TEXT NOT NULL,"
        "  subject TEXT,"
        "  body TEXT,"
        "  received_at INTEGER NOT NULL,"
        "  read_flag INTEGER NOT NULL DEFAULT 0,"
        "  deleted_at INTEGER,"
        "  folder INTEGER NOT NULL DEFAULT 0"
        ");"
        "CREATE INDEX IF NOT EXISTS idx_mail_owner ON messages(owner, folder, received_at DESC);"
        "CREATE TABLE IF NOT EXISTS meta ("
        "  key TEXT PRIMARY KEY,"
        "  value INTEGER NOT NULL"
        ");";

    return sql_exec(db, schema);
}

static void sql_row_to_user(sqlite3_stmt *stmt, hybbx_user_record_t *user)
{
    memset(user, 0, sizeof(*user));
    user->id = (uint64_t)sqlite3_column_int64(stmt, 0);
    hybbx_strlcpy(user->username, (const char *)sqlite3_column_text(stmt, 1),
                  sizeof(user->username));
    if (sqlite3_column_text(stmt, 2) != NULL) {
        hybbx_strlcpy(user->nickname, (const char *)sqlite3_column_text(stmt, 2),
                      sizeof(user->nickname));
    }
    user->level = (hybbx_user_level_t)sqlite3_column_int(stmt, 3);
    user->active = sqlite3_column_int(stmt, 4);
    user->created_at = (time_t)sqlite3_column_int64(stmt, 5);
    if (sqlite3_column_text(stmt, 6) != NULL) {
        hybbx_strlcpy(user->full_name, (const char *)sqlite3_column_text(stmt, 6),
                      sizeof(user->full_name));
    }
    if (sqlite3_column_text(stmt, 7) != NULL) {
        hybbx_strlcpy(user->country, (const char *)sqlite3_column_text(stmt, 7),
                      sizeof(user->country));
    }
    if (sqlite3_column_text(stmt, 8) != NULL) {
        hybbx_strlcpy(user->location, (const char *)sqlite3_column_text(stmt, 8),
                      sizeof(user->location));
    }
    if (sqlite3_column_text(stmt, 9) != NULL) {
        hybbx_strlcpy(user->email, (const char *)sqlite3_column_text(stmt, 9),
                      sizeof(user->email));
    }
    if (sqlite3_column_text(stmt, 10) != NULL) {
        hybbx_strlcpy(user->password, (const char *)sqlite3_column_text(stmt, 10),
                      sizeof(user->password));
    }
    user->last_login_at = (time_t)sqlite3_column_int64(stmt, 11);
}

static hybbx_result_t sql_ensure_default_sysop(hybbx_storage_t *storage)
{
    struct sql_state *state = storage->backend_data;
    size_t sysop_count = 0;
    hybbx_user_record_t sysop;
    char plain_password[HYBBX_PASSWORD_MAX_LEN + 1];
    uint64_t user_id;
    sqlite3_stmt *stmt;
    int rc;
    hybbx_result_t hres;

    hres = hybbx_storage_sql_count_level(storage, HYBBX_LEVEL_SYSOP, &sysop_count);
    if (hres != HYBBX_OK) {
        return hres;
    }
    if (sysop_count > 0) {
        return HYBBX_OK;
    }

    hres = sql_meta_bump(state->users_db, "user_next", &user_id);
    if (hres != HYBBX_OK) {
        return hres;
    }

    memset(&sysop, 0, sizeof(sysop));
    sysop.id = user_id;
    hybbx_strlcpy(sysop.username, "sysop", sizeof(sysop.username));
    hybbx_strlcpy(sysop.nickname, HYBBX_DEFAULT_SYSOP_USERNAME,
                  sizeof(sysop.nickname));
    sysop.level = HYBBX_LEVEL_SYSOP;
    sysop.active = 1;
    sysop.created_at = time(NULL);
    hybbx_strlcpy(sysop.full_name, "System Operator", sizeof(sysop.full_name));

    if (hybbx_password_generate_alnum(plain_password, sizeof(plain_password),
                                      HYBBX_SYSOP_INIT_PASSWORD_MIN,
                                      HYBBX_SYSOP_INIT_PASSWORD_MAX) != HYBBX_OK) {
        return HYBBX_ERR_IO;
    }
    if (hybbx_password_hash(plain_password, sysop.password,
                            sizeof(sysop.password)) != HYBBX_OK) {
        return HYBBX_ERR_IO;
    }

    rc = sqlite3_prepare_v2(state->users_db,
                            "INSERT INTO users(id,username,nickname,level,active,"
                            "created_at,full_name,country,location,email,password,"
                            "last_login_at) VALUES(?1,?2,?3,?4,?5,?6,?7,'','','',?8,0);",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int64(stmt, 1, (sqlite3_int64)sysop.id);
    sqlite3_bind_text(stmt, 2, sysop.username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, sysop.nickname, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 4, (int)sysop.level);
    sqlite3_bind_int(stmt, 5, sysop.active);
    sqlite3_bind_int64(stmt, 6, (sqlite3_int64)sysop.created_at);
    sqlite3_bind_text(stmt, 7, sysop.full_name, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 8, sysop.password, -1, SQLITE_STATIC);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    if (rc != SQLITE_DONE) {
        return HYBBX_ERR_IO;
    }

    hybbx_log_info("[storage] created default Sysop in %s (login: %s / %s)",
           storage->sql_cfg.user_db, sysop.nickname, plain_password);
    hybbx_security_log_write("sysop_created user=%s", sysop.nickname);
    return HYBBX_OK;
}

static hybbx_result_t sql_copy_file(const char *src, const char *dst)
{
    FILE *in_fp;
    FILE *out_fp;
    unsigned char buf[4096];
    size_t n;

    in_fp = fopen(src, "rb");
    if (in_fp == NULL) {
        return HYBBX_ERR_IO;
    }

    out_fp = fopen(dst, "wb");
    if (out_fp == NULL) {
        fclose(in_fp);
        return HYBBX_ERR_IO;
    }

    while ((n = fread(buf, 1, sizeof(buf), in_fp)) > 0) {
        if (fwrite(buf, 1, n, out_fp) != n) {
            fclose(in_fp);
            fclose(out_fp);
            return HYBBX_ERR_IO;
        }
    }

    fclose(in_fp);
    if (fclose(out_fp) != 0) {
        return HYBBX_ERR_IO;
    }

    return HYBBX_OK;
}

static void sql_backup_one(sqlite3 *db, const char *src_path,
                           const char *backup_dir)
{
    char dst[HYBBX_PATH_MAX];
    const char *base;
    hybbx_result_t rc;

    if (db == NULL || src_path == NULL || src_path[0] == '\0') {
        return;
    }

    (void)sqlite3_wal_checkpoint_v2(db, NULL, SQLITE_CHECKPOINT_TRUNCATE, NULL, NULL);

    base = strrchr(src_path, '/');
    base = (base != NULL) ? base + 1 : src_path;

    if (backup_dir != NULL && backup_dir[0] != '\0') {
        char name[HYBBX_PATH_MAX];

        if (mkdir_p(backup_dir) != 0) {
            return;
        }
        if (strlen(base) + strlen(HYBBX_STORAGE_BACKUP_SUFFIX) + 1 >=
            sizeof(name)) {
            return;
        }
        snprintf(name, sizeof(name), "%s%s", base, HYBBX_STORAGE_BACKUP_SUFFIX);
        if (hybbx_path_join(dst, sizeof(dst), backup_dir, name) != HYBBX_OK) {
            return;
        }
    } else {
        if (strlen(src_path) + strlen(HYBBX_STORAGE_BACKUP_SUFFIX) + 1 >=
            sizeof(dst)) {
            return;
        }
        snprintf(dst, sizeof(dst), "%s%s", src_path, HYBBX_STORAGE_BACKUP_SUFFIX);
    }

    rc = sql_copy_file(src_path, dst);
    if (rc != HYBBX_OK) {
        hybbx_log_warn("[storage] backup failed %s -> %s", src_path, dst);
    }
}

hybbx_result_t hybbx_storage_sql_open(hybbx_storage_t *storage)
{
    struct sql_state *state;
    hybbx_result_t rc;

    if (storage == NULL || storage->path == NULL) {
        return HYBBX_ERR_INVALID;
    }

    if (storage->backend == HYBBX_STORAGE_MYSQL ||
        storage->backend == HYBBX_STORAGE_MARIADB) {
        hybbx_log_warn("[storage] MySQL/MariaDB backends are not supported — "
                       "use flatfile or sqlite");
        return HYBBX_ERR_UNSUPPORTED;
    }

    if (mkdir_p(storage->path) != 0) {
        hybbx_log_warn("[storage] cannot create data path '%s'",
                storage->path);
        return HYBBX_ERR_IO;
    }

    state = calloc(1, sizeof(*state));
    if (state == NULL) {
        return HYBBX_ERR_NOMEM;
    }

    rc = sql_open_db(storage->sql_cfg.user_db, &state->users_db);
    if (rc != HYBBX_OK) {
        free(state);
        return rc;
    }

    rc = sql_init_users_schema(state->users_db);
    if (rc != HYBBX_OK) {
        hybbx_storage_sql_close(storage);
        free(state);
        return rc;
    }

    rc = sql_open_db(storage->sql_cfg.mail_db, &state->mail_db);
    if (rc != HYBBX_OK) {
        sqlite3_close(state->users_db);
        free(state);
        return rc;
    }

    rc = sql_init_mail_schema(state->mail_db);
    if (rc != HYBBX_OK) {
        sqlite3_close(state->users_db);
        sqlite3_close(state->mail_db);
        free(state);
        return rc;
    }

    storage->backend_data = state;

    rc = sql_ensure_default_sysop(storage);
    if (rc != HYBBX_OK) {
        hybbx_storage_sql_close(storage);
        return rc;
    }

    hybbx_log_info("[storage] sqlite user_db=%s mail_db=%s backup_interval=%us",
           storage->sql_cfg.user_db, storage->sql_cfg.mail_db,
           storage->sql_cfg.backup_interval_sec);

    return HYBBX_OK;
}

void hybbx_storage_sql_close(hybbx_storage_t *storage)
{
    struct sql_state *state;

    if (storage == NULL) {
        return;
    }

    state = storage->backend_data;
    if (state == NULL) {
        return;
    }

    if (state->users_db != NULL) {
        sqlite3_close(state->users_db);
    }
    if (state->mail_db != NULL) {
        sqlite3_close(state->mail_db);
    }

    free(state);
    storage->backend_data = NULL;
}

sqlite3 *hybbx_storage_sql_mail_db(hybbx_storage_t *storage)
{
    struct sql_state *state;

    if (storage == NULL) {
        return NULL;
    }

    state = storage->backend_data;
    if (state == NULL) {
        return NULL;
    }

    return state->mail_db;
}

static hybbx_result_t sql_find_user_by_column(sqlite3 *db, const char *column,
                                              const char *name,
                                              hybbx_user_record_t *out)
{
    sqlite3_stmt *stmt;
    int rc;
    const char *sql_username =
        "SELECT id,username,nickname,level,active,created_at,full_name,"
        "country,location,email,password,last_login_at "
        "FROM users WHERE lower(username)=lower(?1) LIMIT 1;";
    const char *sql_nickname =
        "SELECT id,username,nickname,level,active,created_at,full_name,"
        "country,location,email,password,last_login_at "
        "FROM users WHERE lower(nickname)=lower(?1) LIMIT 1;";
    const char *sql = sql_str_ieq(column, "nickname") ? sql_nickname :
                                                        sql_username;

    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_text(stmt, 1, name, -1, SQLITE_STATIC);
    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) {
        sql_row_to_user(stmt, out);
        sqlite3_finalize(stmt);
        return HYBBX_OK;
    }

    sqlite3_finalize(stmt);
    return HYBBX_ERR_NOT_FOUND;
}

hybbx_result_t hybbx_storage_sql_find_user(hybbx_storage_t *storage,
                                          const char *username,
                                          hybbx_user_record_t *out)
{
    struct sql_state *state;
    char normalized[HYBBX_USER_NAME_MAX];

    if (storage == NULL || username == NULL || out == NULL) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    hybbx_strlcpy(normalized, username, sizeof(normalized));
    hybbx_username_normalize(normalized);
    return sql_find_user_by_column(state->users_db, "username", normalized, out);
}

hybbx_result_t hybbx_storage_sql_resolve_user(hybbx_storage_t *storage,
                                            const char *name,
                                            hybbx_user_record_t *out)
{
    hybbx_result_t rc;

    if (storage == NULL || name == NULL || out == NULL || name[0] == '\0') {
        return HYBBX_ERR_INVALID;
    }

    rc = hybbx_storage_sql_find_user(storage, name, out);
    if (rc == HYBBX_OK) {
        return HYBBX_OK;
    }
    if (rc != HYBBX_ERR_NOT_FOUND) {
        return rc;
    }

    return sql_find_user_by_column(
        ((struct sql_state *)storage->backend_data)->users_db,
        "nickname", name, out);
}

typedef struct foreach_ctx {
    hybbx_storage_user_fn fn;
    void *user_ctx;
} foreach_ctx_t;

static int sql_foreach_cb(void *ctx, int n_cols, char **values, char **cols)
{
    hybbx_user_record_t user;
    foreach_ctx_t *fctx = (foreach_ctx_t *)ctx;
    hybbx_result_t rc;
    int i;

    (void)n_cols;
    (void)cols;
    memset(&user, 0, sizeof(user));

    for (i = 0; values[i] != NULL; i++) {
        switch (i) {
        case 0: user.id = (uint64_t)strtoull(values[i], NULL, 10); break;
        case 1: hybbx_strlcpy(user.username, values[i], sizeof(user.username)); break;
        case 2: hybbx_strlcpy(user.nickname, values[i], sizeof(user.nickname)); break;
        case 3: user.level = (hybbx_user_level_t)atoi(values[i]); break;
        case 4: user.active = atoi(values[i]); break;
        case 5: user.created_at = (time_t)strtoll(values[i], NULL, 10); break;
        case 6: hybbx_strlcpy(user.full_name, values[i], sizeof(user.full_name)); break;
        case 7: hybbx_strlcpy(user.country, values[i], sizeof(user.country)); break;
        case 8: hybbx_strlcpy(user.location, values[i], sizeof(user.location)); break;
        case 9: hybbx_strlcpy(user.email, values[i], sizeof(user.email)); break;
        case 10: hybbx_strlcpy(user.password, values[i], sizeof(user.password)); break;
        case 11: user.last_login_at = (time_t)strtoll(values[i], NULL, 10); break;
        default: break;
        }
    }

    rc = fctx->fn(&user, fctx->user_ctx);
    return (rc == HYBBX_OK) ? 0 : 1;
}

hybbx_result_t hybbx_storage_sql_foreach_user(hybbx_storage_t *storage,
                                              hybbx_storage_user_fn fn,
                                              void *ctx)
{
    struct sql_state *state;
    foreach_ctx_t fctx;
    char *err = NULL;
    int rc;

    if (storage == NULL || fn == NULL) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    fctx.fn = fn;
    fctx.user_ctx = ctx;

    rc = sqlite3_exec(state->users_db,
                      "SELECT id,username,nickname,level,active,created_at,"
                      "full_name,country,location,email,password,last_login_at "
                      "FROM users ORDER BY id;",
                      sql_foreach_cb, &fctx, &err);
    if (rc == SQLITE_ABORT) {
        sqlite3_free(err);
        return HYBBX_ERR_BUSY;
    }
    if (rc != SQLITE_OK) {
        hybbx_log_warn("[storage] foreach: %s", err != NULL ? err : "error");
        sqlite3_free(err);
        return HYBBX_ERR_IO;
    }

    return HYBBX_OK;
}

hybbx_result_t hybbx_storage_sql_count_level(hybbx_storage_t *storage,
                                             hybbx_user_level_t level,
                                             size_t *count)
{
    struct sql_state *state;
    sqlite3_stmt *stmt;
    int rc;

    if (storage == NULL || count == NULL) {
        return HYBBX_ERR_INVALID;
    }

    *count = 0;
    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    rc = sqlite3_prepare_v2(state->users_db,
                            "SELECT COUNT(*) FROM users WHERE level=?1;",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int(stmt, 1, (int)level);
    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) {
        *count = (size_t)sqlite3_column_int64(stmt, 0);
    }
    sqlite3_finalize(stmt);
    return HYBBX_OK;
}

typedef struct identity_taken_ctx {
    const char *username;
    const char *nickname;
    int taken;
} identity_taken_ctx_t;

static hybbx_result_t identity_taken_cb(const hybbx_user_record_t *user, void *ctx)
{
    identity_taken_ctx_t *ictx = (identity_taken_ctx_t *)ctx;

    if (sql_str_ieq(user->username, ictx->username) ||
        sql_str_ieq(user->username, ictx->nickname) ||
        (user->nickname[0] != '\0' &&
         (sql_str_ieq(user->nickname, ictx->nickname) ||
          sql_str_ieq(user->nickname, ictx->username)))) {
        ictx->taken = 1;
        return HYBBX_ERR_BUSY;
    }

    return HYBBX_OK;
}

hybbx_result_t hybbx_storage_sql_register_user(hybbx_storage_t *storage,
                                               const hybbx_user_registration_t *reg,
                                               hybbx_user_record_t *out)
{
    struct sql_state *state;
    hybbx_user_record_t existing;
    identity_taken_ctx_t taken;
    uint64_t user_id;
    sqlite3_stmt *stmt;
    int rc;
    hybbx_result_t hres;

    if (storage == NULL || reg == NULL || out == NULL) {
        return HYBBX_ERR_INVALID;
    }

    if (!hybbx_registration_valid(reg, storage->guest_prefix)) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    hres = hybbx_storage_sql_find_user(storage, reg->username, &existing);
    if (hres == HYBBX_OK) {
        return HYBBX_ERR_BUSY;
    }
    if (hres != HYBBX_ERR_NOT_FOUND) {
        return hres;
    }

    memset(&taken, 0, sizeof(taken));
    taken.username = reg->username;
    taken.nickname = reg->nickname;
    hres = hybbx_storage_sql_foreach_user(storage, identity_taken_cb, &taken);
    if (hres == HYBBX_ERR_BUSY || taken.taken) {
        return HYBBX_ERR_BUSY;
    }
    if (hres != HYBBX_OK) {
        return hres;
    }

    hres = sql_meta_bump(state->users_db, "user_next", &user_id);
    if (hres != HYBBX_OK) {
        return hres;
    }

    memset(out, 0, sizeof(*out));
    out->id = user_id;
    hybbx_strlcpy(out->username, reg->username, sizeof(out->username));
    hybbx_username_normalize(out->username);
    hybbx_strlcpy(out->nickname, reg->nickname, sizeof(out->nickname));
    out->level = HYBBX_LEVEL_USER;
    out->active = 0;
    out->created_at = time(NULL);
    hybbx_strlcpy(out->full_name, reg->full_name, sizeof(out->full_name));
    hybbx_strlcpy(out->country, reg->country, sizeof(out->country));
    hybbx_strlcpy(out->location, reg->location, sizeof(out->location));
    hybbx_strlcpy(out->email, reg->email, sizeof(out->email));

    if (reg->password[0] != '\0') {
        if (!hybbx_password_plain_valid(reg->password)) {
            return HYBBX_ERR_INVALID;
        }
        hres = hybbx_password_hash(reg->password, out->password,
                                   sizeof(out->password));
        if (hres != HYBBX_OK) {
            return hres;
        }
    }

    rc = sqlite3_prepare_v2(state->users_db,
                            "INSERT INTO users(id,username,nickname,level,active,"
                            "created_at,full_name,country,location,email,password,"
                            "last_login_at) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,0);",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int64(stmt, 1, (sqlite3_int64)out->id);
    sqlite3_bind_text(stmt, 2, out->username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, out->nickname, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 4, (int)out->level);
    sqlite3_bind_int(stmt, 5, out->active);
    sqlite3_bind_int64(stmt, 6, (sqlite3_int64)out->created_at);
    sqlite3_bind_text(stmt, 7, out->full_name, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 8, out->country, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 9, out->location, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 10, out->email, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 11, out->password, -1, SQLITE_STATIC);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    return (rc == SQLITE_DONE) ? HYBBX_OK : HYBBX_ERR_IO;
}

hybbx_result_t hybbx_storage_sql_update_user(hybbx_storage_t *storage,
                                             const hybbx_user_record_t *user)
{
    struct sql_state *state;
    sqlite3_stmt *stmt;
    int rc;

    if (storage == NULL || user == NULL || user->id == 0) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    rc = sqlite3_prepare_v2(state->users_db,
                            "UPDATE users SET username=?2,nickname=?3,level=?4,"
                            "active=?5,created_at=?6,full_name=?7,country=?8,"
                            "location=?9,email=?10,password=?11,last_login_at=?12 "
                            "WHERE id=?1;",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int64(stmt, 1, (sqlite3_int64)user->id);
    sqlite3_bind_text(stmt, 2, user->username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, user->nickname, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 4, (int)user->level);
    sqlite3_bind_int(stmt, 5, user->active);
    sqlite3_bind_int64(stmt, 6, (sqlite3_int64)user->created_at);
    sqlite3_bind_text(stmt, 7, user->full_name, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 8, user->country, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 9, user->location, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 10, user->email, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 11, user->password, -1, SQLITE_STATIC);
    sqlite3_bind_int64(stmt, 12, (sqlite3_int64)user->last_login_at);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    if (rc != SQLITE_DONE) {
        return HYBBX_ERR_IO;
    }
    if (sqlite3_changes(state->users_db) == 0) {
        return HYBBX_ERR_NOT_FOUND;
    }

    return HYBBX_OK;
}

hybbx_result_t hybbx_storage_sql_delete_user(hybbx_storage_t *storage,
                                             uint64_t user_id)
{
    struct sql_state *state;
    sqlite3_stmt *stmt;
    int rc;

    if (storage == NULL || user_id == 0) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    rc = sqlite3_prepare_v2(state->users_db,
                            "DELETE FROM users WHERE id=?1;",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int64(stmt, 1, (sqlite3_int64)user_id);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    if (rc != SQLITE_DONE) {
        return HYBBX_ERR_IO;
    }
    if (sqlite3_changes(state->users_db) == 0) {
        return HYBBX_ERR_NOT_FOUND;
    }

    return HYBBX_OK;
}

hybbx_result_t hybbx_storage_sql_session_begin(hybbx_storage_t *storage,
                                               const hybbx_user_record_t *user,
                                               const char *transport,
                                               hybbx_session_record_t *out)
{
    struct sql_state *state;
    sqlite3_stmt *stmt;
    int rc;
    hybbx_result_t hres;

    if (storage == NULL || user == NULL || transport == NULL || out == NULL) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    memset(out, 0, sizeof(*out));
    hres = sql_meta_bump(state->users_db, "session_next", &out->session_id);
    if (hres != HYBBX_OK) {
        return hres;
    }

    out->user_id = user->id;
    hybbx_strlcpy(out->username, user->username, sizeof(out->username));
    hybbx_strlcpy(out->transport, transport, sizeof(out->transport));
    out->connected_at = time(NULL);
    out->active = 1;

    rc = sqlite3_prepare_v2(state->users_db,
                            "INSERT INTO sessions(session_id,user_id,username,"
                            "transport,remote,connected_at,disconnected_at,active) "
                            "VALUES(?1,?2,?3,?4,'',?5,0,1);",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int64(stmt, 1, (sqlite3_int64)out->session_id);
    sqlite3_bind_int64(stmt, 2, (sqlite3_int64)out->user_id);
    sqlite3_bind_text(stmt, 3, out->username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, out->transport, -1, SQLITE_STATIC);
    sqlite3_bind_int64(stmt, 5, (sqlite3_int64)out->connected_at);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    return (rc == SQLITE_DONE) ? HYBBX_OK : HYBBX_ERR_IO;
}

hybbx_result_t hybbx_storage_sql_session_end(hybbx_storage_t *storage,
                                             uint64_t session_id)
{
    struct sql_state *state;
    sqlite3_stmt *stmt;
    int rc;
    time_t now = time(NULL);

    if (storage == NULL || session_id == 0) {
        return HYBBX_ERR_INVALID;
    }

    state = storage->backend_data;
    if (state == NULL || state->users_db == NULL) {
        return HYBBX_ERR_INVALID;
    }

    rc = sqlite3_prepare_v2(state->users_db,
                            "UPDATE sessions SET disconnected_at=?2, active=0 "
                            "WHERE session_id=?1;",
                            -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        return HYBBX_ERR_IO;
    }

    sqlite3_bind_int64(stmt, 1, (sqlite3_int64)session_id);
    sqlite3_bind_int64(stmt, 2, (sqlite3_int64)now);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    if (rc != SQLITE_DONE) {
        return HYBBX_ERR_IO;
    }

    if (sqlite3_changes(state->users_db) == 0) {
        rc = sqlite3_prepare_v2(state->users_db,
                                "INSERT INTO sessions(session_id,user_id,username,"
                                "transport,remote,connected_at,disconnected_at,"
                                "active) VALUES(?1,0,'','','',0,?2,0);",
                                -1, &stmt, NULL);
        if (rc != SQLITE_OK) {
            return HYBBX_ERR_IO;
        }
        sqlite3_bind_int64(stmt, 1, (sqlite3_int64)session_id);
        sqlite3_bind_int64(stmt, 2, (sqlite3_int64)now);
        rc = sqlite3_step(stmt);
        sqlite3_finalize(stmt);
        if (rc != SQLITE_DONE) {
            return HYBBX_ERR_IO;
        }
    }

    return HYBBX_OK;
}

void hybbx_storage_sql_backup_files(const hybbx_storage_t *storage)
{
    struct sql_state *state;
    const char *backup_dir;

    if (storage == NULL || storage->backend != HYBBX_STORAGE_SQLITE) {
        return;
    }

    state = storage->backend_data;
    if (state == NULL) {
        return;
    }

    backup_dir = storage->sql_cfg.backup_path;
    if (backup_dir != NULL && backup_dir[0] == '\0') {
        backup_dir = NULL;
    }

    sql_backup_one(state->users_db, storage->sql_cfg.user_db, backup_dir);
    sql_backup_one(state->mail_db, storage->sql_cfg.mail_db, backup_dir);
}

void hybbx_storage_sql_backup_tick(hybbx_storage_t *storage)
{
    struct sql_state *state;

    if (storage == NULL || storage->backend != HYBBX_STORAGE_SQLITE) {
        return;
    }

    state = storage->backend_data;
    if (state == NULL || storage->sql_cfg.backup_interval_sec == 0) {
        return;
    }

    state->backup_tick++;
    if (state->backup_tick >= storage->sql_cfg.backup_interval_sec) {
        state->backup_tick = 0;
        hybbx_storage_sql_backup_files(storage);
    }
}

#endif /* HYBBX_HAVE_SQLITE */
git clone -b <branch> https://cgit.mode42.com/<repo>.git
git clone -b <branch> git://cgit.mode42.com/<repo>.git

info@mode42.com