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.
64 const struct GNUNET_CONFIGURATION_Handle *cfg;
72 * Native SQLite database handle.
77 * Precompiled SQL to store records.
79 sqlite3_stmt *store_records;
82 * Precompiled SQL to deltete existing records.
84 sqlite3_stmt *delete_records;
87 * Precompiled SQL for iterate records within a zone.
89 sqlite3_stmt *iterate_zone;
92 * Precompiled SQL for iterate all records within all zones.
94 sqlite3_stmt *iterate_all_zones;
97 * Precompiled SQL to for reverse lookup based on PKEY.
99 sqlite3_stmt *zone_to_name;
102 * Precompiled SQL to lookup records based on label.
104 sqlite3_stmt *lookup_label;
109 * Initialize the database connections and associated
110 * data structures (create tables and indices
111 * as needed as well).
113 * @param plugin the plugin context (state for this module)
114 * @return #GNUNET_OK on success
117 database_setup (struct Plugin *plugin)
119 char *sqlite_filename;
120 struct GNUNET_SQ_ExecuteStatement es[] = {
121 GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"),
122 GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"),
123 GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"),
124 GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"),
125 GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""),
126 GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"),
127 GNUNET_SQ_make_try_execute ("PRAGMA journal_mode=WAL"),
128 GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"),
129 GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records ("
130 " uid INTEGER PRIMARY KEY,"
131 " zone_private_key BLOB NOT NULL,"
133 " rvalue INT8 NOT NULL,"
134 " record_count INT NOT NULL,"
135 " record_data BLOB NOT NULL,"
136 " label TEXT NOT NULL"
138 GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
139 "ON ns098records (zone_private_key,pkey)"),
140 GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
141 "ON ns098records (zone_private_key,uid)"),
142 GNUNET_SQ_EXECUTE_STATEMENT_END
144 struct GNUNET_SQ_PrepareStatement ps[] = {
145 GNUNET_SQ_make_prepare ("INSERT INTO ns098records "
146 "(zone_private_key,pkey,rvalue,record_count,record_data,label)"
147 " VALUES (?, ?, ?, ?, ?, ?)",
148 &plugin->store_records),
149 GNUNET_SQ_make_prepare ("DELETE FROM ns098records "
150 "WHERE zone_private_key=? AND label=?",
151 &plugin->delete_records),
152 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
154 " WHERE zone_private_key=? AND pkey=?",
155 &plugin->zone_to_name),
156 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
158 " WHERE zone_private_key=? AND uid > ?"
161 &plugin->iterate_zone),
162 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label,zone_private_key"
167 &plugin->iterate_all_zones),
168 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
170 " WHERE zone_private_key=? AND label=?",
171 &plugin->lookup_label),
172 GNUNET_SQ_PREPARE_END
176 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
181 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
184 return GNUNET_SYSERR;
187 GNUNET_DISK_file_test (sqlite_filename))
190 GNUNET_DISK_directory_create_for_file (sqlite_filename))
193 GNUNET_free (sqlite_filename);
194 return GNUNET_SYSERR;
197 /* sqlite_filename should be UTF-8-encoded. If it isn't, it's a bug */
198 plugin->fn = sqlite_filename;
200 /* Open database and precompile statements */
202 sqlite3_open (plugin->fn,
205 LOG (GNUNET_ERROR_TYPE_ERROR,
206 _("Unable to initialize SQLite: %s.\n"),
207 sqlite3_errmsg (plugin->dbh));
208 return GNUNET_SYSERR;
210 GNUNET_break (SQLITE_OK ==
211 sqlite3_busy_timeout (plugin->dbh,
214 GNUNET_SQ_exec_statements (plugin->dbh,
218 LOG (GNUNET_ERROR_TYPE_ERROR,
219 _("Failed to setup database at `%s'\n"),
221 return GNUNET_SYSERR;
225 GNUNET_SQ_prepare (plugin->dbh,
229 LOG (GNUNET_ERROR_TYPE_ERROR,
230 _("Failed to setup database at `%s'\n"),
232 return GNUNET_SYSERR;
239 * Shutdown database connection and associate data
241 * @param plugin the plugin context (state for this module)
244 database_shutdown (struct Plugin *plugin)
249 if (NULL != plugin->store_records)
250 sqlite3_finalize (plugin->store_records);
251 if (NULL != plugin->delete_records)
252 sqlite3_finalize (plugin->delete_records);
253 if (NULL != plugin->iterate_zone)
254 sqlite3_finalize (plugin->iterate_zone);
255 if (NULL != plugin->iterate_all_zones)
256 sqlite3_finalize (plugin->iterate_all_zones);
257 if (NULL != plugin->zone_to_name)
258 sqlite3_finalize (plugin->zone_to_name);
259 if (NULL != plugin->lookup_label)
260 sqlite3_finalize (plugin->lookup_label);
261 result = sqlite3_close (plugin->dbh);
262 if (result == SQLITE_BUSY)
264 LOG (GNUNET_ERROR_TYPE_WARNING,
265 _("Tried to close sqlite without finalizing all prepared statements.\n"));
266 stmt = sqlite3_next_stmt (plugin->dbh,
270 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
272 "Closing statement %p\n",
274 result = sqlite3_finalize (stmt);
275 if (result != SQLITE_OK)
276 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
278 "Failed to close statement %p: %d\n",
281 stmt = sqlite3_next_stmt (plugin->dbh,
284 result = sqlite3_close (plugin->dbh);
286 if (SQLITE_OK != result)
288 GNUNET_ERROR_TYPE_ERROR,
291 GNUNET_free_non_null (plugin->fn);
296 * Store a record in the datastore. Removes any existing record in the
297 * same zone with the same name.
299 * @param cls closure (internal context for the plugin)
300 * @param zone_key private key of the zone
301 * @param label name that is being mapped (at most 255 characters long)
302 * @param rd_count number of entries in @a rd array
303 * @param rd array of records with data to store
304 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
307 namestore_sqlite_store_records (void *cls,
308 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
310 unsigned int rd_count,
311 const struct GNUNET_GNSRECORD_Data *rd)
313 struct Plugin *plugin = cls;
315 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
322 for (unsigned int i=0;i<rd_count;i++)
323 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
325 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) ==
327 GNUNET_memcpy (&pkey,
332 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
334 data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
339 return GNUNET_SYSERR;
341 if (data_size > 64 * 65536)
344 return GNUNET_SYSERR;
347 /* First delete 'old' records */
348 char data[data_size];
349 struct GNUNET_SQ_QueryParam dparams[] = {
350 GNUNET_SQ_query_param_auto_from_type (zone_key),
351 GNUNET_SQ_query_param_string (label),
352 GNUNET_SQ_query_param_end
356 ret = GNUNET_GNSRECORD_records_serialize (rd_count,
364 return GNUNET_SYSERR;
367 GNUNET_SQ_bind (plugin->delete_records,
371 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
372 "sqlite3_bind_XXXX");
373 GNUNET_SQ_reset (plugin->dbh,
374 plugin->delete_records);
375 return GNUNET_SYSERR;
378 n = sqlite3_step (plugin->delete_records);
379 GNUNET_SQ_reset (plugin->dbh,
380 plugin->delete_records);
384 uint32_t rd_count32 = (uint32_t) rd_count;
385 struct GNUNET_SQ_QueryParam sparams[] = {
386 GNUNET_SQ_query_param_auto_from_type (zone_key),
387 GNUNET_SQ_query_param_auto_from_type (&pkey),
388 GNUNET_SQ_query_param_uint64 (&rvalue),
389 GNUNET_SQ_query_param_uint32 (&rd_count32),
390 GNUNET_SQ_query_param_fixed_size (data, data_size),
391 GNUNET_SQ_query_param_string (label),
392 GNUNET_SQ_query_param_end
396 GNUNET_SQ_bind (plugin->store_records,
400 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
401 "sqlite3_bind_XXXX");
402 GNUNET_SQ_reset (plugin->dbh,
403 plugin->store_records);
404 return GNUNET_SYSERR;
406 n = sqlite3_step (plugin->store_records);
407 GNUNET_SQ_reset (plugin->dbh,
408 plugin->store_records);
415 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
419 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
425 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
430 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
432 return GNUNET_SYSERR;
438 * The given 'sqlite' statement has been prepared to be run.
439 * It will return a record which should be given to the iterator.
440 * Runs the statement and parses the returned record.
442 * @param plugin plugin context
443 * @param stmt to run (and then clean up)
444 * @param zone_key private key of the zone
445 * @param limit maximum number of results to fetch
446 * @param iter iterator to call with the result
447 * @param iter_cls closure for @a iter
448 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
451 get_records_and_call_iterator (struct Plugin *plugin,
453 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
455 GNUNET_NAMESTORE_RecordIterator iter,
462 for (uint64_t i = 0;i<limit;i++)
464 sret = sqlite3_step (stmt);
466 if (SQLITE_DONE == sret)
468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
469 "Iteration done (no results)\n");
473 if (SQLITE_ROW != sret)
476 GNUNET_ERROR_TYPE_ERROR,
484 uint32_t record_count;
488 struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
489 struct GNUNET_SQ_ResultSpec rs[] = {
490 GNUNET_SQ_result_spec_uint64 (&seq),
491 GNUNET_SQ_result_spec_uint32 (&record_count),
492 GNUNET_SQ_result_spec_variable_size (&data,
494 GNUNET_SQ_result_spec_string (&label),
495 GNUNET_SQ_result_spec_end
497 struct GNUNET_SQ_ResultSpec rsx[] = {
498 GNUNET_SQ_result_spec_uint64 (&seq),
499 GNUNET_SQ_result_spec_uint32 (&record_count),
500 GNUNET_SQ_result_spec_variable_size (&data,
502 GNUNET_SQ_result_spec_string (&label),
503 GNUNET_SQ_result_spec_auto_from_type (&zk),
504 GNUNET_SQ_result_spec_end
507 ret = GNUNET_SQ_extract_result (stmt,
511 if ( (GNUNET_OK != ret) ||
512 (record_count > 64 * 1024) )
514 /* sanity check, don't stack allocate far too much just
515 because database might contain a large value here */
522 struct GNUNET_GNSRECORD_Data rd[record_count];
524 GNUNET_assert (0 != seq);
526 GNUNET_GNSRECORD_records_deserialize (data_size,
537 if (NULL != zone_key)
548 GNUNET_SQ_cleanup_result (rs);
551 GNUNET_SQ_reset (plugin->dbh,
558 * Lookup records in the datastore for which we are the authority.
560 * @param cls closure (internal context for the plugin)
561 * @param zone private key of the zone
562 * @param label name of the record in the zone
563 * @param iter function to call with the result
564 * @param iter_cls closure for @a iter
565 * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
568 namestore_sqlite_lookup_records (void *cls,
569 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
571 GNUNET_NAMESTORE_RecordIterator iter,
574 struct Plugin *plugin = cls;
575 struct GNUNET_SQ_QueryParam params[] = {
576 GNUNET_SQ_query_param_auto_from_type (zone),
577 GNUNET_SQ_query_param_string (label),
578 GNUNET_SQ_query_param_end
584 return GNUNET_SYSERR;
587 GNUNET_SQ_bind (plugin->lookup_label,
590 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
591 "sqlite3_bind_XXXX");
592 GNUNET_SQ_reset (plugin->dbh,
593 plugin->lookup_label);
594 return GNUNET_SYSERR;
596 return get_records_and_call_iterator (plugin,
597 plugin->lookup_label,
606 * Iterate over the results for a particular key and zone in the
607 * datastore. Will return at most one result to the iterator.
609 * @param cls closure (internal context for the plugin)
610 * @param zone hash of public key of the zone, NULL to iterate over all zones
611 * @param serial serial number to exclude in the list of all matching records
612 * @param limit maximum number of results to return
613 * @param iter function to call with the result
614 * @param iter_cls closure for @a iter
615 * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
618 namestore_sqlite_iterate_records (void *cls,
619 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
622 GNUNET_NAMESTORE_RecordIterator iter,
625 struct Plugin *plugin = cls;
631 struct GNUNET_SQ_QueryParam params[] = {
632 GNUNET_SQ_query_param_uint64 (&serial),
633 GNUNET_SQ_query_param_uint64 (&limit),
634 GNUNET_SQ_query_param_end
637 stmt = plugin->iterate_all_zones;
638 err = GNUNET_SQ_bind (stmt,
643 struct GNUNET_SQ_QueryParam params[] = {
644 GNUNET_SQ_query_param_auto_from_type (zone),
645 GNUNET_SQ_query_param_uint64 (&serial),
646 GNUNET_SQ_query_param_uint64 (&limit),
647 GNUNET_SQ_query_param_end
650 stmt = plugin->iterate_zone;
651 err = GNUNET_SQ_bind (stmt,
654 if (GNUNET_OK != err)
657 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
658 "sqlite3_bind_XXXX");
659 GNUNET_SQ_reset (plugin->dbh,
661 return GNUNET_SYSERR;
663 return get_records_and_call_iterator (plugin,
673 * Look for an existing PKEY delegation record for a given public key.
674 * Returns at most one result to the iterator.
676 * @param cls closure (internal context for the plugin)
677 * @param zone private key of the zone to look up in, never NULL
678 * @param value_zone public key of the target zone (value), never NULL
679 * @param iter function to call with the result
680 * @param iter_cls closure for @a iter
681 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
684 namestore_sqlite_zone_to_name (void *cls,
685 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
686 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
687 GNUNET_NAMESTORE_RecordIterator iter,
690 struct Plugin *plugin = cls;
691 struct GNUNET_SQ_QueryParam params[] = {
692 GNUNET_SQ_query_param_auto_from_type (zone),
693 GNUNET_SQ_query_param_auto_from_type (value_zone),
694 GNUNET_SQ_query_param_end
698 GNUNET_SQ_bind (plugin->zone_to_name,
702 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
703 "sqlite3_bind_XXXX");
704 GNUNET_SQ_reset (plugin->dbh,
705 plugin->zone_to_name);
706 return GNUNET_SYSERR;
708 LOG (GNUNET_ERROR_TYPE_DEBUG,
709 "Performing reverse lookup for `%s'\n",
710 GNUNET_GNSRECORD_z2s (value_zone));
711 return get_records_and_call_iterator (plugin,
712 plugin->zone_to_name,
721 * Entry point for the plugin.
723 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
724 * @return NULL on error, otherwise the plugin context
727 libgnunet_plugin_namestore_sqlite_init (void *cls)
729 static struct Plugin plugin;
730 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
731 struct GNUNET_NAMESTORE_PluginFunctions *api;
733 if (NULL != plugin.cfg)
734 return NULL; /* can only initialize once! */
737 sizeof (struct Plugin));
739 if (GNUNET_OK != database_setup (&plugin))
741 database_shutdown (&plugin);
744 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
746 api->store_records = &namestore_sqlite_store_records;
747 api->iterate_records = &namestore_sqlite_iterate_records;
748 api->zone_to_name = &namestore_sqlite_zone_to_name;
749 api->lookup_records = &namestore_sqlite_lookup_records;
750 LOG (GNUNET_ERROR_TYPE_INFO,
751 _("Sqlite database running\n"));
757 * Exit point from the plugin.
759 * @param cls the plugin context (as returned by "init")
760 * @return always NULL
763 libgnunet_plugin_namestore_sqlite_done (void *cls)
765 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
766 struct Plugin *plugin = api->cls;
768 database_shutdown (plugin);
771 LOG (GNUNET_ERROR_TYPE_DEBUG,
772 "sqlite plugin is finished\n");
776 /* end of plugin_namestore_sqlite.c */