Add key iteration functionality to keydb backends.
[onak.git] / keydb_pg.c
1 /*
2  * keydb_pg.c - Routines to store and fetch keys in a PostGres database.
3  *
4  * Jonathan McDowell <noodles@earth.li>
5  *
6  * Copyright 2002-2004 Project Purple
7  */
8
9 #include <postgresql/libpq-fe.h>
10 #include <postgresql/libpq/libpq-fs.h>
11
12 #include <sys/types.h>
13 #include <sys/uio.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <unistd.h>
20
21 #include "hash.h"
22 #include "keydb.h"
23 #include "keyid.h"
24 #include "decodekey.h"
25 #include "keystructs.h"
26 #include "log.h"
27 #include "mem.h"
28 #include "onak-conf.h"
29 #include "parsekey.h"
30
31 /**
32  *      dbconn - our connection to the database.
33  */
34 static PGconn *dbconn = NULL;
35
36 /**
37  *      keydb_fetchchar - Fetches a char from a file.
38  */
39 static int keydb_fetchchar(void *fd, size_t count, unsigned char *c)
40 {
41         return (!lo_read(dbconn, *(int *) fd, (char *) c, count));
42 }
43
44 /**
45  *      keydb_putchar - Puts a char to a file.
46  */
47 static int keydb_putchar(void *fd, size_t count, unsigned char *c)
48 {
49         return !(lo_write(dbconn, *(int *) fd, (char *) c, count));
50 }
51
52 /**
53  *      initdb - Initialize the key database.
54  *
55  *      This function should be called before any of the other functions in
56  *      this file are called in order to allow the DB to be initialized ready
57  *      for access.
58  */
59 void initdb(bool readonly)
60 {
61         dbconn = PQsetdbLogin(config.pg_dbhost, // host
62                         NULL, // port
63                         NULL, // options
64                         NULL, // tty
65                         config.pg_dbname, // database
66                         config.pg_dbuser,  //login
67                         config.pg_dbpass); // password
68
69         if (PQstatus(dbconn) == CONNECTION_BAD) {
70                 logthing(LOGTHING_CRITICAL, "Connection to database failed.");
71                 logthing(LOGTHING_CRITICAL, "%s", PQerrorMessage(dbconn));
72                 PQfinish(dbconn);
73                 dbconn = NULL;
74                 exit(1);
75         }
76 }
77
78 /**
79  *      cleanupdb - De-initialize the key database.
80  *
81  *      This function should be called upon program exit to allow the DB to
82  *      cleanup after itself.
83  */
84 void cleanupdb(void)
85 {
86         PQfinish(dbconn);
87         dbconn = NULL;
88 }
89
90 /**
91  *      starttrans - Start a transaction.
92  *
93  *      Start a transaction. Intended to be used if we're about to perform many
94  *      operations on the database to help speed it all up, or if we want
95  *      something to only succeed if all relevant operations are successful.
96  */
97 bool starttrans(void)
98 {
99         PGresult *result = NULL;
100         
101         result = PQexec(dbconn, "BEGIN");
102         PQclear(result);
103
104         return true;
105 }
106
107 /**
108  *      endtrans - End a transaction.
109  *
110  *      Ends a transaction.
111  */
112 void endtrans(void)
113 {
114         PGresult *result = NULL;
115
116         result = PQexec(dbconn, "COMMIT");
117         PQclear(result);
118
119         return;
120 }
121
122 /**
123  *      fetch_key - Given a keyid fetch the key from storage.
124  *      @keyid: The keyid to fetch.
125  *      @publickey: A pointer to a structure to return the key in.
126  *      @intrans: If we're already in a transaction.
127  *
128  *      We use the hex representation of the keyid as the filename to fetch the
129  *      key from. The key is stored in the file as a binary OpenPGP stream of
130  *      packets, so we can just use read_openpgp_stream() to read the packets
131  *      in and then parse_keys() to parse the packets into a publickey
132  *      structure.
133  */
134 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
135                 bool intrans)
136 {
137         struct openpgp_packet_list *packets = NULL;
138         PGresult *result = NULL;
139         char *oids = NULL;
140         char statement[1024];
141         int fd = -1;
142         int i = 0;
143         int numkeys = 0;
144         Oid key_oid;
145
146         if (!intrans) {
147                 result = PQexec(dbconn, "BEGIN");
148                 PQclear(result);
149         }
150         
151         if (keyid > 0xFFFFFFFF) {
152                 snprintf(statement, 1023,
153                         "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
154                         keyid);
155         } else {
156                 snprintf(statement, 1023,
157                         "SELECT keydata FROM onak_keys WHERE keyid "
158                         "LIKE '%%%llX'",
159                         keyid);
160         }
161         result = PQexec(dbconn, statement);
162
163         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
164                 numkeys = PQntuples(result);
165                 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
166                         oids = PQgetvalue(result, i, 0);
167                         key_oid = (Oid) atoi(oids);
168
169                         fd = lo_open(dbconn, key_oid, INV_READ);
170                         if (fd < 0) {
171                                 logthing(LOGTHING_ERROR,
172                                                 "Can't open large object.");
173                         } else {
174                                 read_openpgp_stream(keydb_fetchchar, &fd,
175                                                 &packets, 0);
176                                 parse_keys(packets, publickey);
177                                 lo_close(dbconn, fd);
178                                 free_packet_list(packets);
179                                 packets = NULL;
180                         }
181                 }
182         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
183                 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
184         }
185
186         PQclear(result);
187
188         if (!intrans) {
189                 result = PQexec(dbconn, "COMMIT");
190                 PQclear(result);
191         }
192         return (numkeys);
193 }
194
195 /**
196  *      fetch_key_text - Trys to find the keys that contain the supplied text.
197  *      @search: The text to search for.
198  *      @publickey: A pointer to a structure to return the key in.
199  *
200  *      This function searches for the supplied text and returns the keys that
201  *      contain it.
202  */
203 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
204 {
205         struct openpgp_packet_list *packets = NULL;
206         PGresult *result = NULL;
207         char *oids = NULL;
208         char statement[1024];
209         int fd = -1;
210         int i = 0;
211         int numkeys = 0;
212         Oid key_oid;
213         char *newsearch = NULL;
214
215         result = PQexec(dbconn, "BEGIN");
216         PQclear(result);
217
218         newsearch = malloc(strlen(search) * 2 + 1);
219         memset(newsearch, 0, strlen(search) * 2 + 1);
220         PQescapeString(newsearch, search, strlen(search));
221         snprintf(statement, 1023,
222                         "SELECT DISTINCT onak_keys.keydata FROM onak_keys, "
223                         "onak_uids WHERE onak_keys.keyid = onak_uids.keyid "
224                         "AND onak_uids.uid LIKE '%%%s%%'",
225                         newsearch);
226         result = PQexec(dbconn, statement);
227         free(newsearch);
228         newsearch = NULL;
229
230         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
231                 numkeys = PQntuples(result);
232                 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
233                         oids = PQgetvalue(result, i, 0);
234                         key_oid = (Oid) atoi(oids);
235
236                         fd = lo_open(dbconn, key_oid, INV_READ);
237                         if (fd < 0) {
238                                 logthing(LOGTHING_ERROR,
239                                                 "Can't open large object.");
240                         } else {
241                                 read_openpgp_stream(keydb_fetchchar, &fd,
242                                                 &packets,
243                                                 0);
244                                 parse_keys(packets, publickey);
245                                 lo_close(dbconn, fd);
246                                 free_packet_list(packets);
247                                 packets = NULL;
248                         }
249                 }
250         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
251                 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
252         }
253
254         PQclear(result);
255
256         result = PQexec(dbconn, "COMMIT");
257         PQclear(result);
258         return (numkeys);
259 }
260
261 /**
262  *      store_key - Takes a key and stores it.
263  *      @publickey: A pointer to the public key to store.
264  *      @intrans: If we're already in a transaction.
265  *      @update: If true the key exists and should be updated.
266  *
267  *      Again we just use the hex representation of the keyid as the filename
268  *      to store the key to. We flatten the public key to a list of OpenPGP
269  *      packets and then use write_openpgp_stream() to write the stream out to
270  *      the file. If update is true then we delete the old key first, otherwise
271  *      we trust that it doesn't exist.
272  */
273 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
274 {
275         struct openpgp_packet_list *packets = NULL;
276         struct openpgp_packet_list *list_end = NULL;
277         struct openpgp_publickey *next = NULL;
278         struct openpgp_signedpacket_list *curuid = NULL;
279         PGresult *result = NULL;
280         char statement[1024];
281         Oid key_oid;
282         int fd;
283         char **uids = NULL;
284         char *primary = NULL;
285         char *safeuid = NULL;
286         int i;
287
288         if (!intrans) {
289                 result = PQexec(dbconn, "BEGIN");
290                 PQclear(result);
291         }
292
293         /*
294          * Delete the key if we already have it.
295          *
296          * TODO: Can we optimize this perhaps? Possibly when other data is
297          * involved as well? I suspect this is easiest and doesn't make a lot
298          * of difference though - the largest chunk of data is the keydata and
299          * it definitely needs updated.
300          */
301         if (update) {
302                 delete_key(get_keyid(publickey), true);
303         }
304
305         next = publickey->next;
306         publickey->next = NULL;
307         flatten_publickey(publickey, &packets, &list_end);
308         publickey->next = next;
309                 
310         key_oid = lo_creat(dbconn, INV_READ | INV_WRITE);
311         if (key_oid == 0) {
312                 logthing(LOGTHING_ERROR, "Can't create key OID");
313         } else {
314                 fd = lo_open(dbconn, key_oid, INV_WRITE);
315                 write_openpgp_stream(keydb_putchar, &fd, packets);
316                 lo_close(dbconn, fd);
317         }
318         free_packet_list(packets);
319         packets = NULL;
320
321         snprintf(statement, 1023, 
322                         "INSERT INTO onak_keys (keyid, keydata) VALUES "
323                         "('%llX', '%d')", 
324                         get_keyid(publickey),
325                         key_oid);
326         result = PQexec(dbconn, statement);
327
328         if (PQresultStatus(result) != PGRES_COMMAND_OK) {
329                 logthing(LOGTHING_ERROR, "Problem storing key in DB.");
330                 logthing(LOGTHING_ERROR, "%s", PQresultErrorMessage(result));
331         }
332         PQclear(result);
333
334         uids = keyuids(publickey, &primary);
335         if (uids != NULL) {
336                 for (i = 0; uids[i] != NULL; i++) {
337                         safeuid = malloc(strlen(uids[i]) * 2 + 1);
338                         if (safeuid != NULL) {
339                                 memset(safeuid, 0, strlen(uids[i]) * 2 + 1);
340                                 PQescapeString(safeuid, uids[i],
341                                                 strlen(uids[i]));
342
343                                 snprintf(statement, 1023,
344                                         "INSERT INTO onak_uids "
345                                         "(keyid, uid, pri) "
346                                         "VALUES ('%llX', '%s', '%c')",
347                                         get_keyid(publickey),
348                                         safeuid,
349                                         (uids[i] == primary) ? 't' : 'f');
350                                 result = PQexec(dbconn, statement);
351
352                                 free(safeuid);
353                                 safeuid = NULL;
354                         }
355                         if (uids[i] != NULL) {
356                                 free(uids[i]);
357                                 uids[i] = NULL;
358                         }
359
360                         if (PQresultStatus(result) != PGRES_COMMAND_OK) {
361                                 logthing(LOGTHING_ERROR,
362                                                 "Problem storing key in DB.");
363                                 logthing(LOGTHING_ERROR, "%s",
364                                                 PQresultErrorMessage(result));
365                         }
366                         /*
367                          * TODO: Check result.
368                          */
369                         PQclear(result);
370                 }
371                 free(uids);
372                 uids = NULL;
373         }
374
375         for (curuid = publickey->uids; curuid != NULL; curuid = curuid->next) {
376                 for (packets = curuid->sigs; packets != NULL; 
377                                 packets = packets->next) {
378                         snprintf(statement, 1023,
379                                 "INSERT INTO onak_sigs (signer, signee) "
380                                 "VALUES ('%llX', '%llX')",
381                                 sig_keyid(packets->packet),
382                                 get_keyid(publickey));
383                         result = PQexec(dbconn, statement);
384                         PQclear(result);
385                 }
386         }
387
388         if (!intrans) {
389                 result = PQexec(dbconn, "COMMIT");
390                 PQclear(result);
391         }
392         
393         return 0;
394 }
395
396 /**
397  *      delete_key - Given a keyid delete the key from storage.
398  *      @keyid: The keyid to delete.
399  *      @intrans: If we're already in a transaction.
400  *
401  *      This function deletes a public key from whatever storage mechanism we
402  *      are using. Returns 0 if the key existed.
403  */
404 int delete_key(uint64_t keyid, bool intrans)
405 {
406         PGresult *result = NULL;
407         char *oids = NULL;
408         char statement[1024];
409         int found = 1;
410         int i;
411         Oid key_oid;
412
413         if (!intrans) {
414                 result = PQexec(dbconn, "BEGIN");
415                 PQclear(result);
416         }
417         
418         snprintf(statement, 1023,
419                         "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
420                         keyid);
421         result = PQexec(dbconn, statement);
422
423         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
424                 found = 0;
425                 i = PQntuples(result);
426                 while (i > 0) {
427                         oids = PQgetvalue(result, i-1, 0);
428                         key_oid = (Oid) atoi(oids);
429                         lo_unlink(dbconn, key_oid);
430                         i--;
431                 }
432                 PQclear(result);
433
434                 snprintf(statement, 1023,
435                         "DELETE FROM onak_keys WHERE keyid = '%llX'",
436                         keyid);
437                 result = PQexec(dbconn, statement);
438                 PQclear(result);
439
440                 snprintf(statement, 1023,
441                         "DELETE FROM onak_sigs WHERE signee = '%llX'",
442                         keyid);
443                 result = PQexec(dbconn, statement);
444                 PQclear(result);
445
446                 snprintf(statement, 1023,
447                         "DELETE FROM onak_uids WHERE keyid = '%llX'",
448                         keyid);
449                 result = PQexec(dbconn, statement);
450         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
451                 logthing(LOGTHING_ERROR,
452                                 "Problem retrieving key (%llX) from DB.",
453                                 keyid);
454         }
455
456         PQclear(result);
457
458         if (!intrans) {
459                 result = PQexec(dbconn, "COMMIT");
460                 PQclear(result);
461         }
462         return (found);
463 }
464
465 /**
466  *      keyid2uid - Takes a keyid and returns the primary UID for it.
467  *      @keyid: The keyid to lookup.
468  */
469 char *keyid2uid(uint64_t keyid)
470 {
471         PGresult *result = NULL;
472         char statement[1024];
473         char *uid = NULL;
474
475         snprintf(statement, 1023,
476                 "SELECT uid FROM onak_uids WHERE keyid = '%llX' AND pri = 't'",
477                 keyid);
478         result = PQexec(dbconn, statement);
479
480         /*
481          * Technically we only expect one response to the query; a key only has
482          * one primary ID. Better to return something than nothing though.
483          *
484          * TODO: Log if we get more than one response? Needs logging framework
485          * first though.
486          */
487         if (PQresultStatus(result) == PGRES_TUPLES_OK &&
488                         PQntuples(result) >= 1) {
489                 uid = strdup(PQgetvalue(result, 0, 0));
490         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
491                 logthing(LOGTHING_ERROR,
492                                 "Problem retrieving key (%llX) from DB.",
493                                 keyid);
494         }
495
496         PQclear(result);
497
498         return uid;
499 }
500
501 /**
502  *      getkeysigs - Gets a linked list of the signatures on a key.
503  *      @keyid: The keyid to get the sigs for.
504  *      @revoked: If the key is revoked.
505  *
506  *      This function gets the list of signatures on a key. Used for key 
507  *      indexing and doing stats bits.
508  */
509 struct ll *getkeysigs(uint64_t keyid, bool *revoked)
510 {
511         struct ll *sigs = NULL;
512         PGresult *result = NULL;
513         uint64_t signer;
514         char statement[1024];
515         int i, j;
516         int numsigs = 0;
517         bool intrans = false;
518         char *str;
519
520         if (!intrans) {
521                 result = PQexec(dbconn, "BEGIN");
522                 PQclear(result);
523         }
524
525         snprintf(statement, 1023,
526                 "SELECT DISTINCT signer FROM onak_sigs WHERE signee = '%llX'",
527                 keyid);
528         result = PQexec(dbconn, statement);
529
530         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
531                 numsigs = PQntuples(result);
532                 for (i = 0; i < numsigs;  i++) {
533                         j = 0;
534                         signer = 0;
535                         str = PQgetvalue(result, i, 0);
536                         while (str[j] != 0) {
537                                 signer <<= 4;
538                                 if (str[j] >= '0' && str[j] <= '9') {
539                                         signer += str[j] - '0';
540                                 } else {
541                                         signer += str[j] - 'A' + 10;
542                                 }
543                                 j++;
544                         }
545                         sigs = lladd(sigs, createandaddtohash(signer));
546                 }
547         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
548                 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
549         }
550
551         PQclear(result);
552
553         if (!intrans) {
554                 result = PQexec(dbconn, "COMMIT");
555                 PQclear(result);
556         }
557
558         /*
559          * TODO: What do we do about revocations? We don't have the details
560          * stored in a separate table, so we'd have to grab the key and decode
561          * it, which we're trying to avoid by having a signers table.
562          */
563         if (revoked != NULL) {
564                 *revoked = false;
565         }
566         
567         return sigs;
568 }
569
570 /**
571  *      dumpdb - dump the key database
572  *      @filenamebase: The base filename to use for the dump.
573  *
574  *      Dumps the database into one or more files, which contain pure OpenPGP
575  *      that can be reimported into onak or gpg. filenamebase provides a base
576  *      file name for the dump; several files may be created, all of which will
577  *      begin with this string and then have a unique number and a .pgp
578  *      extension.
579  *          */
580 int dumpdb(char *filenamebase)
581 {
582         return 0;
583 }
584
585 /**
586  *      iterate_keys - call a function once for each key in the db.
587  *      @iterfunc: The function to call.
588  *      @ctx: A context pointer
589  *
590  *      Calls iterfunc once for each key in the database. ctx is passed
591  *      unaltered to iterfunc. This function is intended to aid database dumps
592  *      and statistic calculations.
593  *
594  *      Returns the number of keys we iterated over.
595  */
596 int iterate_keys(void (*iterfunc)(void *ctx, struct openpgp_publickey *key),
597                 void *ctx)
598 {
599         struct openpgp_packet_list *packets = NULL;
600         struct openpgp_publickey *key = NULL;
601         PGresult *result = NULL;
602         char *oids = NULL;
603         char statement[1024];
604         int fd = -1;
605         int i = 0;
606         int numkeys = 0;
607         Oid key_oid;
608
609         result = PQexec(dbconn, "SELECT keydata FROM onak_keys;");
610
611         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
612                 numkeys = PQntuples(result);
613                 for (i = 0; i < numkeys; i++) {
614                         oids = PQgetvalue(result, i, 0);
615                         key_oid = (Oid) atoi(oids);
616
617                         fd = lo_open(dbconn, key_oid, INV_READ);
618                         if (fd < 0) {
619                                 logthing(LOGTHING_ERROR,
620                                                 "Can't open large object.");
621                         } else {
622                                 read_openpgp_stream(keydb_fetchchar, &fd,
623                                                 &packets, 0);
624                                 parse_keys(packets, key);
625                                 lo_close(dbconn, fd);
626
627                                 iterfunc(ctx, key);
628                                         
629                                 free_publickey(key);
630                                 key = NULL;
631                                 free_packet_list(packets);
632                                 packets = NULL;
633                         }
634                 }
635         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
636                 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
637         }
638
639         PQclear(result);
640
641         return (numkeys);
642 }
643
644 /*
645  * Include the basic keydb routines.
646  */
647 #define NEED_GETFULLKEYID 1
648 #define NEED_UPDATEKEYS 1
649 #include "keydb.c"