2 * keydb_db4.c - Routines to store and fetch keys in a DB4 database.
4 * Jonathan McDowell <noodles@earth.li>
6 * Copyright 2002-2004 Project Purple
21 #include "charfuncs.h"
25 #include "decodekey.h"
26 #include "keystructs.h"
29 #include "onak-conf.h"
34 * dbenv - our database environment.
36 static DB_ENV *dbenv = NULL;
39 * numdb - The number of database files we have.
41 static int numdbs = 16;
44 * dbconn - our connections to the key database files.
46 static DB **dbconns = NULL;
49 * worddb - our connection to the word database.
51 static DB *worddb = NULL;
54 * id32db - our connection to the 32bit ID database.
56 static DB *id32db = NULL;
59 * txn - our current transaction id.
61 static DB_TXN *txn = NULL;
63 DB *keydb(uint64_t keyid)
69 return(dbconns[keytrun % numdbs]);
73 * initdb - Initialize the key database.
75 * This function should be called before any of the other functions in
76 * this file are called in order to allow the DB to be initialized ready
79 void initdb(bool readonly)
87 snprintf(buf, sizeof(buf) - 1, "%s/num_keydb", config.db_dir);
88 numdb = fopen(buf, "r");
90 if (fgets(buf, sizeof(buf), numdb) != NULL) {
94 } else if (!readonly) {
95 logthing(LOGTHING_ERROR, "Couldn't open num_keydb: %s",
97 numdb = fopen(buf, "w");
99 fprintf(numdb, "%d", numdbs);
102 logthing(LOGTHING_ERROR,
103 "Couldn't write num_keydb: %s",
108 dbconns = malloc(sizeof (DB *) * numdbs);
109 if (dbconns == NULL) {
110 logthing(LOGTHING_CRITICAL,
111 "Couldn't allocate memory for dbconns");
116 ret = db_env_create(&dbenv, 0);
118 logthing(LOGTHING_CRITICAL,
119 "db_env_create: %s", db_strerror(ret));
124 * Enable deadlock detection so that we don't block indefinitely on
125 * anything. What we really want is simple 2 state locks, but I'm not
126 * sure how to make the standard DB functions do that yet.
129 ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
131 logthing(LOGTHING_CRITICAL,
132 "db_env_create: %s", db_strerror(ret));
137 ret = dbenv->open(dbenv, config.db_dir,
138 DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_LOCK |
143 logthing(LOGTHING_CRITICAL,
144 "Error opening db environment: %s (%s)",
153 for (i = 0; !ret && i < numdbs; i++) {
154 ret = db_create(&dbconns[i], dbenv, 0);
156 logthing(LOGTHING_CRITICAL,
157 "db_create: %s", db_strerror(ret));
161 snprintf(buf, 1023, "keydb.%d.db", i);
166 ret = dbconns[i]->open(dbconns[i],
174 logthing(LOGTHING_CRITICAL,
175 "Error opening key database:"
186 ret = db_create(&worddb, dbenv, 0);
188 logthing(LOGTHING_CRITICAL, "db_create: %s",
194 ret = worddb->set_flags(worddb, DB_DUP);
198 ret = worddb->open(worddb, txn, "worddb", "worddb", DB_BTREE,
202 logthing(LOGTHING_CRITICAL,
203 "Error opening word database: %s (%s)",
210 ret = db_create(&id32db, dbenv, 0);
212 logthing(LOGTHING_CRITICAL, "db_create: %s",
218 ret = id32db->set_flags(id32db, DB_DUP);
222 ret = id32db->open(id32db, txn, "id32db", "id32db", DB_HASH,
226 logthing(LOGTHING_CRITICAL,
227 "Error opening id32 database: %s (%s)",
239 logthing(LOGTHING_CRITICAL,
240 "Error opening database; exiting");
248 * cleanupdb - De-initialize the key database.
250 * This function should be called upon program exit to allow the DB to
251 * cleanup after itself.
258 dbenv->txn_checkpoint(dbenv, 0, 0, 0);
259 if (id32db != NULL) {
260 id32db->close(id32db, 0);
263 if (worddb != NULL) {
264 worddb->close(worddb, 0);
267 for (i = 0; i < numdbs; i++) {
268 if (dbconns[i] != NULL) {
269 dbconns[i]->close(dbconns[i], 0);
273 dbenv->close(dbenv, 0);
279 * starttrans - Start a transaction.
281 * Start a transaction. Intended to be used if we're about to perform many
282 * operations on the database to help speed it all up, or if we want
283 * something to only succeed if all relevant operations are successful.
285 bool starttrans(void)
289 log_assert(dbenv != NULL);
290 log_assert(txn == NULL);
292 ret = dbenv->txn_begin(dbenv,
293 NULL, /* No parent transaction */
297 logthing(LOGTHING_CRITICAL,
298 "Error starting transaction: %s",
307 * endtrans - End a transaction.
309 * Ends a transaction.
315 log_assert(dbenv != NULL);
316 log_assert(txn != NULL);
318 ret = txn->commit(txn,
321 logthing(LOGTHING_CRITICAL,
322 "Error ending transaction: %s",
332 * fetch_key - Given a keyid fetch the key from storage.
333 * @keyid: The keyid to fetch.
334 * @publickey: A pointer to a structure to return the key in.
335 * @intrans: If we're already in a transaction.
337 * We use the hex representation of the keyid as the filename to fetch the
338 * key from. The key is stored in the file as a binary OpenPGP stream of
339 * packets, so we can just use read_openpgp_stream() to read the packets
340 * in and then parse_keys() to parse the packets into a publickey
343 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
346 struct openpgp_packet_list *packets = NULL;
350 struct buffer_ctx fetchbuf;
352 if (keyid < 0x100000000LL) {
353 keyid = getfullkeyid(keyid);
356 memset(&key, 0, sizeof(key));
357 memset(&data, 0, sizeof(data));
362 key.size = sizeof(keyid);
369 ret = keydb(keyid)->get(keydb(keyid),
376 fetchbuf.buffer = data.data;
378 fetchbuf.size = data.size;
379 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
381 parse_keys(packets, publickey);
382 free_packet_list(packets);
385 } else if (ret != DB_NOTFOUND) {
386 logthing(LOGTHING_ERROR,
387 "Problem retrieving key: %s",
398 int worddb_cmp(const void *d1, const void *d2)
400 return memcmp(d1, d2, 12);
404 * fetch_key_text - Trys to find the keys that contain the supplied text.
405 * @search: The text to search for.
406 * @publickey: A pointer to a structure to return the key in.
408 * This function searches for the supplied text and returns the keys that
411 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
419 char *searchtext = NULL;
420 struct ll *wordlist = NULL;
421 struct ll *curword = NULL;
422 struct keyarray keylist = { NULL, 0, 0 };
423 struct keyarray newkeylist = { NULL, 0, 0 };
426 searchtext = strdup(search);
427 wordlist = makewordlist(wordlist, searchtext);
429 for (curword = wordlist; curword != NULL; curword = curword->next) {
432 ret = worddb->cursor(worddb,
437 memset(&key, 0, sizeof(key));
438 memset(&data, 0, sizeof(data));
439 key.data = curword->object;
440 key.size = strlen(curword->object);
441 data.flags = DB_DBT_MALLOC;
442 ret = cursor->c_get(cursor,
446 while (ret == 0 && strncmp(key.data, curword->object,
448 ((char *) curword->object)[key.size] == 0) {
450 for (i = 4; i < 12; i++) {
452 keyid += ((unsigned char *)
456 if (keylist.count == 0 ||
457 array_find(&keylist, keyid)) {
458 array_add(&newkeylist, keyid);
464 ret = cursor->c_get(cursor,
469 array_free(&keylist);
470 keylist = newkeylist;
471 newkeylist.keys = NULL;
472 newkeylist.count = newkeylist.size = 0;
473 if (data.data != NULL) {
477 ret = cursor->c_close(cursor);
481 llfree(wordlist, NULL);
485 for (i = 0; i < keylist.count; i++) {
486 numkeys += fetch_key(keylist.keys[i],
490 array_free(&keylist);
500 * store_key - Takes a key and stores it.
501 * @publickey: A pointer to the public key to store.
502 * @intrans: If we're already in a transaction.
503 * @update: If true the key exists and should be updated.
505 * Again we just use the hex representation of the keyid as the filename
506 * to store the key to. We flatten the public key to a list of OpenPGP
507 * packets and then use write_openpgp_stream() to write the stream out to
508 * the file. If update is true then we delete the old key first, otherwise
509 * we trust that it doesn't exist.
511 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
513 struct openpgp_packet_list *packets = NULL;
514 struct openpgp_packet_list *list_end = NULL;
515 struct openpgp_publickey *next = NULL;
518 struct buffer_ctx storebuf;
522 uint32_t shortkeyid = 0;
523 uint64_t *subkeyids = NULL;
525 char *primary = NULL;
526 unsigned char worddb_data[12];
527 struct ll *wordlist = NULL;
528 struct ll *curword = NULL;
529 bool deadlock = false;
531 keyid = get_keyid(publickey);
538 * Delete the key if we already have it.
540 * TODO: Can we optimize this perhaps? Possibly when other data is
541 * involved as well? I suspect this is easiest and doesn't make a lot
542 * of difference though - the largest chunk of data is the keydata and
543 * it definitely needs updated.
546 deadlock = (delete_key(keyid, true) == -1);
550 * Convert the key to a flat set of binary data.
553 next = publickey->next;
554 publickey->next = NULL;
555 flatten_publickey(publickey, &packets, &list_end);
556 publickey->next = next;
559 storebuf.size = 8192;
560 storebuf.buffer = malloc(8192);
562 write_openpgp_stream(buffer_putchar, &storebuf, packets);
565 * Now we have the key data store it in the DB; the keyid is
568 memset(&key, 0, sizeof(key));
569 memset(&data, 0, sizeof(data));
571 key.size = sizeof(keyid);
572 data.size = storebuf.offset;
573 data.data = storebuf.buffer;
575 ret = keydb(keyid)->put(keydb(keyid),
581 logthing(LOGTHING_ERROR,
582 "Problem storing key: %s",
584 if (ret == DB_LOCK_DEADLOCK) {
589 free(storebuf.buffer);
590 storebuf.buffer = NULL;
594 free_packet_list(packets);
599 * Walk through our uids storing the words into the db with the keyid.
602 uids = keyuids(publickey, &primary);
605 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
606 wordlist = makewordlist(wordlist, uids[i]);
609 for (curword = wordlist; curword != NULL && !deadlock;
610 curword = curword->next) {
611 memset(&key, 0, sizeof(key));
612 memset(&data, 0, sizeof(data));
613 key.data = curword->object;
614 key.size = strlen(key.data);
615 data.data = worddb_data;
616 data.size = sizeof(worddb_data);
619 * Our data is the key creation time followed by the
622 worddb_data[ 0] = publickey->publickey->data[1];
623 worddb_data[ 1] = publickey->publickey->data[2];
624 worddb_data[ 2] = publickey->publickey->data[3];
625 worddb_data[ 3] = publickey->publickey->data[4];
626 worddb_data[ 4] = (keyid >> 56) & 0xFF;
627 worddb_data[ 5] = (keyid >> 48) & 0xFF;
628 worddb_data[ 6] = (keyid >> 40) & 0xFF;
629 worddb_data[ 7] = (keyid >> 32) & 0xFF;
630 worddb_data[ 8] = (keyid >> 24) & 0xFF;
631 worddb_data[ 9] = (keyid >> 16) & 0xFF;
632 worddb_data[10] = (keyid >> 8) & 0xFF;
633 worddb_data[11] = keyid & 0xFF;
634 ret = worddb->put(worddb,
640 logthing(LOGTHING_ERROR,
641 "Problem storing word: %s",
643 if (ret == DB_LOCK_DEADLOCK) {
650 * Free our UID and word lists.
652 llfree(wordlist, NULL);
653 for (i = 0; uids[i] != NULL; i++) {
662 * Write the truncated 32 bit keyid so we can lookup the full id for
666 shortkeyid = keyid & 0xFFFFFFFF;
668 memset(&key, 0, sizeof(key));
669 memset(&data, 0, sizeof(data));
670 key.data = &shortkeyid;
671 key.size = sizeof(shortkeyid);
673 data.size = sizeof(keyid);
675 ret = id32db->put(id32db,
681 logthing(LOGTHING_ERROR,
682 "Problem storing short keyid: %s",
684 if (ret == DB_LOCK_DEADLOCK) {
691 subkeyids = keysubkeys(publickey);
693 while (subkeyids != NULL && subkeyids[i] != 0) {
694 shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
696 memset(&key, 0, sizeof(key));
697 memset(&data, 0, sizeof(data));
698 key.data = &shortkeyid;
699 key.size = sizeof(shortkeyid);
701 data.size = sizeof(keyid);
703 ret = id32db->put(id32db,
709 logthing(LOGTHING_ERROR,
710 "Problem storing short keyid: %s",
712 if (ret == DB_LOCK_DEADLOCK) {
717 if (subkeyids != NULL) {
727 return deadlock ? -1 : 0 ;
731 * delete_key - Given a keyid delete the key from storage.
732 * @keyid: The keyid to delete.
733 * @intrans: If we're already in a transaction.
735 * This function deletes a public key from whatever storage mechanism we
736 * are using. Returns 0 if the key existed.
738 int delete_key(uint64_t keyid, bool intrans)
740 struct openpgp_publickey *publickey = NULL;
743 uint32_t shortkeyid = 0;
744 uint64_t *subkeyids = NULL;
748 char *primary = NULL;
749 unsigned char worddb_data[12];
750 struct ll *wordlist = NULL;
751 struct ll *curword = NULL;
752 bool deadlock = false;
758 fetch_key(keyid, &publickey, true);
761 * Walk through the uids removing the words from the worddb.
763 if (publickey != NULL) {
764 uids = keyuids(publickey, &primary);
767 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
768 wordlist = makewordlist(wordlist, uids[i]);
771 ret = worddb->cursor(worddb,
776 for (curword = wordlist; curword != NULL && !deadlock;
777 curword = curword->next) {
778 memset(&key, 0, sizeof(key));
779 memset(&data, 0, sizeof(data));
780 key.data = curword->object;
781 key.size = strlen(key.data);
782 data.data = worddb_data;
783 data.size = sizeof(worddb_data);
786 * Our data is the key creation time followed by the
789 worddb_data[ 0] = publickey->publickey->data[1];
790 worddb_data[ 1] = publickey->publickey->data[2];
791 worddb_data[ 2] = publickey->publickey->data[3];
792 worddb_data[ 3] = publickey->publickey->data[4];
793 worddb_data[ 4] = (keyid >> 56) & 0xFF;
794 worddb_data[ 5] = (keyid >> 48) & 0xFF;
795 worddb_data[ 6] = (keyid >> 40) & 0xFF;
796 worddb_data[ 7] = (keyid >> 32) & 0xFF;
797 worddb_data[ 8] = (keyid >> 24) & 0xFF;
798 worddb_data[ 9] = (keyid >> 16) & 0xFF;
799 worddb_data[10] = (keyid >> 8) & 0xFF;
800 worddb_data[11] = keyid & 0xFF;
802 ret = cursor->c_get(cursor,
808 ret = cursor->c_del(cursor, 0);
810 logthing(LOGTHING_ERROR,
811 "Problem deleting word: %s",
817 logthing(LOGTHING_ERROR,
818 "Problem deleting word: %s",
820 if (ret == DB_LOCK_DEADLOCK) {
825 ret = cursor->c_close(cursor);
829 * Free our UID and word lists.
831 llfree(wordlist, NULL);
832 for (i = 0; uids[i] != NULL; i++) {
838 free_publickey(publickey);
843 ret = id32db->cursor(id32db,
848 shortkeyid = keyid & 0xFFFFFFFF;
850 memset(&key, 0, sizeof(key));
851 memset(&data, 0, sizeof(data));
852 key.data = &shortkeyid;
853 key.size = sizeof(shortkeyid);
855 data.size = sizeof(keyid);
857 ret = cursor->c_get(cursor,
863 ret = cursor->c_del(cursor, 0);
865 logthing(LOGTHING_ERROR,
866 "Problem deleting short keyid: %s",
872 logthing(LOGTHING_ERROR,
873 "Problem deleting short keyid: %s",
875 if (ret == DB_LOCK_DEADLOCK) {
880 subkeyids = keysubkeys(publickey);
882 while (subkeyids != NULL && subkeyids[i] != 0) {
883 shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
885 memset(&key, 0, sizeof(key));
886 memset(&data, 0, sizeof(data));
887 key.data = &shortkeyid;
888 key.size = sizeof(shortkeyid);
890 data.size = sizeof(keyid);
892 ret = cursor->c_get(cursor,
898 ret = cursor->c_del(cursor, 0);
900 logthing(LOGTHING_ERROR,
901 "Problem deleting short"
908 logthing(LOGTHING_ERROR,
909 "Problem deleting short keyid: %s",
911 if (ret == DB_LOCK_DEADLOCK) {
916 if (subkeyids != NULL) {
921 ret = cursor->c_close(cursor);
927 key.size = sizeof(keyid);
929 keydb(keyid)->del(keydb(keyid),
939 return deadlock ? (-1) : (ret == DB_NOTFOUND);
943 * dumpdb - dump the key database
944 * @filenamebase: The base filename to use for the dump.
946 * Dumps the database into one or more files, which contain pure OpenPGP
947 * that can be reimported into onak or gpg. filenamebase provides a base
948 * file name for the dump; several files may be created, all of which will
949 * begin with this string and then have a unique number and a .pgp
952 int dumpdb(char *filenamebase)
962 for (i = 0; i < numdbs; i++) {
963 ret = dbconns[i]->cursor(dbconns[i],
968 snprintf(filename, 1023, "%s.%d.pgp", filenamebase, i);
969 fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0640);
971 logthing(LOGTHING_ERROR,
972 "Error opening keydump file (%s): %s",
976 memset(&key, 0, sizeof(key));
977 memset(&data, 0, sizeof(data));
978 ret = cursor->c_get(cursor, &key, &data, DB_NEXT);
980 write(fd, data.data, data.size);
981 memset(&key, 0, sizeof(key));
982 memset(&data, 0, sizeof(data));
983 ret = cursor->c_get(cursor, &key, &data,
986 if (ret != DB_NOTFOUND) {
987 logthing(LOGTHING_ERROR,
988 "Problem reading key: %s",
994 ret = cursor->c_close(cursor);
1002 * iterate_keys - call a function once for each key in the db.
1003 * @iterfunc: The function to call.
1004 * @ctx: A context pointer
1006 * Calls iterfunc once for each key in the database. ctx is passed
1007 * unaltered to iterfunc. This function is intended to aid database dumps
1008 * and statistic calculations.
1010 * Returns the number of keys we iterated over.
1012 int iterate_keys(void (*iterfunc)(void *ctx, struct openpgp_publickey *key),
1020 struct buffer_ctx fetchbuf;
1021 struct openpgp_packet_list *packets = NULL;
1022 struct openpgp_publickey *key = NULL;
1024 for (i = 0; i < numdbs; i++) {
1025 ret = dbconns[i]->cursor(dbconns[i],
1030 memset(&dbkey, 0, sizeof(dbkey));
1031 memset(&data, 0, sizeof(data));
1032 ret = cursor->c_get(cursor, &dbkey, &data, DB_NEXT);
1034 fetchbuf.buffer = data.data;
1035 fetchbuf.offset = 0;
1036 fetchbuf.size = data.size;
1037 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
1039 parse_keys(packets, &key);
1043 free_publickey(key);
1045 free_packet_list(packets);
1048 memset(&dbkey, 0, sizeof(dbkey));
1049 memset(&data, 0, sizeof(data));
1050 ret = cursor->c_get(cursor, &dbkey, &data,
1054 if (ret != DB_NOTFOUND) {
1055 logthing(LOGTHING_ERROR,
1056 "Problem reading key: %s",
1060 ret = cursor->c_close(cursor);
1068 * getfullkeyid - Maps a 32bit key id to a 64bit one.
1069 * @keyid: The 32bit keyid.
1071 * This function maps a 32bit key id to the full 64bit one. It returns the
1072 * full keyid. If the key isn't found a keyid of 0 is returned.
1074 uint64_t getfullkeyid(uint64_t keyid)
1078 uint32_t shortkeyid = 0;
1081 if (keyid < 0x100000000LL) {
1082 ret = id32db->cursor(id32db,
1087 shortkeyid = keyid & 0xFFFFFFFF;
1089 memset(&key, 0, sizeof(key));
1090 memset(&data, 0, sizeof(data));
1091 key.data = &shortkeyid;
1092 key.size = sizeof(shortkeyid);
1093 data.flags = DB_DBT_MALLOC;
1095 ret = cursor->c_get(cursor,
1101 keyid = *(uint64_t *) data.data;
1103 if (data.data != NULL) {
1109 ret = cursor->c_close(cursor);
1117 * Include the basic keydb routines.
1119 #define NEED_GETKEYSIGS 1
1120 #define NEED_KEYID2UID 1
1121 #define NEED_UPDATEKEYS 1