2 * This file is part of GNUnet
3 * (C) 2009-2013 Christian Grothoff (and other contributing authors)
5 * GNUnet is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published
7 * by the Free Software Foundation; either version 3, or (at your
8 * option) any later version.
10 * GNUnet is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with GNUnet; see the file COPYING. If not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
22 * @file namestore/plugin_namestore_postgres.c
23 * @brief postgres-based namestore backend
24 * @author Christian Grothoff
27 #include "gnunet_namestore_plugin.h"
28 #include "gnunet_namestore_service.h"
29 #include "gnunet_postgres_lib.h"
30 #include "namestore.h"
34 * After how many ms "busy" should a DB operation fail for good?
35 * A low value makes sure that we are more responsive to requests
36 * (especially PUTs). A high value guarantees a higher success
37 * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
39 * The default value of 1s should ensure that users do not experience
40 * huge latencies while at the same time allowing operations to succeed
41 * with reasonable probability.
43 #define BUSY_TIMEOUT_MS 1000
47 * Log an error message at log-level 'level' that indicates
48 * a failure of the command 'cmd' on file 'filename'
49 * with the message given by strerror(errno).
51 #define LOG_POSTGRES(db, level, cmd) do { GNUNET_log_from (level, "namestore-postgres", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
53 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-postgres", __VA_ARGS__)
57 * Context for all functions in this plugin.
62 const struct GNUNET_CONFIGURATION_Handle *cfg;
65 * Native Postgres database handle.
73 * Create our database indices.
75 * @param dbh handle to the database
78 create_indices (PGconn * dbh)
82 GNUNET_POSTGRES_exec (dbh,
83 "CREATE INDEX ir_query_hash ON ns096blocks (query,expiration_time)")) ||
85 GNUNET_POSTGRES_exec (dbh,
86 "CREATE INDEX ir_block_expiration ON ns096blocks (expiration_time)")) ||
88 GNUNET_POSTGRES_exec (dbh,
89 "CREATE INDEX ir_pkey_reverse ON ns097records (zone_private_key,pkey)")) ||
91 GNUNET_POSTGRES_exec (dbh,
92 "CREATE INDEX ir_pkey_iter ON ns097records (zone_private_key,rvalue)")) ||
94 GNUNET_POSTGRES_exec (dbh,
95 "CREATE INDEX it_iter ON ns097records (rvalue)")) )
96 LOG (GNUNET_ERROR_TYPE_ERROR,
97 _("Failed to create indices\n"));
102 * Initialize the database connections and associated
103 * data structures (create tables and indices
104 * as needed as well).
106 * @param plugin the plugin context (state for this module)
107 * @return GNUNET_OK on success
110 database_setup (struct Plugin *plugin)
114 plugin->dbh = GNUNET_POSTGRES_connect (plugin->cfg,
115 "namestore-postgres");
116 if (NULL == plugin->dbh)
117 return GNUNET_SYSERR;
119 GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
120 "namestore-postgres",
125 "CREATE TEMPORARY TABLE ns097records ("
126 " zone_private_key BYTEA NOT NULL DEFAULT '',"
127 " pkey BYTEA DEFAULT '',"
128 " rvalue BYTEA NOT NULL DEFAULT '',"
129 " record_count INTEGER NOT NULL DEFAULT 0,"
130 " record_data BYTEA NOT NULL DEFAULT '',"
131 " label TEXT NOT NULL DEFAULT ''"
138 "CREATE TABLE ns097records ("
139 " zone_private_key BYTEA NOT NULL DEFAULT '',"
140 " pkey BYTEA DEFAULT '',"
141 " rvalue BYTEA NOT NULL DEFAULT '',"
142 " record_count INTEGER NOT NULL DEFAULT 0,"
143 " record_data BYTEA NOT NULL DEFAULT '',"
144 " label TEXT NOT NULL DEFAULT ''"
147 if ( (NULL == res) ||
148 ((PQresultStatus (res) != PGRES_COMMAND_OK) &&
149 (0 != strcmp ("42P07", /* duplicate table */
152 PG_DIAG_SQLSTATE)))))
154 (void) GNUNET_POSTGRES_check_result (plugin->dbh, res,
155 PGRES_COMMAND_OK, "CREATE TABLE",
157 PQfinish (plugin->dbh);
159 return GNUNET_SYSERR;
164 GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
165 "namestore-postgres",
170 "CREATE TEMPORARY TABLE ns096blocks ("
171 " query BYTEA NOT NULL DEFAULT '',"
172 " block BYTEA NOT NULL DEFAULT '',"
173 " expiration_time BIGINT NOT NULL DEFAULT 0"
180 "CREATE TABLE ns096blocks ("
181 " query BYTEA NOT NULL DEFAULT '',"
182 " block BYTEA NOT NULL DEFAULT '',"
183 " expiration_time BIGINT NOT NULL DEFAULT 0"
186 if ( (NULL == res) ||
187 ((PQresultStatus (res) != PGRES_COMMAND_OK) &&
188 (0 != strcmp ("42P07", /* duplicate table */
191 PG_DIAG_SQLSTATE)))))
193 (void) GNUNET_POSTGRES_check_result (plugin->dbh, res,
194 PGRES_COMMAND_OK, "CREATE TABLE",
196 PQfinish (plugin->dbh);
198 return GNUNET_SYSERR;
200 if (PQresultStatus (res) == PGRES_COMMAND_OK)
201 create_indices (plugin->dbh);
205 GNUNET_POSTGRES_prepare (plugin->dbh,
207 "INSERT INTO ns096blocks (query, block, expiration_time) VALUES "
208 "($1, $2, $3)", 3)) ||
210 GNUNET_POSTGRES_prepare (plugin->dbh,
212 "DELETE FROM ns096blocks WHERE expiration_time<$1", 1)) ||
214 GNUNET_POSTGRES_prepare (plugin->dbh,
216 "DELETE FROM ns096blocks WHERE query=$1 AND expiration_time<=$2", 2)) ||
218 GNUNET_POSTGRES_prepare (plugin->dbh,
220 "SELECT block FROM ns096blocks WHERE query=$1"
221 " ORDER BY expiration_time DESC LIMIT 1", 1)) ||
223 GNUNET_POSTGRES_prepare (plugin->dbh,
225 "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label) VALUES "
226 "($1, $2, $3, $4, $5, $6)", 6)) ||
228 GNUNET_POSTGRES_prepare (plugin->dbh,
230 "DELETE FROM ns097records WHERE zone_private_key=$1 AND label=$2", 2)) ||
232 GNUNET_POSTGRES_prepare (plugin->dbh,
234 "SELECT record_count,record_data,label FROM ns097records"
235 " WHERE zone_private_key=$1 AND pkey=$2", 2)) ||
237 GNUNET_POSTGRES_prepare (plugin->dbh,
239 "SELECT record_count, record_data, label FROM ns097records"
240 " WHERE zone_private_key=$1 ORDER BY rvalue LIMIT 1 OFFSET $2", 2)) ||
242 GNUNET_POSTGRES_prepare (plugin->dbh,
244 "SELECT record_count,record_data,label,zone_private_key"
245 " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET $1", 1)))
247 PQfinish (plugin->dbh);
249 return GNUNET_SYSERR;
256 * Removes any expired block.
258 * @param plugin the plugin
261 namestore_postgres_expire_blocks (struct Plugin *plugin)
263 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
264 struct GNUNET_TIME_AbsoluteNBO now_be = GNUNET_TIME_absolute_hton (now);
265 const char *paramValues[] = {
266 (const char *) &now_be
268 int paramLengths[] = {
271 const int paramFormats[] = { 1 };
275 PQexecPrepared (plugin->dbh, "expire_blocks", 1,
276 paramValues, paramLengths, paramFormats, 1);
278 GNUNET_POSTGRES_check_result (plugin->dbh,
289 * Delete older block in the datastore.
292 * @param query query for the block
293 * @param expiration time how old does the block have to be for deletion
294 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
297 delete_old_block (struct Plugin *plugin,
298 const struct GNUNET_HashCode *query,
299 struct GNUNET_TIME_AbsoluteNBO expiration_time)
301 const char *paramValues[] = {
302 (const char *) query,
303 (const char *) &expiration_time
305 int paramLengths[] = {
307 sizeof (expiration_time)
309 const int paramFormats[] = { 1, 1 };
313 PQexecPrepared (plugin->dbh, "delete_block", 2,
314 paramValues, paramLengths, paramFormats, 1);
316 GNUNET_POSTGRES_check_result (plugin->dbh,
327 * Cache a block in the datastore.
329 * @param cls closure (internal context for the plugin)
330 * @param block block to cache
331 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
334 namestore_postgres_cache_block (void *cls,
335 const struct GNUNET_NAMESTORE_Block *block)
337 struct Plugin *plugin = cls;
338 struct GNUNET_HashCode query;
339 size_t block_size = ntohl (block->purpose.size) +
340 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
341 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
342 const char *paramValues[] = {
343 (const char *) &query,
344 (const char *) block,
345 (const char *) &block->expiration_time
347 int paramLengths[] = {
350 sizeof (block->expiration_time)
352 const int paramFormats[] = { 1, 1, 1 };
355 namestore_postgres_expire_blocks (plugin);
356 GNUNET_CRYPTO_hash (&block->derived_key,
357 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
359 if (block_size > 64 * 65536)
362 return GNUNET_SYSERR;
364 delete_old_block (plugin, &query, block->expiration_time);
367 PQexecPrepared (plugin->dbh, "cache_block", 3,
368 paramValues, paramLengths, paramFormats, 1);
370 GNUNET_POSTGRES_check_result (plugin->dbh,
375 return GNUNET_SYSERR;
382 * Get the block for a particular zone and label in the
383 * datastore. Will return at most one result to the iterator.
385 * @param cls closure (internal context for the plugin)
386 * @param query hash of public key derived from the zone and the label
387 * @param iter function to call with the result
388 * @param iter_cls closure for @a iter
389 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
392 namestore_postgres_lookup_block (void *cls,
393 const struct GNUNET_HashCode *query,
394 GNUNET_NAMESTORE_BlockCallback iter, void *iter_cls)
396 struct Plugin *plugin = cls;
397 const char *paramValues[] = {
400 int paramLengths[] = {
403 const int paramFormats[] = { 1 };
407 const struct GNUNET_NAMESTORE_Block *block;
409 res = PQexecPrepared (plugin->dbh,
411 paramValues, paramLengths, paramFormats,
414 GNUNET_POSTGRES_check_result (plugin->dbh, res, PGRES_TUPLES_OK,
418 LOG (GNUNET_ERROR_TYPE_DEBUG,
419 "Failing lookup (postgres error)\n");
420 return GNUNET_SYSERR;
422 if (0 == (cnt = PQntuples (res)))
425 LOG (GNUNET_ERROR_TYPE_DEBUG,
426 "Ending iteration (no more results)\n");
430 GNUNET_assert (1 == cnt);
431 GNUNET_assert (1 != PQnfields (res));
432 bsize = PQgetlength (res, 0, 0);
433 block = (const struct GNUNET_NAMESTORE_Block *) PQgetvalue (res, 0, 0);
434 if ( (bsize < sizeof (*block)) ||
435 (bsize != ntohl (block->purpose.size) +
436 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
437 sizeof (struct GNUNET_CRYPTO_EcdsaSignature)) )
440 LOG (GNUNET_ERROR_TYPE_DEBUG,
441 "Failing lookup (corrupt block)\n");
443 return GNUNET_SYSERR;
445 iter (iter_cls, block);
452 * Store a record in the datastore. Removes any existing record in the
453 * same zone with the same name.
455 * @param cls closure (internal context for the plugin)
456 * @param zone_key private key of the zone
457 * @param label name that is being mapped (at most 255 characters long)
458 * @param rd_count number of entries in @a rd array
459 * @param rd array of records with data to store
460 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
463 namestore_postgres_store_records (void *cls,
464 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
466 unsigned int rd_count,
467 const struct GNUNET_NAMESTORE_RecordData *rd)
469 struct Plugin *plugin = cls;
470 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
472 uint32_t rd_count_nbo = htonl ((uint32_t) rd_count);
476 memset (&pkey, 0, sizeof (pkey));
477 for (i=0;i<rd_count;i++)
478 if (GNUNET_NAMESTORE_TYPE_PKEY == rd[i].record_type)
480 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) == rd[i].data_size);
486 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
487 data_size = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
488 if (data_size > 64 * 65536)
491 return GNUNET_SYSERR;
494 char data[data_size];
495 const char *paramValues[] = {
496 (const char *) zone_key,
497 (const char *) &pkey,
498 (const char *) &rvalue,
499 (const char *) &rd_count_nbo,
503 int paramLengths[] = {
507 sizeof (rd_count_nbo),
511 const int paramFormats[] = { 1, 1, 1, 1, 1, 1 };
514 if (data_size != GNUNET_NAMESTORE_records_serialize (rd_count, rd,
518 return GNUNET_SYSERR;
522 PQexecPrepared (plugin->dbh, "store_records", 6,
523 paramValues, paramLengths, paramFormats, 1);
525 GNUNET_POSTGRES_check_result (plugin->dbh,
530 return GNUNET_SYSERR;
538 * A statement has been run. We should evaluate the result, and if possible
539 * call the given @a iter with the result.
541 * @param plugin plugin context
542 * @param res result from the statement that was run (to be cleaned up)
543 * @param zone_key private key of the zone, could be NULL, in which case we should
544 * get the zone from @a res
545 * @param iter iterator to call with the result
546 * @param iter_cls closure for @a iter
547 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
550 get_record_and_call_iterator (struct Plugin *plugin,
552 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
553 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
557 uint32_t record_count;
563 GNUNET_POSTGRES_check_result (plugin->dbh, res, PGRES_TUPLES_OK,
567 LOG (GNUNET_ERROR_TYPE_DEBUG,
568 "Failing lookup (postgres error)\n");
569 return GNUNET_SYSERR;
571 if (0 == (cnt = PQntuples (res)))
574 LOG (GNUNET_ERROR_TYPE_DEBUG,
575 "Ending iteration (no more results)\n");
579 GNUNET_assert (1 == cnt);
580 GNUNET_assert (3 + ((NULL == zone_key) ? 1 : 0) == PQnfields (res));
581 if (NULL == zone_key)
583 if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) != PQgetlength (res, 0, 3))
587 return GNUNET_SYSERR;
589 zone_key = (const struct GNUNET_CRYPTO_EcdsaPrivateKey *) PQgetvalue (res, 0, 3);
591 if (sizeof (uint32_t) != PQfsize (res, 0))
595 return GNUNET_SYSERR;
598 record_count = ntohl (*(uint32_t *) PQgetvalue (res, 0, 0));
599 data = PQgetvalue (res, 0, 1);
600 data_size = PQgetlength (res, 0, 1);
601 label = PQgetvalue (res, 0, 2);
602 label_len = PQgetlength (res, 0, 1);
603 if (record_count > 64 * 1024)
605 /* sanity check, don't stack allocate far too much just
606 because database might contain a large value here */
609 return GNUNET_SYSERR;
612 struct GNUNET_NAMESTORE_RecordData rd[record_count];
613 char buf[label_len + 1];
615 memcpy (buf, label, label_len);
616 buf[label_len] = '\0';
618 GNUNET_NAMESTORE_records_deserialize (data_size, data,
623 return GNUNET_SYSERR;
625 iter (iter_cls, zone_key, buf, record_count, rd);
633 * Iterate over the results for a particular key and zone in the
634 * datastore. Will return at most one result to the iterator.
636 * @param cls closure (internal context for the plugin)
637 * @param zone hash of public key of the zone, NULL to iterate over all zones
638 * @param offset offset in the list of all matching records
639 * @param iter function to call with the result
640 * @param iter_cls closure for @a iter
641 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
644 namestore_postgres_iterate_records (void *cls,
645 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
647 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
649 struct Plugin *plugin = cls;
650 uint64_t offset_be = GNUNET_htonll (offset);
654 const char *paramValues[] = {
655 (const char *) &offset_be
657 int paramLengths[] = {
660 const int paramFormats[] = { 1 };
663 res = PQexecPrepared (plugin->dbh,
664 "iterate_all_zones", 1,
665 paramValues, paramLengths, paramFormats,
667 return get_record_and_call_iterator (plugin,
674 const char *paramValues[] = {
676 (const char *) &offset_be
678 int paramLengths[] = {
682 const int paramFormats[] = { 1, 1 };
685 res = PQexecPrepared (plugin->dbh,
687 paramValues, paramLengths, paramFormats,
689 return get_record_and_call_iterator (plugin,
698 * Look for an existing PKEY delegation record for a given public key.
699 * Returns at most one result to the iterator.
701 * @param cls closure (internal context for the plugin)
702 * @param zone private key of the zone to look up in, never NULL
703 * @param value_zone public key of the target zone (value), never NULL
704 * @param iter function to call with the result
705 * @param iter_cls closure for @a iter
706 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
709 namestore_postgres_zone_to_name (void *cls,
710 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
711 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
712 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
714 struct Plugin *plugin = cls;
715 const char *paramValues[] = {
717 (const char *) value_zone
719 int paramLengths[] = {
723 const int paramFormats[] = { 1, 1 };
726 res = PQexecPrepared (plugin->dbh,
728 paramValues, paramLengths, paramFormats,
730 return get_record_and_call_iterator (plugin,
738 * Shutdown database connection and associate data
741 * @param plugin the plugin context (state for this module)
744 database_shutdown (struct Plugin *plugin)
746 PQfinish (plugin->dbh);
752 * Entry point for the plugin.
754 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
755 * @return NULL on error, othrewise the plugin context
758 libgnunet_plugin_namestore_postgres_init (void *cls)
760 static struct Plugin plugin;
761 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
762 struct GNUNET_NAMESTORE_PluginFunctions *api;
764 if (NULL != plugin.cfg)
765 return NULL; /* can only initialize once! */
766 memset (&plugin, 0, sizeof (struct Plugin));
768 if (GNUNET_OK != database_setup (&plugin))
770 database_shutdown (&plugin);
773 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
775 api->cache_block = &namestore_postgres_cache_block;
776 api->lookup_block = &namestore_postgres_lookup_block;
777 api->store_records = &namestore_postgres_store_records;
778 api->iterate_records = &namestore_postgres_iterate_records;
779 api->zone_to_name = &namestore_postgres_zone_to_name;
780 LOG (GNUNET_ERROR_TYPE_INFO,
781 _("Postgres database running\n"));
787 * Exit point from the plugin.
789 * @param cls the plugin context (as returned by "init")
790 * @return always NULL
793 libgnunet_plugin_namestore_postgres_done (void *cls)
795 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
796 struct Plugin *plugin = api->cls;
798 database_shutdown (plugin);
801 LOG (GNUNET_ERROR_TYPE_DEBUG,
802 "postgres plugin is finished\n");
806 /* end of plugin_namestore_postgres.c */