]> git.sommitrealweird.co.uk Git - onak.git/blob - keydb_db4.c
b443942aea33530a8db6c97001896dcccd226075
[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  *      fetch_key - Given a keyid fetch the key from storage.
337  *      @keyid: The keyid to fetch.
338  *      @publickey: A pointer to a structure to return the key in.
339  *      @intrans: If we're already in a transaction.
340  *
341  *      We use the hex representation of the keyid as the filename to fetch the
342  *      key from. The key is stored in the file as a binary OpenPGP stream of
343  *      packets, so we can just use read_openpgp_stream() to read the packets
344  *      in and then parse_keys() to parse the packets into a publickey
345  *      structure.
346  */
347 static int db4_fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
348                 bool intrans)
349 {
350         struct openpgp_packet_list *packets = NULL;
351         DBT key, data;
352         int ret = 0;
353         int numkeys = 0;
354         struct buffer_ctx fetchbuf;
355
356         if (keyid < 0x100000000LL) {
357                 keyid = getfullkeyid(keyid);
358         }
359
360         memset(&key, 0, sizeof(key));
361         memset(&data, 0, sizeof(data));
362
363         data.size = 0;
364         data.data = NULL;
365
366         key.size = sizeof(keyid);
367         key.data = &keyid;
368
369         if (!intrans) {
370                 db4_starttrans();
371         }
372
373         ret = keydb(keyid)->get(keydb(keyid),
374                         txn,
375                         &key,
376                         &data,
377                         0); /* flags*/
378         
379         if (ret == 0) {
380                 fetchbuf.buffer = data.data;
381                 fetchbuf.offset = 0;
382                 fetchbuf.size = data.size;
383                 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
384                                 &packets, 0);
385                 parse_keys(packets, publickey);
386                 free_packet_list(packets);
387                 packets = NULL;
388                 numkeys++;
389         } else if (ret != DB_NOTFOUND) {
390                 logthing(LOGTHING_ERROR,
391                                 "Problem retrieving key: %s",
392                                 db_strerror(ret));
393         }
394
395         if (!intrans) {
396                 db4_endtrans();
397         }
398
399         return (numkeys);
400 }
401
402 int worddb_cmp(const void *d1, const void *d2)
403 {
404         return memcmp(d1, d2, 12);
405 }
406
407 /**
408  *      fetch_key_text - Trys to find the keys that contain the supplied text.
409  *      @search: The text to search for.
410  *      @publickey: A pointer to a structure to return the key in.
411  *
412  *      This function searches for the supplied text and returns the keys that
413  *      contain it.
414  */
415 static int db4_fetch_key_text(const char *search,
416                 struct openpgp_publickey **publickey)
417 {
418         DBC *cursor = NULL;
419         DBT key, data;
420         int ret;
421         uint64_t keyid;
422         int i;
423         int numkeys;
424         char *searchtext = NULL;
425         struct ll *wordlist = NULL;
426         struct ll *curword = NULL;
427         struct keyarray keylist = { NULL, 0, 0 };
428         struct keyarray newkeylist = { NULL, 0, 0 };
429
430         numkeys = 0;
431         searchtext = strdup(search);
432         wordlist = makewordlist(wordlist, searchtext);
433
434         for (curword = wordlist; curword != NULL; curword = curword->next) {
435                 db4_starttrans();
436
437                 ret = worddb->cursor(worddb,
438                                 txn,
439                                 &cursor,
440                                 0);   /* flags */
441
442                 memset(&key, 0, sizeof(key));
443                 memset(&data, 0, sizeof(data));
444                 key.data = curword->object;
445                 key.size = strlen(curword->object);
446                 data.flags = DB_DBT_MALLOC;
447                 ret = cursor->c_get(cursor,
448                                 &key,
449                                 &data,
450                                 DB_SET);
451                 while (ret == 0 && strncmp(key.data, curword->object,
452                                         key.size) == 0 &&
453                                 ((char *) curword->object)[key.size] == 0) {
454                         keyid = 0;
455                         for (i = 4; i < 12; i++) {
456                                 keyid <<= 8;
457                                 keyid += ((unsigned char *)
458                                                 data.data)[i];
459                         }
460
461                         if (keylist.count == 0 ||
462                                         array_find(&keylist, keyid)) {
463                                 array_add(&newkeylist, keyid);
464                         }
465
466                         free(data.data);
467                         data.data = NULL;
468
469                         ret = cursor->c_get(cursor,
470                                         &key,
471                                         &data,
472                                         DB_NEXT);
473                 }
474                 array_free(&keylist);
475                 keylist = newkeylist;
476                 newkeylist.keys = NULL;
477                 newkeylist.count = newkeylist.size = 0;
478                 if (data.data != NULL) {
479                         free(data.data);
480                         data.data = NULL;
481                 }
482                 ret = cursor->c_close(cursor);
483                 cursor = NULL;
484                 db4_endtrans();
485         }
486         llfree(wordlist, NULL);
487         wordlist = NULL;
488         
489         db4_starttrans();
490         for (i = 0; i < keylist.count; i++) {
491                 numkeys += db4_fetch_key(keylist.keys[i],
492                         publickey,
493                         true);
494         }
495         array_free(&keylist);
496         free(searchtext);
497         searchtext = NULL;
498
499         db4_endtrans();
500         
501         return (numkeys);
502 }
503
504 /**
505  *      delete_key - Given a keyid delete the key from storage.
506  *      @keyid: The keyid to delete.
507  *      @intrans: If we're already in a transaction.
508  *
509  *      This function deletes a public key from whatever storage mechanism we
510  *      are using. Returns 0 if the key existed.
511  */
512 static int db4_delete_key(uint64_t keyid, bool intrans)
513 {
514         struct openpgp_publickey *publickey = NULL;
515         DBT key, data;
516         DBC *cursor = NULL;
517         uint32_t   shortkeyid = 0;
518         uint64_t  *subkeyids = NULL;
519         int ret = 0;
520         int i;
521         char **uids = NULL;
522         char *primary = NULL;
523         unsigned char worddb_data[12];
524         struct ll *wordlist = NULL;
525         struct ll *curword  = NULL;
526         bool deadlock = false;
527
528         if (!intrans) {
529                 db4_starttrans();
530         }
531
532         db4_fetch_key(keyid, &publickey, true);
533
534         /*
535          * Walk through the uids removing the words from the worddb.
536          */
537         if (publickey != NULL) {
538                 uids = keyuids(publickey, &primary);
539         }
540         if (uids != NULL) {
541                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
542                         wordlist = makewordlist(wordlist, uids[i]);
543                 }
544                                 
545                 ret = worddb->cursor(worddb,
546                         txn,
547                         &cursor,
548                         0);   /* flags */
549
550                 for (curword = wordlist; curword != NULL && !deadlock;
551                                 curword = curword->next) {
552                         memset(&key, 0, sizeof(key));
553                         memset(&data, 0, sizeof(data));
554                         key.data = curword->object;
555                         key.size = strlen(key.data);
556                         data.data = worddb_data;
557                         data.size = sizeof(worddb_data);
558
559                         /*
560                          * Our data is the key creation time followed by the
561                          * key id.
562                          */
563                         worddb_data[ 0] = publickey->publickey->data[1];
564                         worddb_data[ 1] = publickey->publickey->data[2];
565                         worddb_data[ 2] = publickey->publickey->data[3];
566                         worddb_data[ 3] = publickey->publickey->data[4];
567                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
568                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
569                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
570                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
571                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
572                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
573                         worddb_data[10] = (keyid >>  8) & 0xFF;
574                         worddb_data[11] = keyid & 0xFF; 
575
576                         ret = cursor->c_get(cursor,
577                                 &key,
578                                 &data,
579                                 DB_GET_BOTH);
580
581                         if (ret == 0) {
582                                 ret = cursor->c_del(cursor, 0);
583                                 if (ret != 0) {
584                                         logthing(LOGTHING_ERROR,
585                                                 "Problem deleting word: %s",
586                                                 db_strerror(ret));
587                                 }
588                         }
589
590                         if (ret != 0) {
591                                 logthing(LOGTHING_ERROR,
592                                         "Problem deleting word: %s",
593                                         db_strerror(ret));
594                                 if (ret == DB_LOCK_DEADLOCK) {
595                                         deadlock = true;
596                                 }
597                         }
598                 }
599                 ret = cursor->c_close(cursor);
600                 cursor = NULL;
601
602                 /*
603                  * Free our UID and word lists.
604                  */
605                 llfree(wordlist, NULL);
606                 for (i = 0; uids[i] != NULL; i++) {
607                         free(uids[i]);
608                         uids[i] = NULL;
609                 }
610                 free(uids);
611                 uids = NULL;
612                 free_publickey(publickey);
613                 publickey = NULL;
614         }
615
616         if (!deadlock) {
617                 ret = id32db->cursor(id32db,
618                         txn,
619                         &cursor,
620                         0);   /* flags */
621
622                 shortkeyid = keyid & 0xFFFFFFFF;
623
624                 memset(&key, 0, sizeof(key));
625                 memset(&data, 0, sizeof(data));
626                 key.data = &shortkeyid;
627                 key.size = sizeof(shortkeyid);
628                 data.data = &keyid;
629                 data.size = sizeof(keyid);
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 short keyid: %s",
641                                         db_strerror(ret));
642                         }
643                 }
644
645                 if (ret != 0) {
646                         logthing(LOGTHING_ERROR,
647                                 "Problem deleting short keyid: %s",
648                                 db_strerror(ret));
649                         if (ret == DB_LOCK_DEADLOCK) {
650                                 deadlock = true;
651                         }
652                 }
653
654                 subkeyids = keysubkeys(publickey);
655                 i = 0;
656                 while (subkeyids != NULL && subkeyids[i] != 0) {
657                         shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
658
659                         memset(&key, 0, sizeof(key));
660                         memset(&data, 0, sizeof(data));
661                         key.data = &shortkeyid;
662                         key.size = sizeof(shortkeyid);
663                         data.data = &keyid;
664                         data.size = sizeof(keyid);
665
666                         ret = cursor->c_get(cursor,
667                                 &key,
668                                 &data,
669                                 DB_GET_BOTH);
670
671                         if (ret == 0) {
672                                 ret = cursor->c_del(cursor, 0);
673                                 if (ret != 0) {
674                                         logthing(LOGTHING_ERROR,
675                                                 "Problem deleting short"
676                                                 " keyid: %s",
677                                                 db_strerror(ret));
678                                 }
679                         }
680
681                         if (ret != 0) {
682                                 logthing(LOGTHING_ERROR,
683                                         "Problem deleting short keyid: %s",
684                                         db_strerror(ret));
685                                 if (ret == DB_LOCK_DEADLOCK) {
686                                         deadlock = true;
687                                 }
688                         }
689                 }
690                 if (subkeyids != NULL) {
691                         free(subkeyids);
692                         subkeyids = NULL;
693                 }
694
695                 ret = cursor->c_close(cursor);
696                 cursor = NULL;
697         }
698
699         if (!deadlock) {
700                 key.data = &keyid;
701                 key.size = sizeof(keyid);
702
703                 keydb(keyid)->del(keydb(keyid),
704                                 txn,
705                                 &key,
706                                 0); /* flags */
707         }
708
709         if (!intrans) {
710                 db4_endtrans();
711         }
712
713         return deadlock ? (-1) : (ret == DB_NOTFOUND);
714 }
715
716 /**
717  *      store_key - Takes a key and stores it.
718  *      @publickey: A pointer to the public key to store.
719  *      @intrans: If we're already in a transaction.
720  *      @update: If true the key exists and should be updated.
721  *
722  *      Again we just use the hex representation of the keyid as the filename
723  *      to store the key to. We flatten the public key to a list of OpenPGP
724  *      packets and then use write_openpgp_stream() to write the stream out to
725  *      the file. If update is true then we delete the old key first, otherwise
726  *      we trust that it doesn't exist.
727  */
728 static int db4_store_key(struct openpgp_publickey *publickey, bool intrans,
729                 bool update)
730 {
731         struct     openpgp_packet_list *packets = NULL;
732         struct     openpgp_packet_list *list_end = NULL;
733         struct     openpgp_publickey *next = NULL;
734         int        ret = 0;
735         int        i = 0;
736         struct     buffer_ctx storebuf;
737         DBT        key;
738         DBT        data;
739         uint64_t   keyid = 0;
740         uint32_t   shortkeyid = 0;
741         uint64_t  *subkeyids = NULL;
742         char     **uids = NULL;
743         char      *primary = NULL;
744         unsigned char worddb_data[12];
745         struct ll *wordlist = NULL;
746         struct ll *curword  = NULL;
747         bool       deadlock = false;
748
749         keyid = get_keyid(publickey);
750
751         if (!intrans) {
752                 db4_starttrans();
753         }
754
755         /*
756          * Delete the key if we already have it.
757          *
758          * TODO: Can we optimize this perhaps? Possibly when other data is
759          * involved as well? I suspect this is easiest and doesn't make a lot
760          * of difference though - the largest chunk of data is the keydata and
761          * it definitely needs updated.
762          */
763         if (update) {
764                 deadlock = (db4_delete_key(keyid, true) == -1);
765         }
766
767         /*
768          * Convert the key to a flat set of binary data.
769          */
770         if (!deadlock) {
771                 next = publickey->next;
772                 publickey->next = NULL;
773                 flatten_publickey(publickey, &packets, &list_end);
774                 publickey->next = next;
775
776                 storebuf.offset = 0; 
777                 storebuf.size = 8192;
778                 storebuf.buffer = malloc(8192);
779         
780                 write_openpgp_stream(buffer_putchar, &storebuf, packets);
781
782                 /*
783                  * Now we have the key data store it in the DB; the keyid is
784                  * the key.
785                  */
786                 memset(&key, 0, sizeof(key));
787                 memset(&data, 0, sizeof(data));
788                 key.data = &keyid;
789                 key.size = sizeof(keyid);
790                 data.size = storebuf.offset;
791                 data.data = storebuf.buffer;
792
793                 ret = keydb(keyid)->put(keydb(keyid),
794                                 txn,
795                                 &key,
796                                 &data,
797                                 0); /* flags*/
798                 if (ret != 0) {
799                         logthing(LOGTHING_ERROR,
800                                         "Problem storing key: %s",
801                                         db_strerror(ret));
802                         if (ret == DB_LOCK_DEADLOCK) {
803                                 deadlock = true;
804                         }
805                 }
806
807                 free(storebuf.buffer);
808                 storebuf.buffer = NULL;
809                 storebuf.size = 0;
810                 storebuf.offset = 0; 
811         
812                 free_packet_list(packets);
813                 packets = NULL;
814         }
815
816         /*
817          * Walk through our uids storing the words into the db with the keyid.
818          */
819         if (!deadlock) {
820                 uids = keyuids(publickey, &primary);
821         }
822         if (uids != NULL) {
823                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
824                         wordlist = makewordlist(wordlist, uids[i]);
825                 }
826
827                 for (curword = wordlist; curword != NULL && !deadlock;
828                                 curword = curword->next) {
829                         memset(&key, 0, sizeof(key));
830                         memset(&data, 0, sizeof(data));
831                         key.data = curword->object;
832                         key.size = strlen(key.data);
833                         data.data = worddb_data;
834                         data.size = sizeof(worddb_data);
835
836                         /*
837                          * Our data is the key creation time followed by the
838                          * key id.
839                          */
840                         worddb_data[ 0] = publickey->publickey->data[1];
841                         worddb_data[ 1] = publickey->publickey->data[2];
842                         worddb_data[ 2] = publickey->publickey->data[3];
843                         worddb_data[ 3] = publickey->publickey->data[4];
844                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
845                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
846                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
847                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
848                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
849                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
850                         worddb_data[10] = (keyid >>  8) & 0xFF;
851                         worddb_data[11] = keyid & 0xFF; 
852                         ret = worddb->put(worddb,
853                                 txn,
854                                 &key,
855                                 &data,
856                                 0);
857                         if (ret != 0) {
858                                 logthing(LOGTHING_ERROR,
859                                         "Problem storing word: %s",
860                                         db_strerror(ret));
861                                 if (ret == DB_LOCK_DEADLOCK) {
862                                         deadlock = true;
863                                 }
864                         }
865                 }
866
867                 /*
868                  * Free our UID and word lists.
869                  */
870                 llfree(wordlist, NULL);
871                 for (i = 0; uids[i] != NULL; i++) {
872                         free(uids[i]);
873                         uids[i] = NULL;
874                 }
875                 free(uids);
876                 uids = NULL;
877         }
878
879         /*
880          * Write the truncated 32 bit keyid so we can lookup the full id for
881          * queries.
882          */
883         if (!deadlock) {
884                 shortkeyid = keyid & 0xFFFFFFFF;
885
886                 memset(&key, 0, sizeof(key));
887                 memset(&data, 0, sizeof(data));
888                 key.data = &shortkeyid;
889                 key.size = sizeof(shortkeyid);
890                 data.data = &keyid;
891                 data.size = sizeof(keyid);
892
893                 ret = id32db->put(id32db,
894                         txn,
895                         &key,
896                         &data,
897                         0);
898                 if (ret != 0) {
899                         logthing(LOGTHING_ERROR,
900                                 "Problem storing short keyid: %s",
901                                 db_strerror(ret));
902                         if (ret == DB_LOCK_DEADLOCK) {
903                                 deadlock = true;
904                         }
905                 }
906         }
907
908         if (!deadlock) {
909                 subkeyids = keysubkeys(publickey);
910                 i = 0;
911                 while (subkeyids != NULL && subkeyids[i] != 0) {
912                         shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
913
914                         memset(&key, 0, sizeof(key));
915                         memset(&data, 0, sizeof(data));
916                         key.data = &shortkeyid;
917                         key.size = sizeof(shortkeyid);
918                         data.data = &keyid;
919                         data.size = sizeof(keyid);
920
921                         ret = id32db->put(id32db,
922                                 txn,
923                                 &key,
924                                 &data,
925                                 0);
926                         if (ret != 0) {
927                                 logthing(LOGTHING_ERROR,
928                                         "Problem storing short keyid: %s",
929                                         db_strerror(ret));
930                                 if (ret == DB_LOCK_DEADLOCK) {
931                                         deadlock = true;
932                                 }
933                         }
934                 }
935                 if (subkeyids != NULL) {
936                         free(subkeyids);
937                         subkeyids = NULL;
938                 }
939         }
940
941         if (!intrans) {
942                 db4_endtrans();
943         }
944
945         return deadlock ? -1 : 0 ;
946 }
947
948 /**
949  *      iterate_keys - call a function once for each key in the db.
950  *      @iterfunc: The function to call.
951  *      @ctx: A context pointer
952  *
953  *      Calls iterfunc once for each key in the database. ctx is passed
954  *      unaltered to iterfunc. This function is intended to aid database dumps
955  *      and statistic calculations.
956  *
957  *      Returns the number of keys we iterated over.
958  */
959 static int db4_iterate_keys(void (*iterfunc)(void *ctx,
960                 struct openpgp_publickey *key), void *ctx)
961 {
962         DBT                         dbkey, data;
963         DBC                        *cursor = NULL;
964         int                         ret = 0;
965         int                         i = 0;
966         int                         numkeys = 0;
967         struct buffer_ctx           fetchbuf;
968         struct openpgp_packet_list *packets = NULL;
969         struct openpgp_publickey   *key = NULL;
970
971         for (i = 0; i < numdbs; i++) {
972                 ret = dbconns[i]->cursor(dbconns[i],
973                         NULL,
974                         &cursor,
975                         0);   /* flags */
976
977                 memset(&dbkey, 0, sizeof(dbkey));
978                 memset(&data, 0, sizeof(data));
979                 ret = cursor->c_get(cursor, &dbkey, &data, DB_NEXT);
980                 while (ret == 0) {
981                         fetchbuf.buffer = data.data;
982                         fetchbuf.offset = 0;
983                         fetchbuf.size = data.size;
984                         read_openpgp_stream(buffer_fetchchar, &fetchbuf,
985                                 &packets, 0);
986                         parse_keys(packets, &key);
987
988                         iterfunc(ctx, key);
989                         
990                         free_publickey(key);
991                         key = NULL;
992                         free_packet_list(packets);
993                         packets = NULL;
994                         
995                         memset(&dbkey, 0, sizeof(dbkey));
996                         memset(&data, 0, sizeof(data));
997                         ret = cursor->c_get(cursor, &dbkey, &data,
998                                         DB_NEXT);
999                         numkeys++;
1000                 }
1001                 if (ret != DB_NOTFOUND) {
1002                         logthing(LOGTHING_ERROR,
1003                                 "Problem reading key: %s",
1004                                 db_strerror(ret));
1005                 }
1006
1007                 ret = cursor->c_close(cursor);
1008                 cursor = NULL;
1009         }
1010         
1011         return numkeys;
1012 }
1013
1014 /**
1015  *      getfullkeyid - Maps a 32bit key id to a 64bit one.
1016  *      @keyid: The 32bit keyid.
1017  *
1018  *      This function maps a 32bit key id to the full 64bit one. It returns the
1019  *      full keyid. If the key isn't found a keyid of 0 is returned.
1020  */
1021 static uint64_t db4_getfullkeyid(uint64_t keyid)
1022 {
1023         DBT       key, data;
1024         DBC      *cursor = NULL;
1025         uint32_t  shortkeyid = 0;
1026         int       ret = 0;
1027
1028         if (keyid < 0x100000000LL) {
1029                 ret = id32db->cursor(id32db,
1030                                 txn,
1031                                 &cursor,
1032                                 0);   /* flags */
1033
1034                 shortkeyid = keyid & 0xFFFFFFFF;
1035
1036                 memset(&key, 0, sizeof(key));
1037                 memset(&data, 0, sizeof(data));
1038                 key.data = &shortkeyid;
1039                 key.size = sizeof(shortkeyid);
1040                 data.flags = DB_DBT_MALLOC;
1041
1042                 ret = cursor->c_get(cursor,
1043                         &key,
1044                         &data,
1045                         DB_SET);
1046
1047                 if (ret == 0) {
1048                         keyid = *(uint64_t *) data.data;
1049
1050                         if (data.data != NULL) {
1051                                 free(data.data);
1052                                 data.data = NULL;
1053                         }
1054                 }
1055
1056                 ret = cursor->c_close(cursor);
1057                 cursor = NULL;
1058         }
1059         
1060         return keyid;
1061 }
1062
1063 /*
1064  * Include the basic keydb routines.
1065  */
1066 #define NEED_GETKEYSIGS 1
1067 #define NEED_KEYID2UID 1
1068 #define NEED_UPDATEKEYS 1
1069 #include "keydb.c"
1070
1071 struct dbfuncs keydb_db4_funcs = {
1072         .initdb                 = db4_initdb,
1073         .cleanupdb              = db4_cleanupdb,
1074         .starttrans             = db4_starttrans,
1075         .endtrans               = db4_endtrans,
1076         .fetch_key              = db4_fetch_key,
1077         .fetch_key_text         = db4_fetch_key_text,
1078         .store_key              = db4_store_key,
1079         .update_keys            = generic_update_keys,
1080         .delete_key             = db4_delete_key,
1081         .getkeysigs             = generic_getkeysigs,
1082         .cached_getkeysigs      = generic_cached_getkeysigs,
1083         .keyid2uid              = generic_keyid2uid,
1084         .getfullkeyid           = db4_getfullkeyid,
1085         .iterate_keys           = db4_iterate_keys,
1086 };