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>
27 #include "keystructs.h"
29 #include "onak-conf.h"
33 * dbconn - our connection to the database.
35 static PGconn *dbconn = NULL;
38 * keydb_fetchchar - Fetches a char from a file.
40 static int keydb_fetchchar(void *fd, size_t count, unsigned char *c)
42 return (!lo_read(dbconn, *(int *) fd, c, count));
46 * keydb_putchar - Puts a char to a file.
48 static int keydb_putchar(void *fd, size_t count, unsigned char *c)
50 return !(lo_write(dbconn, *(int *) fd, c, count));
54 * initdb - Initialize the key database.
56 * This function should be called before any of the other functions in
57 * this file are called in order to allow the DB to be initialized ready
62 dbconn = PQsetdbLogin(config.pg_dbhost, // host
66 config.pg_dbname, // database
67 config.pg_dbuser, //login
68 config.pg_dbpass); // password
70 if (PQstatus(dbconn) == CONNECTION_BAD) {
71 fprintf(stderr, "Connection to database failed.\n");
72 fprintf(stderr, "%s\n", PQerrorMessage(dbconn));
80 * cleanupdb - De-initialize the key database.
82 * This function should be called upon program exit to allow the DB to
83 * cleanup after itself.
92 * starttrans - Start a transaction.
94 * Start a transaction. Intended to be used if we're about to perform many
95 * operations on the database to help speed it all up, or if we want
96 * something to only succeed if all relevant operations are successful.
100 PGresult *result = NULL;
102 result = PQexec(dbconn, "BEGIN");
109 * endtrans - End a transaction.
111 * Ends a transaction.
115 PGresult *result = NULL;
117 result = PQexec(dbconn, "COMMIT");
124 * fetch_key - Given a keyid fetch the key from storage.
125 * @keyid: The keyid to fetch.
126 * @publickey: A pointer to a structure to return the key in.
127 * @intrans: If we're already in a transaction.
129 * We use the hex representation of the keyid as the filename to fetch the
130 * key from. The key is stored in the file as a binary OpenPGP stream of
131 * packets, so we can just use read_openpgp_stream() to read the packets
132 * in and then parse_keys() to parse the packets into a publickey
135 int fetch_key(uint64_t keyid, struct openpgp_publickey **publickey, bool intrans)
137 struct openpgp_packet_list *packets = NULL;
138 PGresult *result = NULL;
140 char statement[1024];
147 result = PQexec(dbconn, "BEGIN");
151 if (keyid > 0xFFFFFFFF) {
152 snprintf(statement, 1023,
153 "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
156 snprintf(statement, 1023,
157 "SELECT keydata FROM onak_keys WHERE keyid "
161 result = PQexec(dbconn, statement);
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);
169 fd = lo_open(dbconn, key_oid, INV_READ);
171 fprintf(stderr, "Can't open large object.\n");
173 read_openpgp_stream(keydb_fetchchar, &fd,
175 parse_keys(packets, publickey);
176 lo_close(dbconn, fd);
179 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
180 fprintf(stderr, "Problem retrieving key from DB.\n");
186 result = PQexec(dbconn, "COMMIT");
193 * fetch_key_text - Trys to find the keys that contain the supplied text.
194 * @search: The text to search for.
195 * @publickey: A pointer to a structure to return the key in.
197 * This function searches for the supplied text and returns the keys that
200 int fetch_key_text(const char *search, struct openpgp_publickey **publickey)
202 struct openpgp_packet_list *packets = NULL;
203 PGresult *result = NULL;
205 char statement[1024];
210 char *newsearch = NULL;
212 result = PQexec(dbconn, "BEGIN");
215 newsearch = malloc(strlen(search) * 2 + 1);
216 memset(newsearch, 0, strlen(search) * 2 + 1);
217 PQescapeString(newsearch, search, strlen(search));
218 snprintf(statement, 1023,
219 "SELECT DISTINCT onak_keys.keydata FROM onak_keys, "
220 "onak_uids WHERE onak_keys.keyid = onak_uids.keyid "
221 "AND onak_uids.uid LIKE '%%%s%%'",
223 result = PQexec(dbconn, statement);
227 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
228 numkeys = PQntuples(result);
229 for (i = 0; i < numkeys && numkeys <= config.maxkeys; i++) {
230 oids = PQgetvalue(result, i, 0);
231 key_oid = (Oid) atoi(oids);
233 fd = lo_open(dbconn, key_oid, INV_READ);
235 fprintf(stderr, "Can't open large object.\n");
237 read_openpgp_stream(keydb_fetchchar, &fd,
239 parse_keys(packets, publickey);
240 lo_close(dbconn, fd);
243 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
244 fprintf(stderr, "Problem retrieving key from DB.\n");
249 result = PQexec(dbconn, "COMMIT");
255 * store_key - Takes a key and stores it.
256 * @publickey: A pointer to the public key to store.
257 * @intrans: If we're already in a transaction.
258 * @update: If true the key exists and should be updated.
260 * Again we just use the hex representation of the keyid as the filename
261 * to store the key to. We flatten the public key to a list of OpenPGP
262 * packets and then use write_openpgp_stream() to write the stream out to
263 * the file. If update is true then we delete the old key first, otherwise
264 * we trust that it doesn't exist.
266 int store_key(struct openpgp_publickey *publickey, bool intrans, bool update)
268 struct openpgp_packet_list *packets = NULL;
269 struct openpgp_packet_list *list_end = NULL;
270 struct openpgp_publickey *next = NULL;
271 struct openpgp_signedpacket_list *curuid = NULL;
272 PGresult *result = NULL;
273 char statement[1024];
277 char *primary = NULL;
278 char *safeuid = NULL;
282 result = PQexec(dbconn, "BEGIN");
287 * Delete the key if we already have it.
289 * TODO: Can we optimize this perhaps? Possibly when other data is
290 * involved as well? I suspect this is easiest and doesn't make a lot
291 * of difference though - the largest chunk of data is the keydata and
292 * it definitely needs updated.
295 delete_key(get_keyid(publickey), true);
298 next = publickey->next;
299 publickey->next = NULL;
300 flatten_publickey(publickey, &packets, &list_end);
301 publickey->next = next;
303 key_oid = lo_creat(dbconn, INV_READ | INV_WRITE);
305 fprintf(stderr, "Can't create key OID\n");
307 fd = lo_open(dbconn, key_oid, INV_WRITE);
308 write_openpgp_stream(keydb_putchar, &fd, packets);
309 lo_close(dbconn, fd);
312 snprintf(statement, 1023,
313 "INSERT INTO onak_keys (keyid, keydata) VALUES "
315 get_keyid(publickey),
317 result = PQexec(dbconn, statement);
319 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
320 fprintf(stderr, "Problem storing key in DB.\n");
321 fprintf(stderr, "%s\n", PQresultErrorMessage(result));
325 uids = keyuids(publickey, &primary);
327 for (i = 0; uids[i] != NULL; i++) {
328 safeuid = malloc(strlen(uids[i]) * 2 + 1);
329 if (safeuid != NULL) {
330 memset(safeuid, 0, strlen(uids[i]) * 2 + 1);
331 PQescapeString(safeuid, uids[i],
334 snprintf(statement, 1023,
335 "INSERT INTO onak_uids "
337 "VALUES ('%llX', '%s', '%c')",
338 get_keyid(publickey),
340 (uids[i] == primary) ? 't' : 'f');
341 result = PQexec(dbconn, statement);
346 if (uids[i] != NULL) {
351 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
352 fprintf(stderr, "Problem storing key in DB.\n");
353 fprintf(stderr, "%s\n",
354 PQresultErrorMessage(result));
357 * TODO: Check result.
365 for (curuid = publickey->uids; curuid != NULL; curuid = curuid->next) {
366 for (packets = curuid->sigs; packets != NULL;
367 packets = packets->next) {
368 snprintf(statement, 1023,
369 "INSERT INTO onak_sigs (signer, signee) "
370 "VALUES ('%llX', '%llX')",
371 sig_keyid(packets->packet),
372 get_keyid(publickey));
373 result = PQexec(dbconn, statement);
379 result = PQexec(dbconn, "COMMIT");
387 * delete_key - Given a keyid delete the key from storage.
388 * @keyid: The keyid to delete.
389 * @intrans: If we're already in a transaction.
391 * This function deletes a public key from whatever storage mechanism we
392 * are using. Returns 0 if the key existed.
394 int delete_key(uint64_t keyid, bool intrans)
396 PGresult *result = NULL;
398 char statement[1024];
404 result = PQexec(dbconn, "BEGIN");
408 snprintf(statement, 1023,
409 "SELECT keydata FROM onak_keys WHERE keyid = '%llX'",
411 result = PQexec(dbconn, statement);
413 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
415 i = PQntuples(result);
417 oids = PQgetvalue(result, i-1, 0);
418 key_oid = (Oid) atoi(oids);
419 lo_unlink(dbconn, key_oid);
424 snprintf(statement, 1023,
425 "DELETE FROM onak_keys WHERE keyid = '%llX'",
427 result = PQexec(dbconn, statement);
430 snprintf(statement, 1023,
431 "DELETE FROM onak_sigs WHERE signee = '%llX'",
433 result = PQexec(dbconn, statement);
436 snprintf(statement, 1023,
437 "DELETE FROM onak_uids WHERE keyid = '%llX'",
439 result = PQexec(dbconn, statement);
440 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
441 fprintf(stderr, "Problem retrieving key (%llX) from DB.\n",
448 result = PQexec(dbconn, "COMMIT");
455 * keyid2uid - Takes a keyid and returns the primary UID for it.
456 * @keyid: The keyid to lookup.
458 char *keyid2uid(uint64_t keyid)
460 PGresult *result = NULL;
461 char statement[1024];
464 snprintf(statement, 1023,
465 "SELECT uid FROM onak_uids WHERE keyid = '%llX' AND pri = 't'",
467 result = PQexec(dbconn, statement);
470 * Technically we only expect one response to the query; a key only has
471 * one primary ID. Better to return something than nothing though.
473 * TODO: Log if we get more than one response? Needs logging framework
476 if (PQresultStatus(result) == PGRES_TUPLES_OK &&
477 PQntuples(result) >= 1) {
478 uid = strdup(PQgetvalue(result, 0, 0));
479 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
480 fprintf(stderr, "Problem retrieving key (%llX) from DB.\n",
490 * getkeysigs - Gets a linked list of the signatures on a key.
491 * @keyid: The keyid to get the sigs for.
493 * This function gets the list of signatures on a key. Used for key
494 * indexing and doing stats bits.
496 struct ll *getkeysigs(uint64_t keyid)
498 struct ll *sigs = NULL;
499 PGresult *result = NULL;
501 char statement[1024];
504 bool intrans = false;
508 result = PQexec(dbconn, "BEGIN");
512 snprintf(statement, 1023,
513 "SELECT DISTINCT signer FROM onak_sigs WHERE signee = '%llX'",
515 result = PQexec(dbconn, statement);
517 if (PQresultStatus(result) == PGRES_TUPLES_OK) {
518 numsigs = PQntuples(result);
519 for (i = 0; i < numsigs; i++) {
522 str = PQgetvalue(result, i, 0);
523 while (str[j] != 0) {
525 if (str[j] >= '0' && str[j] <= '9') {
526 signer += str[j] - '0';
528 signer += str[j] - 'A' + 10;
532 sigs = lladd(sigs, createandaddtohash(signer));
534 } else if (PQresultStatus(result) != PGRES_TUPLES_OK) {
535 fprintf(stderr, "Problem retrieving key from DB.\n");
541 result = PQexec(dbconn, "COMMIT");
548 * Include the basic keydb routines.
550 #define NEED_GETFULLKEYID 1