-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdb.c
1842 lines (1599 loc) · 38.3 KB
/
db.c
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
/*
* Copyright (c) Kristaps Dzonsons <kristaps@bsd.lv>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include <sys/statvfs.h>
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sqlite3.h>
#include "libkcaldav.h"
#include "db.h"
/*
* How many nonces do we allow in the database.
* Too few nonces and a clever attacker can SYN-flood the nonce
* database, and too many and it'll just be ponderous.
*/
#define NONCEMAX 1000
/*
* Length of nonce string w/o NUL terminator.
*/
#define NONCESZ 16
enum sqlstmt {
SQL_COL_GET,
SQL_COL_GET_ID,
SQL_COL_INSERT,
SQL_COL_ITER,
SQL_COL_REMOVE,
SQL_COL_UPDATE,
SQL_COL_UPDATE_CTAG,
SQL_NONCE_COUNT,
SQL_NONCE_GET_COUNT,
SQL_NONCE_INSERT,
SQL_NONCE_REMOVE,
SQL_NONCE_REMOVE_MULTI,
SQL_NONCE_UPDATE,
SQL_OWNER_GET,
SQL_OWNER_INSERT,
SQL_PRNCPL_GET,
SQL_PRNCPL_GET_ID,
SQL_PRNCPL_INSERT,
SQL_PRNCPL_UPDATE,
SQL_PROXY_INSERT,
SQL_PROXY_ITER,
SQL_PROXY_ITER_PRNCPL,
SQL_PROXY_REMOVE,
SQL_PROXY_UPDATE,
SQL_RES_GET,
SQL_RES_GET_ETAG,
SQL_RES_INSERT,
SQL_RES_ITER,
SQL_RES_REMOVE,
SQL_RES_REMOVE_ETAG,
SQL_RES_UPDATE,
SQL__MAX
};
static const char *sqls[SQL__MAX] = {
/* SQL_COL_GET */
"SELECT url,displayname,colour,description,ctag,id "
"FROM collection WHERE principal=? AND url=?",
/* SQL_COL_GET_ID */
"SELECT url,displayname,colour,description,ctag,id "
"FROM collection WHERE principal=? AND id=?",
/* SQL_COL_INSERT */
"INSERT INTO collection (principal, url) VALUES (?,?)",
/* SQL_COL_ITER */
"SELECT url,displayname,colour,description,ctag,id "
"FROM collection WHERE principal=?",
/* SQL_COL_REMOVE */
"DELETE FROM collection WHERE id=?",
/* SQL_COL_UPDATE */
"UPDATE collection SET displayname=?,colour=?,description=? "
"WHERE id=?",
/* SQL_COL_UPDATE_CTAG */
"UPDATE collection SET ctag=ctag+1 WHERE id=?",
/* SQL_NONCE_COUNT */
"SELECT count(*) FROM nonce",
/* SQL_NONCE_GET_COUNT */
"SELECT count FROM nonce WHERE nonce=?",
/* SQL_NONCE_INSERT */
"INSERT INTO nonce (nonce) VALUES (?)",
/* SQL_NONCE_REMOVE */
"DELETE FROM nonce WHERE nonce=?",
/* SQL_NONCE_REMOVE_MULTI */
"DELETE FROM nonce WHERE id IN (SELECT id FROM nonce LIMIT 20)",
/* SQL_NONCE_UDPATE */
"UPDATE nonce SET count=? WHERE nonce=?",
/* SQL_OWNER_GET */
"SELECT owneruid FROM database",
/* SQL_OWNER_INSERT */
"INSERT INTO database (owneruid) VALUES (?)",
/* SQL_PRNCPL_GET */
"SELECT hash,id,email FROM principal WHERE name=?",
/* SQL_PRNCPL_GET_ID */
"SELECT id FROM principal WHERE email=?",
/* SQL_PRNCPL_INSERT */
"INSERT INTO principal (name,hash,email) VALUES (?,?,?)",
/* SQL_PRNCPL_UPDATE */
"UPDATE principal SET hash=?,email=? WHERE id=?",
/* SQL_PROXY_INSERT */
"INSERT INTO proxy (principal,proxy,bits) VALUES (?, ?, ?)",
/* SQL_PROXY_ITER */
"SELECT email,name,bits,principal,proxy.id FROM proxy "
"INNER JOIN principal ON principal.id=principal "
"WHERE proxy=?",
/* SQL_PROXY_ITER_PRNCPL */
"SELECT email,name,bits,proxy,proxy.id FROM proxy "
"INNER JOIN principal ON principal.id=proxy "
"WHERE principal=?",
/* SQL_PROXY_REMOVE */
"DELETE FROM proxy WHERE principal=? AND proxy=?",
/* SQL_PROXY_UPDATE */
"UPDATE proxy SET bits=? WHERE principal=? AND proxy=?",
/* SQL_RES_GET */
"SELECT data,etag,url,id,collection FROM resource "
"WHERE collection=? AND url=?",
/* SQL_RES_GET_ETAG */
"SELECT id FROM resource WHERE url=? AND collection=? "
"AND etag=?",
/* SQL_RES_INSERT */
"INSERT INTO resource (data,url,collection,etag) "
"VALUES (?,?,?,?)",
/* SQL_RES_ITER */
"SELECT data,etag,url,id,collection FROM resource "
"WHERE collection=?",
/* SQL_RES_REMOVE */
"DELETE FROM resource WHERE url=? AND collection=?",
/* SQL_RES_REMOVE_ETAG */
"DELETE FROM resource WHERE url=? AND collection=? "
"AND etag=?",
/* SQL_RES_UPDATE */
"UPDATE resource SET data=?,etag=? WHERE id=?",
};
/* Wrappers for debugging functions. */
static void kdbg(const char *, ...)
__attribute__((format(printf, 1, 2)));
static void kinfo(const char *, ...)
__attribute__((format(printf, 1, 2)));
static void kerr(const char *, ...)
__attribute__((format(printf, 1, 2)));
static void kerrx(const char *, ...)
__attribute__((format(printf, 1, 2)));
/* The database (or NULL) and it's location. */
static sqlite3 *db;
static char dbname[PATH_MAX];
/* Identifier and private data to provide to db_msg functions. */
static const char *msg_ident;
static void *msg_arg;
/*
* Message callbacks: debugging (lowest priority), info (informational,
* low priority), and errors.
*/
static db_msg msg_dbg;
static db_msg msg_info;
static db_msg msg_err;
static db_msg msg_errx;
void
db_set_msg_arg(void *arg)
{
msg_arg = arg;
}
void
db_set_msg_ident(const char *ident)
{
msg_ident = ident;
}
void
db_set_msg_dbg(db_msg msg)
{
msg_dbg = msg;
}
void
db_set_msg_errx(db_msg msg)
{
msg_errx = msg;
}
void
db_set_msg_err(db_msg msg)
{
msg_err = msg;
}
void
db_set_msg_info(db_msg msg)
{
msg_info = msg;
}
/*
* Log information.
* This means an operation that changed the database.
*/
static void
kinfo(const char *fmt, ...)
{
va_list ap;
if (msg_info == NULL)
return;
va_start(ap, fmt);
msg_info(msg_arg, msg_ident, fmt, ap);
va_end(ap);
}
/*
* Debugging log.
* This changed the database---but in a minor way.
* The best example is nonce updates, which aren't important.
*/
static void
kdbg(const char *fmt, ...)
{
va_list ap;
if (msg_dbg == NULL)
return;
va_start(ap, fmt);
msg_dbg(msg_arg, msg_ident, fmt, ap);
va_end(ap);
}
/*
* Error callback.
* This will probably trigger application exit.
*/
static void
kerr(const char *fmt, ...)
{
va_list ap;
if (msg_errx == NULL)
return;
va_start(ap, fmt);
msg_err(msg_arg, msg_ident, fmt, ap);
va_end(ap);
}
/*
* Error callback (no errno).
* This will probably trigger application exit.
*/
static void
kerrx(const char *fmt, ...)
{
va_list ap;
if (msg_errx == NULL)
return;
va_start(ap, fmt);
msg_errx(msg_arg, msg_ident, fmt, ap);
va_end(ap);
}
/*
* Close the database and reset the database filename.
* This should be called on exit time with atexit(3).
*/
static void
db_close(void)
{
if (sqlite3_close(db) != SQLITE_OK)
kerrx("%s", sqlite3_errmsg(db));
db = NULL;
explicit_bzero(dbname, PATH_MAX);
}
/*
* Finalise and nullify a statement.
* Use this instead of sqlite3_finalize() so we catch any re-uses of the
* statement object.
*/
static void
db_finalise(sqlite3_stmt **stmt)
{
if (*stmt == NULL)
return;
sqlite3_finalize(*stmt);
*stmt = NULL;
}
/*
* Provided mainly for Linux that doesn't have arc4random.
* Returns a (non-cryptographic) random number.
*/
static uint32_t
get_random(void)
{
#if HAVE_ARC4RANDOM
return arc4random();
#else
return random();
#endif
}
/*
* Provided mainly for Linux that doesn't have arc4random.
* Returns a (non-cryptographic) random number between [0, sz).
*/
static uint32_t
get_random_uniform(size_t sz)
{
#if HAVE_ARC4RANDOM
return arc4random_uniform(sz);
#else
return random() % sz;
#endif
}
/*
* Sleep for a random period in a sequence of sleeps.
* This is influenced by the PRNG so that we don't have all consumers
* sleeping and waking at the same time.
*/
static void
db_sleep(size_t attempt)
{
if (attempt < 10)
usleep(get_random_uniform(100000));
else
usleep(get_random_uniform(400000));
}
/*
* Interior function managing step errors.
*/
static int
db_step_inner(sqlite3_stmt *stmt, int constrained)
{
int rc;
size_t attempt = 0;
again:
assert(stmt != NULL);
assert(db != NULL);
rc = sqlite3_step(stmt);
switch (rc) {
case SQLITE_BUSY:
db_sleep(attempt++);
goto again;
case SQLITE_LOCKED:
kdbg("sqlite3_step: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_PROTOCOL:
kdbg("sqlite3_step: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_DONE:
/* FALLTHROUGH */
case SQLITE_ROW:
return rc;
case SQLITE_CONSTRAINT:
if (constrained)
return rc;
break;
default:
break;
}
kerrx("sqlite3_step: %s", sqlite3_errmsg(db));
return rc;
}
/*
* Step through any results where the return code can also be
* SQL_CONSTRAINT, i.e., we've violated our constraints.
* If we were using db_step() on that, it'd return failure.
* Returns the sqlite3 error code.
*/
static int
db_step_constrained(sqlite3_stmt *stmt)
{
return db_step_inner(stmt, 1);
}
/*
* Step through any results on a prepared statement.
* We report errors on anything other than SQLITE_ROW and SQLITE_DONE.
* Returns the sqlite3 error code.
*/
static int
db_step(sqlite3_stmt *stmt)
{
return db_step_inner(stmt, 0);
}
/*
* Bind a 64-bit integer "v" to the statement.
* Return zero on failure, non-zero on success.
*/
static int
db_bindint(sqlite3_stmt *stmt, size_t pos, int64_t v)
{
assert(pos > 0);
if (sqlite3_bind_int64(stmt, pos, v) == SQLITE_OK)
return 1;
kerrx("sqlite3_bind_int64: %s", sqlite3_errmsg(db));
return 0;
}
/*
* Bind a NUL-terminated string "name" to the statement.
* Return zero on failure, non-zero on success.
*/
static int
db_bindtext(sqlite3_stmt *stmt, size_t pos, const char *name)
{
assert(pos > 0);
if (sqlite3_bind_text(stmt,
pos, name, -1, SQLITE_STATIC) == SQLITE_OK)
return 1;
kerrx("sqlite3_bind_text: %s", sqlite3_errmsg(db));
return 0;
}
/*
* Execute a non-parameterised SQL statement.
* Returns the sqlite3 error code, reporting the error if it doesn't
* equal SQLITE_OK.
*/
static int
db_exec(const char *sql)
{
size_t attempt = 0;
int rc;
again:
assert(NULL != db);
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
switch (rc) {
case SQLITE_BUSY:
db_sleep(attempt++);
goto again;
case SQLITE_LOCKED:
kdbg("sqlite3_exec: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_PROTOCOL:
kdbg("sqlite3_exec: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_OK:
return rc;
default:
break;
}
kerrx("sqlite3_exec: %s", sqlite3_errmsg(db));
return rc;
}
static int
db_trans_open(void)
{
return(SQLITE_OK == db_exec("BEGIN IMMEDIATE TRANSACTION"));
}
static int
db_trans_rollback(void)
{
return(SQLITE_OK == db_exec("ROLLBACK TRANSACTION"));
}
static int
db_trans_commit(void)
{
return(SQLITE_OK == db_exec("COMMIT TRANSACTION"));
}
/*
* Prepare an SQL statement.
* If errors occur, any fledgling statement is destroyed, so this always
* returns non-NULL on success.
*/
static sqlite3_stmt *
db_prepare(const char *sql)
{
sqlite3_stmt *stmt;
size_t attempt = 0;
int rc;
again:
assert(NULL != db);
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
switch (rc) {
case SQLITE_BUSY:
db_sleep(attempt++);
goto again;
case SQLITE_LOCKED:
kdbg("sqlite3_prepare_v2: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_PROTOCOL:
kdbg("sqlite3_prepare_v2: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_OK:
return stmt;
default:
break;
}
kerrx("sqlite3_stmt: %s", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
return NULL;
}
/*
* Initialise the database, creating it if "create" is specified.
* Note that "dir" refers to the director of creation, not the database
* file itself.
* Returns zero on failure, non-zero on success.
*/
int
db_init(const char *dir, int create)
{
size_t attempt = 0, sz;
int rc;
/*
* Register exit hook for the destruction of the database.
* This allows us to ignore closing the database properly.
*/
if (atexit(db_close) == -1) {
kerr("atexit");
return 0;
}
/* Format the name of the database. */
sz = strlcpy(dbname, dir, sizeof(dbname));
if (sz > sizeof(dbname)) {
kerrx("%s: too long", dir);
return 0;
} else if ('/' == dbname[sz - 1])
dbname[sz - 1] = '\0';
sz = strlcat(dbname, "/kcaldav.db", sizeof(dbname));
if (sz >= sizeof(dbname)) {
kerrx("%s: too long", dir);
return 0;
}
again:
rc = sqlite3_open_v2(dbname, &db,
SQLITE_OPEN_READWRITE |
(create ? SQLITE_OPEN_CREATE : 0),
NULL);
switch (rc) {
case SQLITE_BUSY:
db_sleep(attempt++);
goto again;
case SQLITE_LOCKED:
kdbg("sqlite3_open_v2: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_PROTOCOL:
kdbg("sqlite3_open_v2: %s (re-trying)",
sqlite3_errmsg(db));
db_sleep(attempt++);
goto again;
case SQLITE_OK:
sqlite3_busy_timeout(db, 1000);
return SQLITE_OK ==
db_exec("PRAGMA foreign_keys = ON;");
default:
break;
}
kerrx("sqlite3_open_v2: %s", sqlite3_errmsg(db));
return 0;
}
/*
* Update the tag ("ctag") for the collection.
* Return zero on failure, non-zero on success.
*/
static int
db_collection_update_ctag(int64_t id)
{
sqlite3_stmt *stmt;
if ((stmt = db_prepare(sqls[SQL_COL_UPDATE_CTAG])) == NULL)
goto err;
else if (!db_bindint(stmt, 1, id))
goto err;
else if (db_step(stmt) != SQLITE_DONE)
goto err;
kdbg("updated ctag: collection-%" PRId64, id);
db_finalise(&stmt);
return 1;
err:
db_finalise(&stmt);
return 0;
}
/*
* Delete the nonce row.
* Return zero on failure, non-zero on success.
*/
int
db_nonce_delete(const char *nonce, const struct prncpl *p)
{
sqlite3_stmt *stmt;
if ((stmt = db_prepare(sqls[SQL_NONCE_REMOVE])) == NULL)
goto err;
else if (!db_bindtext(stmt, 1, nonce))
goto err;
else if (db_step(stmt) != SQLITE_DONE)
goto err;
db_finalise(&stmt);
kdbg("deleted nonce: %s", nonce);
return 1;
err:
db_finalise(&stmt);
return 0;
}
/*
* See if the nonce count is valid.
* Return the corresponding error code.
*/
enum nonceerr
db_nonce_validate(const char *nonce, int64_t count)
{
sqlite3_stmt *stmt;
int64_t cmp;
if ((stmt = db_prepare(sqls[SQL_NONCE_GET_COUNT])) == NULL)
goto err;
else if (!db_bindtext(stmt, 1, nonce))
goto err;
switch (db_step(stmt)) {
case SQLITE_ROW:
cmp = sqlite3_column_int64(stmt, 0);
db_finalise(&stmt);
if (count < cmp) {
kerrx("nonce replay attack: %s, "
"%" PRId64 " < %" PRId64,
nonce, count, cmp);
return NONCE_REPLAY;
}
return NONCE_OK;
case SQLITE_DONE:
db_finalise(&stmt);
return NONCE_NOTFOUND;
default:
break;
}
err:
db_finalise(&stmt);
return NONCE_ERR;
}
/*
* Validate then update nonce to be one greater than the given count.
* Returns the corresponding error code.
*/
enum nonceerr
db_nonce_update(const char *nonce, int64_t count)
{
enum nonceerr er;
sqlite3_stmt *stmt;
if (!db_trans_open())
return NONCE_ERR;
if ((er = db_nonce_validate(nonce, count)) != NONCE_OK) {
db_trans_rollback();
return er;
}
/* FIXME: check for (unlikely) integer overflow. */
if ((stmt = db_prepare(sqls[SQL_NONCE_UPDATE])) == NULL)
goto err;
else if (!db_bindint(stmt, 1, count + 1))
goto err;
else if (!db_bindtext(stmt, 2, nonce))
goto err;
else if (db_step(stmt) != SQLITE_DONE)
goto err;
db_finalise(&stmt);
db_trans_commit();
kdbg("nonce updated: %s, count "
"%" PRId64, nonce, count + 1);
return NONCE_OK;
err:
db_finalise(&stmt);
db_trans_rollback();
return NONCE_ERR;
}
/*
* Create a new nonce and on success set its value in "np".
* This is in static storage and is overwritten with every call.
* Return zero on failure, non-zero on success.
*/
int
db_nonce_new(char **np)
{
static char nonce[NONCESZ + 1];
int64_t count;
sqlite3_stmt *stmt;
int rc;
size_t i;
if (!db_trans_open())
return 0;
/*
* If we have more than NONCEMAX nonces in the database, then
* cull the first 20 to make room for more.
*/
if ((stmt = db_prepare(sqls[SQL_NONCE_COUNT])) == NULL)
goto err;
else if ((rc = db_step(stmt)) == SQLITE_ROW)
count = sqlite3_column_int64(stmt, 0);
else if (rc == SQLITE_DONE)
count = 0;
else
goto err;
db_finalise(&stmt);
if (count >= NONCEMAX) {
kdbg("culling from nonce database");
stmt = db_prepare(sqls[SQL_NONCE_REMOVE_MULTI]);
if (stmt == NULL)
goto err;
else if (db_step(stmt) != SQLITE_DONE)
goto err;
db_finalise(&stmt);
}
/*
* Generate a random nonce and insert it into the database.
* Let the uniqueness constraint guarantee that the nonce is
* actually unique within the system.
*/
if ((stmt = db_prepare(sqls[SQL_NONCE_INSERT])) == NULL)
goto err;
for (;;) {
for (i = 0; i < sizeof(nonce) - 1; i++)
snprintf(nonce + i, 2, "%X",
get_random_uniform(16));
if (!db_bindtext(stmt, 1, nonce))
goto err;
rc = db_step_constrained(stmt);
if (rc == SQLITE_CONSTRAINT) {
sqlite3_reset(stmt);
continue;
} else if (rc != SQLITE_DONE)
goto err;
break;
}
db_finalise(&stmt);
db_trans_commit();
*np = nonce;
kdbg("nonce created: %s", *np);
return 1;
err:
db_finalise(&stmt);
db_trans_rollback();
return 0;
}
/*
* Create a new collection.
* Return zero if the collection exists, <0 on error, >0 on success.
*/
static int
db_collection_new_byid(const char *url, int64_t id)
{
sqlite3_stmt *stmt;
int rc;
if ((stmt = db_prepare(sqls[SQL_COL_INSERT])) == NULL)
goto err;
else if (!db_bindint(stmt, 1, id))
goto err;
else if (!db_bindtext(stmt, 2, url))
goto err;
rc = db_step_constrained(stmt);
db_finalise(&stmt);
if (rc == SQLITE_DONE) {
kinfo("collection created: %s", url);
return 1;
} else if (rc == SQLITE_CONSTRAINT)
return 0;
err:
db_finalise(&stmt);
return (-1);
}
int
db_collection_new(const char *url, const struct prncpl *p)
{
return db_collection_new_byid(url, p->id);
}
/*
* Allocate a new principal with a single collection: the principal
* collection (empty collection name) and a calendar collection
* (/calendars).
* Accept their login name, the password hash, and their email.
* This returns <0 on system failure, 0 if the principal already exists,
* and >0 if the principal was created.
*/
int
db_prncpl_new(const char *name, const char *hash,
const char *email, const char *directory)
{
sqlite3_stmt *stmt;
int rc;
int64_t lastid;
assert(directory != NULL && directory[0] != '\0');
if (!db_trans_open())
return (-1);
if ((stmt = db_prepare(sqls[SQL_PRNCPL_INSERT])) == NULL)
goto err;
else if (!db_bindtext(stmt, 1, name))
goto err;
else if (!db_bindtext(stmt, 2, hash))
goto err;
else if (!db_bindtext(stmt, 3, email))
goto err;
rc = db_step_constrained(stmt);
if (rc != SQLITE_DONE && rc != SQLITE_CONSTRAINT)
goto err;
db_finalise(&stmt);
if (SQLITE_CONSTRAINT == rc) {
db_trans_rollback();
return 0;
}
kinfo("principal created: %s, %s", email, name);
lastid = sqlite3_last_insert_rowid(db);
if (db_collection_new_byid(directory, lastid) > 0) {
db_trans_commit();
kinfo("principal collection created: %s", directory);
return 1;
}
err:
db_finalise(&stmt);
db_trans_rollback();
return (-1);
}
/*
* Change the hash and e-mail of a principal to the hash set in the
* principal object.
* This returns zero on constraint failure (email), >0 on success, <0 on
* failure.
*/
int
db_prncpl_update(const struct prncpl *p)
{
sqlite3_stmt *stmt;
int rc;
if ((stmt = db_prepare(sqls[SQL_PRNCPL_UPDATE])) == NULL)
goto err;
else if (!db_bindtext(stmt, 1, p->hash))
goto err;
else if (!db_bindtext(stmt, 2, p->email))
goto err;
else if (!db_bindint(stmt, 3, p->id))
goto err;
rc = db_step_constrained(stmt);
if (rc != SQLITE_CONSTRAINT && rc != SQLITE_DONE)
goto err;
db_finalise(&stmt);
kinfo("principal updated");
return rc == SQLITE_DONE;
err:
db_finalise(&stmt);
return (-1);
}
static int
db_collection_get(struct coln **pp, sqlite3_stmt *stmt)
{
int rc;
if ((rc = db_step(stmt)) == SQLITE_DONE)
return 0;
else if (rc != SQLITE_ROW)
return (-1);
if ((*pp = calloc(1, sizeof(struct coln))) == NULL) {
kerr(NULL);
return (-1);
}
(*pp)->url = strdup
((char *)sqlite3_column_text(stmt, 0));
(*pp)->displayname = strdup
((char *)sqlite3_column_text(stmt, 1));
(*pp)->colour = strdup
((char *)sqlite3_column_text(stmt, 2));
(*pp)->description = strdup
((char *)sqlite3_column_text(stmt, 3));
(*pp)->ctag = sqlite3_column_int64(stmt, 4);
(*pp)->id = sqlite3_column_int64(stmt, 5);
if (NULL != (*pp)->url &&
NULL != (*pp)->displayname &&
NULL != (*pp)->colour &&