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.
45 const struct GNUNET_CONFIGURATION_Handle *cfg;
48 * Postgres database handle.
50 struct GNUNET_PQ_Context *dbh;
55 * Initialize the database connections and associated
56 * data structures (create tables and indices
59 * @param plugin the plugin context (state for this module)
60 * @return #GNUNET_OK on success
63 database_setup (struct Plugin *plugin)
65 struct GNUNET_PQ_ExecuteStatement es_temporary =
66 GNUNET_PQ_make_execute (
67 "CREATE TEMPORARY TABLE IF NOT EXISTS ns098records ("
68 " seq BIGSERIAL PRIMARY KEY,"
69 " zone_private_key BYTEA NOT NULL DEFAULT '',"
70 " pkey BYTEA DEFAULT '',"
71 " rvalue BYTEA NOT NULL DEFAULT '',"
72 " record_count INTEGER NOT NULL DEFAULT 0,"
73 " record_data BYTEA NOT NULL DEFAULT '',"
74 " label TEXT NOT NULL DEFAULT '',"
75 " CONSTRAINT zl UNIQUE (zone_private_key,label)"
78 struct GNUNET_PQ_ExecuteStatement es_default =
79 GNUNET_PQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records ("
80 " seq BIGSERIAL PRIMARY KEY,"
81 " zone_private_key BYTEA NOT NULL DEFAULT '',"
82 " pkey BYTEA DEFAULT '',"
83 " rvalue BYTEA NOT NULL DEFAULT '',"
84 " record_count INTEGER NOT NULL DEFAULT 0,"
85 " record_data BYTEA NOT NULL DEFAULT '',"
86 " label TEXT NOT NULL DEFAULT '',"
87 " CONSTRAINT zl UNIQUE (zone_private_key,label)"
90 const struct GNUNET_PQ_ExecuteStatement *cr;
91 struct GNUNET_PQ_ExecuteStatement sc = GNUNET_PQ_EXECUTE_STATEMENT_END;
94 GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
106 GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
107 "namestore-postgres",
109 sc = GNUNET_PQ_make_try_execute ("SET synchronous_commit TO off");
112 struct GNUNET_PQ_ExecuteStatement es[] = {
114 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
115 "ON ns098records (zone_private_key,pkey)"),
116 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
117 "ON ns098records (zone_private_key,seq)"),
118 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_label "
119 "ON ns098records (label)"),
120 GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS zone_label "
121 "ON ns098records (zone_private_key,label)"),
123 GNUNET_PQ_EXECUTE_STATEMENT_END
125 struct GNUNET_PQ_PreparedStatement ps[] = {
126 GNUNET_PQ_make_prepare ("store_records",
127 "INSERT INTO ns098records"
128 " (zone_private_key, pkey, rvalue, record_count, record_data, label)"
129 " VALUES ($1, $2, $3, $4, $5, $6)"
130 " ON CONFLICT ON CONSTRAINT zl"
132 " SET pkey=$2,rvalue=$3,record_count=$4,record_data=$5"
133 " WHERE ns098records.zone_private_key = $1"
134 " AND ns098records.label = $6",
136 GNUNET_PQ_make_prepare ("delete_records",
137 "DELETE FROM ns098records "
138 "WHERE zone_private_key=$1 AND label=$2",
140 GNUNET_PQ_make_prepare ("zone_to_name",
141 "SELECT seq,record_count,record_data,label FROM ns098records"
142 " WHERE zone_private_key=$1 AND pkey=$2",
144 GNUNET_PQ_make_prepare ("iterate_zone",
145 "SELECT seq,record_count,record_data,label FROM ns098records "
146 "WHERE zone_private_key=$1 AND seq > $2 ORDER BY seq ASC LIMIT $3",
148 GNUNET_PQ_make_prepare ("iterate_all_zones",
149 "SELECT seq,record_count,record_data,label,zone_private_key"
150 " FROM ns098records WHERE seq > $1 ORDER BY seq ASC LIMIT $2",
152 GNUNET_PQ_make_prepare ("lookup_label",
153 "SELECT seq,record_count,record_data,label "
154 "FROM ns098records WHERE zone_private_key=$1 AND label=$2",
156 GNUNET_PQ_PREPARED_STATEMENT_END
159 plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->cfg,
160 "namestore-postgres",
164 if (NULL == plugin->dbh)
165 return GNUNET_SYSERR;
171 * Store a record in the datastore. Removes any existing record in the
172 * same zone with the same name.
174 * @param cls closure (internal context for the plugin)
175 * @param zone_key private key of the zone
176 * @param label name that is being mapped (at most 255 characters long)
177 * @param rd_count number of entries in @a rd array
178 * @param rd array of records with data to store
179 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
182 namestore_postgres_store_records (void *cls,
184 GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
186 unsigned int rd_count,
187 const struct GNUNET_GNSRECORD_Data *rd)
189 struct Plugin *plugin = cls;
190 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
192 uint32_t rd_count32 = (uint32_t) rd_count;
198 for (unsigned int i = 0; i < rd_count; i++)
199 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
201 GNUNET_break (sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) ==
203 GNUNET_memcpy (&pkey,
208 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
210 data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
215 return GNUNET_SYSERR;
217 if (data_size >= UINT16_MAX)
220 return GNUNET_SYSERR;
222 /* if record set is empty, delete existing records */
225 struct GNUNET_PQ_QueryParam params[] = {
226 GNUNET_PQ_query_param_auto_from_type (zone_key),
227 GNUNET_PQ_query_param_string (label),
228 GNUNET_PQ_query_param_end
230 enum GNUNET_DB_QueryStatus res;
232 res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh,
235 if ((GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res) &&
236 (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS != res))
239 return GNUNET_SYSERR;
241 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
246 /* otherwise, UPSERT (i.e. UPDATE if exists, otherwise INSERT) */
248 char data[data_size];
249 struct GNUNET_PQ_QueryParam params[] = {
250 GNUNET_PQ_query_param_auto_from_type (zone_key),
251 GNUNET_PQ_query_param_auto_from_type (&pkey),
252 GNUNET_PQ_query_param_uint64 (&rvalue),
253 GNUNET_PQ_query_param_uint32 (&rd_count32),
254 GNUNET_PQ_query_param_fixed_size (data, data_size),
255 GNUNET_PQ_query_param_string (label),
256 GNUNET_PQ_query_param_end
258 enum GNUNET_DB_QueryStatus res;
261 ret = GNUNET_GNSRECORD_records_serialize (rd_count,
269 return GNUNET_SYSERR;
272 res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh,
275 if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res)
276 return GNUNET_SYSERR;
283 * Closure for #parse_result_call_iterator.
288 * Function to call for each result.
290 GNUNET_NAMESTORE_RecordIterator iter;
293 * Closure for @e iter.
298 * Zone key, NULL if part of record.
300 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key;
303 * Number of results still to return (counted down by
304 * number of results given to iterator).
311 * A statement has been run. We should evaluate the result, and if possible
312 * call the @a iter in @a cls with the result.
314 * @param cls closure of type `struct ParserContext *`
315 * @param result the postgres result
316 * @param num_result the number of results in @a result
319 parse_result_call_iterator (void *cls,
321 unsigned int num_results)
323 struct ParserContext *pc = cls;
325 if (NULL == pc->iter)
326 return; /* no need to do more work */
327 for (unsigned int i = 0; i < num_results; i++)
332 uint32_t record_count;
334 struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
335 struct GNUNET_PQ_ResultSpec rs_with_zone[] = {
336 GNUNET_PQ_result_spec_uint64 ("seq", &serial),
337 GNUNET_PQ_result_spec_uint32 ("record_count", &record_count),
338 GNUNET_PQ_result_spec_variable_size ("record_data", &data, &data_size),
339 GNUNET_PQ_result_spec_string ("label", &label),
340 GNUNET_PQ_result_spec_auto_from_type ("zone_private_key", &zk),
341 GNUNET_PQ_result_spec_end
343 struct GNUNET_PQ_ResultSpec rs_without_zone[] = {
344 GNUNET_PQ_result_spec_uint64 ("seq", &serial),
345 GNUNET_PQ_result_spec_uint32 ("record_count", &record_count),
346 GNUNET_PQ_result_spec_variable_size ("record_data", &data, &data_size),
347 GNUNET_PQ_result_spec_string ("label", &label),
348 GNUNET_PQ_result_spec_end
350 struct GNUNET_PQ_ResultSpec *rs;
352 rs = (NULL == pc->zone_key) ? rs_with_zone : rs_without_zone;
354 GNUNET_PQ_extract_result (res,
362 if (record_count > 64 * 1024)
364 /* sanity check, don't stack allocate far too much just
365 because database might contain a large value here */
367 GNUNET_PQ_cleanup_result (rs);
372 struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL (record_count)];
374 GNUNET_assert (0 != serial);
376 GNUNET_GNSRECORD_records_deserialize (data_size,
382 GNUNET_PQ_cleanup_result (rs);
385 pc->iter (pc->iter_cls,
387 (NULL == pc->zone_key) ? &zk : pc->zone_key,
392 GNUNET_PQ_cleanup_result (rs);
394 pc->limit -= num_results;
399 * Lookup records in the datastore for which we are the authority.
401 * @param cls closure (internal context for the plugin)
402 * @param zone private key of the zone
403 * @param label name of the record in the zone
404 * @param iter function to call with the result
405 * @param iter_cls closure for @a iter
406 * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
409 namestore_postgres_lookup_records (void *cls,
411 GNUNET_CRYPTO_EcdsaPrivateKey *zone,
413 GNUNET_NAMESTORE_RecordIterator iter,
416 struct Plugin *plugin = cls;
417 struct GNUNET_PQ_QueryParam params[] = {
418 GNUNET_PQ_query_param_auto_from_type (zone),
419 GNUNET_PQ_query_param_string (label),
420 GNUNET_PQ_query_param_end
422 struct ParserContext pc;
423 enum GNUNET_DB_QueryStatus res;
428 return GNUNET_SYSERR;
431 pc.iter_cls = iter_cls;
433 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
436 &parse_result_call_iterator,
439 return GNUNET_SYSERR;
440 if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res)
447 * Iterate over the results for a particular key and zone in the
448 * datastore. Will return at most one result to the iterator.
450 * @param cls closure (internal context for the plugin)
451 * @param zone hash of public key of the zone, NULL to iterate over all zones
452 * @param serial serial number to exclude in the list of all matching records
453 * @param limit maximum number of results to fetch
454 * @param iter function to call with the result
455 * @param iter_cls closure for @a iter
456 * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
459 namestore_postgres_iterate_records (void *cls,
461 GNUNET_CRYPTO_EcdsaPrivateKey *zone,
464 GNUNET_NAMESTORE_RecordIterator iter,
467 struct Plugin *plugin = cls;
468 enum GNUNET_DB_QueryStatus res;
469 struct ParserContext pc;
472 pc.iter_cls = iter_cls;
477 struct GNUNET_PQ_QueryParam params_without_zone[] = {
478 GNUNET_PQ_query_param_uint64 (&serial),
479 GNUNET_PQ_query_param_uint64 (&limit),
480 GNUNET_PQ_query_param_end
483 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
486 &parse_result_call_iterator,
491 struct GNUNET_PQ_QueryParam params_with_zone[] = {
492 GNUNET_PQ_query_param_auto_from_type (zone),
493 GNUNET_PQ_query_param_uint64 (&serial),
494 GNUNET_PQ_query_param_uint64 (&limit),
495 GNUNET_PQ_query_param_end
498 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
501 &parse_result_call_iterator,
505 return GNUNET_SYSERR;
507 if ((GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) ||
515 * Look for an existing PKEY delegation record for a given public key.
516 * Returns at most one result to the iterator.
518 * @param cls closure (internal context for the plugin)
519 * @param zone private key of the zone to look up in, never NULL
520 * @param value_zone public key of the target zone (value), never NULL
521 * @param iter function to call with the result
522 * @param iter_cls closure for @a iter
523 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
526 namestore_postgres_zone_to_name (void *cls,
528 GNUNET_CRYPTO_EcdsaPrivateKey *zone,
530 GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
531 GNUNET_NAMESTORE_RecordIterator iter,
534 struct Plugin *plugin = cls;
535 struct GNUNET_PQ_QueryParam params[] = {
536 GNUNET_PQ_query_param_auto_from_type (zone),
537 GNUNET_PQ_query_param_auto_from_type (value_zone),
538 GNUNET_PQ_query_param_end
540 enum GNUNET_DB_QueryStatus res;
541 struct ParserContext pc;
544 pc.iter_cls = iter_cls;
546 res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
549 &parse_result_call_iterator,
552 return GNUNET_SYSERR;
558 * Shutdown database connection and associate data
561 * @param plugin the plugin context (state for this module)
564 database_shutdown (struct Plugin *plugin)
566 GNUNET_PQ_disconnect (plugin->dbh);
572 * Entry point for the plugin.
574 * @param cls the `struct GNUNET_NAMESTORE_PluginEnvironment*`
575 * @return NULL on error, othrewise the plugin context
578 libgnunet_plugin_namestore_postgres_init (void *cls)
580 static struct Plugin plugin;
581 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
582 struct GNUNET_NAMESTORE_PluginFunctions *api;
584 if (NULL != plugin.cfg)
585 return NULL; /* can only initialize once! */
586 memset (&plugin, 0, sizeof(struct Plugin));
588 if (GNUNET_OK != database_setup (&plugin))
590 database_shutdown (&plugin);
593 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
595 api->store_records = &namestore_postgres_store_records;
596 api->iterate_records = &namestore_postgres_iterate_records;
597 api->zone_to_name = &namestore_postgres_zone_to_name;
598 api->lookup_records = &namestore_postgres_lookup_records;
599 LOG (GNUNET_ERROR_TYPE_INFO,
600 "Postgres namestore plugin running\n");
606 * Exit point from the plugin.
608 * @param cls the plugin context (as returned by "init")
609 * @return always NULL
612 libgnunet_plugin_namestore_postgres_done (void *cls)
614 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
615 struct Plugin *plugin = api->cls;
617 database_shutdown (plugin);
620 LOG (GNUNET_ERROR_TYPE_DEBUG,
621 "Postgres namestore plugin is finished\n");
626 /* end of plugin_namestore_postgres.c */