2 * keydb_pg.c - Routines to store and fetch keys in a PostGres database.
4 * Jonathan McDowell <noodles@earth.li>
6 * Copyright 2002 Project Purple
9 #include <postgresql/libpq-fe.h>
10 #include <postgresql/libpq/libpq-fs.h>
12 //#include <libpq-fe.h>
13 //#include <libpq/libpq-fs.h>
14 #include <sys/types.h>
26 #include "decodekey.h"
27 #include "keystructs.h"
30 #include "onak-conf.h"
34 * dbconn - our connection to the database.
36 static PGconn *dbconn = NULL;
39 * keydb_fetchchar - Fetches a char from a file.
41 static int keydb_fetchchar(void *fd, size_t count, unsigned char *c)
43 return (!lo_read(dbconn, *(int *) fd, c, count));
47 * keydb_putchar - Puts a char to a file.
49 static int keydb_putchar(void *fd, size_t count, unsigned char *c)
51 return !(lo_write(dbconn, *(int *) fd, c, count));
55 * initdb - Initialize the key database.
57 * This function should be called before any of the other functions in
58 * this file are called in order to allow the DB to be initialized ready
63 dbconn = PQsetdbLogin(config.pg_dbhost, // host
67 config.pg_dbname, // database
68 config.pg_dbuser, //login
69 config.pg_dbpass); // password
71 if (PQstatus(dbconn) == CONNECTION_BAD) {
72 logthing(LOGTHING_CRITICAL, "Connection to database failed.");
73 logthing(LOGTHING_CRITICAL, "%s", PQerrorMessage(dbconn));
81 * cleanupdb - De-initialize the key database.
83 * This function should be called upon program exit to allow the DB to
84 * cleanup after itself.
93 * starttrans - Start a transaction.
95 * Start a transaction. Intended to be used if we're about to perform many
96 * operations on the database to help speed it all up, or if we want
97 * something to only succeed if all relevant operations are successful.
101 PGresult *result = NULL;
103 result = PQexec(dbconn, "BEGIN");
110 * endtrans - End a transaction.
112 * Ends a transaction.
116 PGresult *result = NULL;
118 result = PQexec(dbconn, "COMMIT");
125 * fetch_key - Given a keyid fetch the key from storage.
126 * @keyid: The keyid to fetch.
127 * @publickey: A pointer to a structure to return the key in.
128 * @intrans: If we're already in a transaction.
130 * We use the hex representation of the keyid as the filename to fetch the
131 * key from. The key is stored in the file as a binary OpenPGP stream of
132 * packets, so we can just use read_openpgp_stream() to read the packets
133 * in and then parse_keys() to parse the packets into a publickey
136 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey,
139 struct openpgp_packet_list *packets = NULL;
140 PGresult *result = NULL;
142 char statement[1024];
149 result = PQexec(dbconn, "BEGIN");
153 if (keyid > 0xFFFFFFFF) {
154 snprintf(statement, 1023,
155 "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
158 snprintf(statement, 1023,
159 "SELECT keydata FROM onak_keys WHERE keyid "
163 result = PQexec(dbconn, statement);
165 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
166 numkeys = PQntuples(result);
167 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
168 oids = PQgetvalue(result, i, 0);
169 key_oid = (Oid) atoi(oids);
171 fd = lo_open(dbconn, key_oid, INV_READ);
173 logthing(LOGTHING_ERROR,
174 "Can't open large object.");
176 read_openpgp_stream(keydb_fetchchar, &fd,
178 parse_keys(packets, publickey);
179 lo_close(dbconn, fd);
180 free_packet_list(packets);
184 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
185 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
191 result = PQexec(dbconn, "COMMIT");
198 * fetch_key_text - Trys to find the keys that contain the supplied text.
199 * @search: The text to search for.
200 * @publickey: A pointer to a structure to return the key in.
202 * This function searches for the supplied text and returns the keys that
205 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
207 struct openpgp_packet_list *packets = NULL;
208 PGresult *result = NULL;
210 char statement[1024];
215 char *newsearch = NULL;
217 result = PQexec(dbconn, "BEGIN");
220 newsearch = malloc(strlen(search) * 2 + 1);
221 memset(newsearch, 0, strlen(search) * 2 + 1);
222 PQescapeString(newsearch, search, strlen(search));
223 snprintf(statement, 1023,
224 "SELECT DISTINCT onak_keys.keydata FROM onak_keys, "
225 "onak_uids WHERE onak_keys.keyid = onak_uids.keyid "
226 "AND onak_uids.uid LIKE '%%%s%%'",
228 result = PQexec(dbconn, statement);
232 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
233 numkeys = PQntuples(result);
234 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
235 oids = PQgetvalue(result, i, 0);
236 key_oid = (Oid) atoi(oids);
238 fd = lo_open(dbconn, key_oid, INV_READ);
240 logthing(LOGTHING_ERROR,
241 "Can't open large object.");
243 read_openpgp_stream(keydb_fetchchar, &fd,
245 parse_keys(packets, publickey);
246 lo_close(dbconn, fd);
247 free_packet_list(packets);
251 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
252 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
257 result = PQexec(dbconn, "COMMIT");
263 * store_key - Takes a key and stores it.
264 * @publickey: A pointer to the public key to store.
265 * @intrans: If we're already in a transaction.
266 * @update: If true the key exists and should be updated.
268 * Again we just use the hex representation of the keyid as the filename
269 * to store the key to. We flatten the public key to a list of OpenPGP
270 * packets and then use write_openpgp_stream() to write the stream out to
271 * the file. If update is true then we delete the old key first, otherwise
272 * we trust that it doesn't exist.
274 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
276 struct openpgp_packet_list *packets = NULL;
277 struct openpgp_packet_list *list_end = NULL;
278 struct openpgp_publickey *next = NULL;
279 struct openpgp_signedpacket_list *curuid = NULL;
280 PGresult *result = NULL;
281 char statement[1024];
285 char *primary = NULL;
286 char *safeuid = NULL;
290 result = PQexec(dbconn, "BEGIN");
295 * Delete the key if we already have it.
297 * TODO: Can we optimize this perhaps? Possibly when other data is
298 * involved as well? I suspect this is easiest and doesn't make a lot
299 * of difference though - the largest chunk of data is the keydata and
300 * it definitely needs updated.
303 delete_key(get_keyid(publickey), true);
306 next = publickey->next;
307 publickey->next = NULL;
308 flatten_publickey(publickey, &packets, &list_end);
309 publickey->next = next;
311 key_oid = lo_creat(dbconn, INV_READ | INV_WRITE);
313 logthing(LOGTHING_ERROR, "Can't create key OID");
315 fd = lo_open(dbconn, key_oid, INV_WRITE);
316 write_openpgp_stream(keydb_putchar, &fd, packets);
317 lo_close(dbconn, fd);
319 free_packet_list(packets);
322 snprintf(statement, 1023,
323 "INSERT INTO onak_keys (keyid, keydata) VALUES "
325 get_keyid(publickey),
327 result = PQexec(dbconn, statement);
329 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
330 logthing(LOGTHING_ERROR, "Problem storing key in DB.");
331 logthing(LOGTHING_ERROR, "%s", PQresultErrorMessage(result));
335 uids = keyuids(publickey, &primary);
337 for (i = 0; uids[i] != NULL; i++) {
338 safeuid = malloc(strlen(uids[i]) * 2 + 1);
339 if (safeuid != NULL) {
340 memset(safeuid, 0, strlen(uids[i]) * 2 + 1);
341 PQescapeString(safeuid, uids[i],
344 snprintf(statement, 1023,
345 "INSERT INTO onak_uids "
347 "VALUES ('%llX', '%s', '%c')",
348 get_keyid(publickey),
350 (uids[i] == primary) ? 't' : 'f');
351 result = PQexec(dbconn, statement);
356 if (uids[i] != NULL) {
361 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
362 logthing(LOGTHING_ERROR,
363 "Problem storing key in DB.");
364 logthing(LOGTHING_ERROR, "%s",
365 PQresultErrorMessage(result));
368 * TODO: Check result.
376 for (curuid = publickey->uids; curuid != NULL; curuid = curuid->next) {
377 for (packets = curuid->sigs; packets != NULL;
378 packets = packets->next) {
379 snprintf(statement, 1023,
380 "INSERT INTO onak_sigs (signer, signee) "
381 "VALUES ('%llX', '%llX')",
382 sig_keyid(packets->packet),
383 get_keyid(publickey));
384 result = PQexec(dbconn, statement);
390 result = PQexec(dbconn, "COMMIT");
398 * delete_key - Given a keyid delete the key from storage.
399 * @keyid: The keyid to delete.
400 * @intrans: If we're already in a transaction.
402 * This function deletes a public key from whatever storage mechanism we
403 * are using. Returns 0 if the key existed.
405 int delete_key(uint64_t keyid, bool intrans)
407 PGresult *result = NULL;
409 char statement[1024];
415 result = PQexec(dbconn, "BEGIN");
419 snprintf(statement, 1023,
420 "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
422 result = PQexec(dbconn, statement);
424 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
426 i = PQntuples(result);
428 oids = PQgetvalue(result, i-1, 0);
429 key_oid = (Oid) atoi(oids);
430 lo_unlink(dbconn, key_oid);
435 snprintf(statement, 1023,
436 "DELETE FROM onak_keys WHERE keyid = '%llX'",
438 result = PQexec(dbconn, statement);
441 snprintf(statement, 1023,
442 "DELETE FROM onak_sigs WHERE signee = '%llX'",
444 result = PQexec(dbconn, statement);
447 snprintf(statement, 1023,
448 "DELETE FROM onak_uids WHERE keyid = '%llX'",
450 result = PQexec(dbconn, statement);
451 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
452 logthing(LOGTHING_ERROR,
453 "Problem retrieving key (%llX) from DB.",
460 result = PQexec(dbconn, "COMMIT");
467 * keyid2uid - Takes a keyid and returns the primary UID for it.
468 * @keyid: The keyid to lookup.
470 char *keyid2uid(uint64_t keyid)
472 PGresult *result = NULL;
473 char statement[1024];
476 snprintf(statement, 1023,
477 "SELECT uid FROM onak_uids WHERE keyid = '%llX' AND pri = 't'",
479 result = PQexec(dbconn, statement);
482 * Technically we only expect one response to the query; a key only has
483 * one primary ID. Better to return something than nothing though.
485 * TODO: Log if we get more than one response? Needs logging framework
488 if (PQresultStatus(result) == PGRES_TUPLES_OK &&
489 PQntuples(result) >= 1) {
490 uid = strdup(PQgetvalue(result, 0, 0));
491 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
492 logthing(LOGTHING_ERROR,
493 "Problem retrieving key (%llX) from DB.",
503 * getkeysigs - Gets a linked list of the signatures on a key.
504 * @keyid: The keyid to get the sigs for.
506 * This function gets the list of signatures on a key. Used for key
507 * indexing and doing stats bits.
509 struct ll *getkeysigs(uint64_t keyid)
511 struct ll *sigs = NULL;
512 PGresult *result = NULL;
514 char statement[1024];
517 bool intrans = false;
521 result = PQexec(dbconn, "BEGIN");
525 snprintf(statement, 1023,
526 "SELECT DISTINCT signer FROM onak_sigs WHERE signee = '%llX'",
528 result = PQexec(dbconn, statement);
530 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
531 numsigs = PQntuples(result);
532 for (i = 0; i < numsigs; i++) {
535 str = PQgetvalue(result, i, 0);
536 while (str[j] != 0) {
538 if (str[j] >= '0' && str[j] <= '9') {
539 signer += str[j] - '0';
541 signer += str[j] - 'A' + 10;
545 sigs = lladd(sigs, createandaddtohash(signer));
547 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
548 logthing(LOGTHING_ERROR, "Problem retrieving key from DB.");
554 result = PQexec(dbconn, "COMMIT");
561 * Include the basic keydb routines.
563 #define NEED_GETFULLKEYID 1