2 * keydb_db3.c - Routines to store and fetch keys in a DB3 database.
4 * Jonathan McDowell <noodles@earth.li>
6 * Copyright 2002 Project Purple
8 * $Id: keydb_db3.c,v 1.23 2004/03/23 12:33:46 noodles Exp $
12 #include <sys/types.h>
24 #include "charfuncs.h"
27 #include "decodekey.h"
28 #include "keystructs.h"
31 #include "onak-conf.h"
35 * dbenv - our database environment.
37 static DB_ENV *dbenv = NULL;
40 * numdb - The number of database files we have.
42 static int numdbs = 16;
45 * dbconn - our connections to the key database files.
47 static DB **dbconns = NULL;
50 * worddb - our connection to the word database.
52 static DB *worddb = NULL;
55 * txn - our current transaction id.
57 static DB_TXN *txn = NULL;
59 DB *keydb(uint64_t keyid)
65 return(dbconns[keytrun % numdbs]);
69 * makewordlist - Takes a string and splits it into a set of unique words.
70 * @wordlist: The current word list.
71 * @words: The string to split and add.
73 * We take words and split it on non alpha numeric characters. These get
74 * added to the word list if they're not already present. If the wordlist
75 * is NULL then we start a new list, otherwise it's search for already
76 * added words. Note that words is modified in the process of scanning.
78 * Returns the new word list.
80 struct ll *makewordlist(struct ll *wordlist, char *word)
86 * Walk through the words string, spliting on non alphanumerics and
87 * then checking if the word already exists in the list. If not then
91 while (end != NULL && *end != 0) {
93 while (*start != 0 && !isalnum(*start)) {
97 while (*end != 0 && isalnum(*end)) {
101 if (end - start > 1) {
107 if (llfind(wordlist, start,
109 wordlist = lladd(wordlist,
119 * initdb - Initialize the key database.
121 * This function should be called before any of the other functions in
122 * this file are called in order to allow the DB to be initialized ready
125 void initdb(bool readonly)
132 snprintf(buf, sizeof(buf) - 1, "%s/num_keydb", config.db_dir);
133 numdb = fopen(buf, "r");
135 if (fgets(buf, sizeof(buf), numdb) != NULL) {
140 logthing(LOGTHING_ERROR, "Couldn't open num_keydb: %s",
142 numdb = fopen(buf, "w");
144 fprintf(numdb, "%d", numdbs);
147 logthing(LOGTHING_ERROR,
148 "Couldn't write num_keydb: %s",
153 dbconns = malloc(sizeof (DB *) * numdbs);
154 if (dbconns == NULL) {
155 logthing(LOGTHING_CRITICAL,
156 "Couldn't allocate memory for dbconns");
160 ret = db_env_create(&dbenv, 0);
162 logthing(LOGTHING_CRITICAL,
163 "db_env_create: %s", db_strerror(ret));
168 * Enable deadlock detection so that we don't block indefinitely on
169 * anything. What we really want is simple 2 state locks, but I'm not
170 * sure how to make the standard DB functions do that yet.
172 ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
174 logthing(LOGTHING_CRITICAL,
175 "db_env_create: %s", db_strerror(ret));
179 ret = dbenv->open(dbenv, config.db_dir,
180 DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_LOCK |
185 logthing(LOGTHING_CRITICAL,
186 "Error opening db environment: %s (%s)",
192 for (i = 0; i < numdbs; i++) {
193 ret = db_create(&dbconns[i], dbenv, 0);
195 logthing(LOGTHING_CRITICAL,
196 "db_create: %s", db_strerror(ret));
200 snprintf(buf, 1023, "keydb.%d.db", i);
201 ret = dbconns[i]->open(dbconns[i], buf,
207 logthing(LOGTHING_CRITICAL,
208 "Error opening key database: %s (%s)",
215 ret = db_create(&worddb, dbenv, 0);
217 logthing(LOGTHING_CRITICAL, "db_create: %s", db_strerror(ret));
220 ret = worddb->set_flags(worddb, DB_DUP);
222 ret = worddb->open(worddb, "worddb", NULL, DB_BTREE,
226 logthing(LOGTHING_CRITICAL,
227 "Error opening word database: %s (%s)",
237 * cleanupdb - De-initialize the key database.
239 * This function should be called upon program exit to allow the DB to
240 * cleanup after itself.
246 txn_checkpoint(dbenv, 0, 0, 0);
247 worddb->close(worddb, 0);
249 for (i = 0; i < numdbs; i++) {
250 dbconns[i]->close(dbconns[i], 0);
253 dbenv->close(dbenv, 0);
258 * starttrans - Start a transaction.
260 * Start a transaction. Intended to be used if we're about to perform many
261 * operations on the database to help speed it all up, or if we want
262 * something to only succeed if all relevant operations are successful.
264 bool starttrans(void)
268 assert(dbenv != NULL);
271 ret = txn_begin(dbenv,
272 NULL, /* No parent transaction */
276 logthing(LOGTHING_CRITICAL,
277 "Error starting transaction: %s",
286 * endtrans - End a transaction.
288 * Ends a transaction.
294 assert(dbenv != NULL);
297 ret = txn_commit(txn,
300 logthing(LOGTHING_CRITICAL,
301 "Error ending transaction: %s",
311 * fetch_key - Given a keyid fetch the key from storage.
312 * @keyid: The keyid to fetch.
313 * @publickey: A pointer to a structure to return the key in.
314 * @intrans: If we're already in a transaction.
316 * We use the hex representation of the keyid as the filename to fetch the
317 * key from. The key is stored in the file as a binary OpenPGP stream of
318 * packets, so we can just use read_openpgp_stream() to read the packets
319 * in and then parse_keys() to parse the packets into a publickey
322 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
325 struct openpgp_packet_list *packets = NULL;
329 struct buffer_ctx fetchbuf;
331 memset(&key, 0, sizeof(key));
332 memset(&data, 0, sizeof(data));
337 key.size = sizeof(keyid);
345 ret = keydb(keyid)->get(keydb(keyid),
352 fetchbuf.buffer = data.data;
354 fetchbuf.size = data.size;
355 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
357 parse_keys(packets, publickey);
358 free_packet_list(packets);
361 } else if (ret != DB_NOTFOUND) {
362 logthing(LOGTHING_ERROR,
363 "Problem retrieving key: %s",
374 int worddb_cmp(const char *d1, const char *d2)
376 return memcmp(d1, d2, 12);
380 * fetch_key_text - Trys to find the keys that contain the supplied text.
381 * @search: The text to search for.
382 * @publickey: A pointer to a structure to return the key in.
384 * This function searches for the supplied text and returns the keys that
387 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
395 char *searchtext = NULL;
396 struct ll *wordlist = NULL;
397 struct ll *curword = NULL;
398 struct ll *keylist = NULL;
399 struct ll *newkeylist = NULL;
402 searchtext = strdup(search);
403 wordlist = makewordlist(wordlist, searchtext);
407 ret = worddb->cursor(worddb,
412 for (curword = wordlist; curword != NULL; curword = curword->next) {
413 memset(&key, 0, sizeof(key));
414 memset(&data, 0, sizeof(data));
415 key.data = curword->object;
416 key.size = strlen(curword->object);
417 data.flags = DB_DBT_MALLOC;
418 ret = cursor->c_get(cursor,
422 while (ret == 0 && strncmp(key.data, curword->object,
424 ((char *) curword->object)[key.size] == 0) {
426 for (i = 4; i < 12; i++) {
428 keyid += ((unsigned char *)
432 if (keylist == NULL ||
433 llfind(keylist, data.data,
434 worddb_cmp) != NULL) {
435 newkeylist = lladd(newkeylist, data.data);
441 ret = cursor->c_get(cursor,
446 llfree(keylist, free);
447 keylist = newkeylist;
449 if (data.data != NULL) {
454 llfree(wordlist, NULL);
457 for (newkeylist = keylist;
458 newkeylist != NULL && numkeys < config.maxkeys;
459 newkeylist = newkeylist->next) {
462 for (i = 4; i < 12; i++) {
464 keyid += ((unsigned char *)
465 newkeylist->object)[i];
468 numkeys += fetch_key(keyid,
472 llfree(keylist, free);
477 ret = cursor->c_close(cursor);
486 * store_key - Takes a key and stores it.
487 * @publickey: A pointer to the public key to store.
488 * @intrans: If we're already in a transaction.
489 * @update: If true the key exists and should be updated.
491 * Again we just use the hex representation of the keyid as the filename
492 * to store the key to. We flatten the public key to a list of OpenPGP
493 * packets and then use write_openpgp_stream() to write the stream out to
494 * the file. If update is true then we delete the old key first, otherwise
495 * we trust that it doesn't exist.
497 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
499 struct openpgp_packet_list *packets = NULL;
500 struct openpgp_packet_list *list_end = NULL;
501 struct openpgp_publickey *next = NULL;
504 struct buffer_ctx storebuf;
509 char *primary = NULL;
510 unsigned char worddb_data[12];
511 struct ll *wordlist = NULL;
512 struct ll *curword = NULL;
513 bool deadlock = false;
515 keyid = get_keyid(publickey);
522 * Delete the key if we already have it.
524 * TODO: Can we optimize this perhaps? Possibly when other data is
525 * involved as well? I suspect this is easiest and doesn't make a lot
526 * of difference though - the largest chunk of data is the keydata and
527 * it definitely needs updated.
530 deadlock = (delete_key(keyid, true) == -1);
534 * Convert the key to a flat set of binary data.
537 next = publickey->next;
538 publickey->next = NULL;
539 flatten_publickey(publickey, &packets, &list_end);
540 publickey->next = next;
543 storebuf.size = 8192;
544 storebuf.buffer = malloc(8192);
546 write_openpgp_stream(buffer_putchar, &storebuf, packets);
549 * Now we have the key data store it in the DB; the keyid is
552 memset(&key, 0, sizeof(key));
553 memset(&data, 0, sizeof(data));
555 key.size = sizeof(keyid);
557 data.size = storebuf.offset;
558 data.data = storebuf.buffer;
560 ret = keydb(keyid)->put(keydb(keyid),
566 logthing(LOGTHING_ERROR,
567 "Problem storing key: %s",
569 if (ret == DB_LOCK_DEADLOCK) {
574 free(storebuf.buffer);
575 storebuf.buffer = NULL;
579 free_packet_list(packets);
584 * Walk through our uids storing the words into the db with the keyid.
587 uids = keyuids(publickey, &primary);
590 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
591 wordlist = makewordlist(wordlist, uids[i]);
594 for (curword = wordlist; curword != NULL && !deadlock;
595 curword = curword->next) {
596 memset(&key, 0, sizeof(key));
597 memset(&data, 0, sizeof(data));
598 key.data = curword->object;
599 key.size = strlen(key.data);
600 data.data = worddb_data;
601 data.size = sizeof(worddb_data);
604 * Our data is the key creation time followed by the
607 worddb_data[ 0] = publickey->publickey->data[1];
608 worddb_data[ 1] = publickey->publickey->data[2];
609 worddb_data[ 2] = publickey->publickey->data[3];
610 worddb_data[ 3] = publickey->publickey->data[4];
611 worddb_data[ 4] = (keyid >> 56) & 0xFF;
612 worddb_data[ 5] = (keyid >> 48) & 0xFF;
613 worddb_data[ 6] = (keyid >> 40) & 0xFF;
614 worddb_data[ 7] = (keyid >> 32) & 0xFF;
615 worddb_data[ 8] = (keyid >> 24) & 0xFF;
616 worddb_data[ 9] = (keyid >> 16) & 0xFF;
617 worddb_data[10] = (keyid >> 8) & 0xFF;
618 worddb_data[11] = keyid & 0xFF;
619 ret = worddb->put(worddb,
625 logthing(LOGTHING_ERROR,
626 "Problem storing word: %s",
628 if (ret == DB_LOCK_DEADLOCK) {
635 * Free our UID and word lists.
637 llfree(wordlist, NULL);
638 for (i = 0; uids[i] != NULL; i++) {
650 return deadlock ? -1 : 0 ;
654 * delete_key - Given a keyid delete the key from storage.
655 * @keyid: The keyid to delete.
656 * @intrans: If we're already in a transaction.
658 * This function deletes a public key from whatever storage mechanism we
659 * are using. Returns 0 if the key existed.
661 int delete_key(uint64_t keyid, bool intrans)
663 struct openpgp_publickey *publickey = NULL;
669 char *primary = NULL;
670 unsigned char worddb_data[12];
671 struct ll *wordlist = NULL;
672 struct ll *curword = NULL;
673 bool deadlock = false;
681 fetch_key(keyid, &publickey, true);
684 * Walk through the uids removing the words from the worddb.
686 if (publickey != NULL) {
687 uids = keyuids(publickey, &primary);
690 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
691 wordlist = makewordlist(wordlist, uids[i]);
694 ret = worddb->cursor(worddb,
699 for (curword = wordlist; curword != NULL && !deadlock;
700 curword = curword->next) {
701 memset(&key, 0, sizeof(key));
702 memset(&data, 0, sizeof(data));
703 key.data = curword->object;
704 key.size = strlen(key.data);
705 data.data = worddb_data;
706 data.size = sizeof(worddb_data);
709 * Our data is the key creation time followed by the
712 worddb_data[ 0] = publickey->publickey->data[1];
713 worddb_data[ 1] = publickey->publickey->data[2];
714 worddb_data[ 2] = publickey->publickey->data[3];
715 worddb_data[ 3] = publickey->publickey->data[4];
716 worddb_data[ 4] = (keyid >> 56) & 0xFF;
717 worddb_data[ 5] = (keyid >> 48) & 0xFF;
718 worddb_data[ 6] = (keyid >> 40) & 0xFF;
719 worddb_data[ 7] = (keyid >> 32) & 0xFF;
720 worddb_data[ 8] = (keyid >> 24) & 0xFF;
721 worddb_data[ 9] = (keyid >> 16) & 0xFF;
722 worddb_data[10] = (keyid >> 8) & 0xFF;
723 worddb_data[11] = keyid & 0xFF;
725 ret = cursor->c_get(cursor,
731 ret = cursor->c_del(cursor, 0);
733 logthing(LOGTHING_ERROR,
734 "Problem deleting word: %s",
740 logthing(LOGTHING_ERROR,
741 "Problem deleting word: %s",
743 if (ret == DB_LOCK_DEADLOCK) {
748 ret = cursor->c_close(cursor);
752 * Free our UID and word lists.
754 llfree(wordlist, NULL);
755 for (i = 0; uids[i] != NULL; i++) {
761 free_publickey(publickey);
767 key.size = sizeof(keyid);
769 keydb(keyid)->del(keydb(keyid),
779 return deadlock ? (-1) : (ret == DB_NOTFOUND);
783 * dumpdb - dump the key database
784 * @filenamebase: The base filename to use for the dump.
786 * Dumps the database into one or more files, which contain pure OpenPGP
787 * that can be reimported into onak or gpg. filenamebase provides a base
788 * file name for the dump; several files may be created, all of which will
789 * begin with this string and then have a unique number and a .pgp
792 int dumpdb(char *filenamebase)
802 for (i = 0; i < numdbs; i++) {
803 ret = dbconns[i]->cursor(dbconns[i],
808 snprintf(filename, 1023, "%s.%d.pgp", filenamebase, i);
809 fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0640);
811 logthing(LOGTHING_ERROR,
812 "Error opening keydump file (%s): %s",
816 memset(&key, 0, sizeof(key));
817 memset(&data, 0, sizeof(data));
818 ret = cursor->c_get(cursor, &key, &data, DB_NEXT);
820 write(fd, data.data, data.size);
821 memset(&key, 0, sizeof(key));
822 memset(&data, 0, sizeof(data));
823 ret = cursor->c_get(cursor, &key, &data,
826 if (ret != DB_NOTFOUND) {
827 logthing(LOGTHING_ERROR,
828 "Problem reading key: %s",
834 ret = cursor->c_close(cursor);
842 * Include the basic keydb routines.
844 #define NEED_GETFULLKEYID 1
845 #define NEED_GETKEYSIGS 1
846 #define NEED_KEYID2UID 1