cscvs to tla changeset 59
[onak.git] / keydb_db3.c
1 /*
2  * keydb_db3.c - Routines to store and fetch keys in a DB3 database.
3  *
4  * Jonathan McDowell <noodles@earth.li>
5  *
6  * Copyright 2002 Project Purple
7  */
8
9 #include <assert.h>
10 #include <sys/types.h>
11 #include <sys/uio.h>
12 #include <ctype.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <unistd.h>
19
20 #include <db.h>
21
22 #include "charfuncs.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
32 /**
33  *      dbenv - our database environment.
34  */
35 static DB_ENV *dbenv = NULL;
36
37 /**
38  *      dbconn - our connection to the key database.
39  */
40 static DB *dbconn = NULL;
41
42 /**
43  *      worddb - our connection to the word database.
44  */
45 static DB *worddb = NULL;
46
47 /**
48  *      txn - our current transaction id.
49  */
50 static DB_TXN *txn = NULL;
51
52 /**
53  *      makewordlist - Takes a string and splits it into a set of unique words.
54  *      @wordlist: The current word list.
55  *      @words: The string to split and add.
56  *
57  *      We take words and split it on non alpha numeric characters. These get
58  *      added to the word list if they're not already present. If the wordlist
59  *      is NULL then we start a new list, otherwise it's search for already
60  *      added words. Note that words is modified in the process of scanning.
61  *
62  *      Returns the new word list.
63  */
64 struct ll *makewordlist(struct ll *wordlist, char *word)
65 {
66         char *start = NULL;
67         char *end = NULL;
68
69         /*
70          * Walk through the words string, spliting on non alphanumerics and
71          * then checking if the word already exists in the list. If not then
72          * we add it.
73          */
74         end = word;
75         while (end != NULL && *end != 0) {
76                 start = end;
77                 while (*start != 0 && !isalnum(*start)) {
78                         start++;
79                 }
80                 end = start;
81                 while (*end != 0 && isalnum(*end)) {
82                         *end = tolower(*end);
83                         end++;
84                 }
85                 if (end - start > 1) {
86                         if (*end != 0) {
87                                 *end = 0;
88                                 end++;
89                         }
90                         
91                         if (llfind(wordlist, start,
92                                         strcmp) == NULL) {
93                                 wordlist = lladd(wordlist,
94                                                 start);
95                         }
96                 }
97         }
98
99         return wordlist;
100 }
101
102 /**
103  *      initdb - Initialize the key database.
104  *
105  *      This function should be called before any of the other functions in
106  *      this file are called in order to allow the DB to be initialized ready
107  *      for access.
108  */
109 void initdb(void)
110 {
111         int ret = 0;
112
113         ret = db_env_create(&dbenv, 0);
114         if (ret != 0) {
115                 logthing(LOGTHING_CRITICAL,
116                         "db_env_create: %s", db_strerror(ret));
117                 exit(1);
118         }
119
120         /*
121          * Enable deadlock detection so that we don't block indefinitely on
122          * anything. What we really want is simple 2 state locks, but I'm not
123          * sure how to make the standard DB functions do that yet.
124          */
125         ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT);
126         if (ret != 0) {
127                 logthing(LOGTHING_CRITICAL,
128                         "db_env_create: %s", db_strerror(ret));
129                 exit(1);
130         }
131
132         ret = dbenv->open(dbenv, config.db_dir,
133                         DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_LOCK |
134                         DB_INIT_TXN |
135                         DB_CREATE,
136                         0);
137         if (ret != 0) {
138                 dbenv->err(dbenv, ret, "%s", config.db_dir);
139                 exit(1);
140         }
141
142         ret = db_create(&dbconn, dbenv, 0);
143         if (ret != 0) {
144                 logthing(LOGTHING_CRITICAL,
145                                 "db_create: %s", db_strerror(ret));
146                 exit(1);
147         }
148
149         ret = dbconn->open(dbconn, "keydb.db", 
150                         NULL,
151                         DB_HASH,
152                         DB_CREATE,
153                         0664);
154         if (ret != 0) {
155                 dbconn->err(dbconn, ret, "keydb.db");
156                 exit(1);
157         }
158
159         ret = db_create(&worddb, dbenv, 0);
160         if (ret != 0) {
161                 logthing(LOGTHING_CRITICAL, "db_create: %s", db_strerror(ret));
162                 exit(1);
163         }
164         ret = worddb->set_flags(worddb, DB_DUP);
165
166         ret = worddb->open(worddb, "worddb", NULL, DB_BTREE,
167                         DB_CREATE,
168                         0664);
169         if (ret != 0) {
170                 worddb->err(worddb, ret, "worddb");
171                 exit(1);
172         }
173         
174         return;
175 }
176
177 /**
178  *      cleanupdb - De-initialize the key database.
179  *
180  *      This function should be called upon program exit to allow the DB to
181  *      cleanup after itself.
182  */
183 void cleanupdb(void)
184 {
185         worddb->close(worddb, 0);
186         worddb = NULL;
187         dbconn->close(dbconn, 0);
188         dbconn = NULL;
189         dbenv->close(dbenv, 0);
190         dbenv = NULL;
191 }
192
193 /**
194  *      starttrans - Start a transaction.
195  *
196  *      Start a transaction. Intended to be used if we're about to perform many
197  *      operations on the database to help speed it all up, or if we want
198  *      something to only succeed if all relevant operations are successful.
199  */
200 bool starttrans(void)
201 {
202         int ret;
203
204         assert(dbenv != NULL);
205         assert(txn == NULL);
206
207         ret = txn_begin(dbenv,
208                 NULL, /* No parent transaction */
209                 &txn,
210                 0);
211         if (ret != 0) {
212                 dbenv->err(dbenv, ret, "starttrans():");
213                 exit(1);
214         }
215
216         return true;
217 }
218
219 /**
220  *      endtrans - End a transaction.
221  *
222  *      Ends a transaction.
223  */
224 void endtrans(void)
225 {
226         int ret;
227
228         assert(dbenv != NULL);
229         assert(txn != NULL);
230
231         ret = txn_commit(txn,
232                 0);
233         if (ret != 0) {
234                 dbenv->err(dbenv, ret, "endtrans():");
235                 exit(1);
236         }
237         txn = NULL;
238
239         return;
240 }
241
242 /**
243  *      fetch_key - Given a keyid fetch the key from storage.
244  *      @keyid: The keyid to fetch.
245  *      @publickey: A pointer to a structure to return the key in.
246  *      @intrans: If we're already in a transaction.
247  *
248  *      We use the hex representation of the keyid as the filename to fetch the
249  *      key from. The key is stored in the file as a binary OpenPGP stream of
250  *      packets, so we can just use read_openpgp_stream() to read the packets
251  *      in and then parse_keys() to parse the packets into a publickey
252  *      structure.
253  */
254 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
255                 bool intrans)
256 {
257         struct openpgp_packet_list *packets = NULL;
258         DBT key, data;
259         int ret = 0;
260         int numkeys = 0;
261         struct buffer_ctx fetchbuf;
262
263         memset(&key, 0, sizeof(key));
264         memset(&data, 0, sizeof(data));
265
266         data.size = 0;
267         data.data = NULL;
268
269         key.size = sizeof(keyid);
270         key.data = &keyid;
271         keyid &= 0xFFFFFFFF;
272
273         if (!intrans) {
274                 starttrans();
275         }
276
277         ret = dbconn->get(dbconn,
278                         txn,
279                         &key,
280                         &data,
281                         0); /* flags*/
282         
283         if (ret == 0) {
284                 fetchbuf.buffer = data.data;
285                 fetchbuf.offset = 0;
286                 fetchbuf.size = data.size;
287                 read_openpgp_stream(buffer_fetchchar, &fetchbuf,
288                                 &packets);
289                 parse_keys(packets, publickey);
290                 free_packet_list(packets);
291                 packets = NULL;
292                 numkeys++;
293         } else if (ret != DB_NOTFOUND) {
294                 dbconn->err(dbconn, ret, "Problem retrieving key");
295         }
296
297         if (!intrans) {
298                 endtrans();
299         }
300
301         return (numkeys);
302 }
303
304 int worddb_cmp(const char *d1, const char *d2)
305 {
306         return memcmp(d1, d2, 12);
307 }
308
309 /**
310  *      fetch_key_text - Trys to find the keys that contain the supplied text.
311  *      @search: The text to search for.
312  *      @publickey: A pointer to a structure to return the key in.
313  *
314  *      This function searches for the supplied text and returns the keys that
315  *      contain it.
316  */
317 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
318 {
319         DBC *cursor = NULL;
320         DBT key, data;
321         int ret;
322         uint64_t keyid;
323         int i;
324         int numkeys;
325         char *searchtext = NULL;
326         struct ll *wordlist = NULL;
327         struct ll *curword = NULL;
328         struct ll *keylist = NULL;
329         struct ll *newkeylist = NULL;
330
331         numkeys = 0;
332         searchtext = strdup(search);
333         wordlist = makewordlist(wordlist, searchtext);
334
335         starttrans();
336
337         ret = worddb->cursor(worddb,
338                         txn,
339                         &cursor,
340                         0);   /* flags */
341
342         for (curword = wordlist; curword != NULL; curword = curword->next) {
343                 memset(&key, 0, sizeof(key));
344                 memset(&data, 0, sizeof(data));
345                 key.data = curword->object;
346                 key.size = strlen(curword->object);
347                 data.flags = DB_DBT_MALLOC;
348                 ret = cursor->c_get(cursor,
349                                 &key,
350                                 &data,
351                                 DB_SET);
352                 while (ret == 0 && strncmp(key.data, curword->object,
353                                         key.size) == 0 &&
354                                 ((char *) curword->object)[key.size] == 0) {
355                         keyid = 0;
356                         for (i = 4; i < 12; i++) {
357                                 keyid <<= 8;
358                                 keyid += ((unsigned char *)
359                                                 data.data)[i];
360                         }
361
362                         if (keylist == NULL ||
363                                         llfind(keylist, data.data,
364                                                 worddb_cmp) != NULL) {
365                                 newkeylist = lladd(newkeylist, data.data);
366                                 data.data = NULL;
367                         } else {
368                                 free(data.data);
369                                 data.data = NULL;
370                         }
371                         ret = cursor->c_get(cursor,
372                                         &key,
373                                         &data,
374                                         DB_NEXT);
375                 }
376                 llfree(keylist, free);
377                 keylist = newkeylist;
378                 newkeylist = NULL;
379                 if (data.data != NULL) {
380                         free(data.data);
381                         data.data = NULL;
382                 }
383         }
384         llfree(wordlist, NULL);
385         wordlist = NULL;
386         
387         for (newkeylist = keylist;
388                         newkeylist != NULL && numkeys < config.maxkeys;
389                         newkeylist = newkeylist->next) {
390
391                         keyid = 0;
392                         for (i = 4; i < 12; i++) {
393                                 keyid <<= 8;
394                                 keyid += ((unsigned char *)
395                                                 newkeylist->object)[i];
396                         }
397
398                         numkeys += fetch_key(keyid,
399                                         publickey,
400                                         true);
401         }
402         llfree(keylist, free);
403         keylist = NULL;
404         free(searchtext);
405         searchtext = NULL;
406
407         ret = cursor->c_close(cursor);
408         cursor = NULL;
409
410         endtrans();
411         
412         return (numkeys);
413 }
414
415 /**
416  *      store_key - Takes a key and stores it.
417  *      @publickey: A pointer to the public key to store.
418  *      @intrans: If we're already in a transaction.
419  *      @update: If true the key exists and should be updated.
420  *
421  *      Again we just use the hex representation of the keyid as the filename
422  *      to store the key to. We flatten the public key to a list of OpenPGP
423  *      packets and then use write_openpgp_stream() to write the stream out to
424  *      the file. If update is true then we delete the old key first, otherwise
425  *      we trust that it doesn't exist.
426  */
427 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
428 {
429         struct     openpgp_packet_list *packets = NULL;
430         struct     openpgp_packet_list *list_end = NULL;
431         struct     openpgp_publickey *next = NULL;
432         int        ret = 0;
433         int        i = 0;
434         struct     buffer_ctx storebuf;
435         DBT        key;
436         DBT        data;
437         uint64_t   keyid = 0;
438         char     **uids = NULL;
439         char      *primary = NULL;
440         unsigned char worddb_data[12];
441         struct ll *wordlist = NULL;
442         struct ll *curword  = NULL;
443         bool       deadlock = false;
444
445         keyid = get_keyid(publickey);
446
447         if (!intrans) {
448                 starttrans();
449         }
450
451         /*
452          * Delete the key if we already have it.
453          *
454          * TODO: Can we optimize this perhaps? Possibly when other data is
455          * involved as well? I suspect this is easiest and doesn't make a lot
456          * of difference though - the largest chunk of data is the keydata and
457          * it definitely needs updated.
458          */
459         if (update) {
460                 deadlock = (delete_key(keyid, true) == -1);
461         }
462
463         /*
464          * Convert the key to a flat set of binary data.
465          */
466         if (!deadlock) {
467                 next = publickey->next;
468                 publickey->next = NULL;
469                 flatten_publickey(publickey, &packets, &list_end);
470                 publickey->next = next;
471
472                 storebuf.offset = 0; 
473                 storebuf.size = 8192;
474                 storebuf.buffer = malloc(8192);
475         
476                 write_openpgp_stream(buffer_putchar, &storebuf, packets);
477
478                 /*
479                  * Now we have the key data store it in the DB; the keyid is
480                  * the key.
481                  */
482                 memset(&key, 0, sizeof(key));
483                 memset(&data, 0, sizeof(data));
484                 key.data = &keyid;
485                 key.size = sizeof(keyid);
486                 keyid &= 0xFFFFFFFF;
487                 data.size = storebuf.offset;
488                 data.data = storebuf.buffer;
489
490                 ret = dbconn->put(dbconn,
491                                 txn,
492                                 &key,
493                                 &data,
494                                 0); /* flags*/
495                 if (ret != 0) {
496                         dbconn->err(dbconn, ret, "Problem storing key");
497                         if (ret == DB_LOCK_DEADLOCK) {
498                                 deadlock = true;
499                         }
500                 }
501
502                 free(storebuf.buffer);
503                 storebuf.buffer = NULL;
504                 storebuf.size = 0;
505                 storebuf.offset = 0; 
506         
507                 free_packet_list(packets);
508                 packets = NULL;
509         }
510
511         /*
512          * Walk through our uids storing the words into the db with the keyid.
513          */
514         if (!deadlock) {
515                 uids = keyuids(publickey, &primary);
516         }
517         if (uids != NULL) {
518                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
519                         wordlist = makewordlist(wordlist, uids[i]);
520                 }
521
522                 for (curword = wordlist; curword != NULL && !deadlock;
523                                 curword = curword->next) {
524                         memset(&key, 0, sizeof(key));
525                         memset(&data, 0, sizeof(data));
526                         key.data = curword->object;
527                         key.size = strlen(key.data);
528                         data.data = worddb_data;
529                         data.size = sizeof(worddb_data);
530
531                         /*
532                          * Our data is the key creation time followed by the
533                          * key id.
534                          */
535                         worddb_data[ 0] = publickey->publickey->data[1];
536                         worddb_data[ 1] = publickey->publickey->data[2];
537                         worddb_data[ 2] = publickey->publickey->data[3];
538                         worddb_data[ 3] = publickey->publickey->data[4];
539                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
540                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
541                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
542                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
543                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
544                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
545                         worddb_data[10] = (keyid >>  8) & 0xFF;
546                         worddb_data[11] = keyid & 0xFF; 
547                         ret = worddb->put(worddb,
548                                 txn,
549                                 &key,
550                                 &data,
551                                 0);
552                         if (ret != 0) {
553                                 worddb->err(worddb, ret,
554                                         "Problem storing key");
555                                 if (ret == DB_LOCK_DEADLOCK) {
556                                         deadlock = true;
557                                 }
558                         }
559                 }
560
561                 /*
562                  * Free our UID and word lists.
563                  */
564                 llfree(wordlist, NULL);
565                 for (i = 0; uids[i] != NULL; i++) {
566                         free(uids[i]);
567                         uids[i] = NULL;
568                 }
569                 free(uids);
570                 uids = NULL;
571         }
572
573         if (!intrans) {
574                 endtrans();
575         }
576
577         return deadlock ? -1 : 0 ;
578 }
579
580 /**
581  *      delete_key - Given a keyid delete the key from storage.
582  *      @keyid: The keyid to delete.
583  *      @intrans: If we're already in a transaction.
584  *
585  *      This function deletes a public key from whatever storage mechanism we
586  *      are using. Returns 0 if the key existed.
587  */
588 int delete_key(uint64_t keyid, bool intrans)
589 {
590         struct openpgp_publickey *publickey = NULL;
591         DBT key, data;
592         DBC *cursor = NULL;
593         int ret = 0;
594         int i;
595         char **uids = NULL;
596         char *primary = NULL;
597         unsigned char worddb_data[12];
598         struct ll *wordlist = NULL;
599         struct ll *curword  = NULL;
600         bool deadlock = false;
601
602         keyid &= 0xFFFFFFFF;
603
604         if (!intrans) {
605                 starttrans();
606         }
607
608         fetch_key(keyid, &publickey, true);
609
610         /*
611          * Walk through the uids removing the words from the worddb.
612          */
613         if (publickey != NULL) {
614                 uids = keyuids(publickey, &primary);
615         }
616         if (uids != NULL) {
617                 for (i = 0; ret == 0 && uids[i] != NULL; i++) {
618                         wordlist = makewordlist(wordlist, uids[i]);
619                 }
620                                 
621                 ret = worddb->cursor(worddb,
622                         txn,
623                         &cursor,
624                         0);   /* flags */
625
626                 for (curword = wordlist; curword != NULL && !deadlock;
627                                 curword = curword->next) {
628                         memset(&key, 0, sizeof(key));
629                         memset(&data, 0, sizeof(data));
630                         key.data = curword->object;
631                         key.size = strlen(key.data);
632                         data.data = worddb_data;
633                         data.size = sizeof(worddb_data);
634
635                         /*
636                          * Our data is the key creation time followed by the
637                          * key id.
638                          */
639                         worddb_data[ 0] = publickey->publickey->data[1];
640                         worddb_data[ 1] = publickey->publickey->data[2];
641                         worddb_data[ 2] = publickey->publickey->data[3];
642                         worddb_data[ 3] = publickey->publickey->data[4];
643                         worddb_data[ 4] = (keyid >> 56) & 0xFF;
644                         worddb_data[ 5] = (keyid >> 48) & 0xFF;
645                         worddb_data[ 6] = (keyid >> 40) & 0xFF;
646                         worddb_data[ 7] = (keyid >> 32) & 0xFF;
647                         worddb_data[ 8] = (keyid >> 24) & 0xFF;
648                         worddb_data[ 9] = (keyid >> 16) & 0xFF;
649                         worddb_data[10] = (keyid >>  8) & 0xFF;
650                         worddb_data[11] = keyid & 0xFF; 
651
652                         ret = cursor->c_get(cursor,
653                                 &key,
654                                 &data,
655                                 DB_GET_BOTH);
656
657                         if (ret == 0) {
658                                 ret = cursor->c_del(cursor, 0);
659                                 if (ret != 0) {
660                                         worddb->err(worddb, ret,
661                                                 "Problem deleting word.");
662                                 }
663                         }
664
665                         if (ret != 0) {
666                                 worddb->err(worddb, ret,
667                                         "Problem deleting word.");
668                                 if (ret == DB_LOCK_DEADLOCK) {
669                                         deadlock = true;
670                                 }
671                         }
672                 }
673                 ret = cursor->c_close(cursor);
674                 cursor = NULL;
675
676                 /*
677                  * Free our UID and word lists.
678                  */
679                 llfree(wordlist, NULL);
680                 for (i = 0; uids[i] != NULL; i++) {
681                         free(uids[i]);
682                         uids[i] = NULL;
683                 }
684                 free(uids);
685                 uids = NULL;
686                 free_publickey(publickey);
687                 publickey = NULL;
688         }
689
690         if (!deadlock) {
691                 key.data = &keyid;
692                 key.size = sizeof(keyid);
693
694                 dbconn->del(dbconn,
695                                 txn,
696                                 &key,
697                                 0); /* flags */
698         }
699
700         if (!intrans) {
701                 endtrans();
702         }
703
704         return deadlock ? (-1) : (ret == DB_NOTFOUND);
705 }
706
707 /**
708  *      dumpdb - dump the key database
709  *      @filenamebase: The base filename to use for the dump.
710  *
711  *      Dumps the database into one or more files, which contain pure OpenPGP
712  *      that can be reimported into onak or gpg. filenamebase provides a base
713  *      file name for the dump; several files may be created, all of which will
714  *      begin with this string and then have a unique number and a .pgp
715  *      extension.
716  */
717 int dumpdb(char *filenamebase)
718 {
719         DBT key, data;
720         DBC *cursor = NULL;
721         int ret = 0;
722         int fd = -1;
723
724         starttrans();
725         
726         ret = dbconn->cursor(dbconn,
727                 txn,
728                 &cursor,
729                 0);   /* flags */
730
731         fd = open(filenamebase, O_CREAT | O_WRONLY | O_TRUNC, 0640);
732         memset(&key, 0, sizeof(key));
733         memset(&data, 0, sizeof(data));
734         ret = cursor->c_get(cursor, &key, &data, DB_NEXT);
735         while (ret == 0) {
736                 write(fd, data.data, data.size);
737                 memset(&key, 0, sizeof(key));
738                 memset(&data, 0, sizeof(data));
739                 ret = cursor->c_get(cursor, &key, &data, DB_NEXT);
740         }
741         dbconn->err(dbconn, ret, "Problem reading key");
742
743         close(fd);
744
745         ret = cursor->c_close(cursor);
746         cursor = NULL;
747         
748         endtrans();
749         
750         return 0;
751 }
752
753 /*
754  * Include the basic keydb routines.
755  */
756 #define NEED_GETFULLKEYID 1
757 #define NEED_GETKEYSIGS 1
758 #define NEED_KEYID2UID 1
759 #include "keydb.c"