]> the.earth.li Git - onak.git/blob - keydb_pg.c
Add support for displaying EC/ECDSA key types
[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         if (get_keyid(publickey, &keyid) != ONAK_E_OK) {
380                 logthing(LOGTHING_ERROR, "Couldn't find key ID for key.");
381                 return 0;
382         }
383
384         /*
385          * Delete the key if we already have it.
386          *
387          * TODO: Can we optimize this perhaps? Possibly when other data is
388          * involved as well? I suspect this is easiest and doesn't make a lot
389          * of difference though - the largest chunk of data is the keydata and
390          * it definitely needs updated.
391          */
392         if (update) {
393                 pg_delete_key(keyid, true);
394         }
395
396         next = publickey->next;
397         publickey->next = NULL;
398         flatten_publickey(publickey, &packets, &list_end);
399         publickey->next = next;
400                 
401         key_oid = lo_creat(dbconn, INV_READ | INV_WRITE);
402         if (key_oid == 0) {
403                 logthing(LOGTHING_ERROR, "Can't create key OID");
404         } else {
405                 fd = lo_open(dbconn, key_oid, INV_WRITE);
406                 write_openpgp_stream(keydb_putchar, &fd, packets);
407                 lo_close(dbconn, fd);
408         }
409         free_packet_list(packets);
410         packets = NULL;
411
412         snprintf(statement, 1023, 
413                         "INSERT INTO onak_keys (keyid, keydata) VALUES "
414                         "('%" PRIX64 "', '%d')", 
415                         keyid,
416                         key_oid);
417         result = PQexec(dbconn, statement);
418
419         if (PQresultStatus(result) != PGRES_COMMAND_OK) {
420                 logthing(LOGTHING_ERROR, "Problem storing key in DB.");
421                 logthing(LOGTHING_ERROR, "%s", PQresultErrorMessage(result));
422         }
423         PQclear(result);
424
425         uids = keyuids(publickey, &primary);
426         if (uids != NULL) {
427                 for (i = 0; uids[i] != NULL; i++) {
428                         safeuid = malloc(strlen(uids[i]) * 2 + 1);
429                         if (safeuid != NULL) {
430                                 memset(safeuid, 0, strlen(uids[i]) * 2 + 1);
431                                 PQescapeStringConn(dbconn, safeuid, uids[i],
432                                                 strlen(uids[i]), NULL);
433
434                                 snprintf(statement, 1023,
435                                         "INSERT INTO onak_uids "
436                                         "(keyid, uid, pri) "
437                                         "VALUES ('%" PRIX64 "', '%s', '%c')",
438                                         keyid,
439                                         safeuid,
440                                         (uids[i] == primary) ? 't' : 'f');
441                                 result = PQexec(dbconn, statement);
442
443                                 free(safeuid);
444                                 safeuid = NULL;
445                         }
446                         if (uids[i] != NULL) {
447                                 free(uids[i]);
448                                 uids[i] = NULL;
449                         }
450
451                         if (PQresultStatus(result) != PGRES_COMMAND_OK) {
452                                 logthing(LOGTHING_ERROR,
453                                                 "Problem storing key in DB.");
454                                 logthing(LOGTHING_ERROR, "%s",
455                                                 PQresultErrorMessage(result));
456                         }
457                         /*
458                          * TODO: Check result.
459                          */
460                         PQclear(result);
461                 }
462                 free(uids);
463                 uids = NULL;
464         }
465
466         for (curuid = publickey->uids; curuid != NULL; curuid = curuid->next) {
467                 for (packets = curuid->sigs; packets != NULL; 
468                                 packets = packets->next) {
469                         snprintf(statement, 1023,
470                                 "INSERT INTO onak_sigs (signer, signee) "
471                                 "VALUES ('%" PRIX64 "', '%" PRIX64 "')",
472                                 sig_keyid(packets->packet),
473                                 keyid);
474                         result = PQexec(dbconn, statement);
475                         PQclear(result);
476                 }
477         }
478
479         if (!intrans) {
480                 result = PQexec(dbconn, "COMMIT");
481                 PQclear(result);
482         }
483         
484         return 0;
485 }
486
487 /**
488  *      keyid2uid - Takes a keyid and returns the primary UID for it.
489  *      @keyid: The keyid to lookup.
490  */
491 static char *pg_keyid2uid(uint64_t keyid)
492 {
493         PGresult *result = NULL;
494         char statement[1024];
495         char *uid = NULL;
496
497         snprintf(statement, 1023,
498                 "SELECT uid FROM onak_uids WHERE keyid = '%" PRIX64
499                 "' AND pri = 't'",
500                 keyid);
501         result = PQexec(dbconn, statement);
502
503         /*
504          * Technically we only expect one response to the query; a key only has
505          * one primary ID. Better to return something than nothing though.
506          *
507          * TODO: Log if we get more than one response? Needs logging framework
508          * first though.
509          */
510         if (PQresultStatus(result) == PGRES_TUPLES_OK &&
511                         PQntuples(result) >= 1) {
512                 uid = strdup(PQgetvalue(result, 0, 0));
513         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
514                 logthing(LOGTHING_ERROR,
515                                 "Problem retrieving key (%" PRIX64
516                                 ") from DB.",
517                                 keyid);
518         }
519
520         PQclear(result);
521
522         return uid;
523 }
524
525 /**
526  *      getkeysigs - Gets a linked list of the signatures on a key.
527  *      @keyid: The keyid to get the sigs for.
528  *      @revoked: If the key is revoked.
529  *
530  *      This function gets the list of signatures on a key. Used for key 
531  *      indexing and doing stats bits.
532  */
533 static struct ll *pg_getkeysigs(uint64_t keyid, bool *revoked)
534 {
535         struct ll *sigs = NULL;
536         PGresult *result = NULL;
537         uint64_t signer;
538         char statement[1024];
539         int i, j;
540         int numsigs = 0;
541         bool intrans = false;
542         char *str;
543
544         if (!intrans) {
545                 result = PQexec(dbconn, "BEGIN");
546                 PQclear(result);
547         }
548
549         snprintf(statement, 1023,
550                 "SELECT DISTINCT signer FROM onak_sigs WHERE signee = '%"
551                 PRIX64 "'",
552                 keyid);
553         result = PQexec(dbconn, statement);
554
555         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
556                 numsigs = PQntuples(result);
557                 for (i = 0; i < numsigs;  i++) {
558                         j = 0;
559                         signer = 0;
560                         str = PQgetvalue(result, i, 0);
561                         while (str[j] != 0) {
562                                 signer <<= 4;
563                                 if (str[j] >= '0' && str[j] <= '9') {
564                                         signer += str[j] - '0';
565                                 } else {
566                                         signer += str[j] - 'A' + 10;
567                                 }
568                                 j++;
569                         }
570                         sigs = lladd(sigs, createandaddtohash(signer));
571                 }
572         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
573                 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
574         }
575
576         PQclear(result);
577
578         if (!intrans) {
579                 result = PQexec(dbconn, "COMMIT");
580                 PQclear(result);
581         }
582
583         /*
584          * TODO: What do we do about revocations? We don't have the details
585          * stored in a separate table, so we'd have to grab the key and decode
586          * it, which we're trying to avoid by having a signers table.
587          */
588         if (revoked != NULL) {
589                 *revoked = false;
590         }
591         
592         return sigs;
593 }
594
595 /**
596  *      iterate_keys - call a function once for each key in the db.
597  *      @iterfunc: The function to call.
598  *      @ctx: A context pointer
599  *
600  *      Calls iterfunc once for each key in the database. ctx is passed
601  *      unaltered to iterfunc. This function is intended to aid database dumps
602  *      and statistic calculations.
603  *
604  *      Returns the number of keys we iterated over.
605  */
606 static int pg_iterate_keys(void (*iterfunc)(void *ctx,
607                 struct openpgp_publickey *key), void *ctx)
608 {
609         struct openpgp_packet_list *packets = NULL;
610         struct openpgp_publickey *key = NULL;
611         PGresult *result = NULL;
612         char *oids = NULL;
613         int fd = -1;
614         int i = 0;
615         int numkeys = 0;
616         Oid key_oid;
617
618         result = PQexec(dbconn, "SELECT keydata FROM onak_keys;");
619
620         if (PQresultStatus(result) == PGRES_TUPLES_OK) {
621                 numkeys = PQntuples(result);
622                 for (i = 0; i < numkeys; i++) {
623                         oids = PQgetvalue(result, i, 0);
624                         key_oid = (Oid) atoi(oids);
625
626                         fd = lo_open(dbconn, key_oid, INV_READ);
627                         if (fd < 0) {
628                                 logthing(LOGTHING_ERROR,
629                                                 "Can't open large object.");
630                         } else {
631                                 read_openpgp_stream(keydb_fetchchar, &fd,
632                                                 &packets, 0);
633                                 parse_keys(packets, &key);
634                                 lo_close(dbconn, fd);
635
636                                 iterfunc(ctx, key);
637                                         
638                                 free_publickey(key);
639                                 key = NULL;
640                                 free_packet_list(packets);
641                                 packets = NULL;
642                         }
643                 }
644         } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
645                 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
646         }
647
648         PQclear(result);
649
650         return (numkeys);
651 }
652
653 /*
654  * Include the basic keydb routines.
655  */
656 #define NEED_GETFULLKEYID 1
657 #define NEED_UPDATEKEYS 1
658 #include "keydb.c"
659
660 struct dbfuncs keydb_pg_funcs = {
661         .initdb                 = pg_initdb,
662         .cleanupdb              = pg_cleanupdb,
663         .starttrans             = pg_starttrans,
664         .endtrans               = pg_endtrans,
665         .fetch_key              = pg_fetch_key,
666         .fetch_key_text         = pg_fetch_key_text,
667         .store_key              = pg_store_key,
668         .update_keys            = generic_update_keys,
669         .delete_key             = pg_delete_key,
670         .getkeysigs             = pg_getkeysigs,
671         .cached_getkeysigs      = generic_cached_getkeysigs,
672         .keyid2uid              = pg_keyid2uid,
673         .getfullkeyid           = generic_getfullkeyid,
674         .iterate_keys           = pg_iterate_keys,
675 };