-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpseudo_db.c
2865 lines (2719 loc) · 74.3 KB
/
pseudo_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
/*
* pseudo_db.c, sqlite3 interface
*
* Copyright (c) 2008-2010,2013 Wind River Systems, Inc.
*
* SPDX-License-Identifier: LGPL-2.1-only
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/xattr.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <sqlite3.h>
#include "pseudo.h"
#include "pseudo_ipc.h"
#include "pseudo_db.h"
/* #define NPROFILE */
#ifdef NPROFILE
void xProfile(void * pArg, const char * pQuery, sqlite3_uint64 pTimeTaken)
{
pseudo_diag("profile: %lld %s\n", pTimeTaken, pQuery);
}
#endif
struct log_history {
int rc;
unsigned long fields;
sqlite3_stmt *stmt;
};
struct pdb_file_list {
int rc;
sqlite3_stmt *stmt;
};
static int file_db_dirty = 0;
#ifdef USE_MEMORY_DB
static sqlite3 *real_file_db = 0;
#endif
static sqlite3 *file_db = 0;
static sqlite3 *log_db = 0;
/* What's going on here, you might well ask?
* This contains a template to build the database. I suppose maybe it
* should have been elegantly done as a big chunk of embedded SQL, but
* this looked like a good idea at the time.
*/
typedef struct { char *fmt; int arg; } id_row;
/* So the migrations were getting to be large and complicated. Phase
* one of getting rid of that is to merge their effects in and set up
* a dummy migration to indicate that this was done.
*/
static id_row files_default_migrations[] = {
{ "%d, -1, 'N/A (initial setup)'", 8 },
{ NULL, 0 },
};
static id_row logs_default_migrations[] = {
{ "%d, -1, 'N/A (initial setup)'", 7 },
{ NULL, 0 },
};
/* This seemed like a really good idea at the time. The idea is that these
* structures let me write semi-abstract code to "create a database" without
* duplicating as much of the code.
*/
static struct sql_table {
char *name;
char *sql;
char *names;
id_row *values;
} file_tables[] = {
{ "files",
"id INTEGER PRIMARY KEY, "
"path VARCHAR, "
"dev INTEGER, "
"ino INTEGER, "
"uid INTEGER, "
"gid INTEGER, "
"mode INTEGER, "
"rdev INTEGER, "
"deleting INTEGER",
NULL,
NULL },
{ "xattrs",
"id INTEGER PRIMARY KEY, "
"dev INTEGER, "
"ino INTEGER, "
"name VARCHAR, "
"value VARCHAR",
NULL,
NULL },
{ "migrations",
"id INTEGER PRIMARY KEY, "
"version INTEGER, "
"stamp INTEGER, "
"sql VARCHAR",
"version, stamp, sql",
files_default_migrations },
{ NULL, NULL, NULL, NULL },
}, log_tables[] = {
{ "logs",
"id INTEGER PRIMARY KEY, "
"stamp INTEGER, "
"op INTEGER, "
"client INTEGER, "
"fd INTEGER, "
"dev INTEGER, "
"ino INTEGER, "
"mode INTEGER, "
"path VARCHAR, "
"result INTEGER, "
"severity INTEGER, "
"text VARCHAR, "
"tag VARCHAR, "
"uid INTEGER, "
"gid INTEGER, "
"access INTEGER, "
"program VARCHAR, "
"type INTEGER"
,
NULL,
NULL },
{ "migrations",
"id INTEGER PRIMARY KEY, "
"version INTEGER, "
"stamp INTEGER, "
"sql VARCHAR",
"version, stamp, sql",
logs_default_migrations },
{ NULL, NULL, NULL, NULL },
};
/* similarly, this creates indexes generically. */
static struct sql_index {
char *name;
char *table;
char *keys;
} file_indexes[] = {
{ "files__path_dev_ino", "files", "path, dev, ino" },
{ "files__dev_ino", "files", "dev, ino" },
{ "migration__version", "migrations", "version" },
{ "xattrs_dev_ino", "xattrs", "dev, ino" },
{ "xattrs_dev_ino_name", "xattrs", "dev, ino, name" },
{ NULL, NULL, NULL },
}, log_indexes[] = {
{ "migration__version", "migrations", "version" },
{ NULL, NULL, NULL },
};
static char *file_pragmas[] = {
"PRAGMA legacy_file_format = OFF;",
#ifdef USE_MEMORY_DB
/* the default page size produces painfully bad behavior
* for memory databases with some versions of sqlite.
*/
"PRAGMA page_size = 8192;",
"PRAGMA journal_mode = OFF;",
#else
/* Use WAL mode when using the on-disk database. If user care about
* performance, they can use the in-memory database, but if they care
* more about resilience, they can disable it and WAL mode will prevent
* corruption of the on-disk database (for a slight performance
* penalty). Note that the database still keeps synchronous to OFF,
* meaning its resilient to the pseudo process crashing or being killed
* unexpectedly, but not to the OS crashing and losing buffered disk
* state
*/
"PRAGMA journal_mode = WAL;",
#endif
"PRAGMA locking_mode = EXCLUSIVE;",
/* Setting this to NORMAL makes pseudo noticably slower
* than fakeroot, but is perhaps more secure. However,
* note that sqlite always flushes to the OS; what is lacking
* in non-synchronous mode is waiting for the OS to
* confirm delivery to media, and also a bunch of cache
* flushing and reloading which we probably don't really
* need.
*/
"PRAGMA synchronous = OFF;",
"PRAGMA foreign_keys = ON;",
NULL
};
static char *log_pragmas[] = {
"PRAGMA legacy_file_format = OFF;",
"PRAGMA journal_mode = OFF;",
"PRAGMA locking_mode = EXCLUSIVE;",
"PRAGMA synchronous = OFF;",
NULL
};
/* table migrations: */
/* If there is no migration table, we assume "version -1" -- the
* version shipped with wrlinux 3.0, which had no version
* number. Otherwise, we check it for the highest version recorded.
* We then perform, and then record, each migration in sequence.
* The first migration is the migration to create the migrations
* table; this way, it'll work on existing databases. It'll also
* work for new databases -- the migrations get performed in order
* before the databases are considered to be set up.
*/
static char create_migration_table[] =
"CREATE TABLE migrations ("
"id INTEGER PRIMARY KEY, "
"version INTEGER, "
"stamp INTEGER, "
"sql VARCHAR"
");";
static char index_migration_table[] =
"CREATE INDEX migration__version ON migrations (version)";
/* This used to be a { version, sql } pair, but version was always
* the same as index into the table, so I removed it.
* The first migration in each database is migration #0 -- the
* creation of the migration table now being used for versioning.
* The second is indexing on version -- sqlite3 can grab MAX(version)
* faster if it's indexed. (Indexing this table is very cheap, since
* there are very few migrations and each one produces exactly
* one insert.)
*/
static struct sql_migration {
char *sql;
} file_migrations[] = {
{ create_migration_table },
{ index_migration_table },
{ "ALTER TABLE files ADD deleting INTEGER;" },
/* oops. I made a design mistake, and the table is in the wrong
* format. But sqlite doesn't support modifying constraints on an
* existing table, or dropping columns. Soooooo.
*
* Also, you can't have a foreign key relationship to data which
* aren't actually unique, but the entire problem is that dev/ino
* are not unique.
*
* Note that the name entry is not really all that useful; it's mostly
* there to help with debugging, now.
*/
{
"CREATE TABLE xattrs_new ("
"id INTEGER PRIMARY KEY, "
"dev INTEGER, "
"ino INTEGER, "
"name VARCHAR, "
"value VARCHAR"
");",
},
{
"INSERT INTO xattrs_new (dev, ino, name, value) "
"SELECT "
"(SELECT dev FROM files WHERE id = file_id), "
"(SELECT ino FROM files WHERE id = file_id), "
"name, "
"value "
"FROM xattrs;"
},
{
"DROP TABLE xattrs;"
},
{
"ALTER TABLE xattrs_new RENAME TO xattrs;",
},
{
"CREATE INDEX xattrs__dev_ino ON xattrs (dev, ino);",
},
{
"CREATE UNIQUE INDEX xattrs__dev_ino_name ON xattrs (dev, ino, name);",
},
{ NULL },
}, log_migrations[] = {
{ create_migration_table },
{ index_migration_table },
/* support for hostdeps merge -- this allows us to log "tags"
* along with events.
*/
{ "ALTER TABLE logs ADD tag VARCHAR;" },
/* the logs table was defined so early I hadn't realized I cared
* about UID and GID.
*/
{ "ALTER TABLE logs ADD uid INTEGER;" },
{ "ALTER TABLE logs ADD gid INTEGER;" },
/* track access types (read/write, etc) */
{ "ALTER TABLE logs ADD access INTEGER;" },
/* client program/path */
{ "ALTER TABLE logs ADD program VARCHAR;" },
/* message type (ping, op) */
{ "ALTER TABLE logs ADD type INTEGER;" },
{ NULL },
};
/* cleanup database before getting started
*
* On a large build, the logs database gets GIGANTIC... And
* we rarely-if-ever delete things from it. So instead of
* doing the vacuum operation on it at startup, which can impose
* a several-minute delay, we do it only on deletions.
*
* There's no setup for log database right now.
*/
char *file_setups[] = {
"VACUUM;",
NULL,
};
struct database_info {
char *pathname;
struct sql_index *indexes;
struct sql_table *tables;
struct sql_migration *migrations;
char **pragmas;
char **setups;
struct sqlite3 **db;
};
static struct database_info db_infos[] = {
{
"logs.db",
log_indexes,
log_tables,
log_migrations,
log_pragmas,
NULL,
&log_db
},
{
"files.db",
file_indexes,
file_tables,
file_migrations,
file_pragmas,
file_setups,
#ifdef USE_MEMORY_DB
&real_file_db
},
{
":memory:",
file_indexes,
file_tables,
file_migrations,
file_pragmas,
file_setups,
#endif
&file_db
},
{ 0, 0, 0, 0, 0, 0, 0 }
};
/* pretty-print error along with the underlying SQL error. */
static void
dberr(sqlite3 *db, char *fmt, ...) {
va_list ap;
char debuff[8192];
int len;
va_start(ap, fmt);
len = vsnprintf(debuff, 8192, fmt, ap);
va_end(ap);
len = write(pseudo_util_debug_fd, debuff, len);
if (db) {
len = snprintf(debuff, 8192, ": %s\n", sqlite3_errmsg(db));
len = write(pseudo_util_debug_fd, debuff, len);
} else {
len = write(pseudo_util_debug_fd, " (no db)\n", 9);
}
}
/* sqlite3 supports only signed integers, thus, the highest positive
* value is 2^63-1. some filesystems with 64-bit ino_t will produce
* ino_t values in the 2^63..2^64-1 range. we convert those into
* the value you'd get treating the 2^63 bit as a sign bit, so sqlite
* doesn't convert them into floats, because the float type can't
* represent values accurately in this range, which can result in
* erroneous matches, etcetera.
*
* note, when reading the values back out, the conversion does the
* right thing. e.g., if the inode number had been 2^63 exactly,
* it will convert to -(2^63). that, converted to unsigned, will
* convert back to 2^63 exactly, etcetera.
*
* so far as i know, ino_t is always unsigned. we don't care about
* the 32-bit inode case; sqlite can represent those just fine.
*/
static int64_t
signed_ino(ino_t ino) {
if (ino > (uint64_t) INT64_MAX) {
return (int64_t) (ino + INT64_MIN) + INT64_MIN;
}
return (int64_t) ino;
}
#ifdef USE_MEMORY_DB
void
pdb_backup() {
sqlite3_backup *pBackup;
/* no point in doing this if we don't have a database to back up,
* or nothing's changed.
*/
if (!file_db || !real_file_db || !file_db_dirty)
return;
pBackup = sqlite3_backup_init(real_file_db, "main", file_db, "main");
if (pBackup) {
int rc;
(void)sqlite3_backup_step(pBackup, -1);
rc = sqlite3_backup_finish(pBackup);
if (rc != SQLITE_OK) {
dberr(real_file_db, "error during flush to disk");
}
}
file_db_dirty = 0;
}
static void
pdb_restore() {
sqlite3_backup *pBackup;
/* no point in doing this if we don't have a database to back up */
if (!file_db || !real_file_db)
return;
pBackup = sqlite3_backup_init(file_db, "main", real_file_db, "main");
if (pBackup) {
int rc;
(void)sqlite3_backup_step(pBackup, -1);
rc = sqlite3_backup_finish(pBackup);
if (rc != SQLITE_OK) {
dberr(file_db, "error during load from disk");
}
}
file_db_dirty = 0;
}
int
pdb_maybe_backup(void) {
static int occasional = 0;
if (file_db && real_file_db) {
occasional = (occasional + 1) % 10;
if (occasional == 0) {
pdb_backup();
return 1;
}
}
return 0;
}
#else /* USE_MEMORY_DB */
int
pdb_maybe_backup(void) {
return 0;
}
#endif
/* those who enjoy children, sausages, and databases, should not watch
* them being made.
*/
static int
make_tables(sqlite3 *db,
struct sql_table *sql_tables,
struct sql_index *sql_indexes,
struct sql_migration *sql_migrations,
char **existing, int rows) {
static sqlite3_stmt *stmt;
sqlite3_stmt *update_version = 0;
struct sql_migration *m;
int available_migrations;
int version = -1;
int i, j;
char *sql;
char *errmsg;
int rc;
int found = 0;
for (i = 0; sql_tables[i].name; ++i) {
found = 0;
printf("considering table %s\n", sql_tables[i].name);
for (j = 1; j <= rows; ++j) {
if (!strcmp(existing[j], sql_tables[i].name)) {
found = 1;
break;
}
}
if (found)
continue;
/* now to create the table */
sql = sqlite3_mprintf("CREATE TABLE %s ( %s );",
sql_tables[i].name, sql_tables[i].sql);
rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
sqlite3_free(sql);
if (rc) {
dberr(db, "error trying to create %s", sql_tables[i].name);
return 1;
}
if (sql_tables[i].values) {
for (j = 0; sql_tables[i].values[j].fmt; ++j) {
char buffer[256];
snprintf(buffer, sizeof(buffer), sql_tables[i].values[j].fmt, sql_tables[i].values[j].arg);
sql = sqlite3_mprintf("INSERT INTO %s ( %s ) VALUES ( %s );",
sql_tables[i].name,
sql_tables[i].names,
buffer);
pseudo_debug(PDBGF_DB, "data setup: %s\n", sql);
rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
sqlite3_free(sql);
if (rc) {
dberr(db, "error trying to populate %s",
sql_tables[i].name);
return 1;
}
}
}
for (j = 0; sql_indexes[j].name; ++j) {
if (strcmp(sql_indexes[j].table, sql_tables[i].name))
continue;
sql = sqlite3_mprintf("CREATE INDEX %s ON %s ( %s );",
sql_indexes[j].name,
sql_indexes[j].table,
sql_indexes[j].keys);
rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
sqlite3_free(sql);
if (rc) {
dberr(db, "error trying to index %s",
sql_tables[i].name);
return 1;
}
}
}
/* the migrations table is assumed to exist, because we now
* create it automatically; in a previous implementation, it was
* only created by the first migration.
*/
sql = "SELECT MAX(version) FROM migrations;";
rc = sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);
if (rc) {
dberr(db, "couldn't examine migrations table");
return 1;
}
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
version = (unsigned long) sqlite3_column_int64(stmt, 0);
rc = sqlite3_step(stmt);
} else {
version = -1;
}
if (rc != SQLITE_DONE) {
dberr(db, "not done after the single row we expected?", rc);
return 1;
}
pseudo_debug(PDBGF_DB, "existing database version: %d\n", version);
rc = sqlite3_finalize(stmt);
if (rc) {
dberr(db, "couldn't finalize version check");
return 1;
}
for (m = sql_migrations; m->sql; ++m)
;
/* m points to the null, so available migrations is one lower */
available_migrations = m - sql_migrations - 1;
/* I am pretty sure this can never happen. */
if (version < -1)
version = -1;
/* I hope this can never happen. */
pseudo_debug(PDBGF_DB, "version %d, available_migrations %d\n",
version, available_migrations);
if (version > available_migrations)
version = available_migrations;
for (m = sql_migrations + (version + 1); m->sql; ++m) {
int migration = (m - sql_migrations);
pseudo_debug(PDBGF_DB, "considering migration %d\n", migration);
if (version >= migration)
continue;
pseudo_debug(PDBGF_DB, "running migration %d\n", migration);
rc = sqlite3_prepare_v2(db,
m->sql,
strlen(m->sql),
&stmt, NULL);
if (rc) {
dberr(log_db, "couldn't prepare migration %d (%s)",
migration, m->sql);
return 1;
}
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
dberr(file_db, "migration %d failed",
migration);
return 1;
}
sqlite3_finalize(stmt);
/* this has to occur here, because the first migration
* executed CREATES the migration table, so you can't
* prepare this statement if you haven't already executed
* the first migration.
*
* Lesson learned: Yes, it actually WILL be a sort of big
* deal to add versioning later.
*/
static char *update_sql =
"INSERT INTO migrations ("
"version, stamp, sql"
") VALUES (?, ?, ?);";
rc = sqlite3_prepare_v2(db,
update_sql,
strlen(update_sql),
&update_version, NULL);
if (rc) {
dberr(db, "couldn't prepare statement to update migrations");
return 1;
}
sqlite3_bind_int(update_version, 1, migration);
sqlite3_bind_int(update_version, 2, time(NULL));
sqlite3_bind_text(update_version, 3, m->sql, -1, SQLITE_STATIC);
rc = sqlite3_step(update_version);
if (rc != SQLITE_DONE) {
dberr(db, "couldn't update migrations table (after migration to version %d)",
migration);
sqlite3_finalize(update_version);
return 1;
} else {
pseudo_debug(PDBGF_DB, "update of migrations (after %d) fine.\n",
migration);
}
sqlite3_finalize(update_version);
update_version = 0;
version = migration;
}
return 0;
}
/* registered with atexit */
static void
cleanup_db(void) {
char datebuf[64];
struct tm stamp_tm;
struct timeval stamp;
gettimeofday(&stamp, NULL);
localtime_r(&stamp.tv_sec, &stamp_tm);
strftime(datebuf, 64, "%H:%M:%S", &stamp_tm);
pseudo_diag("db cleanup for server shutdown, %s.%03d\n",
datebuf, (int) (stamp.tv_usec / 1000));
#ifdef USE_MEMORY_DB
if (real_file_db) {
pdb_backup();
sqlite3_close(real_file_db);
}
gettimeofday(&stamp, NULL);
localtime_r(&stamp.tv_sec, &stamp_tm);
strftime(datebuf, 64, "%H:%M:%S", &stamp_tm);
pseudo_diag("memory-to-file backup complete, %s.%03d.\n",
datebuf, (int) (stamp.tv_usec / 1000));
#endif
if (file_db)
sqlite3_close(file_db);
if (log_db)
sqlite3_close(log_db);
gettimeofday(&stamp, NULL);
localtime_r(&stamp.tv_sec, &stamp_tm);
strftime(datebuf, 64, "%H:%M:%S", &stamp_tm);
pseudo_diag("db cleanup finished, %s.%03d\n",
datebuf, (int) (stamp.tv_usec / 1000));
}
/* This function has been rewritten and I no longer hate it. I just feel
* like it's important to say that.
*/
static int
get_db(struct database_info *dbinfo) {
int rc;
int i;
char *sql;
char **results;
int rows, columns;
char *errmsg;
static int registered_cleanup = 0;
char *dbfile;
sqlite3 *db;
if (!dbinfo)
return 1;
if (!dbinfo->db)
return 1;
/* this database is perhaps already initialized? */
if (*(dbinfo->db))
return 0;
pseudo_debug(PDBGF_DB, "get_db(%s)\n", dbinfo->pathname);
dbfile = pseudo_localstatedir_path(dbinfo->pathname);
#ifdef USE_MEMORY_DB
if (!strcmp(dbinfo->pathname, ":memory:")) {
rc = sqlite3_open(dbinfo->pathname, &db);
} else
#endif
rc = sqlite3_open(dbfile, &db);
free(dbfile);
if (rc) {
pseudo_diag("Failed: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
*(dbinfo->db) = NULL;
return 1;
}
/* we store this in the database_info, but hereafter we'll just use
* the name db, because it is shorter.
*/
*dbinfo->db = db;
if (!registered_cleanup) {
atexit(cleanup_db);
registered_cleanup = 1;
}
if (dbinfo->pragmas) {
for (i = 0; dbinfo->pragmas[i]; ++i) {
rc = sqlite3_exec(db, dbinfo->pragmas[i], NULL, NULL, &errmsg);
pseudo_debug(PDBGF_SQL | PDBGF_VERBOSE, "executed pragma: '%s', rc %d.\n",
dbinfo->pragmas[i], rc);
if (rc) {
dberr(db, dbinfo->pragmas[i]);
}
}
}
/* create database tables or die trying */
sql = "SELECT name FROM sqlite_master "
"WHERE type = 'table' "
"ORDER BY name;";
rc = sqlite3_get_table(db, sql, &results, &rows, &columns, &errmsg);
if (rc) {
pseudo_diag("Failed: %s\n", errmsg);
} else {
rc = make_tables(db, dbinfo->tables, dbinfo->indexes, dbinfo->migrations, results, rows);
sqlite3_free_table(results);
}
/* as of now, the only setup is a vacuum operation which we don't care about
* the results of.
*/
if (dbinfo->setups) {
for (i = 0; dbinfo->setups[i]; ++i) {
sqlite3_exec(db, dbinfo->setups[i], NULL, NULL, &errmsg);
}
}
return rc;
}
static int
get_dbs(void) {
int err = 0;
int i;
#ifdef USE_MEMORY_DB
int already_loaded = 0;
if (file_db)
already_loaded = 1;
#endif
for (i = 0; db_infos[i].db; ++i) {
if (get_db(&db_infos[i])) {
pseudo_diag("Error getting '%s' database.\n",
db_infos[i].pathname);
err = 1;
}
}
#ifdef USE_MEMORY_DB
if (!already_loaded && file_db)
pdb_restore();
#endif
return err;
}
/* put a prepared log entry into the database */
int
pdb_log_traits(pseudo_query_t *traits) {
pseudo_query_t *trait;
log_entry *e;
int rc;
if (!log_db && get_dbs()) {
pseudo_diag("%s: database error.\n", __func__);
return 1;
}
e = calloc(sizeof(*e), 1);
if (!e) {
pseudo_diag("can't allocate space for log entry.");
return 1;
}
for (trait = traits; trait; trait = trait->next) {
switch (trait->field) {
case PSQF_ACCESS:
e->access = trait->data.ivalue;
break;
case PSQF_CLIENT:
e->client = trait->data.ivalue;
break;
case PSQF_DEV:
e->dev = trait->data.ivalue;
break;
case PSQF_FD:
e->fd = trait->data.ivalue;
break;
case PSQF_FTYPE:
e->mode |= (trait->data.ivalue & S_IFMT);
break;
case PSQF_GID:
e->gid = trait->data.ivalue;
break;
case PSQF_INODE:
e->ino = (ino_t) trait->data.ivalue;
break;
case PSQF_MODE:
e->mode = trait->data.ivalue;
break;
case PSQF_OP:
e->op = trait->data.ivalue;
break;
case PSQF_PATH:
e->path = trait->data.svalue ?
strdup(trait->data.svalue) : NULL;
break;
case PSQF_PERM:
e->mode |= (trait->data.ivalue & ~(S_IFMT) & 0177777);
break;
case PSQF_PROGRAM:
e->program = trait->data.svalue ?
strdup(trait->data.svalue) : NULL;
break;
case PSQF_RESULT:
e->result = trait->data.ivalue;
break;
case PSQF_SEVERITY:
e->severity = trait->data.ivalue;
break;
case PSQF_STAMP:
e->stamp = trait->data.ivalue;
break;
case PSQF_TAG:
e->tag = trait->data.svalue ?
strdup(trait->data.svalue) : NULL;
break;
case PSQF_TEXT:
e->text = trait->data.svalue ?
strdup(trait->data.svalue) : NULL;
break;
case PSQF_TYPE:
e->type = trait->data.ivalue;
break;
case PSQF_UID:
e->uid = trait->data.ivalue;
break;
case PSQF_ID:
case PSQF_ORDER:
default:
pseudo_diag("Invalid trait %s for log creation.\n",
pseudo_query_field_name(trait->field));
free(e);
return 1;
break;
}
}
rc = pdb_log_entry(e);
log_entry_free(e);
return rc;
}
/* create a log from a given log entry, with tag and text */
int
pdb_log_entry(log_entry *e) {
char *sql = "INSERT INTO logs "
"(stamp, op, access, client, dev, gid, ino, mode, path, result, severity, text, program, tag, type, uid)"
" VALUES "
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
static sqlite3_stmt *insert;
int field;
int rc;
if (!log_db && get_dbs()) {
pseudo_diag("%s: database error.\n", __func__);
return 1;
}
if (!insert) {
rc = sqlite3_prepare_v2(log_db, sql, strlen(sql), &insert, NULL);
if (rc) {
dberr(log_db, "couldn't prepare INSERT statement");
return 1;
}
}
field = 1;
if (e) {
if (e->stamp) {
sqlite3_bind_int(insert, field++, e->stamp);
} else {
sqlite3_bind_int(insert, field++, (unsigned long) time(NULL));
}
sqlite3_bind_int(insert, field++, e->op);
sqlite3_bind_int(insert, field++, e->access);
sqlite3_bind_int(insert, field++, e->client);
sqlite3_bind_int(insert, field++, e->dev);
sqlite3_bind_int(insert, field++, e->gid);
sqlite3_bind_int64(insert, field++, signed_ino(e->ino));
sqlite3_bind_int(insert, field++, e->mode);
if (e->path) {
sqlite3_bind_text(insert, field++, e->path, -1, SQLITE_STATIC);
} else {
sqlite3_bind_null(insert, field++);
}
sqlite3_bind_int(insert, field++, e->result);
sqlite3_bind_int(insert, field++, e->severity);
if (e->text) {
sqlite3_bind_text(insert, field++, e->text, -1, SQLITE_STATIC);
} else {
sqlite3_bind_null(insert, field++);
}
if (e->program) {
sqlite3_bind_text(insert, field++, e->program, -1, SQLITE_STATIC);
} else {
sqlite3_bind_null(insert, field++);
}
if (e->tag) {
sqlite3_bind_text(insert, field++, e->tag, -1, SQLITE_STATIC);
} else {
sqlite3_bind_null(insert, field++);
}
sqlite3_bind_int(insert, field++, e->type);
sqlite3_bind_int(insert, field++, e->uid);
} else {
sqlite3_bind_int(insert, field++, (unsigned long) time(NULL));
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_null(insert, field++);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_null(insert, field++);
sqlite3_bind_null(insert, field++);
sqlite3_bind_null(insert, field++);
sqlite3_bind_int(insert, field++, 0);
sqlite3_bind_int(insert, field++, 0);
}
rc = sqlite3_step(insert);
if (rc != SQLITE_DONE) {
dberr(log_db, "insert may have failed");
}
sqlite3_reset(insert);
sqlite3_clear_bindings(insert);
return rc != SQLITE_DONE;
}
/* create a log from a given message, with tag and text */
int
pdb_log_msg(pseudo_sev_t severity, pseudo_msg_t *msg, const char *program, const char *tag, const char *text, ...) {
char *sql = "INSERT INTO logs "
"(stamp, op, access, client, dev, gid, ino, mode, path, result, uid, severity, text, program, tag, type)"
" VALUES "
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
static sqlite3_stmt *insert;
char buffer[8192];
int field;
int rc;
va_list ap;
if (text) {
va_start(ap, text);
vsnprintf(buffer, 8192, text, ap);
va_end(ap);
text = buffer;
}
if (!log_db && get_dbs()) {
pseudo_diag("%s: database error.\n", __func__);
return 1;
}
if (!insert) {
rc = sqlite3_prepare_v2(log_db, sql, strlen(sql), &insert, NULL);
if (rc) {
dberr(log_db, "couldn't prepare INSERT statement");
return 1;
}
}
field = 1;
sqlite3_bind_int(insert, field++, (unsigned long) time(NULL));
if (msg) {
sqlite3_bind_int(insert, field++, msg->op);
sqlite3_bind_int(insert, field++, msg->access);
sqlite3_bind_int(insert, field++, msg->client);
sqlite3_bind_int(insert, field++, msg->dev);
sqlite3_bind_int(insert, field++, msg->gid);
sqlite3_bind_int64(insert, field++, signed_ino(msg->ino));
sqlite3_bind_int(insert, field++, msg->mode);