Use C99 uint32_t rather than u_int32_t
[onak.git] / keydb_db4.c
1 /*
2  * keydb_db4.c - Routines to store and fetch keys in a DB4 database.
3  *
4  * Copyright 2002-2008 Jonathan McDowell <noodles@earth.li>
5  *
6  * This program is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the Free
8  * Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/uio.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #include <db.h>
32
33 #include "charfuncs.h"
34 #include "keyarray.h"
35 #include "keydb.h"
36 #include "keyid.h"
37 #include "decodekey.h"
38 #include "keystructs.h"
39 #include "mem.h"
40 #include "log.h"
41 #include "onak-conf.h"
42 #include "parsekey.h"
43 #include "wordlist.h"
44
45 #define DB4_UPGRADE_FILE "db_upgrade.lck"
46
47 /**
48  *      dbenv - our database environment.
49  */
50 static DB_ENV *dbenv = NULL;
51
52 /**
53  *      numdb - The number of database files we have.
54  */
55 static int numdbs = 16;
56
57 /**
58  *      dbconn - our connections to the key database files.
59  */
60 static DB **dbconns = NULL;
61
62 /**
63  *      worddb - our connection to the word database.
64  */
65 static DB *worddb = NULL;
66
67 /**
68  *      id32db - our connection to the 32bit ID database.
69  */
70 static DB *id32db = NULL;
71
72 /**
73  *      skshashdb - our connection to the SKS hash database.
74  */
75 static DB *skshashdb = NULL;
76
77 /**
78  *      txn - our current transaction id.
79  */
80 static DB_TXN *txn = NULL;
81
82 DB *keydb(uint64_t keyid)
83 {
84         uint64_t keytrun;
85
86         keytrun = keyid >> 8;
87
88         return(dbconns[keytrun % numdbs]);
89 }
90
91 /**
92  *      db4_errfunc - Direct DB errors to logfile
93  *
94  *      Basic function to take errors from the DB library and output them to
95  *      the logfile rather than stderr.
96  */
97 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR < 3)
98 static void db4_errfunc(const char *errpfx, const char *errmsg)
99 #else
100 static void db4_errfunc(const DB_ENV *edbenv, const char *errpfx,
101                 const char *errmsg)
102 #endif
103 {
104         if (errpfx) {
105                 logthing(LOGTHING_DEBUG, "db4 error: %s:%s", errpfx, errmsg);
106         } else {
107                 logthing(LOGTHING_DEBUG, "db4 error: %s", errmsg);
108         }
109
110         return;
111 }
112
113 /**
114  *      starttrans - Start a transaction.
115  *
116  *      Start a transaction. Intended to be used if we're about to perform many
117  *      operations on the database to help speed it all up, or if we want
118  *      something to only succeed if all relevant operations are successful.
119  */
120 static bool db4_starttrans(void)
121 {
122         int ret;
123
124         log_assert(dbenv != NULL);
125         log_assert(txn == NULL);
126
127         ret = dbenv->txn_begin(dbenv,
128                 NULL, /* No parent transaction */
129                 &txn,
130                 0);
131         if (ret != 0) {
132                 logthing(LOGTHING_CRITICAL,
133                                 "Error starting transaction: %s",
134                                 db_strerror(ret));
135                 exit(1);
136         }
137
138         return true;
139 }
140
141 /**
142  *      endtrans - End a transaction.
143  *
144  *      Ends a transaction.
145  */
146 static void db4_endtrans(void)
147 {
148         int ret;
149
150         log_assert(dbenv != NULL);
151         log_assert(txn != NULL);
152
153         ret = txn->commit(txn,
154                 0);
155         if (ret != 0) {
156                 logthing(LOGTHING_CRITICAL,
157                                 "Error ending transaction: %s",
158                                 db_strerror(ret));
159                 exit(1);
160         }
161         txn = NULL;
162
163         return;
164 }
165
166 /**
167  *      cleanupdb - De-initialize the key database.
168  *
169  *      This function should be called upon program exit to allow the DB to
170  *      cleanup after itself.
171  */
172 static void db4_cleanupdb(void)
173 {
174         int i = 0;
175
176         if (dbenv != NULL) {
177                 dbenv->txn_checkpoint(dbenv, 0, 0, 0);
178                 if (skshashdb != NULL) {
179                         skshashdb->close(skshashdb, 0);
180                         skshashdb = NULL;
181                 }
182                 if (id32db != NULL) {
183                         id32db->close(id32db, 0);
184                         id32db = NULL;
185                 }
186                 if (worddb != NULL) {
187                         worddb->close(worddb, 0);
188                         worddb = NULL;
189                 }
190                 for (i = 0; i < numdbs; i++) {
191                         if (dbconns[i] != NULL) {
192                                 dbconns[i]->close(dbconns[i], 0);
193                                 dbconns[i] = NULL;
194                         }
195                 }
196                 free(dbconns);
197                 dbconns = NULL;
198                 dbenv->close(dbenv, 0);
199                 dbenv = NULL;
200         }
201 }
202
203 /**
204  *      db4_upgradedb - Upgrade a DB4 database
205  *
206  *      Called if we discover we need to upgrade our DB4 database; ie if
207  *      we're running with a newer version of db4 than the database was
208  *      created with.
209  */
210 static int db4_upgradedb(int numdb)
211 {
212         DB *curdb = NULL;
213         int ret;
214         int i;
215         char buf[1024];
216         int lockfile_fd;
217         struct stat statbuf;
218
219         snprintf(buf, sizeof(buf) - 1, "%s/%s", config.db_dir,
220                         DB4_UPGRADE_FILE);
221         lockfile_fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0600);
222         if (lockfile_fd < 0) {
223                 if (errno == EEXIST) {
224                         while (stat(buf, &statbuf) == 0) ;
225                         return 0;
226                 } else {
227                         logthing(LOGTHING_CRITICAL, "Couldn't open database "
228                                 "update lock file: %s", strerror(errno));
229                         return -1;
230                 }
231         }
232         snprintf(buf, sizeof(buf) - 1, "%d", getpid());
233         write(lockfile_fd, buf, strlen(buf));
234         close(lockfile_fd);
235
236         logthing(LOGTHING_NOTICE, "Upgrading DB4 database");
237         ret = db_env_create(&dbenv, 0);
238         dbenv->set_errcall(dbenv, &db4_errfunc);
239         dbenv->remove(dbenv, config.db_dir, 0);
240         dbenv = NULL;
241         for (i = 0; i < numdb; i++) {
242                 ret = db_create(&curdb, NULL, 0);
243                 if (ret == 0) {
244                         snprintf(buf, sizeof(buf) - 1, "%s/keydb.%d.db",
245                                 config.db_dir, i);
246                         logthing(LOGTHING_DEBUG, "Upgrading %s", buf);
247                         ret = curdb->upgrade(curdb, buf, 0);
248                         curdb->close(curdb, 0);
249                 } else {
250                         logthing(LOGTHING_ERROR, "Error upgrading DB %s : %s",
251                                 buf,
252                                 db_strerror(ret));
253                 }
254         }
255
256         ret = db_create(&curdb, NULL, 0);
257         if (ret == 0) {
258                 snprintf(buf, sizeof(buf) - 1, "%s/worddb", config.db_dir);
259                 logthing(LOGTHING_DEBUG, "Upgrading %s", buf);
260                 ret = curdb->upgrade(curdb, buf, 0);
261                 curdb->close(curdb, 0);
262         } else {
263                 logthing(LOGTHING_ERROR, "Error upgrading DB %s : %s",
264                         buf,
265                         db_strerror(ret));
266         }
267
268         ret = db_create(&curdb, NULL, 0);
269         if (ret == 0) {
270                 snprintf(buf, sizeof(buf) - 1, "%s/id32db", config.db_dir);
271                 logthing(LOGTHING_DEBUG, "Upgrading %s", buf);
272                 ret = curdb->upgrade(curdb, buf, 0);
273                 curdb->close(curdb, 0);
274         } else {
275                 logthing(LOGTHING_ERROR, "Error upgrading DB %s : %s",
276                         buf,
277                         db_strerror(ret));
278         }
279
280         ret = db_create(&curdb, NULL, 0);
281         if (ret == 0) {
282                 snprintf(buf, sizeof(buf) - 1, "%s/skshashdb", config.db_dir);
283                 logthing(LOGTHING_DEBUG, "Upgrading %s", buf);
284                 ret = curdb->upgrade(curdb, buf, 0);
285                 curdb->close(curdb, 0);
286         } else {
287                 logthing(LOGTHING_ERROR, "Error upgrading DB %s : %s",
288                         buf,
289                         db_strerror(ret));
290         }
291
292         snprintf(buf, sizeof(buf) - 1, "%s/%s", config.db_dir,
293                         DB4_UPGRADE_FILE);
294         unlink(buf);
295
296         return ret;
297 }
298
299 /**
300  *      initdb - Initialize the key database.
301  *
302  *      This function should be called before any of the other functions in
303  *      this file are called in order to allow the DB to be initialized ready
304  *      for access.
305  */
306 static void db4_initdb(bool readonly)
307 {
308         char       buf[1024];
309         FILE      *numdb = NULL;
310         int        ret = 0;
311         int        i = 0;
312         uint32_t   flags = 0;
313         struct stat statbuf;
314         int        maxlocks;
315
316         snprintf(buf, sizeof(buf) - 1, "%s/%s", config.db_dir,
317                         DB4_UPGRADE_FILE);
318         ret = stat(buf, &statbuf);
319         while ((ret == 0) || (errno != ENOENT)) {
320                 if (ret != 0) {
321                         logthing(LOGTHING_CRITICAL, "Couldn't stat upgrade "
322                                 "lock file: %s (%d)", strerror(errno), ret);
323                         exit(1);
324                 }
325                 logthing(LOGTHING_DEBUG, "DB4 upgrade in progress; waiting.");
326                 sleep(5);
327                 ret = stat(buf, &statbuf);
328         }
329         ret = 0;
330
331         snprintf(buf, sizeof(buf) - 1, "%s/num_keydb", config.db_dir);
332         numdb = fopen(buf, "r");
333         if (numdb != NULL) {
334                 if (fgets(buf, sizeof(buf), numdb) != NULL) {
335                         numdbs = atoi(buf);
336                 }
337                 fclose(numdb);
338         } else if (!readonly) {
339                 logthing(LOGTHING_ERROR, "Couldn't open num_keydb: %s",
340                                 strerror(errno));
341                 numdb = fopen(buf, "w");
342                 if (numdb != NULL) {
343                         fprintf(numdb, "%d", numdbs);
344                         fclose(numdb);
345                 } else {
346                         logthing(LOGTHING_ERROR,
347                                 "Couldn't write num_keydb: %s",
348                                 strerror(errno));
349                 }
350         }
351
352         dbconns = calloc(numdbs, sizeof (DB *));
353         if (dbconns == NULL) {
354                 logthing(LOGTHING_CRITICAL,
355                                 "Couldn't allocate memory for dbconns");
356                 ret = 1;
357         }
358
359         if (ret == 0) {
360                 ret = db_env_create(&dbenv, 0);
361                 if (ret != 0) {
362                         logthing(LOGTHING_CRITICAL,
363                                 "db_env_create: %s", db_strerror(ret));
364                 }
365         }
366
367         /*
368          * Up the number of locks we're allowed at once. We base this on
369          * the maximum number of keys we're going to return.
370          */
371         maxlocks = config.maxkeys * 16;
372         if (maxlocks < 1000) {
373                 maxlocks = 1000;
374         }
375         dbenv->set_lk_max_locks(dbenv, maxlocks);
376         dbenv->set_lk_max_objects(dbenv, maxlocks);
377
378         /*
379          * Enable deadlock detection so that we don't block indefinitely on
380          * anything. What we really want is simple 2 state locks, but I'm not
381          * sure how to make the standard DB functions do that yet.
382          */
383         if (ret == 0) {
384                 dbenv->set_errcall(dbenv, &db4_errfunc);
385                 ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
386                 if (ret != 0) {
387                         logthing(LOGTHING_CRITICAL,
388                                 "db_env_create: %s", db_strerror(ret));
389                 }
390         }
391
392         if (ret == 0) {
393                 ret = dbenv->open(dbenv, config.db_dir,
394                                 DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_LOCK |
395                                 DB_INIT_TXN |
396                                 DB_CREATE,
397                                 0);
398 #ifdef DB_VERSION_MISMATCH
399                 if (ret == DB_VERSION_MISMATCH) {
400                         dbenv->close(dbenv, 0);
401                         dbenv = NULL;
402                         ret = db4_upgradedb(numdbs);
403                         if (ret == 0) {
404                                 ret = db_env_create(&dbenv, 0);
405                         }
406                         if (ret == 0) {
407                                 dbenv->set_errcall(dbenv, &db4_errfunc);
408                                 dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
409                                 ret = dbenv->open(dbenv, config.db_dir,
410                                         DB_INIT_LOG | DB_INIT_MPOOL |
411                                         DB_INIT_LOCK | DB_INIT_TXN |
412                                         DB_CREATE | DB_RECOVER,
413                                         0);
414
415                                 if (ret == 0) {
416                                         dbenv->txn_checkpoint(dbenv,
417                                                         0,
418                                                         0,
419                                                         DB_FORCE);
420                                 }
421                         }
422                 }
423 #endif
424                 if (ret != 0) {
425                         logthing(LOGTHING_CRITICAL,
426                                         "Error opening db environment: %s (%s)",
427                                         config.db_dir,
428                                         db_strerror(ret));
429                         dbenv->close(dbenv, 0);
430                         dbenv = NULL;
431                 }
432         }
433
434         if (ret == 0) {
435                 db4_starttrans();
436
437                 for (i = 0; !ret && i < numdbs; i++) {
438                         ret = db_create(&dbconns[i], dbenv, 0);
439                         if (ret != 0) {
440                                 logthing(LOGTHING_CRITICAL,
441                                         "db_create: %s", db_strerror(ret));
442                         }
443
444                         if (ret == 0) {
445                                 snprintf(buf, 1023, "keydb.%d.db", i);
446                                 flags = DB_CREATE;
447                                 if (readonly) {
448                                         flags = DB_RDONLY;
449                                 }
450                                 ret = dbconns[i]->open(dbconns[i],
451                                                 txn,
452                                                 buf,
453                                                 "keydb",
454                                                 DB_HASH,
455                                                 flags,
456                                                 0664);
457                                 if (ret != 0) {
458                                         logthing(LOGTHING_CRITICAL,
459                                                 "Error opening key database:"
460                                                 " %s (%s)",
461                                                 buf,
462                                                 db_strerror(ret));
463                                 }
464                         }
465                 }
466
467         }
468
469         if (ret == 0) {
470                 ret = db_create(&worddb, dbenv, 0);
471                 if (ret != 0) {
472                         logthing(LOGTHING_CRITICAL, "db_create: %s",
473                                         db_strerror(ret));
474                 }
475         }
476
477         if (ret == 0) {
478                 ret = worddb->set_flags(worddb, DB_DUP);
479         }
480
481         if (ret == 0) {
482                 ret = worddb->open(worddb, txn, "worddb", "worddb", DB_BTREE,
483                                 flags,
484                                 0664);
485                 if (ret != 0) {
486                         logthing(LOGTHING_CRITICAL,
487                                         "Error opening word database: %s (%s)",
488                                         "worddb",
489                                         db_strerror(ret));
490                 }
491         }
492
493         if (ret == 0) {
494                 ret = db_create(&id32db, dbenv, 0);
495                 if (ret != 0) {
496                         logthing(LOGTHING_CRITICAL, "db_create: %s",
497                                         db_strerror(ret));
498                 }
499         }
500
501         if (ret == 0) {
502                 ret = id32db->set_flags(id32db, DB_DUP);
503         }
504
505         if (ret == 0) {
506                 ret = id32db->open(id32db, txn, "id32db", "id32db", DB_HASH,
507                                 flags,
508                                 0664);
509                 if (ret != 0) {
510                         logthing(LOGTHING_CRITICAL,
511                                         "Error opening id32 database: %s (%s)",
512                                         "id32db",
513                                         db_strerror(ret));
514                 }
515         }
516
517         if (ret == 0) {
518                 ret = db_create(&skshashdb, dbenv, 0);
519                 if (ret != 0) {
520                         logthing(LOGTHING_CRITICAL, "db_create: %s",
521                                         db_strerror(ret));
522                 }
523         }
524
525         if (ret == 0) {
526                 ret = skshashdb->open(skshashdb, txn, "skshashdb",
527                                 "skshashdb", DB_HASH,
528                                 flags,
529                                 0664);
530                 if (ret != 0) {
531                         logthing(LOGTHING_CRITICAL,
532                                 "Error opening skshash database: %s (%s)",
533                                 "skshashdb",
534                                 db_strerror(ret));
535                 }
536         }
537
538         if (txn != NULL) {
539                 db4_endtrans();
540         }
541
542         if (ret != 0) {
543                 db4_cleanupdb();
544                 logthing(LOGTHING_CRITICAL,
545                                 "Error opening database; exiting");
546                 exit(EXIT_FAILURE);
547         }
548         
549         return;
550 }
551
552 /**
553  *      getfullkeyid - Maps a 32bit key id to a 64bit one.
554  *      @keyid: The 32bit keyid.
555  *
556  *      This function maps a 32bit key id to the full 64bit one. It returns the
557  *      full keyid. If the key isn't found a keyid of 0 is returned.
558  */
559 static uint64_t db4_getfullkeyid(uint64_t keyid)
560 {
561         DBT       key, data;
562         DBC      *cursor = NULL;
563         uint32_t  shortkeyid = 0;
564         int       ret = 0;
565
566         if (keyid < 0x100000000LL) {
567                 ret = id32db->cursor(id32db,
568                                 txn,
569                                 &cursor,
570                                 0);   /* flags */
571
572                 shortkeyid = keyid & 0xFFFFFFFF;
573
574                 memset(&key, 0, sizeof(key));
575                 memset(&data, 0, sizeof(data));
576                 key.data = &shortkeyid;
577                 key.size = sizeof(shortkeyid);
578                 data.flags = DB_DBT_MALLOC;
579
580                 ret = cursor->c_get(cursor,
581                         &key,
582                         &data,
583                         DB_SET);
584
585                 if (ret == 0) {
586                         keyid = *(uint64_t *) data.data;
587
588                         if (data.data != NULL) {
589                                 free(data.data);
590                                 data.data = NULL;
591                         }
592                 }
593
594                 ret = cursor->c_close(cursor);
595                 cursor = NULL;
596         }
597         
598         return keyid;
599 }
600
601 /**
602  *      fetch_key - Given a keyid fetch the key from storage.
603  *      @keyid: The keyid to fetch.
604  *      @publickey: A pointer to a structure to return the key in.
605  *      @intrans: If we're already in a transaction.
606  *
607  *      We use the hex representation of the keyid as the filename to fetch the
608  *      key from. The key is stored in the file as a binary OpenPGP stream of
609  *      packets, so we can just use read_openpgp_stream() to read the packets
610  *      in and then parse_keys() to parse the packets into a publickey
611  *      structure.
612  */
613 static int db4_fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
614                 bool intrans)
615 {
616         struct openpgp_packet_list *packets = NULL;
617         DBT key, data;
618         int ret = 0;
619         int numkeys = 0;
620         struct buffer_ctx fetchbuf;
621
622         if (keyid < 0x100000000LL) {
623                 keyid = db4_getfullkeyid(keyid);
624         }
625
626         memset(&key, 0, sizeof(key));
627         memset(&data, 0, sizeof(data));
628
629         data.size = 0;
630         data.data = NULL;
631
632         key.size = sizeof(keyid);
633         key.data = &keyid;
634
635         if (!intrans) {
636                 db4_starttrans();
637         }
638
639         ret = keydb(keyid)->get(keydb(keyid),
640                         txn,
641                         &key,
642                         &data,
643                         0); /* flags*/
644         
645         if (ret == 0) {
646                 fetchbuf.buffer = data.data;
647                 fetchbuf.offset = 0;
648                 fetchbuf.size = data.size;
649                 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
650                                 &packets, 0);
651                 parse_keys(packets, publickey);
652                 free_packet_list(packets);
653                 packets = NULL;
654                 numkeys++;
655         } else if (ret != DB_NOTFOUND) {
656                 logthing(LOGTHING_ERROR,
657                                 "Problem retrieving key: %s",
658                                 db_strerror(ret));
659         }
660
661         if (!intrans) {
662                 db4_endtrans();
663         }
664
665         return (numkeys);
666 }
667
668 int worddb_cmp(const void *d1, const void *d2)
669 {
670         return memcmp(d1, d2, 12);
671 }
672
673 /**
674  *      fetch_key_text - Trys to find the keys that contain the supplied text.
675  *      @search: The text to search for.
676  *      @publickey: A pointer to a structure to return the key in.
677  *
678  *      This function searches for the supplied text and returns the keys that
679  *      contain it.
680  */
681 static int db4_fetch_key_text(const char *search,
682                 struct openpgp_publickey **publickey)
683 {
684         DBC *cursor = NULL;
685         DBT key, data;
686         int ret;
687         uint64_t keyid;
688         int i;
689         int numkeys;
690         char *searchtext = NULL;
691         struct ll *wordlist = NULL;
692         struct ll *curword = NULL;
693         struct keyarray keylist = { NULL, 0, 0 };
694         struct keyarray newkeylist = { NULL, 0, 0 };
695         int firstpass = 1;
696
697         numkeys = 0;
698         searchtext = strdup(search);
699         wordlist = makewordlist(wordlist, searchtext);
700
701         for (curword = wordlist; curword != NULL; curword = curword->next) {
702                 db4_starttrans();
703
704                 ret = worddb->cursor(worddb,
705                                 txn,
706                                 &cursor,
707                                 0);   /* flags */
708
709                 memset(&key, 0, sizeof(key));
710                 memset(&data, 0, sizeof(data));
711                 key.data = curword->object;
712                 key.size = strlen(curword->object);
713                 data.flags = DB_DBT_MALLOC;
714                 ret = cursor->c_get(cursor,
715                                 &key,
716                                 &data,
717                                 DB_SET);
718                 while (ret == 0 && strncmp(key.data, curword->object,
719                                         key.size) == 0 &&
720                                 ((char *) curword->object)[key.size] == 0) {
721                         keyid = 0;
722                         for (i = 4; i < 12; i++) {
723                                 keyid <<= 8;
724                                 keyid += ((unsigned char *)
725                                                 data.data)[i];
726                         }
727
728                         /*
729                          * Only add the keys containing this word if this is
730                          * our first pass (ie we have no existing key list),
731                          * or the key contained a previous word.
732                          */
733                         if (firstpass || array_find(&keylist, keyid)) {
734                                 array_add(&newkeylist, keyid);
735                         }
736
737                         free(data.data);
738                         data.data = NULL;
739
740                         ret = cursor->c_get(cursor,
741                                         &key,
742                                         &data,
743                                         DB_NEXT);
744                 }
745                 array_free(&keylist);
746                 keylist = newkeylist;
747                 newkeylist.keys = NULL;
748                 newkeylist.count = newkeylist.size = 0;
749                 if (data.data != NULL) {
750                         free(data.data);
751                         data.data = NULL;
752                 }
753                 ret = cursor->c_close(cursor);
754                 cursor = NULL;
755                 firstpass = 0;
756                 db4_endtrans();
757         }
758         llfree(wordlist, NULL);
759         wordlist = NULL;
760
761         if (keylist.count > config.maxkeys) {
762                 keylist.count = config.maxkeys;
763         }
764         
765         db4_starttrans();
766         for (i = 0; i < keylist.count; i++) {
767                 numkeys += db4_fetch_key(keylist.keys[i],
768                         publickey,
769                         true);
770         }
771         array_free(&keylist);
772         free(searchtext);
773         searchtext = NULL;
774
775         db4_endtrans();
776         
777         return (numkeys);
778 }
779
780 static int db4_fetch_key_skshash(const struct skshash *hash,
781                 struct openpgp_publickey **publickey)
782 {
783         DBT       key, data;
784         DBC      *cursor = NULL;
785         uint64_t  keyid = 0;
786         int       ret = 0;
787
788         ret = skshashdb->cursor(skshashdb,
789                         txn,
790                         &cursor,
791                         0);   /* flags */
792
793         memset(&key, 0, sizeof(key));
794         memset(&data, 0, sizeof(data));
795         key.data = (void *) hash->hash;
796         key.size = sizeof(hash->hash);
797         data.flags = DB_DBT_MALLOC;
798
799         ret = cursor->c_get(cursor,
800                 &key,
801                 &data,
802                 DB_SET);
803
804         if (ret == 0) {
805                 keyid = *(uint64_t *) data.data;
806
807                 if (data.data != NULL) {
808                         free(data.data);
809                         data.data = NULL;
810                 }
811         }
812
813         ret = cursor->c_close(cursor);
814         cursor = NULL;
815
816         return db4_fetch_key(keyid, publickey, false);
817 }
818
819 /**
820  *      delete_key - Given a keyid delete the key from storage.
821  *      @keyid: The keyid to delete.
822  *      @intrans: If we're already in a transaction.
823  *
824  *      This function deletes a public key from whatever storage mechanism we
825  *      are using. Returns 0 if the key existed.
826  */
827 static int db4_delete_key(uint64_t keyid, bool intrans)
828 {
829         struct openpgp_publickey *publickey = NULL;
830         DBT key, data;
831         DBC *cursor = NULL;
832         uint32_t   shortkeyid = 0;
833         uint64_t  *subkeyids = NULL;
834         int ret = 0;
835         int i;
836         char **uids = NULL;
837         char *primary = NULL;
838         unsigned char worddb_data[12];
839         struct ll *wordlist = NULL;
840         struct ll *curword  = NULL;
841         bool deadlock = false;
842         struct skshash hash;
843
844         if (!intrans) {
845                 db4_starttrans();
846         }
847
848         db4_fetch_key(keyid, &publickey, true);
849
850         /*
851          * Walk through the uids removing the words from the worddb.
852          */
853         if (publickey != NULL) {
854                 uids = keyuids(publickey, &primary);
855         }
856         if (uids != NULL) {
857                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
858                         wordlist = makewordlist(wordlist, uids[i]);
859                 }
860                                 
861                 ret = worddb->cursor(worddb,
862                         txn,
863                         &cursor,
864                         0);   /* flags */
865
866                 for (curword = wordlist; curword != NULL && !deadlock;
867                                 curword = curword->next) {
868                         memset(&key, 0, sizeof(key));
869                         memset(&data, 0, sizeof(data));
870                         key.data = curword->object;
871                         key.size = strlen(key.data);
872                         data.data = worddb_data;
873                         data.size = sizeof(worddb_data);
874
875                         /*
876                          * Our data is the key creation time followed by the
877                          * key id.
878                          */
879                         worddb_data[ 0] = publickey->publickey->data[1];
880                         worddb_data[ 1] = publickey->publickey->data[2];
881                         worddb_data[ 2] = publickey->publickey->data[3];
882                         worddb_data[ 3] = publickey->publickey->data[4];
883                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
884                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
885                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
886                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
887                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
888                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
889                         worddb_data[10] = (keyid >>  8) & 0xFF;
890                         worddb_data[11] = keyid & 0xFF; 
891
892                         ret = cursor->c_get(cursor,
893                                 &key,
894                                 &data,
895                                 DB_GET_BOTH);
896
897                         if (ret == 0) {
898                                 ret = cursor->c_del(cursor, 0);
899                                 if (ret != 0) {
900                                         logthing(LOGTHING_ERROR,
901                                                 "Problem deleting word: %s",
902                                                 db_strerror(ret));
903                                 }
904                         }
905
906                         if (ret != 0) {
907                                 logthing(LOGTHING_ERROR,
908                                         "Problem deleting word: %s",
909                                         db_strerror(ret));
910                                 if (ret == DB_LOCK_DEADLOCK) {
911                                         deadlock = true;
912                                 }
913                         }
914                 }
915                 ret = cursor->c_close(cursor);
916                 cursor = NULL;
917
918                 /*
919                  * Free our UID and word lists.
920                  */
921                 llfree(wordlist, NULL);
922                 for (i = 0; uids[i] != NULL; i++) {
923                         free(uids[i]);
924                         uids[i] = NULL;
925                 }
926                 free(uids);
927                 uids = NULL;
928                 free_publickey(publickey);
929                 publickey = NULL;
930         }
931
932         if (!deadlock) {
933                 ret = id32db->cursor(id32db,
934                         txn,
935                         &cursor,
936                         0);   /* flags */
937
938                 shortkeyid = keyid & 0xFFFFFFFF;
939
940                 memset(&key, 0, sizeof(key));
941                 memset(&data, 0, sizeof(data));
942                 key.data = &shortkeyid;
943                 key.size = sizeof(shortkeyid);
944                 data.data = &keyid;
945                 data.size = sizeof(keyid);
946
947                 ret = cursor->c_get(cursor,
948                         &key,
949                         &data,
950                         DB_GET_BOTH);
951
952                 if (ret == 0) {
953                         ret = cursor->c_del(cursor, 0);
954                         if (ret != 0) {
955                                 logthing(LOGTHING_ERROR,
956                                         "Problem deleting short keyid: %s",
957                                         db_strerror(ret));
958                         }
959                 }
960
961                 if (ret != 0) {
962                         logthing(LOGTHING_ERROR,
963                                 "Problem deleting short keyid: %s",
964                                 db_strerror(ret));
965                         if (ret == DB_LOCK_DEADLOCK) {
966                                 deadlock = true;
967                         }
968                 }
969
970                 subkeyids = keysubkeys(publickey);
971                 i = 0;
972                 while (subkeyids != NULL && subkeyids[i] != 0) {
973                         shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
974
975                         memset(&key, 0, sizeof(key));
976                         memset(&data, 0, sizeof(data));
977                         key.data = &shortkeyid;
978                         key.size = sizeof(shortkeyid);
979                         data.data = &keyid;
980                         data.size = sizeof(keyid);
981
982                         ret = cursor->c_get(cursor,
983                                 &key,
984                                 &data,
985                                 DB_GET_BOTH);
986
987                         if (ret == 0) {
988                                 ret = cursor->c_del(cursor, 0);
989                                 if (ret != 0) {
990                                         logthing(LOGTHING_ERROR,
991                                                 "Problem deleting short"
992                                                 " keyid: %s",
993                                                 db_strerror(ret));
994                                 }
995                         }
996
997                         if (ret != 0) {
998                                 logthing(LOGTHING_ERROR,
999                                         "Problem deleting short keyid: %s",
1000                                         db_strerror(ret));
1001                                 if (ret == DB_LOCK_DEADLOCK) {
1002                                         deadlock = true;
1003                                 }
1004                         }
1005                 }
1006                 if (subkeyids != NULL) {
1007                         free(subkeyids);
1008                         subkeyids = NULL;
1009                 }
1010                 ret = cursor->c_close(cursor);
1011                 cursor = NULL;
1012
1013         }
1014
1015         if (!deadlock) {
1016                 get_skshash(publickey, &hash);
1017
1018                 memset(&key, 0, sizeof(key));
1019                 memset(&data, 0, sizeof(data));
1020                 key.data = hash.hash;
1021                 key.size = sizeof(hash.hash);
1022                 data.data = &keyid;
1023                 data.size = sizeof(keyid);
1024
1025                 ret = cursor->c_get(cursor,
1026                         &key,
1027                         &data,
1028                         DB_GET_BOTH);
1029
1030                 if (ret == 0) {
1031                         ret = cursor->c_del(cursor, 0);
1032                 }
1033
1034                 if (ret != 0) {
1035                         logthing(LOGTHING_ERROR,
1036                                 "Problem deleting skshash: %s",
1037                                 db_strerror(ret));
1038                         if (ret == DB_LOCK_DEADLOCK) {
1039                                 deadlock = true;
1040                         }
1041                 }
1042
1043                 ret = cursor->c_close(cursor);
1044                 cursor = NULL;
1045         }
1046
1047         if (!deadlock) {
1048                 key.data = &keyid;
1049                 key.size = sizeof(keyid);
1050
1051                 keydb(keyid)->del(keydb(keyid),
1052                                 txn,
1053                                 &key,
1054                                 0); /* flags */
1055         }
1056
1057         if (!intrans) {
1058                 db4_endtrans();
1059         }
1060
1061         return deadlock ? (-1) : (ret == DB_NOTFOUND);
1062 }
1063
1064 /**
1065  *      store_key - Takes a key and stores it.
1066  *      @publickey: A pointer to the public key to store.
1067  *      @intrans: If we're already in a transaction.
1068  *      @update: If true the key exists and should be updated.
1069  *
1070  *      Again we just use the hex representation of the keyid as the filename
1071  *      to store the key to. We flatten the public key to a list of OpenPGP
1072  *      packets and then use write_openpgp_stream() to write the stream out to
1073  *      the file. If update is true then we delete the old key first, otherwise
1074  *      we trust that it doesn't exist.
1075  */
1076 static int db4_store_key(struct openpgp_publickey *publickey, bool intrans,
1077                 bool update)
1078 {
1079         struct     openpgp_packet_list *packets = NULL;
1080         struct     openpgp_packet_list *list_end = NULL;
1081         struct     openpgp_publickey *next = NULL;
1082         int        ret = 0;
1083         int        i = 0;
1084         struct     buffer_ctx storebuf;
1085         DBT        key;
1086         DBT        data;
1087         uint64_t   keyid = 0;
1088         uint32_t   shortkeyid = 0;
1089         uint64_t  *subkeyids = NULL;
1090         char     **uids = NULL;
1091         char      *primary = NULL;
1092         unsigned char worddb_data[12];
1093         struct ll *wordlist = NULL;
1094         struct ll *curword  = NULL;
1095         bool       deadlock = false;
1096         struct skshash hash;
1097
1098         keyid = get_keyid(publickey);
1099
1100         if (!intrans) {
1101                 db4_starttrans();
1102         }
1103
1104         /*
1105          * Delete the key if we already have it.
1106          *
1107          * TODO: Can we optimize this perhaps? Possibly when other data is
1108          * involved as well? I suspect this is easiest and doesn't make a lot
1109          * of difference though - the largest chunk of data is the keydata and
1110          * it definitely needs updated.
1111          */
1112         if (update) {
1113                 deadlock = (db4_delete_key(keyid, true) == -1);
1114         }
1115
1116         /*
1117          * Convert the key to a flat set of binary data.
1118          */
1119         if (!deadlock) {
1120                 next = publickey->next;
1121                 publickey->next = NULL;
1122                 flatten_publickey(publickey, &packets, &list_end);
1123                 publickey->next = next;
1124
1125                 storebuf.offset = 0; 
1126                 storebuf.size = 8192;
1127                 storebuf.buffer = malloc(8192);
1128         
1129                 write_openpgp_stream(buffer_putchar, &storebuf, packets);
1130
1131                 /*
1132                  * Now we have the key data store it in the DB; the keyid is
1133                  * the key.
1134                  */
1135                 memset(&key, 0, sizeof(key));
1136                 memset(&data, 0, sizeof(data));
1137                 key.data = &keyid;
1138                 key.size = sizeof(keyid);
1139                 data.size = storebuf.offset;
1140                 data.data = storebuf.buffer;
1141
1142                 ret = keydb(keyid)->put(keydb(keyid),
1143                                 txn,
1144                                 &key,
1145                                 &data,
1146                                 0); /* flags*/
1147                 if (ret != 0) {
1148                         logthing(LOGTHING_ERROR,
1149                                         "Problem storing key: %s",
1150                                         db_strerror(ret));
1151                         if (ret == DB_LOCK_DEADLOCK) {
1152                                 deadlock = true;
1153                         }
1154                 }
1155
1156                 free(storebuf.buffer);
1157                 storebuf.buffer = NULL;
1158                 storebuf.size = 0;
1159                 storebuf.offset = 0; 
1160         
1161                 free_packet_list(packets);
1162                 packets = NULL;
1163         }
1164
1165         /*
1166          * Walk through our uids storing the words into the db with the keyid.
1167          */
1168         if (!deadlock) {
1169                 uids = keyuids(publickey, &primary);
1170         }
1171         if (uids != NULL) {
1172                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
1173                         wordlist = makewordlist(wordlist, uids[i]);
1174                 }
1175
1176                 for (curword = wordlist; curword != NULL && !deadlock;
1177                                 curword = curword->next) {
1178                         memset(&key, 0, sizeof(key));
1179                         memset(&data, 0, sizeof(data));
1180                         key.data = curword->object;
1181                         key.size = strlen(key.data);
1182                         data.data = worddb_data;
1183                         data.size = sizeof(worddb_data);
1184
1185                         /*
1186                          * Our data is the key creation time followed by the
1187                          * key id.
1188                          */
1189                         worddb_data[ 0] = publickey->publickey->data[1];
1190                         worddb_data[ 1] = publickey->publickey->data[2];
1191                         worddb_data[ 2] = publickey->publickey->data[3];
1192                         worddb_data[ 3] = publickey->publickey->data[4];
1193                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
1194                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
1195                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
1196                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
1197                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
1198                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
1199                         worddb_data[10] = (keyid >>  8) & 0xFF;
1200                         worddb_data[11] = keyid & 0xFF; 
1201                         ret = worddb->put(worddb,
1202                                 txn,
1203                                 &key,
1204                                 &data,
1205                                 0);
1206                         if (ret != 0) {
1207                                 logthing(LOGTHING_ERROR,
1208                                         "Problem storing word: %s",
1209                                         db_strerror(ret));
1210                                 if (ret == DB_LOCK_DEADLOCK) {
1211                                         deadlock = true;
1212                                 }
1213                         }
1214                 }
1215
1216                 /*
1217                  * Free our UID and word lists.
1218                  */
1219                 llfree(wordlist, NULL);
1220                 for (i = 0; uids[i] != NULL; i++) {
1221                         free(uids[i]);
1222                         uids[i] = NULL;
1223                 }
1224                 free(uids);
1225                 uids = NULL;
1226         }
1227
1228         /*
1229          * Write the truncated 32 bit keyid so we can lookup the full id for
1230          * queries.
1231          */
1232         if (!deadlock) {
1233                 shortkeyid = keyid & 0xFFFFFFFF;
1234
1235                 memset(&key, 0, sizeof(key));
1236                 memset(&data, 0, sizeof(data));
1237                 key.data = &shortkeyid;
1238                 key.size = sizeof(shortkeyid);
1239                 data.data = &keyid;
1240                 data.size = sizeof(keyid);
1241
1242                 ret = id32db->put(id32db,
1243                         txn,
1244                         &key,
1245                         &data,
1246                         0);
1247                 if (ret != 0) {
1248                         logthing(LOGTHING_ERROR,
1249                                 "Problem storing short keyid: %s",
1250                                 db_strerror(ret));
1251                         if (ret == DB_LOCK_DEADLOCK) {
1252                                 deadlock = true;
1253                         }
1254                 }
1255         }
1256
1257         if (!deadlock) {
1258                 subkeyids = keysubkeys(publickey);
1259                 i = 0;
1260                 while (subkeyids != NULL && subkeyids[i] != 0) {
1261                         shortkeyid = subkeyids[i++] & 0xFFFFFFFF;
1262
1263                         memset(&key, 0, sizeof(key));
1264                         memset(&data, 0, sizeof(data));
1265                         key.data = &shortkeyid;
1266                         key.size = sizeof(shortkeyid);
1267                         data.data = &keyid;
1268                         data.size = sizeof(keyid);
1269
1270                         ret = id32db->put(id32db,
1271                                 txn,
1272                                 &key,
1273                                 &data,
1274                                 0);
1275                         if (ret != 0) {
1276                                 logthing(LOGTHING_ERROR,
1277                                         "Problem storing short keyid: %s",
1278                                         db_strerror(ret));
1279                                 if (ret == DB_LOCK_DEADLOCK) {
1280                                         deadlock = true;
1281                                 }
1282                         }
1283                 }
1284                 if (subkeyids != NULL) {
1285                         free(subkeyids);
1286                         subkeyids = NULL;
1287                 }
1288         }
1289
1290         if (!deadlock) {
1291                 get_skshash(publickey, &hash);
1292                 memset(&key, 0, sizeof(key));
1293                 memset(&data, 0, sizeof(data));
1294                 key.data = hash.hash;
1295                 key.size = sizeof(hash.hash);
1296                 data.data = &keyid;
1297                 data.size = sizeof(keyid);
1298
1299                 ret = skshashdb->put(skshashdb,
1300                         txn,
1301                         &key,
1302                         &data,
1303                         0);
1304                 if (ret != 0) {
1305                         logthing(LOGTHING_ERROR,
1306                                 "Problem storing SKS hash: %s",
1307                                 db_strerror(ret));
1308                         if (ret == DB_LOCK_DEADLOCK) {
1309                                 deadlock = true;
1310                         }
1311                 }
1312         }
1313
1314         if (!intrans) {
1315                 db4_endtrans();
1316         }
1317
1318         return deadlock ? -1 : 0 ;
1319 }
1320
1321 /**
1322  *      iterate_keys - call a function once for each key in the db.
1323  *      @iterfunc: The function to call.
1324  *      @ctx: A context pointer
1325  *
1326  *      Calls iterfunc once for each key in the database. ctx is passed
1327  *      unaltered to iterfunc. This function is intended to aid database dumps
1328  *      and statistic calculations.
1329  *
1330  *      Returns the number of keys we iterated over.
1331  */
1332 static int db4_iterate_keys(void (*iterfunc)(void *ctx,
1333                 struct openpgp_publickey *key), void *ctx)
1334 {
1335         DBT                         dbkey, data;
1336         DBC                        *cursor = NULL;
1337         int                         ret = 0;
1338         int                         i = 0;
1339         int                         numkeys = 0;
1340         struct buffer_ctx           fetchbuf;
1341         struct openpgp_packet_list *packets = NULL;
1342         struct openpgp_publickey   *key = NULL;
1343
1344         for (i = 0; i < numdbs; i++) {
1345                 ret = dbconns[i]->cursor(dbconns[i],
1346                         NULL,
1347                         &cursor,
1348                         0);   /* flags */
1349
1350                 memset(&dbkey, 0, sizeof(dbkey));
1351                 memset(&data, 0, sizeof(data));
1352                 ret = cursor->c_get(cursor, &dbkey, &data, DB_NEXT);
1353                 while (ret == 0) {
1354                         fetchbuf.buffer = data.data;
1355                         fetchbuf.offset = 0;
1356                         fetchbuf.size = data.size;
1357                         read_openpgp_stream(buffer_fetchchar, &fetchbuf,
1358                                 &packets, 0);
1359                         parse_keys(packets, &key);
1360
1361                         iterfunc(ctx, key);
1362                         
1363                         free_publickey(key);
1364                         key = NULL;
1365                         free_packet_list(packets);
1366                         packets = NULL;
1367                         
1368                         memset(&dbkey, 0, sizeof(dbkey));
1369                         memset(&data, 0, sizeof(data));
1370                         ret = cursor->c_get(cursor, &dbkey, &data,
1371                                         DB_NEXT);
1372                         numkeys++;
1373                 }
1374                 if (ret != DB_NOTFOUND) {
1375                         logthing(LOGTHING_ERROR,
1376                                 "Problem reading key: %s",
1377                                 db_strerror(ret));
1378                 }
1379
1380                 ret = cursor->c_close(cursor);
1381                 cursor = NULL;
1382         }
1383         
1384         return numkeys;
1385 }
1386
1387 /*
1388  * Include the basic keydb routines.
1389  */
1390 #define NEED_GETKEYSIGS 1
1391 #define NEED_KEYID2UID 1
1392 #define NEED_UPDATEKEYS 1
1393 #include "keydb.c"
1394
1395 struct dbfuncs keydb_db4_funcs = {
1396         .initdb                 = db4_initdb,
1397         .cleanupdb              = db4_cleanupdb,
1398         .starttrans             = db4_starttrans,
1399         .endtrans               = db4_endtrans,
1400         .fetch_key              = db4_fetch_key,
1401         .fetch_key_text         = db4_fetch_key_text,
1402         .fetch_key_skshash      = db4_fetch_key_skshash,
1403         .store_key              = db4_store_key,
1404         .update_keys            = generic_update_keys,
1405         .delete_key             = db4_delete_key,
1406         .getkeysigs             = generic_getkeysigs,
1407         .cached_getkeysigs      = generic_cached_getkeysigs,
1408         .keyid2uid              = generic_keyid2uid,
1409         .getfullkeyid           = db4_getfullkeyid,
1410         .iterate_keys           = db4_iterate_keys,
1411 };