2 * This file is part of GNUnet
3 * Copyright (C) 2009-2013 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 namecache/plugin_namecache_sqlite.c
23 * @brief sqlite-based namecache backend
24 * @author Christian Grothoff
27 #include "gnunet_sq_lib.h"
28 #include "gnunet_namecache_plugin.h"
29 #include "gnunet_namecache_service.h"
30 #include "gnunet_gnsrecord_lib.h"
31 #include "namecache.h"
35 * After how many ms "busy" should a DB operation fail for good? A
36 * low value makes sure that we are more responsive to requests
37 * (especially PUTs). A high value guarantees a higher success rate
38 * (SELECTs in iterate can take several seconds despite LIMIT=1).
40 * The default value of 1s should ensure that users do not experience
41 * huge latencies while at the same time allowing operations to
42 * succeed with reasonable probability.
44 #define BUSY_TIMEOUT_MS 1000
48 * Log an error message at log-level 'level' that indicates
49 * a failure of the command 'cmd' on file 'filename'
50 * with the message given by strerror(errno).
52 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "namecache-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
54 #define LOG(kind,...) GNUNET_log_from (kind, "namecache-sqlite", __VA_ARGS__)
58 * Context for all functions in this plugin.
63 const struct GNUNET_CONFIGURATION_Handle *cfg;
71 * Native SQLite database handle.
76 * Precompiled SQL for caching a block
78 sqlite3_stmt *cache_block;
81 * Precompiled SQL for deleting an older block
83 sqlite3_stmt *delete_block;
86 * Precompiled SQL for looking up a block
88 sqlite3_stmt *lookup_block;
91 * Precompiled SQL for removing expired blocks
93 sqlite3_stmt *expire_blocks;
99 * Initialize the database connections and associated
100 * data structures (create tables and indices
101 * as needed as well).
103 * @param plugin the plugin context (state for this module)
104 * @return #GNUNET_OK on success
107 database_setup (struct Plugin *plugin)
109 struct GNUNET_SQ_ExecuteStatement es[] = {
110 GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"),
111 GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"),
112 GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"),
113 GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"),
114 GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""),
115 GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"),
116 GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"),
117 GNUNET_SQ_make_try_execute ("PRAGMA journal_mode=WAL"),
118 GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns096blocks ("
119 " query BLOB NOT NULL,"
120 " block BLOB NOT NULL,"
121 " expiration_time INT8 NOT NULL"
123 GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_query_hash "
124 "ON ns096blocks (query,expiration_time)"),
125 GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_block_expiration "
126 "ON ns096blocks (expiration_time)"),
127 GNUNET_SQ_EXECUTE_STATEMENT_END
129 struct GNUNET_SQ_PrepareStatement ps[] = {
130 GNUNET_SQ_make_prepare ("INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
131 &plugin->cache_block),
132 GNUNET_SQ_make_prepare ("DELETE FROM ns096blocks WHERE expiration_time<?",
133 &plugin->expire_blocks),
134 GNUNET_SQ_make_prepare ("DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
135 &plugin->delete_block),
136 GNUNET_SQ_make_prepare ("SELECT block FROM ns096blocks WHERE query=? "
137 "ORDER BY expiration_time DESC LIMIT 1",
138 &plugin->lookup_block),
139 GNUNET_SQ_PREPARE_END
144 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
149 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
152 return GNUNET_SYSERR;
155 GNUNET_DISK_file_test (afsdir))
158 GNUNET_DISK_directory_create_for_file (afsdir))
161 GNUNET_free (afsdir);
162 return GNUNET_SYSERR;
165 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
168 /* Open database and precompile statements */
170 sqlite3_open (plugin->fn, &plugin->dbh))
172 LOG (GNUNET_ERROR_TYPE_ERROR,
173 _("Unable to initialize SQLite: %s.\n"),
174 sqlite3_errmsg (plugin->dbh));
175 return GNUNET_SYSERR;
178 GNUNET_SQ_exec_statements (plugin->dbh,
182 LOG (GNUNET_ERROR_TYPE_ERROR,
183 _("Failed to setup database at `%s'\n"),
185 return GNUNET_SYSERR;
187 GNUNET_break (SQLITE_OK ==
188 sqlite3_busy_timeout (plugin->dbh,
192 GNUNET_SQ_prepare (plugin->dbh,
196 LOG (GNUNET_ERROR_TYPE_ERROR,
197 _("Failed to setup database at `%s'\n"),
199 return GNUNET_SYSERR;
207 * Shutdown database connection and associate data
209 * @param plugin the plugin context (state for this module)
212 database_shutdown (struct Plugin *plugin)
217 if (NULL != plugin->cache_block)
218 sqlite3_finalize (plugin->cache_block);
219 if (NULL != plugin->lookup_block)
220 sqlite3_finalize (plugin->lookup_block);
221 if (NULL != plugin->expire_blocks)
222 sqlite3_finalize (plugin->expire_blocks);
223 if (NULL != plugin->delete_block)
224 sqlite3_finalize (plugin->delete_block);
225 result = sqlite3_close (plugin->dbh);
226 if (result == SQLITE_BUSY)
228 LOG (GNUNET_ERROR_TYPE_WARNING,
229 _("Tried to close sqlite without finalizing all prepared statements.\n"));
230 stmt = sqlite3_next_stmt (plugin->dbh,
234 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
236 "Closing statement %p\n",
238 result = sqlite3_finalize (stmt);
239 if (result != SQLITE_OK)
240 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
242 "Failed to close statement %p: %d\n",
245 stmt = sqlite3_next_stmt (plugin->dbh,
248 result = sqlite3_close (plugin->dbh);
250 if (SQLITE_OK != result)
252 GNUNET_ERROR_TYPE_ERROR,
255 GNUNET_free_non_null (plugin->fn);
260 * Removes any expired block.
262 * @param plugin the plugin
265 namecache_sqlite_expire_blocks (struct Plugin *plugin)
267 struct GNUNET_TIME_Absolute now;
268 struct GNUNET_SQ_QueryParam params[] = {
269 GNUNET_SQ_query_param_absolute_time (&now),
270 GNUNET_SQ_query_param_end
274 now = GNUNET_TIME_absolute_get ();
276 GNUNET_SQ_bind (plugin->expire_blocks,
280 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
281 "sqlite3_bind_XXXX");
282 GNUNET_SQ_reset (plugin->dbh,
283 plugin->expire_blocks);
286 n = sqlite3_step (plugin->expire_blocks);
287 GNUNET_SQ_reset (plugin->dbh,
288 plugin->expire_blocks);
292 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
294 "Records expired\n");
298 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
303 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
311 * Cache a block in the datastore.
313 * @param cls closure (internal context for the plugin)
314 * @param block block to cache
315 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
318 namecache_sqlite_cache_block (void *cls,
319 const struct GNUNET_GNSRECORD_Block *block)
321 static struct GNUNET_TIME_Absolute last_expire;
322 struct Plugin *plugin = cls;
323 struct GNUNET_HashCode query;
324 struct GNUNET_TIME_Absolute expiration;
325 size_t block_size = ntohl (block->purpose.size) +
326 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
327 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
328 struct GNUNET_SQ_QueryParam del_params[] = {
329 GNUNET_SQ_query_param_auto_from_type (&query),
330 GNUNET_SQ_query_param_absolute_time (&expiration),
331 GNUNET_SQ_query_param_end
333 struct GNUNET_SQ_QueryParam ins_params[] = {
334 GNUNET_SQ_query_param_auto_from_type (&query),
335 GNUNET_SQ_query_param_fixed_size (block,
337 GNUNET_SQ_query_param_absolute_time (&expiration),
338 GNUNET_SQ_query_param_end
342 /* run expiration of old cache entries once per hour */
343 if (GNUNET_TIME_absolute_get_duration (last_expire).rel_value_us >
344 GNUNET_TIME_UNIT_HOURS.rel_value_us)
346 last_expire = GNUNET_TIME_absolute_get ();
347 namecache_sqlite_expire_blocks (plugin);
349 GNUNET_CRYPTO_hash (&block->derived_key,
350 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
352 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
353 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
354 "Caching new version of block %s (expires %s)\n",
356 GNUNET_STRINGS_absolute_time_to_string (expiration));
357 if (block_size > 64 * 65536)
360 return GNUNET_SYSERR;
363 /* delete old version of the block */
365 GNUNET_SQ_bind (plugin->delete_block,
368 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
369 "sqlite3_bind_XXXX");
370 GNUNET_SQ_reset (plugin->dbh,
371 plugin->delete_block);
372 return GNUNET_SYSERR;
374 n = sqlite3_step (plugin->delete_block);
378 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
380 "Old block deleted\n");
384 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
389 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
393 GNUNET_SQ_reset (plugin->dbh,
394 plugin->delete_block);
396 /* insert new version of the block */
398 GNUNET_SQ_bind (plugin->cache_block,
402 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
403 "sqlite3_bind_XXXX");
404 GNUNET_SQ_reset (plugin->dbh,
405 plugin->cache_block);
406 return GNUNET_SYSERR;
409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
410 "Caching block under derived key `%s'\n",
411 GNUNET_h2s_full (&query));
412 n = sqlite3_step (plugin->cache_block);
413 GNUNET_SQ_reset (plugin->dbh,
414 plugin->cache_block);
418 LOG (GNUNET_ERROR_TYPE_DEBUG,
423 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
428 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
430 return GNUNET_SYSERR;
436 * Get the block for a particular zone and label in the
437 * datastore. Will return at most one result to the iterator.
439 * @param cls closure (internal context for the plugin)
440 * @param query hash of public key derived from the zone and the label
441 * @param iter function to call with the result
442 * @param iter_cls closure for @a iter
443 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
446 namecache_sqlite_lookup_block (void *cls,
447 const struct GNUNET_HashCode *query,
448 GNUNET_NAMECACHE_BlockCallback iter,
451 struct Plugin *plugin = cls;
455 const struct GNUNET_GNSRECORD_Block *block;
456 struct GNUNET_SQ_QueryParam params[] = {
457 GNUNET_SQ_query_param_auto_from_type (query),
458 GNUNET_SQ_query_param_end
460 struct GNUNET_SQ_ResultSpec rs[] = {
461 GNUNET_SQ_result_spec_variable_size ((void **) &block,
463 GNUNET_SQ_result_spec_end
467 GNUNET_SQ_bind (plugin->lookup_block,
471 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
472 "sqlite3_bind_XXXX");
473 GNUNET_SQ_reset (plugin->dbh,
474 plugin->lookup_block);
475 return GNUNET_SYSERR;
479 (sret = sqlite3_step (plugin->lookup_block)))
482 GNUNET_SQ_extract_result (plugin->lookup_block,
488 else if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) ||
489 (ntohl (block->purpose.size) +
490 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
491 sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
494 GNUNET_SQ_cleanup_result (rs);
499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
500 "Found block under derived key `%s'\n",
501 GNUNET_h2s_full (query));
504 GNUNET_SQ_cleanup_result (rs);
510 if (SQLITE_DONE != sret)
513 GNUNET_ERROR_TYPE_ERROR,
519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
520 "No block found under derived key `%s'\n",
521 GNUNET_h2s_full (query));
524 GNUNET_SQ_reset (plugin->dbh,
525 plugin->lookup_block);
531 * Entry point for the plugin.
533 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
534 * @return NULL on error, otherwise the plugin context
537 libgnunet_plugin_namecache_sqlite_init (void *cls)
539 static struct Plugin plugin;
540 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
541 struct GNUNET_NAMECACHE_PluginFunctions *api;
543 if (NULL != plugin.cfg)
544 return NULL; /* can only initialize once! */
545 memset (&plugin, 0, sizeof (struct Plugin));
547 if (GNUNET_OK != database_setup (&plugin))
549 database_shutdown (&plugin);
552 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
554 api->cache_block = &namecache_sqlite_cache_block;
555 api->lookup_block = &namecache_sqlite_lookup_block;
556 LOG (GNUNET_ERROR_TYPE_INFO,
557 _("Sqlite database running\n"));
563 * Exit point from the plugin.
565 * @param cls the plugin context (as returned by "init")
566 * @return always NULL
569 libgnunet_plugin_namecache_sqlite_done (void *cls)
571 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
572 struct Plugin *plugin = api->cls;
574 database_shutdown (plugin);
577 LOG (GNUNET_ERROR_TYPE_DEBUG,
578 "sqlite plugin is finished\n");
582 /* end of plugin_namecache_sqlite.c */