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/>.
20 * @file namestore/plugin_namestore_sqlite.c
21 * @brief sqlite-based namestore backend
22 * @author Christian Grothoff
26 #include "gnunet_namestore_plugin.h"
27 #include "gnunet_namestore_service.h"
28 #include "gnunet_gnsrecord_lib.h"
29 #include "gnunet_sq_lib.h"
30 #include "namestore.h"
34 * After how many ms "busy" should a DB operation fail for good? A
35 * low value makes sure that we are more responsive to requests
36 * (especially PUTs). A high value guarantees a higher success rate
37 * (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
41 * succeed 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_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)
53 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-sqlite", __VA_ARGS__)
57 * 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 page_size=4092"),
126 GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records ("
127 " uid INTEGER PRIMARY KEY,"
128 " zone_private_key BLOB NOT NULL,"
130 " rvalue INT8 NOT NULL,"
131 " record_count INT NOT NULL,"
132 " record_data BLOB NOT NULL,"
133 " label TEXT NOT NULL"
135 GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
136 "ON ns098records (zone_private_key,pkey)"),
137 GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
138 "ON ns098records (zone_private_key,uid)"),
139 GNUNET_SQ_EXECUTE_STATEMENT_END
141 struct GNUNET_SQ_PrepareStatement ps[] = {
142 GNUNET_SQ_make_prepare ("INSERT INTO ns098records "
143 "(zone_private_key,pkey,rvalue,record_count,record_data,label)"
144 " VALUES (?, ?, ?, ?, ?, ?)",
145 &plugin->store_records),
146 GNUNET_SQ_make_prepare ("DELETE FROM ns098records "
147 "WHERE zone_private_key=? AND label=?",
148 &plugin->delete_records),
149 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
151 " WHERE zone_private_key=? AND pkey=?",
152 &plugin->zone_to_name),
153 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label"
155 " WHERE zone_private_key=? AND _rowid_ >= ?"
156 " ORDER BY _rowid_ ASC"
158 &plugin->iterate_zone),
159 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label,zone_private_key"
161 " WHERE _rowid_ >= ?"
162 " ORDER BY _rowid_ ASC"
164 &plugin->iterate_all_zones),
165 GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label,zone_private_key"
167 " WHERE zone_private_key=? AND label=?",
168 &plugin->lookup_label),
169 GNUNET_SQ_PREPARE_END
173 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
178 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
181 return GNUNET_SYSERR;
184 GNUNET_DISK_file_test (sqlite_filename))
187 GNUNET_DISK_directory_create_for_file (sqlite_filename))
190 GNUNET_free (sqlite_filename);
191 return GNUNET_SYSERR;
194 /* sqlite_filename should be UTF-8-encoded. If it isn't, it's a bug */
195 plugin->fn = sqlite_filename;
197 /* Open database and precompile statements */
199 sqlite3_open (plugin->fn,
202 LOG (GNUNET_ERROR_TYPE_ERROR,
203 _("Unable to initialize SQLite: %s.\n"),
204 sqlite3_errmsg (plugin->dbh));
205 return GNUNET_SYSERR;
207 GNUNET_break (SQLITE_OK ==
208 sqlite3_busy_timeout (plugin->dbh,
211 GNUNET_SQ_exec_statements (plugin->dbh,
215 LOG (GNUNET_ERROR_TYPE_ERROR,
216 _("Failed to setup database at `%s'\n"),
218 return GNUNET_SYSERR;
222 GNUNET_SQ_prepare (plugin->dbh,
226 LOG (GNUNET_ERROR_TYPE_ERROR,
227 _("Failed to setup database at `%s'\n"),
229 return GNUNET_SYSERR;
236 * Shutdown database connection and associate data
238 * @param plugin the plugin context (state for this module)
241 database_shutdown (struct Plugin *plugin)
246 if (NULL != plugin->store_records)
247 sqlite3_finalize (plugin->store_records);
248 if (NULL != plugin->delete_records)
249 sqlite3_finalize (plugin->delete_records);
250 if (NULL != plugin->iterate_zone)
251 sqlite3_finalize (plugin->iterate_zone);
252 if (NULL != plugin->iterate_all_zones)
253 sqlite3_finalize (plugin->iterate_all_zones);
254 if (NULL != plugin->zone_to_name)
255 sqlite3_finalize (plugin->zone_to_name);
256 if (NULL != plugin->lookup_label)
257 sqlite3_finalize (plugin->lookup_label);
258 result = sqlite3_close (plugin->dbh);
259 if (result == SQLITE_BUSY)
261 LOG (GNUNET_ERROR_TYPE_WARNING,
262 _("Tried to close sqlite without finalizing all prepared statements.\n"));
263 stmt = sqlite3_next_stmt (plugin->dbh,
267 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
269 "Closing statement %p\n",
271 result = sqlite3_finalize (stmt);
272 if (result != SQLITE_OK)
273 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
275 "Failed to close statement %p: %d\n",
278 stmt = sqlite3_next_stmt (plugin->dbh,
281 result = sqlite3_close (plugin->dbh);
283 if (SQLITE_OK != result)
285 GNUNET_ERROR_TYPE_ERROR,
288 GNUNET_free_non_null (plugin->fn);
293 * Store a record in the datastore. Removes any existing record in the
294 * same zone with the same name.
296 * @param cls closure (internal context for the plugin)
297 * @param zone_key private key of the zone
298 * @param label name that is being mapped (at most 255 characters long)
299 * @param rd_count number of entries in @a rd array
300 * @param rd array of records with data to store
301 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
304 namestore_sqlite_store_records (void *cls,
305 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
307 unsigned int rd_count,
308 const struct GNUNET_GNSRECORD_Data *rd)
310 struct Plugin *plugin = cls;
312 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
319 for (unsigned int i=0;i<rd_count;i++)
320 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
322 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) ==
324 GNUNET_memcpy (&pkey,
329 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
331 data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
336 return GNUNET_SYSERR;
338 if (data_size > 64 * 65536)
341 return GNUNET_SYSERR;
344 /* First delete 'old' records */
345 char data[data_size];
346 struct GNUNET_SQ_QueryParam dparams[] = {
347 GNUNET_SQ_query_param_auto_from_type (zone_key),
348 GNUNET_SQ_query_param_string (label),
349 GNUNET_SQ_query_param_end
353 ret = GNUNET_GNSRECORD_records_serialize (rd_count,
361 return GNUNET_SYSERR;
364 GNUNET_SQ_bind (plugin->delete_records,
368 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
369 "sqlite3_bind_XXXX");
370 GNUNET_SQ_reset (plugin->dbh,
371 plugin->delete_records);
372 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,
422 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
427 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
429 return GNUNET_SYSERR;
435 * The given 'sqlite' statement has been prepared to be run.
436 * It will return a record which should be given to the iterator.
437 * Runs the statement and parses the returned record.
439 * @param plugin plugin context
440 * @param stmt to run (and then clean up)
441 * @param zone_key private key of the zone
442 * @param limit maximum number of results to fetch
443 * @param iter iterator to call with the result
444 * @param iter_cls closure for @a iter
445 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
448 get_records_and_call_iterator (struct Plugin *plugin,
450 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
452 GNUNET_NAMESTORE_RecordIterator iter,
459 for (uint64_t i = 0;i<limit;i++)
461 sret = sqlite3_step (stmt);
463 if (SQLITE_DONE == sret)
465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
466 "Iteration done (no results)\n");
470 if (SQLITE_ROW != sret)
473 GNUNET_ERROR_TYPE_ERROR,
481 uint32_t record_count;
485 struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
486 struct GNUNET_SQ_ResultSpec rs[] = {
487 GNUNET_SQ_result_spec_uint64 (&seq),
488 GNUNET_SQ_result_spec_uint32 (&record_count),
489 GNUNET_SQ_result_spec_variable_size (&data,
491 GNUNET_SQ_result_spec_string (&label),
492 GNUNET_SQ_result_spec_end
494 struct GNUNET_SQ_ResultSpec rsx[] = {
495 GNUNET_SQ_result_spec_uint64 (&seq),
496 GNUNET_SQ_result_spec_uint32 (&record_count),
497 GNUNET_SQ_result_spec_variable_size (&data,
499 GNUNET_SQ_result_spec_string (&label),
500 GNUNET_SQ_result_spec_auto_from_type (&zk),
501 GNUNET_SQ_result_spec_end
504 if (NULL == zone_key)
507 ret = GNUNET_SQ_extract_result (stmt,
512 ret = GNUNET_SQ_extract_result (stmt,
515 if ( (GNUNET_OK != ret) ||
516 (record_count > 64 * 1024) )
518 /* sanity check, don't stack allocate far too much just
519 because database might contain a large value here */
526 struct GNUNET_GNSRECORD_Data rd[record_count];
529 GNUNET_GNSRECORD_records_deserialize (data_size,
549 GNUNET_SQ_cleanup_result (rs);
552 GNUNET_SQ_reset (plugin->dbh,
559 * Lookup records in the datastore for which we are the authority.
561 * @param cls closure (internal context for the plugin)
562 * @param zone private key of the zone
563 * @param label name of the record in the zone
564 * @param iter function to call with the result
565 * @param iter_cls closure for @a iter
566 * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR
569 namestore_sqlite_lookup_records (void *cls,
570 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
572 GNUNET_NAMESTORE_RecordIterator iter,
575 struct Plugin *plugin = cls;
576 struct GNUNET_SQ_QueryParam params[] = {
577 GNUNET_SQ_query_param_auto_from_type (zone),
578 GNUNET_SQ_query_param_string (label),
579 GNUNET_SQ_query_param_end
585 return GNUNET_SYSERR;
588 GNUNET_SQ_bind (plugin->lookup_label,
591 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
592 "sqlite3_bind_XXXX");
593 GNUNET_SQ_reset (plugin->dbh,
594 plugin->lookup_label);
595 return GNUNET_SYSERR;
597 return get_records_and_call_iterator (plugin,
598 plugin->lookup_label,
607 * Iterate over the results for a particular key and zone in the
608 * datastore. Will return at most one result to the iterator.
610 * @param cls closure (internal context for the plugin)
611 * @param zone hash of public key of the zone, NULL to iterate over all zones
612 * @param serial serial number to exclude in the list of all matching records
613 * @param limit maximum number of results to return
614 * @param iter function to call with the result
615 * @param iter_cls closure for @a iter
616 * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error
619 namestore_sqlite_iterate_records (void *cls,
620 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
623 GNUNET_NAMESTORE_RecordIterator iter,
626 struct Plugin *plugin = cls;
632 struct GNUNET_SQ_QueryParam params[] = {
633 GNUNET_SQ_query_param_uint64 (&serial),
634 GNUNET_SQ_query_param_uint64 (&limit),
635 GNUNET_SQ_query_param_end
638 stmt = plugin->iterate_all_zones;
639 err = GNUNET_SQ_bind (stmt,
644 struct GNUNET_SQ_QueryParam params[] = {
645 GNUNET_SQ_query_param_auto_from_type (zone),
646 GNUNET_SQ_query_param_uint64 (&serial),
647 GNUNET_SQ_query_param_uint64 (&limit),
648 GNUNET_SQ_query_param_end
651 stmt = plugin->iterate_zone;
652 err = GNUNET_SQ_bind (stmt,
655 if (GNUNET_OK != err)
658 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
659 "sqlite3_bind_XXXX");
660 GNUNET_SQ_reset (plugin->dbh,
662 return GNUNET_SYSERR;
664 return get_records_and_call_iterator (plugin,
674 * Look for an existing PKEY delegation record for a given public key.
675 * Returns at most one result to the iterator.
677 * @param cls closure (internal context for the plugin)
678 * @param zone private key of the zone to look up in, never NULL
679 * @param value_zone public key of the target zone (value), never NULL
680 * @param iter function to call with the result
681 * @param iter_cls closure for @a iter
682 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
685 namestore_sqlite_zone_to_name (void *cls,
686 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
687 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
688 GNUNET_NAMESTORE_RecordIterator iter,
691 struct Plugin *plugin = cls;
692 struct GNUNET_SQ_QueryParam params[] = {
693 GNUNET_SQ_query_param_auto_from_type (zone),
694 GNUNET_SQ_query_param_auto_from_type (value_zone),
695 GNUNET_SQ_query_param_end
699 GNUNET_SQ_bind (plugin->zone_to_name,
703 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
704 "sqlite3_bind_XXXX");
705 GNUNET_SQ_reset (plugin->dbh,
706 plugin->zone_to_name);
707 return GNUNET_SYSERR;
709 LOG (GNUNET_ERROR_TYPE_DEBUG,
710 "Performing reverse lookup for `%s'\n",
711 GNUNET_GNSRECORD_z2s (value_zone));
712 return get_records_and_call_iterator (plugin,
713 plugin->zone_to_name,
722 * Entry point for the plugin.
724 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
725 * @return NULL on error, otherwise the plugin context
728 libgnunet_plugin_namestore_sqlite_init (void *cls)
730 static struct Plugin plugin;
731 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
732 struct GNUNET_NAMESTORE_PluginFunctions *api;
734 if (NULL != plugin.cfg)
735 return NULL; /* can only initialize once! */
738 sizeof (struct Plugin));
740 if (GNUNET_OK != database_setup (&plugin))
742 database_shutdown (&plugin);
745 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
747 api->store_records = &namestore_sqlite_store_records;
748 api->iterate_records = &namestore_sqlite_iterate_records;
749 api->zone_to_name = &namestore_sqlite_zone_to_name;
750 api->lookup_records = &namestore_sqlite_lookup_records;
751 LOG (GNUNET_ERROR_TYPE_INFO,
752 _("Sqlite database running\n"));
758 * Exit point from the plugin.
760 * @param cls the plugin context (as returned by "init")
761 * @return always NULL
764 libgnunet_plugin_namestore_sqlite_done (void *cls)
766 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
767 struct Plugin *plugin = api->cls;
769 database_shutdown (plugin);
772 LOG (GNUNET_ERROR_TYPE_DEBUG,
773 "sqlite plugin is finished\n");
777 /* end of plugin_namestore_sqlite.c */