-
Notifications
You must be signed in to change notification settings - Fork 0
/
keydb.cpp
63 lines (54 loc) · 1.2 KB
/
keydb.cpp
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
#include "keydb.h"
#include <string.h>
#include <stdlib.h>
TDB_CONTEXT *db_open(void)
{
return tdb_open(KEY_FILE, 1000, 0, O_RDWR | O_CREAT, 0600);
}
TDB_CONTEXT *db_open_transaction(void)
{
auto *db = db_open();
if (db == nullptr) {
return db;
}
tdb_transaction_start(db);
return db;
}
void db_close(TDB_CONTEXT *db)
{
tdb_close(db);
}
void db_close_cancel(TDB_CONTEXT *db)
{
tdb_transaction_cancel(db);
db_close(db);
}
void db_close_commit(TDB_CONTEXT *db)
{
tdb_transaction_prepare_commit(db);
tdb_transaction_commit(db);
db_close(db);
}
bool db_load_key(TDB_CONTEXT *db, int port2, struct KeyEntry &key)
{
TDB_DATA k;
k.dptr = (uint8_t *)&port2;
k.dsize = sizeof(int);
auto d = tdb_fetch(db, k);
if (d.dptr == nullptr || d.dsize != sizeof(key)) {
return false;
}
memcpy(&key, d.dptr, sizeof(key));
free(d.dptr);
return key.magic == KEY_MAGIC;
}
bool db_save_key(TDB_CONTEXT *tdb, int port2, const struct KeyEntry &ke)
{
TDB_DATA k;
k.dptr = (uint8_t*)&port2;
k.dsize = sizeof(int);
TDB_DATA d;
d.dptr = (uint8_t*)&ke;
d.dsize = sizeof(ke);
return tdb_store(tdb, k, d, TDB_REPLACE) == 0;
}