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