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