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 "keystructs.h"
28 #include "onak-conf.h"
32 * dbconn - our connection to the database.
34 static PGconn *dbconn = NULL;
37 * keydb_fetchchar - Fetches a char from a file.
39 static int keydb_fetchchar(void *fd, size_t count, unsigned char *c)
41 return (!lo_read(dbconn, *(int *) fd, c, count));
45 * keydb_putchar - Puts a char to a file.
47 static int keydb_putchar(void *fd, size_t count, unsigned char *c)
49 return !(lo_write(dbconn, *(int *) fd, c, count));
53 * initdb - Initialize the key database.
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
61 dbconn = PQsetdbLogin(config.pg_dbhost, // host
65 config.pg_dbname, // database
66 config.pg_dbuser, //login
67 config.pg_dbpass); // password
69 if (PQstatus(dbconn) == CONNECTION_BAD) {
70 fprintf(stderr, "Connection to database failed.\n");
71 fprintf(stderr, "%s\n", PQerrorMessage(dbconn));
79 * cleanupdb - De-initialize the key database.
81 * This function should be called upon program exit to allow the DB to
82 * cleanup after itself.
91 * starttrans - Start a transaction.
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.
99 PGresult *result = NULL;
101 result = PQexec(dbconn, "BEGIN");
108 * endtrans - End a transaction.
110 * Ends a transaction.
114 PGresult *result = NULL;
116 result = PQexec(dbconn, "COMMIT");
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.
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
134 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey, bool intrans)
136 struct openpgp_packet_list *packets = NULL;
137 PGresult *result = NULL;
139 char statement[1024];
146 result = PQexec(dbconn, "BEGIN");
150 if (keyid > 0xFFFFFFFF) {
151 snprintf(statement, 1023,
152 "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
155 snprintf(statement, 1023,
156 "SELECT keydata FROM onak_keys WHERE keyid "
160 result = PQexec(dbconn, statement);
162 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
163 numkeys = PQntuples(result);
164 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
165 oids = PQgetvalue(result, i, 0);
166 key_oid = (Oid) atoi(oids);
168 fd = lo_open(dbconn, key_oid, INV_READ);
170 fprintf(stderr, "Can't open large object.\n");
172 read_openpgp_stream(keydb_fetchchar, &fd,
174 parse_keys(packets, publickey);
175 lo_close(dbconn, fd);
178 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
179 fprintf(stderr, "Problem retrieving key from DB.\n");
185 result = PQexec(dbconn, "COMMIT");
192 * fetch_key_text - Trys to find the keys that contain the supplied text.
193 * @search: The text to search for.
194 * @publickey: A pointer to a structure to return the key in.
196 * This function searches for the supplied text and returns the keys that
199 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
201 struct openpgp_packet_list *packets = NULL;
202 PGresult *result = NULL;
204 char statement[1024];
209 char *newsearch = NULL;
211 result = PQexec(dbconn, "BEGIN");
214 newsearch = malloc(strlen(search) * 2 + 1);
215 memset(newsearch, 0, strlen(search) * 2 + 1);
216 PQescapeString(newsearch, search, strlen(search));
217 snprintf(statement, 1023,
218 "SELECT DISTINCT onak_keys.keydata FROM onak_keys, "
219 "onak_uids WHERE onak_keys.keyid = onak_uids.keyid "
220 "AND onak_uids.uid LIKE '%%%s%%'",
222 result = PQexec(dbconn, statement);
226 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
227 numkeys = PQntuples(result);
228 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
229 oids = PQgetvalue(result, i, 0);
230 key_oid = (Oid) atoi(oids);
232 fd = lo_open(dbconn, key_oid, INV_READ);
234 fprintf(stderr, "Can't open large object.\n");
236 read_openpgp_stream(keydb_fetchchar, &fd,
238 parse_keys(packets, publickey);
239 lo_close(dbconn, fd);
242 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
243 fprintf(stderr, "Problem retrieving key from DB.\n");
248 result = PQexec(dbconn, "COMMIT");
254 * store_key - Takes a key and stores it.
255 * @publickey: A pointer to the public key to store.
256 * @intrans: If we're already in a transaction.
257 * @update: If true the key exists and should be updated.
259 * Again we just use the hex representation of the keyid as the filename
260 * to store the key to. We flatten the public key to a list of OpenPGP
261 * packets and then use write_openpgp_stream() to write the stream out to
262 * the file. If update is true then we delete the old key first, otherwise we
263 * trust that it doesn't exist.
265 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
267 struct openpgp_packet_list *packets = NULL;
268 struct openpgp_packet_list *list_end = NULL;
269 struct openpgp_publickey *next = NULL;
270 PGresult *result = NULL;
271 char statement[1024];
275 char *primary = NULL;
276 char *safeuid = NULL;
280 result = PQexec(dbconn, "BEGIN");
285 * Delete the key if we already have it.
287 * TODO: Can we optimize this perhaps? Possibly when other data is
288 * involved as well? I suspect this is easiest and doesn't make a lot
289 * of difference though - the largest chunk of data is the keydata and
290 * it definitely needs updated.
293 delete_key(get_keyid(publickey), true);
296 next = publickey->next;
297 publickey->next = NULL;
298 flatten_publickey(publickey, &packets, &list_end);
299 publickey->next = next;
301 key_oid = lo_creat(dbconn, INV_READ | INV_WRITE);
303 fprintf(stderr, "Can't create key OID\n");
305 fd = lo_open(dbconn, key_oid, INV_WRITE);
306 write_openpgp_stream(keydb_putchar, &fd, packets);
307 lo_close(dbconn, fd);
310 snprintf(statement, 1023,
311 "INSERT INTO onak_keys (keyid, keydata) VALUES "
313 get_keyid(publickey),
315 result = PQexec(dbconn, statement);
317 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
318 fprintf(stderr, "Problem storing key in DB.\n");
319 fprintf(stderr, "%s\n", PQresultErrorMessage(result));
323 uids = keyuids(publickey, &primary);
325 for (i = 0; uids[i] != NULL; i++) {
326 safeuid = malloc(strlen(uids[i]) * 2 + 1);
327 if (safeuid != NULL) {
328 memset(safeuid, 0, strlen(uids[i]) * 2 + 1);
329 PQescapeString(safeuid, uids[i],
332 snprintf(statement, 1023,
333 "INSERT INTO onak_uids "
335 "VALUES ('%llX', '%s', '%c')",
336 get_keyid(publickey),
338 (uids[i] == primary) ? 't' : 'f');
339 result = PQexec(dbconn, statement);
344 if (uids[i] != NULL) {
349 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
350 fprintf(stderr, "Problem storing key in DB.\n");
351 fprintf(stderr, "%s\n",
352 PQresultErrorMessage(result));
355 * TODO: Check result.
364 result = PQexec(dbconn, "COMMIT");
372 * delete_key - Given a keyid delete the key from storage.
373 * @keyid: The keyid to delete.
374 * @intrans: If we're already in a transaction.
376 * This function deletes a public key from whatever storage mechanism we
377 * are using. Returns 0 if the key existed.
379 int delete_key(uint64_t keyid, bool intrans)
381 PGresult *result = NULL;
383 char statement[1024];
389 result = PQexec(dbconn, "BEGIN");
393 snprintf(statement, 1023,
394 "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
396 result = PQexec(dbconn, statement);
398 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
400 i = PQntuples(result);
402 oids = PQgetvalue(result, i-1, 0);
403 key_oid = (Oid) atoi(oids);
404 lo_unlink(dbconn, key_oid);
409 snprintf(statement, 1023,
410 "DELETE FROM onak_keys WHERE keyid = '%llX'",
412 result = PQexec(dbconn, statement);
415 snprintf(statement, 1023,
416 "DELETE FROM onak_uids WHERE keyid = '%llX'",
418 result = PQexec(dbconn, statement);
419 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
420 fprintf(stderr, "Problem retrieving key (%llX) from DB.\n",
427 result = PQexec(dbconn, "COMMIT");
434 * keyid2uid - Takes a keyid and returns the primary UID for it.
435 * @keyid: The keyid to lookup.
437 char *keyid2uid(uint64_t keyid)
439 PGresult *result = NULL;
440 char statement[1024];
443 snprintf(statement, 1023,
444 "SELECT uid FROM onak_uids WHERE keyid = '%llX' AND pri = 't'",
446 result = PQexec(dbconn, statement);
449 * Technically we only expect one response to the query; a key only has
450 * one primary ID. Better to return something than nothing though.
452 * TODO: Log if we get more than one response? Needs logging framework
455 if (PQresultStatus(result) == PGRES_TUPLES_OK &&
456 PQntuples(result) >= 1) {
457 uid = strdup(PQgetvalue(result, 0, 0));
458 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
459 fprintf(stderr, "Problem retrieving key (%llX) from DB.\n",
469 * Include the basic keydb routines.
471 #define NEED_GETKEYSIGS 1
472 #define NEED_GETFULLKEYID 1