2 * This file is part of GNUnet
3 * Copyright (C) 2009-2017 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_sqlite.c
23 * @brief sqlite-based namestore backend
24 * @author Christian Grothoff
28 #include "gnunet_namestore_plugin.h"
29 #include "gnunet_namestore_service.h"
30 #include "gnunet_gnsrecord_lib.h"
31 #include "gnunet_sq_lib.h"
32 #include "namestore.h"
36 * After how many ms "busy" should a DB operation fail for good? A
37 * low value makes sure that we are more responsive to requests
38 * (especially PUTs). A high value guarantees a higher success rate
39 * (SELECTs in iterate can take several seconds despite LIMIT=1).
41 * The default value of 1s should ensure that users do not experience
42 * huge latencies while at the same time allowing operations to
43 * succeed with reasonable probability.
45 #define BUSY_TIMEOUT_MS 1000
49 * Log an error message at log-level 'level' that indicates
50 * a failure of the command 'cmd' on file 'filename'
51 * with the message given by strerror(errno).
53 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from(level, "namestore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while (0)
55 #define LOG(kind, ...) GNUNET_log_from(kind, "namestore-sqlite", __VA_ARGS__)
59 * Context for all functions in this plugin.
62 const struct GNUNET_CONFIGURATION_Handle *cfg;
70 * Native SQLite database handle.
75 * Precompiled SQL to store records.
77 sqlite3_stmt *store_records;
80 * Precompiled SQL to deltete existing records.
82 sqlite3_stmt *delete_records;
85 * Precompiled SQL for iterate records within a zone.
87 sqlite3_stmt *iterate_zone;
90 * Precompiled SQL for iterate all records within all zones.
92 sqlite3_stmt *iterate_all_zones;
95 * Precompiled SQL to for reverse lookup based on PKEY.
97 sqlite3_stmt *zone_to_name;
100 * Precompiled SQL to lookup records based on label.
102 sqlite3_stmt *lookup_label;
107 * Initialize the database connections and associated
108 * data structures (create tables and indices
109 * as needed as well).
111 * @param plugin the plugin context (state for this module)
112 * @return #GNUNET_OK on success
115 database_setup(struct Plugin *plugin)
117 char *sqlite_filename;
118 struct GNUNET_SQ_ExecuteStatement es[] = {
119 GNUNET_SQ_make_try_execute("PRAGMA temp_store=MEMORY"),
120 GNUNET_SQ_make_try_execute("PRAGMA synchronous=NORMAL"),
121 GNUNET_SQ_make_try_execute("PRAGMA legacy_file_format=OFF"),
122 GNUNET_SQ_make_try_execute("PRAGMA auto_vacuum=INCREMENTAL"),
123 GNUNET_SQ_make_try_execute("PRAGMA encoding=\"UTF-8\""),
124 GNUNET_SQ_make_try_execute("PRAGMA locking_mode=EXCLUSIVE"),
125 GNUNET_SQ_make_try_execute("PRAGMA journal_mode=WAL"),
126 GNUNET_SQ_make_try_execute("PRAGMA page_size=4092"),
127 GNUNET_SQ_make_execute("CREATE TABLE IF NOT EXISTS ns098records ("
128 " uid INTEGER PRIMARY KEY,"
129 " zone_private_key BLOB NOT NULL,"
131 " rvalue INT8 NOT NULL,"
132 " record_count INT NOT NULL,"
133 " record_data BLOB NOT NULL,"
134 " label TEXT NOT NULL"
136 GNUNET_SQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
137 "ON ns098records (zone_private_key,pkey)"),
138 GNUNET_SQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
139 "ON ns098records (zone_private_key,uid)"),
140 GNUNET_SQ_EXECUTE_STATEMENT_END
142 struct GNUNET_SQ_PrepareStatement ps[] = {
143 GNUNET_SQ_make_prepare("INSERT INTO ns098records "
144 "(zone_private_key,pkey,rvalue,record_count,record_data,label)"
145 " VALUES (?, ?, ?, ?, ?, ?)",
146 &plugin->store_records),
147 GNUNET_SQ_make_prepare("DELETE FROM ns098records "
148 "WHERE zone_private_key=? AND label=?",
149 &plugin->delete_records),
150 GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label"
152 " WHERE zone_private_key=? AND pkey=?",
153 &plugin->zone_to_name),
154 GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label"
156 " WHERE zone_private_key=? AND uid > ?"
159 &plugin->iterate_zone),
160 GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label,zone_private_key"
165 &plugin->iterate_all_zones),
166 GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label"
168 " WHERE zone_private_key=? AND label=?",
169 &plugin->lookup_label),
170 GNUNET_SQ_PREPARE_END
174 GNUNET_CONFIGURATION_get_value_filename(plugin->cfg,
179 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
182 return GNUNET_SYSERR;
185 GNUNET_DISK_file_test(sqlite_filename))
188 GNUNET_DISK_directory_create_for_file(sqlite_filename))
191 GNUNET_free(sqlite_filename);
192 return GNUNET_SYSERR;
195 /* sqlite_filename should be UTF-8-encoded. If it isn't, it's a bug */
196 plugin->fn = sqlite_filename;
198 /* Open database and precompile statements */
200 sqlite3_open(plugin->fn,
203 LOG(GNUNET_ERROR_TYPE_ERROR,
204 _("Unable to initialize SQLite: %s.\n"),
205 sqlite3_errmsg(plugin->dbh));
206 return GNUNET_SYSERR;
208 GNUNET_break(SQLITE_OK ==
209 sqlite3_busy_timeout(plugin->dbh,
212 GNUNET_SQ_exec_statements(plugin->dbh,
216 LOG(GNUNET_ERROR_TYPE_ERROR,
217 _("Failed to setup database at `%s'\n"),
219 return GNUNET_SYSERR;
223 GNUNET_SQ_prepare(plugin->dbh,
227 LOG(GNUNET_ERROR_TYPE_ERROR,
228 _("Failed to setup database at `%s'\n"),
230 return GNUNET_SYSERR;
237 * Shutdown database connection and associate data
239 * @param plugin the plugin context (state for this module)
242 database_shutdown(struct Plugin *plugin)
247 if (NULL != plugin->store_records)
248 sqlite3_finalize(plugin->store_records);
249 if (NULL != plugin->delete_records)
250 sqlite3_finalize(plugin->delete_records);
251 if (NULL != plugin->iterate_zone)
252 sqlite3_finalize(plugin->iterate_zone);
253 if (NULL != plugin->iterate_all_zones)
254 sqlite3_finalize(plugin->iterate_all_zones);
255 if (NULL != plugin->zone_to_name)
256 sqlite3_finalize(plugin->zone_to_name);
257 if (NULL != plugin->lookup_label)
258 sqlite3_finalize(plugin->lookup_label);
259 result = sqlite3_close(plugin->dbh);
260 if (result == SQLITE_BUSY)
262 LOG(GNUNET_ERROR_TYPE_WARNING,
263 _("Tried to close sqlite without finalizing all prepared statements.\n"));
264 stmt = sqlite3_next_stmt(plugin->dbh,
268 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG,
270 "Closing statement %p\n",
272 result = sqlite3_finalize(stmt);
273 if (result != SQLITE_OK)
274 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING,
276 "Failed to close statement %p: %d\n",
279 stmt = sqlite3_next_stmt(plugin->dbh,
282 result = sqlite3_close(plugin->dbh);
284 if (SQLITE_OK != result)
286 GNUNET_ERROR_TYPE_ERROR,
289 GNUNET_free_non_null(plugin->fn);
294 * Store a record in the datastore. Removes any existing record in the
295 * same zone with the same name.
297 * @param cls closure (internal context for the plugin)
298 * @param zone_key private key of the zone
299 * @param label name that is being mapped (at most 255 characters long)
300 * @param rd_count number of entries in @a rd array
301 * @param rd array of records with data to store
302 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
305 namestore_sqlite_store_records(void *cls,
306 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
308 unsigned int rd_count,
309 const struct GNUNET_GNSRECORD_Data *rd)
311 struct Plugin *plugin = cls;
313 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
320 for (unsigned int i = 0; i < rd_count; i++)
321 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
323 GNUNET_break(sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) ==
330 rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK,
332 data_size = GNUNET_GNSRECORD_records_get_size(rd_count,
337 return GNUNET_SYSERR;
339 if (data_size > 64 * 65536)
342 return GNUNET_SYSERR;
345 /* First delete 'old' records */
346 char data[data_size];
347 struct GNUNET_SQ_QueryParam dparams[] = {
348 GNUNET_SQ_query_param_auto_from_type(zone_key),
349 GNUNET_SQ_query_param_string(label),
350 GNUNET_SQ_query_param_end
354 ret = GNUNET_GNSRECORD_records_serialize(rd_count,
362 return GNUNET_SYSERR;
365 GNUNET_SQ_bind(plugin->delete_records,
369 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
370 "sqlite3_bind_XXXX");
371 GNUNET_SQ_reset(plugin->dbh,
372 plugin->delete_records);
373 return GNUNET_SYSERR;
375 n = sqlite3_step(plugin->delete_records);
376 GNUNET_SQ_reset(plugin->dbh,
377 plugin->delete_records);
381 uint32_t rd_count32 = (uint32_t)rd_count;
382 struct GNUNET_SQ_QueryParam sparams[] = {
383 GNUNET_SQ_query_param_auto_from_type(zone_key),
384 GNUNET_SQ_query_param_auto_from_type(&pkey),
385 GNUNET_SQ_query_param_uint64(&rvalue),
386 GNUNET_SQ_query_param_uint32(&rd_count32),
387 GNUNET_SQ_query_param_fixed_size(data, data_size),
388 GNUNET_SQ_query_param_string(label),
389 GNUNET_SQ_query_param_end
393 GNUNET_SQ_bind(plugin->store_records,
397 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
398 "sqlite3_bind_XXXX");
399 GNUNET_SQ_reset(plugin->dbh,
400 plugin->store_records);
401 return GNUNET_SYSERR;
403 n = sqlite3_step(plugin->store_records);
404 GNUNET_SQ_reset(plugin->dbh,
405 plugin->store_records);
412 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG,
416 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG,
423 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
429 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
431 return GNUNET_SYSERR;
437 * The given 'sqlite' statement has been prepared to be run.
438 * It will return a record which should be given to the iterator.
439 * Runs the statement and parses the returned record.
441 * @param plugin plugin context
442 * @param stmt to run (and then clean up)
443 * @param zone_key private key of the zone
444 * @param limit maximum number of results to fetch
445 * @param iter iterator to call with the result
446 * @param iter_cls closure for @a iter
447 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
450 get_records_and_call_iterator(struct Plugin *plugin,
452 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
454 GNUNET_NAMESTORE_RecordIterator iter,
461 for (uint64_t i = 0; i < limit; i++)
463 sret = sqlite3_step(stmt);
465 if (SQLITE_DONE == sret)
467 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
468 "Iteration done (no results)\n");
472 if (SQLITE_ROW != sret)
475 GNUNET_ERROR_TYPE_ERROR,
483 uint32_t record_count;
487 struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
488 struct GNUNET_SQ_ResultSpec rs[] = {
489 GNUNET_SQ_result_spec_uint64(&seq),
490 GNUNET_SQ_result_spec_uint32(&record_count),
491 GNUNET_SQ_result_spec_variable_size(&data,
493 GNUNET_SQ_result_spec_string(&label),
494 GNUNET_SQ_result_spec_end
496 struct GNUNET_SQ_ResultSpec rsx[] = {
497 GNUNET_SQ_result_spec_uint64(&seq),
498 GNUNET_SQ_result_spec_uint32(&record_count),
499 GNUNET_SQ_result_spec_variable_size(&data,
501 GNUNET_SQ_result_spec_string(&label),
502 GNUNET_SQ_result_spec_auto_from_type(&zk),
503 GNUNET_SQ_result_spec_end
506 ret = GNUNET_SQ_extract_result(stmt,
510 if ((GNUNET_OK != ret) ||
511 (record_count > 64 * 1024))
513 /* sanity check, don't stack allocate far too much just
514 because database might contain a large value here */
521 struct GNUNET_GNSRECORD_Data rd[record_count];
523 GNUNET_assert(0 != seq);
525 GNUNET_GNSRECORD_records_deserialize(data_size,
536 if (NULL != zone_key)
547 GNUNET_SQ_cleanup_result(rs);
550 GNUNET_SQ_reset(plugin->dbh,
557 * Lookup records in the datastore for which we are the authority.
559 * @param cls closure (internal context for the plugin)
560 * @param zone private key of the zone
561 * @param label name of the record in the zone
562 * @param iter function to call with the result
563 * @param iter_cls closure for @a iter
564 * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
567 namestore_sqlite_lookup_records(void *cls,
568 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
570 GNUNET_NAMESTORE_RecordIterator iter,
573 struct Plugin *plugin = cls;
574 struct GNUNET_SQ_QueryParam params[] = {
575 GNUNET_SQ_query_param_auto_from_type(zone),
576 GNUNET_SQ_query_param_string(label),
577 GNUNET_SQ_query_param_end
583 return GNUNET_SYSERR;
586 GNUNET_SQ_bind(plugin->lookup_label,
589 LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
590 "sqlite3_bind_XXXX");
591 GNUNET_SQ_reset(plugin->dbh,
592 plugin->lookup_label);
593 return GNUNET_SYSERR;
595 return get_records_and_call_iterator(plugin,
596 plugin->lookup_label,
605 * Iterate over the results for a particular key and zone in the
606 * datastore. Will return at most one result to the iterator.
608 * @param cls closure (internal context for the plugin)
609 * @param zone hash of public key of the zone, NULL to iterate over all zones
610 * @param serial serial number to exclude in the list of all matching records
611 * @param limit maximum number of results to return
612 * @param iter function to call with the result
613 * @param iter_cls closure for @a iter
614 * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
617 namestore_sqlite_iterate_records(void *cls,
618 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
621 GNUNET_NAMESTORE_RecordIterator iter,
624 struct Plugin *plugin = cls;
630 struct GNUNET_SQ_QueryParam params[] = {
631 GNUNET_SQ_query_param_uint64(&serial),
632 GNUNET_SQ_query_param_uint64(&limit),
633 GNUNET_SQ_query_param_end
636 stmt = plugin->iterate_all_zones;
637 err = GNUNET_SQ_bind(stmt,
642 struct GNUNET_SQ_QueryParam params[] = {
643 GNUNET_SQ_query_param_auto_from_type(zone),
644 GNUNET_SQ_query_param_uint64(&serial),
645 GNUNET_SQ_query_param_uint64(&limit),
646 GNUNET_SQ_query_param_end
649 stmt = plugin->iterate_zone;
650 err = GNUNET_SQ_bind(stmt,
653 if (GNUNET_OK != err)
656 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
657 "sqlite3_bind_XXXX");
658 GNUNET_SQ_reset(plugin->dbh,
660 return GNUNET_SYSERR;
662 return get_records_and_call_iterator(plugin,
672 * Look for an existing PKEY delegation record for a given public key.
673 * Returns at most one result to the iterator.
675 * @param cls closure (internal context for the plugin)
676 * @param zone private key of the zone to look up in, never NULL
677 * @param value_zone public key of the target zone (value), never NULL
678 * @param iter function to call with the result
679 * @param iter_cls closure for @a iter
680 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
683 namestore_sqlite_zone_to_name(void *cls,
684 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
685 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
686 GNUNET_NAMESTORE_RecordIterator iter,
689 struct Plugin *plugin = cls;
690 struct GNUNET_SQ_QueryParam params[] = {
691 GNUNET_SQ_query_param_auto_from_type(zone),
692 GNUNET_SQ_query_param_auto_from_type(value_zone),
693 GNUNET_SQ_query_param_end
697 GNUNET_SQ_bind(plugin->zone_to_name,
701 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
702 "sqlite3_bind_XXXX");
703 GNUNET_SQ_reset(plugin->dbh,
704 plugin->zone_to_name);
705 return GNUNET_SYSERR;
707 LOG(GNUNET_ERROR_TYPE_DEBUG,
708 "Performing reverse lookup for `%s'\n",
709 GNUNET_GNSRECORD_z2s(value_zone));
710 return get_records_and_call_iterator(plugin,
711 plugin->zone_to_name,
720 * Entry point for the plugin.
722 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
723 * @return NULL on error, otherwise the plugin context
726 libgnunet_plugin_namestore_sqlite_init(void *cls)
728 static struct Plugin plugin;
729 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
730 struct GNUNET_NAMESTORE_PluginFunctions *api;
732 if (NULL != plugin.cfg)
733 return NULL; /* can only initialize once! */
736 sizeof(struct Plugin));
738 if (GNUNET_OK != database_setup(&plugin))
740 database_shutdown(&plugin);
743 api = GNUNET_new(struct GNUNET_NAMESTORE_PluginFunctions);
745 api->store_records = &namestore_sqlite_store_records;
746 api->iterate_records = &namestore_sqlite_iterate_records;
747 api->zone_to_name = &namestore_sqlite_zone_to_name;
748 api->lookup_records = &namestore_sqlite_lookup_records;
749 LOG(GNUNET_ERROR_TYPE_INFO,
750 _("Sqlite database running\n"));
756 * Exit point from the plugin.
758 * @param cls the plugin context (as returned by "init")
759 * @return always NULL
762 libgnunet_plugin_namestore_sqlite_done(void *cls)
764 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
765 struct Plugin *plugin = api->cls;
767 database_shutdown(plugin);
770 LOG(GNUNET_ERROR_TYPE_DEBUG,
771 "sqlite plugin is finished\n");
775 /* end of plugin_namestore_sqlite.c */