Cleanup db4 properly if we fail to open it.
[onak.git] / keydb_db4.c
1 /*
2  * keydb_db4.c - Routines to store and fetch keys in a DB4 database.
3  *
4  * Jonathan McDowell <noodles@earth.li>
5  *
6  * Copyright 2002-2004 Project Purple
7  */
8
9 #include <sys/types.h>
10 #include <sys/uio.h>
11 #include <ctype.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18
19 #include <db.h>
20
21 #include "charfuncs.h"
22 #include "keydb.h"
23 #include "keyid.h"
24 #include "decodekey.h"
25 #include "keystructs.h"
26 #include "mem.h"
27 #include "log.h"
28 #include "onak-conf.h"
29 #include "parsekey.h"
30 #include "wordlist.h"
31
32 /**
33  *      dbenv - our database environment.
34  */
35 static DB_ENV *dbenv = NULL;
36
37 /**
38  *      numdb - The number of database files we have.
39  */
40 static int numdbs = 16;
41
42 /**
43  *      dbconn - our connections to the key database files.
44  */
45 static DB **dbconns = NULL;
46
47 /**
48  *      worddb - our connection to the word database.
49  */
50 static DB *worddb = NULL;
51
52 /**
53  *      id32db - our connection to the 32bit ID database.
54  */
55 static DB *id32db = NULL;
56
57 /**
58  *      txn - our current transaction id.
59  */
60 static DB_TXN *txn = NULL;
61
62 DB *keydb(uint64_t keyid)
63 {
64         uint64_t keytrun;
65
66         keytrun = keyid >> 8;
67
68         return(dbconns[keytrun % numdbs]);
69 }
70
71 /**
72  *      initdb - Initialize the key database.
73  *
74  *      This function should be called before any of the other functions in
75  *      this file are called in order to allow the DB to be initialized ready
76  *      for access.
77  */
78 void initdb(bool readonly)
79 {
80         char       buf[1024];
81         FILE      *numdb = NULL;
82         int        ret = 0;
83         int        i = 0;
84         u_int32_t  flags = 0;
85
86         snprintf(buf, sizeof(buf) - 1, "%s/num_keydb", config.db_dir);
87         numdb = fopen(buf, "r");
88         if (numdb != NULL) {
89                 if (fgets(buf, sizeof(buf), numdb) != NULL) {
90                         numdbs = atoi(buf);
91                 }
92                 fclose(numdb);
93         } else if (!readonly) {
94                 logthing(LOGTHING_ERROR, "Couldn't open num_keydb: %s",
95                                 strerror(errno));
96                 numdb = fopen(buf, "w");
97                 if (numdb != NULL) {
98                         fprintf(numdb, "%d", numdbs);
99                         fclose(numdb);
100                 } else {
101                         logthing(LOGTHING_ERROR,
102                                 "Couldn't write num_keydb: %s",
103                                 strerror(errno));
104                 }
105         }
106
107         dbconns = malloc(sizeof (DB *) * numdbs);
108         if (dbconns == NULL) {
109                 logthing(LOGTHING_CRITICAL,
110                                 "Couldn't allocate memory for dbconns");
111                 ret = 1;
112         }
113
114         if (ret == 0) {
115                 ret = db_env_create(&dbenv, 0);
116                 if (ret != 0) {
117                         logthing(LOGTHING_CRITICAL,
118                                 "db_env_create: %s", db_strerror(ret));
119                 }
120         }
121
122         /*
123          * Enable deadlock detection so that we don't block indefinitely on
124          * anything. What we really want is simple 2 state locks, but I'm not
125          * sure how to make the standard DB functions do that yet.
126          */
127         if (ret == 0) {
128                 ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
129                 if (ret != 0) {
130                         logthing(LOGTHING_CRITICAL,
131                                 "db_env_create: %s", db_strerror(ret));
132                 }
133         }
134
135         if (ret == 0) {
136                 ret = dbenv->open(dbenv, config.db_dir,
137                                 DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_LOCK |
138                                 DB_INIT_TXN |
139                                 DB_CREATE,
140                                 0);
141                 if (ret != 0) {
142                         logthing(LOGTHING_CRITICAL,
143                                         "Error opening db environment: %s (%s)",
144                                         config.db_dir,
145                                         db_strerror(ret));
146                 }
147         }
148
149         if (ret == 0) {
150                 starttrans();
151
152                 for (i = 0; !ret && i < numdbs; i++) {
153                         ret = db_create(&dbconns[i], dbenv, 0);
154                         if (ret != 0) {
155                                 logthing(LOGTHING_CRITICAL,
156                                         "db_create: %s", db_strerror(ret));
157                         }
158
159                         if (ret == 0) {
160                                 snprintf(buf, 1023, "keydb.%d.db", i);
161                                 flags = DB_CREATE;
162                                 if (readonly) {
163                                         flags = DB_RDONLY;
164                                 }
165                                 ret = dbconns[i]->open(dbconns[i],
166                                                 txn,
167                                                 buf,
168                                                 "keydb",
169                                                 DB_HASH,
170                                                 flags,
171                                                 0664);
172                                 if (ret != 0) {
173                                         logthing(LOGTHING_CRITICAL,
174                                                 "Error opening key database:"
175                                                 " %s (%s)",
176                                                 buf,
177                                                 db_strerror(ret));
178                                 }
179                         }
180                 }
181
182         }
183
184         if (ret == 0) {
185                 ret = db_create(&worddb, dbenv, 0);
186                 if (ret != 0) {
187                         logthing(LOGTHING_CRITICAL, "db_create: %s",
188                                         db_strerror(ret));
189                 }
190         }
191
192         if (ret == 0) {
193                 ret = worddb->set_flags(worddb, DB_DUP);
194         }
195
196         if (ret == 0) {
197                 ret = worddb->open(worddb, txn, "worddb", "worddb", DB_BTREE,
198                                 flags,
199                                 0664);
200                 if (ret != 0) {
201                         logthing(LOGTHING_CRITICAL,
202                                         "Error opening word database: %s (%s)",
203                                         "worddb",
204                                         db_strerror(ret));
205                 }
206         }
207
208         if (ret == 0) {
209                 ret = db_create(&id32db, dbenv, 0);
210                 if (ret != 0) {
211                         logthing(LOGTHING_CRITICAL, "db_create: %s",
212                                         db_strerror(ret));
213                 }
214         }
215
216         if (ret == 0) {
217                 ret = id32db->set_flags(id32db, DB_DUP);
218         }
219
220         if (ret == 0) {
221                 ret = id32db->open(id32db, txn, "id32db", "id32db", DB_HASH,
222                                 flags,
223                                 0664);
224                 if (ret != 0) {
225                         logthing(LOGTHING_CRITICAL,
226                                         "Error opening id32 database: %s (%s)",
227                                         "id32db",
228                                         db_strerror(ret));
229                 }
230         }
231
232         if (txn != NULL) {
233                 endtrans();
234         }
235
236         if (ret != 0) {
237                 cleanupdb();
238                 logthing(LOGTHING_CRITICAL,
239                                 "Error opening database; exiting");
240                 exit(EXIT_FAILURE);
241         }
242         
243         return;
244 }
245
246 /**
247  *      cleanupdb - De-initialize the key database.
248  *
249  *      This function should be called upon program exit to allow the DB to
250  *      cleanup after itself.
251  */
252 void cleanupdb(void)
253 {
254         int i = 0;
255
256         if (dbenv != NULL) {
257                 dbenv->txn_checkpoint(dbenv, 0, 0, 0);
258                 if (id32db != NULL) {
259                         id32db->close(id32db, 0);
260                         id32db = NULL;
261                 }
262                 if (worddb != NULL) {
263                         worddb->close(worddb, 0);
264                         worddb = NULL;
265                 }
266                 for (i = 0; i < numdbs; i++) {
267                         if (dbconns[i] != NULL) {
268                                 dbconns[i]->close(dbconns[i], 0);
269                                 dbconns[i] = NULL;
270                         }
271                 }
272                 dbenv->close(dbenv, 0);
273                 dbenv = NULL;
274         }
275 }
276
277 /**
278  *      starttrans - Start a transaction.
279  *
280  *      Start a transaction. Intended to be used if we're about to perform many
281  *      operations on the database to help speed it all up, or if we want
282  *      something to only succeed if all relevant operations are successful.
283  */
284 bool starttrans(void)
285 {
286         int ret;
287
288         log_assert(dbenv != NULL);
289         log_assert(txn == NULL);
290
291         ret = dbenv->txn_begin(dbenv,
292                 NULL, /* No parent transaction */
293                 &txn,
294                 0);
295         if (ret != 0) {
296                 logthing(LOGTHING_CRITICAL,
297                                 "Error starting transaction: %s",
298                                 db_strerror(ret));
299                 exit(1);
300         }
301
302         return true;
303 }
304
305 /**
306  *      endtrans - End a transaction.
307  *
308  *      Ends a transaction.
309  */
310 void endtrans(void)
311 {
312         int ret;
313
314         log_assert(dbenv != NULL);
315         log_assert(txn != NULL);
316
317         ret = txn->commit(txn,
318                 0);
319         if (ret != 0) {
320                 logthing(LOGTHING_CRITICAL,
321                                 "Error ending transaction: %s",
322                                 db_strerror(ret));
323                 exit(1);
324         }
325         txn = NULL;
326
327         return;
328 }
329
330 /**
331  *      fetch_key - Given a keyid fetch the key from storage.
332  *      @keyid: The keyid to fetch.
333  *      @publickey: A pointer to a structure to return the key in.
334  *      @intrans: If we're already in a transaction.
335  *
336  *      We use the hex representation of the keyid as the filename to fetch the
337  *      key from. The key is stored in the file as a binary OpenPGP stream of
338  *      packets, so we can just use read_openpgp_stream() to read the packets
339  *      in and then parse_keys() to parse the packets into a publickey
340  *      structure.
341  */
342 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
343                 bool intrans)
344 {
345         struct openpgp_packet_list *packets = NULL;
346         DBT key, data;
347         int ret = 0;
348         int numkeys = 0;
349         struct buffer_ctx fetchbuf;
350
351         if (keyid < 0x100000000LL) {
352                 keyid = getfullkeyid(keyid);
353         }
354
355         memset(&key, 0, sizeof(key));
356         memset(&data, 0, sizeof(data));
357
358         data.size = 0;
359         data.data = NULL;
360
361         key.size = sizeof(keyid);
362         key.data = &keyid;
363
364         if (!intrans) {
365                 starttrans();
366         }
367
368         ret = keydb(keyid)->get(keydb(keyid),
369                         txn,
370                         &key,
371                         &data,
372                         0); /* flags*/
373         
374         if (ret == 0) {
375                 fetchbuf.buffer = data.data;
376                 fetchbuf.offset = 0;
377                 fetchbuf.size = data.size;
378                 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
379                                 &packets, 0);
380                 parse_keys(packets, publickey);
381                 free_packet_list(packets);
382                 packets = NULL;
383                 numkeys++;
384         } else if (ret != DB_NOTFOUND) {
385                 logthing(LOGTHING_ERROR,
386                                 "Problem retrieving key: %s",
387                                 db_strerror(ret));
388         }
389
390         if (!intrans) {
391                 endtrans();
392         }
393
394         return (numkeys);
395 }
396
397 int worddb_cmp(const void *d1, const void *d2)
398 {
399         return memcmp(d1, d2, 12);
400 }
401
402 /**
403  *      fetch_key_text - Trys to find the keys that contain the supplied text.
404  *      @search: The text to search for.
405  *      @publickey: A pointer to a structure to return the key in.
406  *
407  *      This function searches for the supplied text and returns the keys that
408  *      contain it.
409  */
410 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
411 {
412         DBC *cursor = NULL;
413         DBT key, data;
414         int ret;
415         uint64_t keyid;
416         int i;
417         int numkeys;
418         char *searchtext = NULL;
419         struct ll *wordlist = NULL;
420         struct ll *curword = NULL;
421         struct ll *keylist = NULL;
422         struct ll *newkeylist = NULL;
423
424         numkeys = 0;
425         searchtext = strdup(search);
426         wordlist = makewordlist(wordlist, searchtext);
427
428         starttrans();
429
430         ret = worddb->cursor(worddb,
431                         txn,
432                         &cursor,
433                         0);   /* flags */
434
435         for (curword = wordlist; curword != NULL; curword = curword->next) {
436                 memset(&key, 0, sizeof(key));
437                 memset(&data, 0, sizeof(data));
438                 key.data = curword->object;
439                 key.size = strlen(curword->object);
440                 data.flags = DB_DBT_MALLOC;
441                 ret = cursor->c_get(cursor,
442                                 &key,
443                                 &data,
444                                 DB_SET);
445                 while (ret == 0 && strncmp(key.data, curword->object,
446                                         key.size) == 0 &&
447                                 ((char *) curword->object)[key.size] == 0) {
448                         keyid = 0;
449                         for (i = 4; i < 12; i++) {
450                                 keyid <<= 8;
451                                 keyid += ((unsigned char *)
452                                                 data.data)[i];
453                         }
454
455                         if (keylist == NULL ||
456                                         llfind(keylist, data.data,
457                                                 worddb_cmp) != NULL) {
458                                 newkeylist = lladd(newkeylist, data.data);
459                                 data.data = NULL;
460                         } else {
461                                 free(data.data);
462                                 data.data = NULL;
463                         }
464                         ret = cursor->c_get(cursor,
465                                         &key,
466                                         &data,
467                                         DB_NEXT);
468                 }
469                 llfree(keylist, free);
470                 keylist = newkeylist;
471                 newkeylist = NULL;
472                 if (data.data != NULL) {
473                         free(data.data);
474                         data.data = NULL;
475                 }
476         }
477         llfree(wordlist, NULL);
478         wordlist = NULL;
479         
480         for (newkeylist = keylist;
481                         newkeylist != NULL && numkeys < config.maxkeys;
482                         newkeylist = newkeylist->next) {
483
484                         keyid = 0;
485                         for (i = 4; i < 12; i++) {
486                                 keyid <<= 8;
487                                 keyid += ((unsigned char *)
488                                                 newkeylist->object)[i];
489                         }
490
491                         numkeys += fetch_key(keyid,
492                                         publickey,
493                                         true);
494         }
495         llfree(keylist, free);
496         keylist = NULL;
497         free(searchtext);
498         searchtext = NULL;
499
500         ret = cursor->c_close(cursor);
501         cursor = NULL;
502
503         endtrans();
504         
505         return (numkeys);
506 }
507
508 /**
509  *      store_key - Takes a key and stores it.
510  *      @publickey: A pointer to the public key to store.
511  *      @intrans: If we're already in a transaction.
512  *      @update: If true the key exists and should be updated.
513  *
514  *      Again we just use the hex representation of the keyid as the filename
515  *      to store the key to. We flatten the public key to a list of OpenPGP
516  *      packets and then use write_openpgp_stream() to write the stream out to
517  *      the file. If update is true then we delete the old key first, otherwise
518  *      we trust that it doesn't exist.
519  */
520 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
521 {
522         struct     openpgp_packet_list *packets = NULL;
523         struct     openpgp_packet_list *list_end = NULL;
524         struct     openpgp_publickey *next = NULL;
525         int        ret = 0;
526         int        i = 0;
527         struct     buffer_ctx storebuf;
528         DBT        key;
529         DBT        data;
530         uint64_t   keyid = 0;
531         uint32_t   shortkeyid = 0;
532         uint64_t  *subkeyids = NULL;
533         char     **uids = NULL;
534         char      *primary = NULL;
535         unsigned char worddb_data[12];
536         struct ll *wordlist = NULL;
537         struct ll *curword  = NULL;
538         bool       deadlock = false;
539
540         keyid = get_keyid(publickey);
541
542         if (!intrans) {
543                 starttrans();
544         }
545
546         /*
547          * Delete the key if we already have it.
548          *
549          * TODO: Can we optimize this perhaps? Possibly when other data is
550          * involved as well? I suspect this is easiest and doesn't make a lot
551          * of difference though - the largest chunk of data is the keydata and
552          * it definitely needs updated.
553          */
554         if (update) {
555                 deadlock = (delete_key(keyid, true) == -1);
556         }
557
558         /*
559          * Convert the key to a flat set of binary data.
560          */
561         if (!deadlock) {
562                 next = publickey->next;
563                 publickey->next = NULL;
564                 flatten_publickey(publickey, &packets, &list_end);
565                 publickey->next = next;
566
567                 storebuf.offset = 0; 
568                 storebuf.size = 8192;
569                 storebuf.buffer = malloc(8192);
570         
571                 write_openpgp_stream(buffer_putchar, &storebuf, packets);
572
573                 /*
574                  * Now we have the key data store it in the DB; the keyid is
575                  * the key.
576                  */
577                 memset(&key, 0, sizeof(key));
578                 memset(&data, 0, sizeof(data));
579                 key.data = &keyid;
580                 key.size = sizeof(keyid);
581                 data.size = storebuf.offset;
582                 data.data = storebuf.buffer;
583
584                 ret = keydb(keyid)->put(keydb(keyid),
585                                 txn,
586                                 &key,
587                                 &data,
588                                 0); /* flags*/
589                 if (ret != 0) {
590                         logthing(LOGTHING_ERROR,
591                                         "Problem storing key: %s",
592                                         db_strerror(ret));
593                         if (ret == DB_LOCK_DEADLOCK) {
594                                 deadlock = true;
595                         }
596                 }
597
598                 free(storebuf.buffer);
599                 storebuf.buffer = NULL;
600                 storebuf.size = 0;
601                 storebuf.offset = 0; 
602         
603                 free_packet_list(packets);
604                 packets = NULL;
605         }
606
607         /*
608          * Walk through our uids storing the words into the db with the keyid.
609          */
610         if (!deadlock) {
611                 uids = keyuids(publickey, &primary);
612         }
613         if (uids != NULL) {
614                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
615                         wordlist = makewordlist(wordlist, uids[i]);
616                 }
617
618                 for (curword = wordlist; curword != NULL && !deadlock;
619                                 curword = curword->next) {
620                         memset(&key, 0, sizeof(key));
621                         memset(&data, 0, sizeof(data));
622                         key.data = curword->object;
623                         key.size = strlen(key.data);
624                         data.data = worddb_data;
625                         data.size = sizeof(worddb_data);
626
627                         /*
628                          * Our data is the key creation time followed by the
629                          * key id.
630                          */
631                         worddb_data[ 0] = publickey->publickey->data[1];
632                         worddb_data[ 1] = publickey->publickey->data[2];
633                         worddb_data[ 2] = publickey->publickey->data[3];
634                         worddb_data[ 3] = publickey->publickey->data[4];
635                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
636                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
637                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
638                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
639                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
640                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
641                         worddb_data[10] = (keyid >>  8) & 0xFF;
642                         worddb_data[11] = keyid & 0xFF; 
643                         ret = worddb->put(worddb,
644                                 txn,
645                                 &key,
646                                 &data,
647                                 0);
648                         if (ret != 0) {
649                                 logthing(LOGTHING_ERROR,
650                                         "Problem storing word: %s",
651                                         db_strerror(ret));
652                                 if (ret == DB_LOCK_DEADLOCK) {
653                                         deadlock = true;
654                                 }
655                         }
656                 }
657
658                 /*
659                  * Free our UID and word lists.
660                  */
661                 llfree(wordlist, NULL);
662                 for (i = 0; uids[i] != NULL; i++) {
663                         free(uids[i]);
664                         uids[i] = NULL;
665                 }
666                 free(uids);
667                 uids = NULL;
668         }
669
670         /*
671          * Write the truncated 32 bit keyid so we can lookup the full id for
672          * queries.
673          */
674         if (!deadlock) {
675                 shortkeyid = keyid & 0xFFFFFFFF;
676
677                 memset(&key, 0, sizeof(key));
678                 memset(&data, 0, sizeof(data));
679                 key.data = &shortkeyid;
680                 key.size = sizeof(shortkeyid);
681                 data.data = &keyid;
682                 data.size = sizeof(keyid);
683
684                 ret = id32db->put(id32db,
685                         txn,
686                         &key,
687                         &data,
688                         0);
689                 if (ret != 0) {
690                         logthing(LOGTHING_ERROR,
691                                 "Problem storing short keyid: %s",
692                                 db_strerror(ret));
693                         if (ret == DB_LOCK_DEADLOCK) {
694                                 deadlock = true;
695                         }
696                 }
697         }
698
699         if (!deadlock) {
700                 subkeyids = keysubkeys(publickey);
701                 i = 0;
702                 while (subkeyids != NULL && subkeyids[i] != 0) {
703                         shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
704
705                         memset(&key, 0, sizeof(key));
706                         memset(&data, 0, sizeof(data));
707                         key.data = &shortkeyid;
708                         key.size = sizeof(shortkeyid);
709                         data.data = &keyid;
710                         data.size = sizeof(keyid);
711
712                         ret = id32db->put(id32db,
713                                 txn,
714                                 &key,
715                                 &data,
716                                 0);
717                         if (ret != 0) {
718                                 logthing(LOGTHING_ERROR,
719                                         "Problem storing short keyid: %s",
720                                         db_strerror(ret));
721                                 if (ret == DB_LOCK_DEADLOCK) {
722                                         deadlock = true;
723                                 }
724                         }
725                 }
726                 if (subkeyids != NULL) {
727                         free(subkeyids);
728                         subkeyids = NULL;
729                 }
730         }
731
732         if (!intrans) {
733                 endtrans();
734         }
735
736         return deadlock ? -1 : 0 ;
737 }
738
739 /**
740  *      delete_key - Given a keyid delete the key from storage.
741  *      @keyid: The keyid to delete.
742  *      @intrans: If we're already in a transaction.
743  *
744  *      This function deletes a public key from whatever storage mechanism we
745  *      are using. Returns 0 if the key existed.
746  */
747 int delete_key(uint64_t keyid, bool intrans)
748 {
749         struct openpgp_publickey *publickey = NULL;
750         DBT key, data;
751         DBC *cursor = NULL;
752         uint32_t   shortkeyid = 0;
753         uint64_t  *subkeyids = NULL;
754         int ret = 0;
755         int i;
756         char **uids = NULL;
757         char *primary = NULL;
758         unsigned char worddb_data[12];
759         struct ll *wordlist = NULL;
760         struct ll *curword  = NULL;
761         bool deadlock = false;
762
763         if (!intrans) {
764                 starttrans();
765         }
766
767         fetch_key(keyid, &publickey, true);
768
769         /*
770          * Walk through the uids removing the words from the worddb.
771          */
772         if (publickey != NULL) {
773                 uids = keyuids(publickey, &primary);
774         }
775         if (uids != NULL) {
776                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
777                         wordlist = makewordlist(wordlist, uids[i]);
778                 }
779                                 
780                 ret = worddb->cursor(worddb,
781                         txn,
782                         &cursor,
783                         0);   /* flags */
784
785                 for (curword = wordlist; curword != NULL && !deadlock;
786                                 curword = curword->next) {
787                         memset(&key, 0, sizeof(key));
788                         memset(&data, 0, sizeof(data));
789                         key.data = curword->object;
790                         key.size = strlen(key.data);
791                         data.data = worddb_data;
792                         data.size = sizeof(worddb_data);
793
794                         /*
795                          * Our data is the key creation time followed by the
796                          * key id.
797                          */
798                         worddb_data[ 0] = publickey->publickey->data[1];
799                         worddb_data[ 1] = publickey->publickey->data[2];
800                         worddb_data[ 2] = publickey->publickey->data[3];
801                         worddb_data[ 3] = publickey->publickey->data[4];
802                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
803                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
804                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
805                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
806                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
807                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
808                         worddb_data[10] = (keyid >>  8) & 0xFF;
809                         worddb_data[11] = keyid & 0xFF; 
810
811                         ret = cursor->c_get(cursor,
812                                 &key,
813                                 &data,
814                                 DB_GET_BOTH);
815
816                         if (ret == 0) {
817                                 ret = cursor->c_del(cursor, 0);
818                                 if (ret != 0) {
819                                         logthing(LOGTHING_ERROR,
820                                                 "Problem deleting word: %s",
821                                                 db_strerror(ret));
822                                 }
823                         }
824
825                         if (ret != 0) {
826                                 logthing(LOGTHING_ERROR,
827                                         "Problem deleting word: %s",
828                                         db_strerror(ret));
829                                 if (ret == DB_LOCK_DEADLOCK) {
830                                         deadlock = true;
831                                 }
832                         }
833                 }
834                 ret = cursor->c_close(cursor);
835                 cursor = NULL;
836
837                 /*
838                  * Free our UID and word lists.
839                  */
840                 llfree(wordlist, NULL);
841                 for (i = 0; uids[i] != NULL; i++) {
842                         free(uids[i]);
843                         uids[i] = NULL;
844                 }
845                 free(uids);
846                 uids = NULL;
847                 free_publickey(publickey);
848                 publickey = NULL;
849         }
850
851         if (!deadlock) {
852                 ret = id32db->cursor(id32db,
853                         txn,
854                         &cursor,
855                         0);   /* flags */
856
857                 shortkeyid = keyid & 0xFFFFFFFF;
858
859                 memset(&key, 0, sizeof(key));
860                 memset(&data, 0, sizeof(data));
861                 key.data = &shortkeyid;
862                 key.size = sizeof(shortkeyid);
863                 data.data = &keyid;
864                 data.size = sizeof(keyid);
865
866                 ret = cursor->c_get(cursor,
867                         &key,
868                         &data,
869                         DB_GET_BOTH);
870
871                 if (ret == 0) {
872                         ret = cursor->c_del(cursor, 0);
873                         if (ret != 0) {
874                                 logthing(LOGTHING_ERROR,
875                                         "Problem deleting short keyid: %s",
876                                         db_strerror(ret));
877                         }
878                 }
879
880                 if (ret != 0) {
881                         logthing(LOGTHING_ERROR,
882                                 "Problem deleting short keyid: %s",
883                                 db_strerror(ret));
884                         if (ret == DB_LOCK_DEADLOCK) {
885                                 deadlock = true;
886                         }
887                 }
888
889                 subkeyids = keysubkeys(publickey);
890                 i = 0;
891                 while (subkeyids != NULL && subkeyids[i] != 0) {
892                         shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
893
894                         memset(&key, 0, sizeof(key));
895                         memset(&data, 0, sizeof(data));
896                         key.data = &shortkeyid;
897                         key.size = sizeof(shortkeyid);
898                         data.data = &keyid;
899                         data.size = sizeof(keyid);
900
901                         ret = cursor->c_get(cursor,
902                                 &key,
903                                 &data,
904                                 DB_GET_BOTH);
905
906                         if (ret == 0) {
907                                 ret = cursor->c_del(cursor, 0);
908                                 if (ret != 0) {
909                                         logthing(LOGTHING_ERROR,
910                                                 "Problem deleting short"
911                                                 " keyid: %s",
912                                                 db_strerror(ret));
913                                 }
914                         }
915
916                         if (ret != 0) {
917                                 logthing(LOGTHING_ERROR,
918                                         "Problem deleting short keyid: %s",
919                                         db_strerror(ret));
920                                 if (ret == DB_LOCK_DEADLOCK) {
921                                         deadlock = true;
922                                 }
923                         }
924                 }
925                 if (subkeyids != NULL) {
926                         free(subkeyids);
927                         subkeyids = NULL;
928                 }
929
930                 ret = cursor->c_close(cursor);
931                 cursor = NULL;
932         }
933
934         if (!deadlock) {
935                 key.data = &keyid;
936                 key.size = sizeof(keyid);
937
938                 keydb(keyid)->del(keydb(keyid),
939                                 txn,
940                                 &key,
941                                 0); /* flags */
942         }
943
944         if (!intrans) {
945                 endtrans();
946         }
947
948         return deadlock ? (-1) : (ret == DB_NOTFOUND);
949 }
950
951 /**
952  *      dumpdb - dump the key database
953  *      @filenamebase: The base filename to use for the dump.
954  *
955  *      Dumps the database into one or more files, which contain pure OpenPGP
956  *      that can be reimported into onak or gpg. filenamebase provides a base
957  *      file name for the dump; several files may be created, all of which will
958  *      begin with this string and then have a unique number and a .pgp
959  *      extension.
960  */
961 int dumpdb(char *filenamebase)
962 {
963         DBT   key, data;
964         DBC  *cursor = NULL;
965         int   ret = 0;
966         int   fd = -1;
967         int   i = 0;
968         char  filename[1024];
969
970         filename[1023] = 0;
971         for (i = 0; i < numdbs; i++) {
972                 ret = dbconns[i]->cursor(dbconns[i],
973                         NULL,
974                         &cursor,
975                         0);   /* flags */
976
977                 snprintf(filename, 1023, "%s.%d.pgp", filenamebase, i);
978                 fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0640);
979                 if (fd == -1) {
980                         logthing(LOGTHING_ERROR,
981                                 "Error opening keydump file (%s): %s",
982                                 filename,
983                                 strerror(errno));
984                 } else {
985                         memset(&key, 0, sizeof(key));
986                         memset(&data, 0, sizeof(data));
987                         ret = cursor->c_get(cursor, &key, &data, DB_NEXT);
988                         while (ret == 0) {
989                                 write(fd, data.data, data.size);
990                                 memset(&key, 0, sizeof(key));
991                                 memset(&data, 0, sizeof(data));
992                                 ret = cursor->c_get(cursor, &key, &data,
993                                                 DB_NEXT);
994                         }
995                         if (ret != DB_NOTFOUND) {
996                                 logthing(LOGTHING_ERROR,
997                                         "Problem reading key: %s",
998                                         db_strerror(ret));
999                         }
1000                         close(fd);
1001                 }
1002
1003                 ret = cursor->c_close(cursor);
1004                 cursor = NULL;
1005         }
1006         
1007         return 0;
1008 }
1009
1010 /**
1011  *      iterate_keys - call a function once for each key in the db.
1012  *      @iterfunc: The function to call.
1013  *      @ctx: A context pointer
1014  *
1015  *      Calls iterfunc once for each key in the database. ctx is passed
1016  *      unaltered to iterfunc. This function is intended to aid database dumps
1017  *      and statistic calculations.
1018  *
1019  *      Returns the number of keys we iterated over.
1020  */
1021 int iterate_keys(void (*iterfunc)(void *ctx, struct openpgp_publickey *key),
1022                 void *ctx)
1023 {
1024         DBT                         dbkey, data;
1025         DBC                        *cursor = NULL;
1026         int                         ret = 0;
1027         int                         i = 0;
1028         int                         numkeys = 0;
1029         struct buffer_ctx           fetchbuf;
1030         struct openpgp_packet_list *packets = NULL;
1031         struct openpgp_publickey   *key = NULL;
1032
1033         for (i = 0; i < numdbs; i++) {
1034                 ret = dbconns[i]->cursor(dbconns[i],
1035                         NULL,
1036                         &cursor,
1037                         0);   /* flags */
1038
1039                 memset(&dbkey, 0, sizeof(dbkey));
1040                 memset(&data, 0, sizeof(data));
1041                 ret = cursor->c_get(cursor, &dbkey, &data, DB_NEXT);
1042                 while (ret == 0) {
1043                         fetchbuf.buffer = data.data;
1044                         fetchbuf.offset = 0;
1045                         fetchbuf.size = data.size;
1046                         read_openpgp_stream(buffer_fetchchar, &fetchbuf,
1047                                 &packets, 0);
1048                         parse_keys(packets, &key);
1049
1050                         iterfunc(ctx, key);
1051                         
1052                         free_publickey(key);
1053                         key = NULL;
1054                         free_packet_list(packets);
1055                         packets = NULL;
1056                         
1057                         memset(&dbkey, 0, sizeof(dbkey));
1058                         memset(&data, 0, sizeof(data));
1059                         ret = cursor->c_get(cursor, &dbkey, &data,
1060                                         DB_NEXT);
1061                         numkeys++;
1062                 }
1063                 if (ret != DB_NOTFOUND) {
1064                         logthing(LOGTHING_ERROR,
1065                                 "Problem reading key: %s",
1066                                 db_strerror(ret));
1067                 }
1068
1069                 ret = cursor->c_close(cursor);
1070                 cursor = NULL;
1071         }
1072         
1073         return numkeys;
1074 }
1075
1076 /**
1077  *      getfullkeyid - Maps a 32bit key id to a 64bit one.
1078  *      @keyid: The 32bit keyid.
1079  *
1080  *      This function maps a 32bit key id to the full 64bit one. It returns the
1081  *      full keyid. If the key isn't found a keyid of 0 is returned.
1082  */
1083 uint64_t getfullkeyid(uint64_t keyid)
1084 {
1085         DBT       key, data;
1086         DBC      *cursor = NULL;
1087         uint32_t  shortkeyid = 0;
1088         int       ret = 0;
1089
1090         if (keyid < 0x100000000LL) {
1091                 ret = id32db->cursor(id32db,
1092                                 txn,
1093                                 &cursor,
1094                                 0);   /* flags */
1095
1096                 shortkeyid = keyid & 0xFFFFFFFF;
1097
1098                 memset(&key, 0, sizeof(key));
1099                 memset(&data, 0, sizeof(data));
1100                 key.data = &shortkeyid;
1101                 key.size = sizeof(shortkeyid);
1102                 data.flags = DB_DBT_MALLOC;
1103
1104                 ret = cursor->c_get(cursor,
1105                         &key,
1106                         &data,
1107                         DB_SET);
1108
1109                 if (ret == 0) {
1110                         keyid = *(uint64_t *) data.data;
1111
1112                         if (data.data != NULL) {
1113                                 free(data.data);
1114                                 data.data = NULL;
1115                         }
1116                 }
1117
1118                 ret = cursor->c_close(cursor);
1119                 cursor = NULL;
1120         }
1121         
1122         return keyid;
1123 }
1124
1125 /*
1126  * Include the basic keydb routines.
1127  */
1128 #define NEED_GETKEYSIGS 1
1129 #define NEED_KEYID2UID 1
1130 #define NEED_UPDATEKEYS 1
1131 #include "keydb.c"