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