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
6 * it under the terms of the GNU General Public License as published
7 * by the Free Software Foundation; either version 3, or (at your
8 * 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 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with GNUnet; see the file COPYING. If not, write to the
17 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
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 * @brief Prepare a SQL statement
111 * @param dbh handle to the database
112 * @param zSql SQL statement, UTF-8 encoded
113 * @param ppStmt set to the prepared statement
114 * @return 0 on success
117 sq_prepare (sqlite3 *dbh,
119 sqlite3_stmt **ppStmt)
125 sqlite3_prepare_v2 (dbh,
129 (const char **) &dummy);
130 LOG (GNUNET_ERROR_TYPE_DEBUG,
131 "Prepared `%s' / %p: %d\n",
140 * Create our database indices.
142 * @param dbh handle to the database
145 create_indices (sqlite3 * dbh)
150 "CREATE INDEX IF NOT EXISTS ir_pkey_reverse ON ns097records (zone_private_key,pkey)",
151 NULL, NULL, NULL)) ||
154 "CREATE INDEX IF NOT EXISTS ir_pkey_iter ON ns097records (zone_private_key,rvalue)",
155 NULL, NULL, NULL)) ||
158 "CREATE INDEX IF NOT EXISTS it_iter ON ns097records (rvalue)",
160 LOG (GNUNET_ERROR_TYPE_ERROR,
161 "Failed to create indices: %s\n",
162 sqlite3_errmsg (dbh));
167 #define CHECK(a) GNUNET_break(a)
171 #define ENULL_DEFINED 1
172 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
177 * Initialize the database connections and associated
178 * data structures (create tables and indices
179 * as needed as well).
181 * @param plugin the plugin context (state for this module)
182 * @return #GNUNET_OK on success
185 database_setup (struct Plugin *plugin)
194 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
199 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
202 return GNUNET_SYSERR;
205 GNUNET_DISK_file_test (afsdir))
208 GNUNET_DISK_directory_create_for_file (afsdir))
211 GNUNET_free (afsdir);
212 return GNUNET_SYSERR;
215 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
218 /* Open database and precompile statements */
219 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
221 LOG (GNUNET_ERROR_TYPE_ERROR,
222 _("Unable to initialize SQLite: %s.\n"),
223 sqlite3_errmsg (plugin->dbh));
224 return GNUNET_SYSERR;
227 sqlite3_exec (plugin->dbh,
228 "PRAGMA temp_store=MEMORY", NULL, NULL,
231 sqlite3_exec (plugin->dbh,
232 "PRAGMA synchronous=NORMAL", NULL, NULL,
235 sqlite3_exec (plugin->dbh,
236 "PRAGMA legacy_file_format=OFF", NULL, NULL,
239 sqlite3_exec (plugin->dbh,
240 "PRAGMA auto_vacuum=INCREMENTAL", NULL,
243 sqlite3_exec (plugin->dbh,
244 "PRAGMA encoding=\"UTF-8\"", NULL,
247 sqlite3_exec (plugin->dbh,
248 "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
251 sqlite3_exec (plugin->dbh,
252 "PRAGMA page_size=4092", NULL, NULL,
256 sqlite3_busy_timeout (plugin->dbh,
262 sq_prepare (plugin->dbh,
263 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns097records'",
265 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
268 "CREATE TABLE ns097records ("
269 " zone_private_key BLOB NOT NULL,"
271 " rvalue INT8 NOT NULL,"
272 " record_count INT NOT NULL,"
273 " record_data BLOB NOT NULL,"
274 " label TEXT NOT NULL"
276 NULL, NULL, NULL) != SQLITE_OK))
278 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR,
280 sqlite3_finalize (stmt);
281 return GNUNET_SYSERR;
283 sqlite3_finalize (stmt);
285 create_indices (plugin->dbh);
288 sq_prepare (plugin->dbh,
289 "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label)"
290 " VALUES (?, ?, ?, ?, ?, ?)",
291 &plugin->store_records)) ||
293 sq_prepare (plugin->dbh,
294 "DELETE FROM ns097records WHERE zone_private_key=? AND label=?",
295 &plugin->delete_records)) ||
297 sq_prepare (plugin->dbh,
298 "SELECT record_count,record_data,label"
299 " FROM ns097records WHERE zone_private_key=? AND pkey=?",
300 &plugin->zone_to_name)) ||
302 sq_prepare (plugin->dbh,
303 "SELECT record_count,record_data,label"
304 " FROM ns097records WHERE zone_private_key=?"
305 " ORDER BY rvalue LIMIT 1 OFFSET ?",
306 &plugin->iterate_zone)) ||
308 sq_prepare (plugin->dbh,
309 "SELECT record_count,record_data,label,zone_private_key"
310 " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET ?",
311 &plugin->iterate_all_zones)) ||
313 sq_prepare (plugin->dbh,
314 "SELECT record_count,record_data,label,zone_private_key"
315 " FROM ns097records WHERE zone_private_key=? AND label=?",
316 &plugin->lookup_label))
320 GNUNET_ERROR_TYPE_ERROR,
322 return GNUNET_SYSERR;
329 * Shutdown database connection and associate data
331 * @param plugin the plugin context (state for this module)
334 database_shutdown (struct Plugin *plugin)
339 if (NULL != plugin->store_records)
340 sqlite3_finalize (plugin->store_records);
341 if (NULL != plugin->delete_records)
342 sqlite3_finalize (plugin->delete_records);
343 if (NULL != plugin->iterate_zone)
344 sqlite3_finalize (plugin->iterate_zone);
345 if (NULL != plugin->iterate_all_zones)
346 sqlite3_finalize (plugin->iterate_all_zones);
347 if (NULL != plugin->zone_to_name)
348 sqlite3_finalize (plugin->zone_to_name);
349 if (NULL != plugin->lookup_label)
350 sqlite3_finalize (plugin->lookup_label);
351 result = sqlite3_close (plugin->dbh);
352 if (result == SQLITE_BUSY)
354 LOG (GNUNET_ERROR_TYPE_WARNING,
355 _("Tried to close sqlite without finalizing all prepared statements.\n"));
356 stmt = sqlite3_next_stmt (plugin->dbh,
360 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
362 "Closing statement %p\n",
364 result = sqlite3_finalize (stmt);
365 if (result != SQLITE_OK)
366 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
368 "Failed to close statement %p: %d\n",
371 stmt = sqlite3_next_stmt (plugin->dbh,
374 result = sqlite3_close (plugin->dbh);
376 if (SQLITE_OK != result)
378 GNUNET_ERROR_TYPE_ERROR,
381 GNUNET_free_non_null (plugin->fn);
386 * Store a record in the datastore. Removes any existing record in the
387 * same zone with the same name.
389 * @param cls closure (internal context for the plugin)
390 * @param zone_key private key of the zone
391 * @param label name that is being mapped (at most 255 characters long)
392 * @param rd_count number of entries in @a rd array
393 * @param rd array of records with data to store
394 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
397 namestore_sqlite_store_records (void *cls,
398 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
400 unsigned int rd_count,
401 const struct GNUNET_GNSRECORD_Data *rd)
403 struct Plugin *plugin = cls;
405 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
410 memset (&pkey, 0, sizeof (pkey));
411 for (i=0;i<rd_count;i++)
412 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
414 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) ==
416 GNUNET_memcpy (&pkey,
421 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
423 data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
425 if (data_size > 64 * 65536)
428 return GNUNET_SYSERR;
431 /* First delete 'old' records */
432 char data[data_size];
433 struct GNUNET_SQ_QueryParam dparams[] = {
434 GNUNET_SQ_query_param_auto_from_type (zone_key),
435 GNUNET_SQ_query_param_string (label),
436 GNUNET_SQ_query_param_end
440 ret = GNUNET_GNSRECORD_records_serialize (rd_count,
445 (data_size != (size_t) ret) )
448 return GNUNET_SYSERR;
451 GNUNET_SQ_bind (plugin->delete_records,
455 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
456 "sqlite3_bind_XXXX");
457 GNUNET_SQ_reset (plugin->dbh,
458 plugin->delete_records);
459 return GNUNET_SYSERR;
462 n = sqlite3_step (plugin->delete_records);
463 GNUNET_SQ_reset (plugin->dbh,
464 plugin->delete_records);
468 uint32_t rd_count32 = (uint32_t) rd_count;
469 struct GNUNET_SQ_QueryParam sparams[] = {
470 GNUNET_SQ_query_param_auto_from_type (zone_key),
471 GNUNET_SQ_query_param_auto_from_type (&pkey),
472 GNUNET_SQ_query_param_uint64 (&rvalue),
473 GNUNET_SQ_query_param_uint32 (&rd_count32),
474 GNUNET_SQ_query_param_fixed_size (data, data_size),
475 GNUNET_SQ_query_param_string (label),
476 GNUNET_SQ_query_param_end
480 GNUNET_SQ_bind (plugin->store_records,
484 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
485 "sqlite3_bind_XXXX");
486 GNUNET_SQ_reset (plugin->dbh,
487 plugin->store_records);
488 return GNUNET_SYSERR;
490 n = sqlite3_step (plugin->store_records);
491 GNUNET_SQ_reset (plugin->dbh,
492 plugin->store_records);
499 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
503 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
509 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
514 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
516 return GNUNET_SYSERR;
522 * The given 'sqlite' statement has been prepared to be run.
523 * It will return a record which should be given to the iterator.
524 * Runs the statement and parses the returned record.
526 * @param plugin plugin context
527 * @param stmt to run (and then clean up)
528 * @param zone_key private key of the zone
529 * @param iter iterator to call with the result
530 * @param iter_cls closure for @a iter
531 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
534 get_record_and_call_iterator (struct Plugin *plugin,
536 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
537 GNUNET_NAMESTORE_RecordIterator iter,
540 uint32_t record_count;
544 struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
549 if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
551 struct GNUNET_SQ_ResultSpec rs[] = {
552 GNUNET_SQ_result_spec_uint32 (&record_count),
553 GNUNET_SQ_result_spec_variable_size (&data, &data_size),
554 GNUNET_SQ_result_spec_string (&label),
555 GNUNET_SQ_result_spec_end
557 struct GNUNET_SQ_ResultSpec rsx[] = {
558 GNUNET_SQ_result_spec_uint32 (&record_count),
559 GNUNET_SQ_result_spec_variable_size (&data, &data_size),
560 GNUNET_SQ_result_spec_string (&label),
561 GNUNET_SQ_result_spec_auto_from_type (&zk),
562 GNUNET_SQ_result_spec_end
565 if (NULL == zone_key)
568 ret = GNUNET_SQ_extract_result (stmt,
573 ret = GNUNET_SQ_extract_result (stmt,
576 if ( (GNUNET_OK != ret) ||
577 (record_count > 64 * 1024) )
579 /* sanity check, don't stack allocate far too much just
580 because database might contain a large value here */
586 struct GNUNET_GNSRECORD_Data rd[record_count];
589 GNUNET_GNSRECORD_records_deserialize (data_size,
608 GNUNET_SQ_cleanup_result (rs);
612 if (SQLITE_DONE != sret)
614 GNUNET_ERROR_TYPE_ERROR,
617 GNUNET_SQ_reset (plugin->dbh,
624 * Lookup records in the datastore for which we are the authority.
626 * @param cls closure (internal context for the plugin)
627 * @param zone private key of the zone
628 * @param label name of the record in the zone
629 * @param iter function to call with the result
630 * @param iter_cls closure for @a iter
631 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
634 namestore_sqlite_lookup_records (void *cls,
635 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
637 GNUNET_NAMESTORE_RecordIterator iter,
640 struct Plugin *plugin = cls;
641 struct GNUNET_SQ_QueryParam params[] = {
642 GNUNET_SQ_query_param_auto_from_type (zone),
643 GNUNET_SQ_query_param_string (label),
644 GNUNET_SQ_query_param_end
648 return GNUNET_SYSERR;
650 GNUNET_SQ_bind (plugin->lookup_label,
653 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
654 "sqlite3_bind_XXXX");
655 GNUNET_SQ_reset (plugin->dbh,
656 plugin->lookup_label);
657 return GNUNET_SYSERR;
659 return get_record_and_call_iterator (plugin,
660 plugin->lookup_label,
668 * Iterate over the results for a particular key and zone in the
669 * datastore. Will return at most one result to the iterator.
671 * @param cls closure (internal context for the plugin)
672 * @param zone hash of public key of the zone, NULL to iterate over all zones
673 * @param offset offset in the list of all matching records
674 * @param iter function to call with the result
675 * @param iter_cls closure for @a iter
676 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
679 namestore_sqlite_iterate_records (void *cls,
680 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
682 GNUNET_NAMESTORE_RecordIterator iter,
685 struct Plugin *plugin = cls;
691 struct GNUNET_SQ_QueryParam params[] = {
692 GNUNET_SQ_query_param_uint64 (&offset),
693 GNUNET_SQ_query_param_end
696 stmt = plugin->iterate_all_zones;
697 err = GNUNET_SQ_bind (stmt,
702 struct GNUNET_SQ_QueryParam params[] = {
703 GNUNET_SQ_query_param_auto_from_type (zone),
704 GNUNET_SQ_query_param_uint64 (&offset),
705 GNUNET_SQ_query_param_end
708 stmt = plugin->iterate_zone;
709 err = GNUNET_SQ_bind (stmt,
712 if (GNUNET_OK != err)
715 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
716 "sqlite3_bind_XXXX");
717 GNUNET_SQ_reset (plugin->dbh,
719 return GNUNET_SYSERR;
721 return get_record_and_call_iterator (plugin,
730 * Look for an existing PKEY delegation record for a given public key.
731 * Returns at most one result to the iterator.
733 * @param cls closure (internal context for the plugin)
734 * @param zone private key of the zone to look up in, never NULL
735 * @param value_zone public key of the target zone (value), never NULL
736 * @param iter function to call with the result
737 * @param iter_cls closure for @a iter
738 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
741 namestore_sqlite_zone_to_name (void *cls,
742 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
743 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
744 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
746 struct Plugin *plugin = cls;
747 struct GNUNET_SQ_QueryParam params[] = {
748 GNUNET_SQ_query_param_auto_from_type (zone),
749 GNUNET_SQ_query_param_auto_from_type (value_zone),
750 GNUNET_SQ_query_param_end
754 GNUNET_SQ_bind (plugin->zone_to_name,
758 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
759 "sqlite3_bind_XXXX");
760 GNUNET_SQ_reset (plugin->dbh,
761 plugin->zone_to_name);
762 return GNUNET_SYSERR;
764 LOG (GNUNET_ERROR_TYPE_DEBUG,
765 "Performing reverse lookup for `%s'\n",
766 GNUNET_GNSRECORD_z2s (value_zone));
767 return get_record_and_call_iterator (plugin,
768 plugin->zone_to_name,
776 * Entry point for the plugin.
778 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
779 * @return NULL on error, otherwise the plugin context
782 libgnunet_plugin_namestore_sqlite_init (void *cls)
784 static struct Plugin plugin;
785 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
786 struct GNUNET_NAMESTORE_PluginFunctions *api;
788 if (NULL != plugin.cfg)
789 return NULL; /* can only initialize once! */
790 memset (&plugin, 0, sizeof (struct Plugin));
792 if (GNUNET_OK != database_setup (&plugin))
794 database_shutdown (&plugin);
797 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
799 api->store_records = &namestore_sqlite_store_records;
800 api->iterate_records = &namestore_sqlite_iterate_records;
801 api->zone_to_name = &namestore_sqlite_zone_to_name;
802 api->lookup_records = &namestore_sqlite_lookup_records;
803 LOG (GNUNET_ERROR_TYPE_INFO,
804 _("Sqlite database running\n"));
810 * Exit point from the plugin.
812 * @param cls the plugin context (as returned by "init")
813 * @return always NULL
816 libgnunet_plugin_namestore_sqlite_done (void *cls)
818 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
819 struct Plugin *plugin = api->cls;
821 database_shutdown (plugin);
824 LOG (GNUNET_ERROR_TYPE_DEBUG,
825 "sqlite plugin is finished\n");
829 /* end of plugin_namestore_sqlite.c */