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, \
53 "namecache-sqlite", _ ( \
54 "`%s' failed at %s:%d with error: %s\n"), \
61 #define LOG(kind, ...) GNUNET_log_from (kind, "namecache-sqlite", __VA_ARGS__)
65 * Context for all functions in this plugin.
69 const struct GNUNET_CONFIGURATION_Handle *cfg;
77 * Native SQLite database handle.
82 * Precompiled SQL for caching a block
84 sqlite3_stmt *cache_block;
87 * Precompiled SQL for deleting an older block
89 sqlite3_stmt *delete_block;
92 * Precompiled SQL for looking up a block
94 sqlite3_stmt *lookup_block;
97 * Precompiled SQL for removing expired blocks
99 sqlite3_stmt *expire_blocks;
104 * Initialize the database connections and associated
105 * data structures (create tables and indices
106 * as needed as well).
108 * @param plugin the plugin context (state for this module)
109 * @return #GNUNET_OK on success
112 database_setup (struct Plugin *plugin)
114 struct GNUNET_SQ_ExecuteStatement es[] = {
115 GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"),
116 GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"),
117 GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"),
118 GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"),
119 GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""),
120 GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"),
121 GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"),
122 GNUNET_SQ_make_try_execute ("PRAGMA journal_mode=WAL"),
123 GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns096blocks ("
124 " query BLOB NOT NULL,"
125 " block BLOB NOT NULL,"
126 " expiration_time INT8 NOT NULL"
128 GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_query_hash "
129 "ON ns096blocks (query,expiration_time)"),
130 GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_block_expiration "
131 "ON ns096blocks (expiration_time)"),
132 GNUNET_SQ_EXECUTE_STATEMENT_END
134 struct GNUNET_SQ_PrepareStatement ps[] = {
135 GNUNET_SQ_make_prepare (
136 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
137 &plugin->cache_block),
138 GNUNET_SQ_make_prepare ("DELETE FROM ns096blocks WHERE expiration_time<?",
139 &plugin->expire_blocks),
140 GNUNET_SQ_make_prepare (
141 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
142 &plugin->delete_block),
143 GNUNET_SQ_make_prepare ("SELECT block FROM ns096blocks WHERE query=? "
144 "ORDER BY expiration_time DESC LIMIT 1",
145 &plugin->lookup_block),
146 GNUNET_SQ_PREPARE_END
151 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
156 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
159 return GNUNET_SYSERR;
162 GNUNET_DISK_file_test (afsdir))
165 GNUNET_DISK_directory_create_for_file (afsdir))
168 GNUNET_free (afsdir);
169 return GNUNET_SYSERR;
172 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
175 /* Open database and precompile statements */
177 sqlite3_open (plugin->fn, &plugin->dbh))
179 LOG (GNUNET_ERROR_TYPE_ERROR,
180 _ ("Unable to initialize SQLite: %s.\n"),
181 sqlite3_errmsg (plugin->dbh));
182 return GNUNET_SYSERR;
185 GNUNET_SQ_exec_statements (plugin->dbh,
189 LOG (GNUNET_ERROR_TYPE_ERROR,
190 _ ("Failed to setup database at `%s'\n"),
192 return GNUNET_SYSERR;
194 GNUNET_break (SQLITE_OK ==
195 sqlite3_busy_timeout (plugin->dbh,
199 GNUNET_SQ_prepare (plugin->dbh,
203 LOG (GNUNET_ERROR_TYPE_ERROR,
204 _ ("Failed to setup database at `%s'\n"),
206 return GNUNET_SYSERR;
214 * Shutdown database connection and associate data
216 * @param plugin the plugin context (state for this module)
219 database_shutdown (struct Plugin *plugin)
224 if (NULL != plugin->cache_block)
225 sqlite3_finalize (plugin->cache_block);
226 if (NULL != plugin->lookup_block)
227 sqlite3_finalize (plugin->lookup_block);
228 if (NULL != plugin->expire_blocks)
229 sqlite3_finalize (plugin->expire_blocks);
230 if (NULL != plugin->delete_block)
231 sqlite3_finalize (plugin->delete_block);
232 result = sqlite3_close (plugin->dbh);
233 if (result == SQLITE_BUSY)
235 LOG (GNUNET_ERROR_TYPE_WARNING,
237 "Tried to close sqlite without finalizing all prepared statements.\n"));
238 stmt = sqlite3_next_stmt (plugin->dbh,
242 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
244 "Closing statement %p\n",
246 result = sqlite3_finalize (stmt);
247 if (result != SQLITE_OK)
248 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
250 "Failed to close statement %p: %d\n",
253 stmt = sqlite3_next_stmt (plugin->dbh,
256 result = sqlite3_close (plugin->dbh);
258 if (SQLITE_OK != result)
260 GNUNET_ERROR_TYPE_ERROR,
263 GNUNET_free_non_null (plugin->fn);
268 * Removes any expired block.
270 * @param plugin the plugin
273 namecache_sqlite_expire_blocks (struct Plugin *plugin)
275 struct GNUNET_TIME_Absolute now;
276 struct GNUNET_SQ_QueryParam params[] = {
277 GNUNET_SQ_query_param_absolute_time (&now),
278 GNUNET_SQ_query_param_end
282 now = GNUNET_TIME_absolute_get ();
284 GNUNET_SQ_bind (plugin->expire_blocks,
288 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
289 "sqlite3_bind_XXXX");
290 GNUNET_SQ_reset (plugin->dbh,
291 plugin->expire_blocks);
294 n = sqlite3_step (plugin->expire_blocks);
295 GNUNET_SQ_reset (plugin->dbh,
296 plugin->expire_blocks);
300 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
302 "Records expired\n");
307 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
313 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
321 * Cache a block in the datastore.
323 * @param cls closure (internal context for the plugin)
324 * @param block block to cache
325 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
328 namecache_sqlite_cache_block (void *cls,
329 const struct GNUNET_GNSRECORD_Block *block)
331 static struct GNUNET_TIME_Absolute last_expire;
332 struct Plugin *plugin = cls;
333 struct GNUNET_HashCode query;
334 struct GNUNET_TIME_Absolute expiration;
335 size_t block_size = ntohl (block->purpose.size)
336 + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)
337 + sizeof(struct GNUNET_CRYPTO_EcdsaSignature);
338 struct GNUNET_SQ_QueryParam del_params[] = {
339 GNUNET_SQ_query_param_auto_from_type (&query),
340 GNUNET_SQ_query_param_absolute_time (&expiration),
341 GNUNET_SQ_query_param_end
343 struct GNUNET_SQ_QueryParam ins_params[] = {
344 GNUNET_SQ_query_param_auto_from_type (&query),
345 GNUNET_SQ_query_param_fixed_size (block,
347 GNUNET_SQ_query_param_absolute_time (&expiration),
348 GNUNET_SQ_query_param_end
352 /* run expiration of old cache entries once per hour */
353 if (GNUNET_TIME_absolute_get_duration (last_expire).rel_value_us >
354 GNUNET_TIME_UNIT_HOURS.rel_value_us)
356 last_expire = GNUNET_TIME_absolute_get ();
357 namecache_sqlite_expire_blocks (plugin);
359 GNUNET_CRYPTO_hash (&block->derived_key,
360 sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey),
362 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
363 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
364 "Caching new version of block %s (expires %s)\n",
366 GNUNET_STRINGS_absolute_time_to_string (expiration));
367 if (block_size > 64 * 65536)
370 return GNUNET_SYSERR;
373 /* delete old version of the block */
375 GNUNET_SQ_bind (plugin->delete_block,
378 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
379 "sqlite3_bind_XXXX");
380 GNUNET_SQ_reset (plugin->dbh,
381 plugin->delete_block);
382 return GNUNET_SYSERR;
384 n = sqlite3_step (plugin->delete_block);
388 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
390 "Old block deleted\n");
395 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
401 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
405 GNUNET_SQ_reset (plugin->dbh,
406 plugin->delete_block);
408 /* insert new version of the block */
410 GNUNET_SQ_bind (plugin->cache_block,
414 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415 "sqlite3_bind_XXXX");
416 GNUNET_SQ_reset (plugin->dbh,
417 plugin->cache_block);
418 return GNUNET_SYSERR;
420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
421 "Caching block under derived key `%s'\n",
422 GNUNET_h2s_full (&query));
423 n = sqlite3_step (plugin->cache_block);
424 GNUNET_SQ_reset (plugin->dbh,
425 plugin->cache_block);
429 LOG (GNUNET_ERROR_TYPE_DEBUG,
435 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
441 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
443 return GNUNET_SYSERR;
449 * Get the block for a particular zone and label in the
450 * datastore. Will return at most one result to the iterator.
452 * @param cls closure (internal context for the plugin)
453 * @param query hash of public key derived from the zone and the label
454 * @param iter function to call with the result
455 * @param iter_cls closure for @a iter
456 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
459 namecache_sqlite_lookup_block (void *cls,
460 const struct GNUNET_HashCode *query,
461 GNUNET_NAMECACHE_BlockCallback iter,
464 struct Plugin *plugin = cls;
468 const struct GNUNET_GNSRECORD_Block *block;
469 struct GNUNET_SQ_QueryParam params[] = {
470 GNUNET_SQ_query_param_auto_from_type (query),
471 GNUNET_SQ_query_param_end
473 struct GNUNET_SQ_ResultSpec rs[] = {
474 GNUNET_SQ_result_spec_variable_size ((void **) &block,
476 GNUNET_SQ_result_spec_end
480 GNUNET_SQ_bind (plugin->lookup_block,
484 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
485 "sqlite3_bind_XXXX");
486 GNUNET_SQ_reset (plugin->dbh,
487 plugin->lookup_block);
488 return GNUNET_SYSERR;
492 (sret = sqlite3_step (plugin->lookup_block)))
495 GNUNET_SQ_extract_result (plugin->lookup_block,
501 else if ((block_size < sizeof(struct GNUNET_GNSRECORD_Block)) ||
502 (ntohl (block->purpose.size)
503 + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)
504 + sizeof(struct GNUNET_CRYPTO_EcdsaSignature) != block_size))
507 GNUNET_SQ_cleanup_result (rs);
512 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
513 "Found block under derived key `%s'\n",
514 GNUNET_h2s_full (query));
517 GNUNET_SQ_cleanup_result (rs);
523 if (SQLITE_DONE != sret)
526 GNUNET_ERROR_TYPE_ERROR,
532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
533 "No block found under derived key `%s'\n",
534 GNUNET_h2s_full (query));
537 GNUNET_SQ_reset (plugin->dbh,
538 plugin->lookup_block);
544 * Entry point for the plugin.
546 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
547 * @return NULL on error, otherwise the plugin context
550 libgnunet_plugin_namecache_sqlite_init (void *cls)
552 static struct Plugin plugin;
553 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
554 struct GNUNET_NAMECACHE_PluginFunctions *api;
556 if (NULL != plugin.cfg)
557 return NULL; /* can only initialize once! */
558 memset (&plugin, 0, sizeof(struct Plugin));
560 if (GNUNET_OK != database_setup (&plugin))
562 database_shutdown (&plugin);
565 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
567 api->cache_block = &namecache_sqlite_cache_block;
568 api->lookup_block = &namecache_sqlite_lookup_block;
569 LOG (GNUNET_ERROR_TYPE_INFO,
570 _ ("Sqlite database running\n"));
576 * Exit point from the plugin.
578 * @param cls the plugin context (as returned by "init")
579 * @return always NULL
582 libgnunet_plugin_namecache_sqlite_done (void *cls)
584 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
585 struct Plugin *plugin = api->cls;
587 database_shutdown (plugin);
590 LOG (GNUNET_ERROR_TYPE_DEBUG,
591 "sqlite plugin is finished\n");
596 /* end of plugin_namecache_sqlite.c */