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