2 * This file is part of GNUnet
3 * Copyright (C) 2009-2013, 2016-2018 GNUnet e.V.
5 * GNUnet is free software: you can redistribute it and/or modify it
6 * under the terms of the GNU Affero General Public License as published
7 * by the Free Software Foundation, either version 3 of the License,
8 * or (at your 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 * Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
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_gnsrecord_lib.h"
30 #include "gnunet_pq_lib.h"
31 #include "namestore.h"
34 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-postgres", __VA_ARGS__)
38 * Context for all functions in this plugin.
46 const struct GNUNET_CONFIGURATION_Handle *cfg;
49 * Native Postgres database handle.
57 * Initialize the database connections and associated
58 * data structures (create tables and indices
61 * @param plugin the plugin context (state for this module)
62 * @return #GNUNET_OK on success
65 database_setup (struct Plugin *plugin)
67 struct GNUNET_PQ_ExecuteStatement es_temporary =
68 GNUNET_PQ_make_execute ("CREATE TEMPORARY TABLE IF NOT EXISTS ns098records ("
69 " seq BIGSERIAL PRIMARY KEY,"
70 " zone_private_key BYTEA NOT NULL DEFAULT '',"
71 " pkey BYTEA DEFAULT '',"
72 " rvalue BYTEA NOT NULL DEFAULT '',"
73 " record_count INTEGER NOT NULL DEFAULT 0,"
74 " record_data BYTEA NOT NULL DEFAULT '',"
75 " label TEXT NOT NULL DEFAULT '',"
76 " CONSTRAINT zl UNIQUE (zone_private_key,label)"
79 struct GNUNET_PQ_ExecuteStatement es_default =
80 GNUNET_PQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records ("
81 " seq BIGSERIAL PRIMARY KEY,"
82 " zone_private_key BYTEA NOT NULL DEFAULT '',"
83 " pkey BYTEA DEFAULT '',"
84 " rvalue BYTEA NOT NULL DEFAULT '',"
85 " record_count INTEGER NOT NULL DEFAULT 0,"
86 " record_data BYTEA NOT NULL DEFAULT '',"
87 " label TEXT NOT NULL DEFAULT '',"
88 " CONSTRAINT zl UNIQUE (zone_private_key,label)"
91 const struct GNUNET_PQ_ExecuteStatement *cr;
93 plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->cfg,
94 "namestore-postgres");
95 if (NULL == plugin->dbh)
98 GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
102 struct GNUNET_PQ_ExecuteStatement es[] = {
103 GNUNET_PQ_make_try_execute ("SET synchronous_commit TO off"),
104 GNUNET_PQ_EXECUTE_STATEMENT_END
108 GNUNET_PQ_exec_statements (plugin->dbh,
111 PQfinish (plugin->dbh);
113 return GNUNET_SYSERR;
117 GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
118 "namestore-postgres",
129 struct GNUNET_PQ_ExecuteStatement es[] = {
131 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
132 "ON ns098records (zone_private_key,pkey)"),
133 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
134 "ON ns098records (zone_private_key,seq)"),
135 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_label "
136 "ON ns098records (label)"),
137 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS zone_label "
138 "ON ns098records (zone_private_key,label)"),
139 GNUNET_PQ_EXECUTE_STATEMENT_END
143 GNUNET_PQ_exec_statements (plugin->dbh,
146 PQfinish (plugin->dbh);
148 return GNUNET_SYSERR;
153 struct GNUNET_PQ_PreparedStatement ps[] = {
154 GNUNET_PQ_make_prepare ("store_records",
155 "INSERT INTO ns098records"
156 " (zone_private_key, pkey, rvalue, record_count, record_data, label)"
157 " VALUES ($1, $2, $3, $4, $5, $6)"
158 " ON CONFLICT ON CONSTRAINT zl"
160 " SET pkey=$2,rvalue=$3,record_count=$4,record_data=$5"
161 " WHERE ns098records.zone_private_key = $1"
162 " AND ns098records.label = $6",
164 GNUNET_PQ_make_prepare ("delete_records",
165 "DELETE FROM ns098records "
166 "WHERE zone_private_key=$1 AND label=$2",
168 GNUNET_PQ_make_prepare ("zone_to_name",
169 "SELECT seq,record_count,record_data,label FROM ns098records"
170 " WHERE zone_private_key=$1 AND pkey=$2",
172 GNUNET_PQ_make_prepare ("iterate_zone",
173 "SELECT seq,record_count,record_data,label FROM ns098records "
174 "WHERE zone_private_key=$1 AND seq > $2 ORDER BY seq ASC LIMIT $3",
176 GNUNET_PQ_make_prepare ("iterate_all_zones",
177 "SELECT seq,record_count,record_data,label,zone_private_key"
178 " FROM ns098records WHERE seq > $1 ORDER BY seq ASC LIMIT $2",
180 GNUNET_PQ_make_prepare ("lookup_label",
181 "SELECT seq,record_count,record_data,label "
182 "FROM ns098records WHERE zone_private_key=$1 AND label=$2",
184 GNUNET_PQ_PREPARED_STATEMENT_END
188 GNUNET_PQ_prepare_statements (plugin->dbh,
191 PQfinish (plugin->dbh);
193 return GNUNET_SYSERR;
202 * Store a record in the datastore. Removes any existing record in the
203 * same zone with the same name.
205 * @param cls closure (internal context for the plugin)
206 * @param zone_key private key of the zone
207 * @param label name that is being mapped (at most 255 characters long)
208 * @param rd_count number of entries in @a rd array
209 * @param rd array of records with data to store
210 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
213 namestore_postgres_store_records (void *cls,
214 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
216 unsigned int rd_count,
217 const struct GNUNET_GNSRECORD_Data *rd)
219 struct Plugin *plugin = cls;
220 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
222 uint32_t rd_count32 = (uint32_t) rd_count;
228 for (unsigned int i=0;i<rd_count;i++)
229 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
231 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) == rd[i].data_size);
232 GNUNET_memcpy (&pkey,
237 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
239 data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
244 return GNUNET_SYSERR;
246 if (data_size >= UINT16_MAX)
249 return GNUNET_SYSERR;
251 /* if record set is empty, delete existing records */
254 struct GNUNET_PQ_QueryParam params[] = {
255 GNUNET_PQ_query_param_auto_from_type (zone_key),
256 GNUNET_PQ_query_param_string (label),
257 GNUNET_PQ_query_param_end
259 enum GNUNET_DB_QueryStatus res;
261 res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh,
264 if ( (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res) &&
265 (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS != res) )
268 return GNUNET_SYSERR;
270 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
275 /* otherwise, UPSERT (i.e. UPDATE if exists, otherwise INSERT) */
277 char data[data_size];
278 struct GNUNET_PQ_QueryParam params[] = {
279 GNUNET_PQ_query_param_auto_from_type (zone_key),
280 GNUNET_PQ_query_param_auto_from_type (&pkey),
281 GNUNET_PQ_query_param_uint64 (&rvalue),
282 GNUNET_PQ_query_param_uint32 (&rd_count32),
283 GNUNET_PQ_query_param_fixed_size (data, data_size),
284 GNUNET_PQ_query_param_string (label),
285 GNUNET_PQ_query_param_end
287 enum GNUNET_DB_QueryStatus res;
290 ret = GNUNET_GNSRECORD_records_serialize (rd_count,
298 return GNUNET_SYSERR;
301 res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh,
304 if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res)
305 return GNUNET_SYSERR;
312 * Closure for #parse_result_call_iterator.
317 * Function to call for each result.
319 GNUNET_NAMESTORE_RecordIterator iter;
322 * Closure for @e iter.
327 * Zone key, NULL if part of record.
329 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key;
332 * Number of results still to return (counted down by
333 * number of results given to iterator).
340 * A statement has been run. We should evaluate the result, and if possible
341 * call the @a iter in @a cls with the result.
343 * @param cls closure of type `struct ParserContext *`
344 * @param result the postgres result
345 * @param num_result the number of results in @a result
348 parse_result_call_iterator (void *cls,
350 unsigned int num_results)
352 struct ParserContext *pc = cls;
354 if (NULL == pc->iter)
355 return; /* no need to do more work */
356 for (unsigned int i=0;i<num_results;i++)
361 uint32_t record_count;
363 struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
364 struct GNUNET_PQ_ResultSpec rs_with_zone[] = {
365 GNUNET_PQ_result_spec_uint64 ("seq", &serial),
366 GNUNET_PQ_result_spec_uint32 ("record_count", &record_count),
367 GNUNET_PQ_result_spec_variable_size ("record_data", &data, &data_size),
368 GNUNET_PQ_result_spec_string ("label", &label),
369 GNUNET_PQ_result_spec_auto_from_type ("zone_private_key", &zk),
370 GNUNET_PQ_result_spec_end
372 struct GNUNET_PQ_ResultSpec rs_without_zone[] = {
373 GNUNET_PQ_result_spec_uint64 ("seq", &serial),
374 GNUNET_PQ_result_spec_uint32 ("record_count", &record_count),
375 GNUNET_PQ_result_spec_variable_size ("record_data", &data, &data_size),
376 GNUNET_PQ_result_spec_string ("label", &label),
377 GNUNET_PQ_result_spec_end
379 struct GNUNET_PQ_ResultSpec *rs;
381 rs = (NULL == pc->zone_key) ? rs_with_zone : rs_without_zone;
383 GNUNET_PQ_extract_result (res,
391 if (record_count > 64 * 1024)
393 /* sanity check, don't stack allocate far too much just
394 because database might contain a large value here */
396 GNUNET_PQ_cleanup_result (rs);
401 struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(record_count)];
403 GNUNET_assert (0 != serial);
405 GNUNET_GNSRECORD_records_deserialize (data_size,
411 GNUNET_PQ_cleanup_result (rs);
414 pc->iter (pc->iter_cls,
416 (NULL == pc->zone_key) ? &zk : pc->zone_key,
421 GNUNET_PQ_cleanup_result (rs);
423 pc->limit -= num_results;
428 * Lookup records in the datastore for which we are the authority.
430 * @param cls closure (internal context for the plugin)
431 * @param zone private key of the zone
432 * @param label name of the record in the zone
433 * @param iter function to call with the result
434 * @param iter_cls closure for @a iter
435 * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
438 namestore_postgres_lookup_records (void *cls,
439 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
441 GNUNET_NAMESTORE_RecordIterator iter,
444 struct Plugin *plugin = cls;
445 struct GNUNET_PQ_QueryParam params[] = {
446 GNUNET_PQ_query_param_auto_from_type (zone),
447 GNUNET_PQ_query_param_string (label),
448 GNUNET_PQ_query_param_end
450 struct ParserContext pc;
451 enum GNUNET_DB_QueryStatus res;
456 return GNUNET_SYSERR;
459 pc.iter_cls = iter_cls;
461 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
464 &parse_result_call_iterator,
467 return GNUNET_SYSERR;
468 if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res)
475 * Iterate over the results for a particular key and zone in the
476 * datastore. Will return at most one result to the iterator.
478 * @param cls closure (internal context for the plugin)
479 * @param zone hash of public key of the zone, NULL to iterate over all zones
480 * @param serial serial number to exclude in the list of all matching records
481 * @param limit maximum number of results to fetch
482 * @param iter function to call with the result
483 * @param iter_cls closure for @a iter
484 * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
487 namestore_postgres_iterate_records (void *cls,
488 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
491 GNUNET_NAMESTORE_RecordIterator iter,
494 struct Plugin *plugin = cls;
495 enum GNUNET_DB_QueryStatus res;
496 struct ParserContext pc;
499 pc.iter_cls = iter_cls;
504 struct GNUNET_PQ_QueryParam params_without_zone[] = {
505 GNUNET_PQ_query_param_uint64 (&serial),
506 GNUNET_PQ_query_param_uint64 (&limit),
507 GNUNET_PQ_query_param_end
510 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
513 &parse_result_call_iterator,
518 struct GNUNET_PQ_QueryParam params_with_zone[] = {
519 GNUNET_PQ_query_param_auto_from_type (zone),
520 GNUNET_PQ_query_param_uint64 (&serial),
521 GNUNET_PQ_query_param_uint64 (&limit),
522 GNUNET_PQ_query_param_end
525 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
528 &parse_result_call_iterator,
532 return GNUNET_SYSERR;
534 if ( (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) ||
542 * Look for an existing PKEY delegation record for a given public key.
543 * Returns at most one result to the iterator.
545 * @param cls closure (internal context for the plugin)
546 * @param zone private key of the zone to look up in, never NULL
547 * @param value_zone public key of the target zone (value), never NULL
548 * @param iter function to call with the result
549 * @param iter_cls closure for @a iter
550 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
553 namestore_postgres_zone_to_name (void *cls,
554 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
555 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
556 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
558 struct Plugin *plugin = cls;
559 struct GNUNET_PQ_QueryParam params[] = {
560 GNUNET_PQ_query_param_auto_from_type (zone),
561 GNUNET_PQ_query_param_auto_from_type (value_zone),
562 GNUNET_PQ_query_param_end
564 enum GNUNET_DB_QueryStatus res;
565 struct ParserContext pc;
568 pc.iter_cls = iter_cls;
570 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
573 &parse_result_call_iterator,
576 return GNUNET_SYSERR;
582 * Shutdown database connection and associate data
585 * @param plugin the plugin context (state for this module)
588 database_shutdown (struct Plugin *plugin)
590 PQfinish (plugin->dbh);
596 * Entry point for the plugin.
598 * @param cls the `struct GNUNET_NAMESTORE_PluginEnvironment*`
599 * @return NULL on error, othrewise the plugin context
602 libgnunet_plugin_namestore_postgres_init (void *cls)
604 static struct Plugin plugin;
605 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
606 struct GNUNET_NAMESTORE_PluginFunctions *api;
608 if (NULL != plugin.cfg)
609 return NULL; /* can only initialize once! */
610 memset (&plugin, 0, sizeof (struct Plugin));
612 if (GNUNET_OK != database_setup (&plugin))
614 database_shutdown (&plugin);
617 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
619 api->store_records = &namestore_postgres_store_records;
620 api->iterate_records = &namestore_postgres_iterate_records;
621 api->zone_to_name = &namestore_postgres_zone_to_name;
622 api->lookup_records = &namestore_postgres_lookup_records;
623 LOG (GNUNET_ERROR_TYPE_INFO,
624 "Postgres namestore plugin running\n");
630 * Exit point from the plugin.
632 * @param cls the plugin context (as returned by "init")
633 * @return always NULL
636 libgnunet_plugin_namestore_postgres_done (void *cls)
638 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
639 struct Plugin *plugin = api->cls;
641 database_shutdown (plugin);
644 LOG (GNUNET_ERROR_TYPE_DEBUG,
645 "Postgres namestore plugin is finished\n");
649 /* end of plugin_namestore_postgres.c */