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
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 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;
100 * @brief Prepare a SQL statement
102 * @param dbh handle to the database
103 * @param zSql SQL statement, UTF-8 encoded
104 * @param ppStmt set to the prepared statement
105 * @return 0 on success
108 sq_prepare (sqlite3 *dbh,
110 sqlite3_stmt **ppStmt)
115 result = sqlite3_prepare_v2 (dbh,
119 (const char **) &dummy);
120 LOG (GNUNET_ERROR_TYPE_DEBUG,
121 "Prepared `%s' / %p: %d\n",
130 * Create our database indices.
132 * @param dbh handle to the database
135 create_indices (sqlite3 * dbh)
140 "CREATE INDEX IF NOT EXISTS ir_query_hash ON ns096blocks (query,expiration_time)",
141 NULL, NULL, NULL)) ||
144 "CREATE INDEX IF NOT EXISTS ir_block_expiration ON ns096blocks (expiration_time)",
146 LOG (GNUNET_ERROR_TYPE_ERROR,
147 "Failed to create indices: %s\n",
148 sqlite3_errmsg (dbh));
153 #define CHECK(a) GNUNET_break(a)
157 #define ENULL_DEFINED 1
158 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
163 * Initialize the database connections and associated
164 * data structures (create tables and indices
165 * as needed as well).
167 * @param plugin the plugin context (state for this module)
168 * @return #GNUNET_OK on success
171 database_setup (struct Plugin *plugin)
180 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
185 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
188 return GNUNET_SYSERR;
191 GNUNET_DISK_file_test (afsdir))
194 GNUNET_DISK_directory_create_for_file (afsdir))
197 GNUNET_free (afsdir);
198 return GNUNET_SYSERR;
201 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
204 /* Open database and precompile statements */
206 sqlite3_open (plugin->fn, &plugin->dbh))
208 LOG (GNUNET_ERROR_TYPE_ERROR,
209 _("Unable to initialize SQLite: %s.\n"),
210 sqlite3_errmsg (plugin->dbh));
211 return GNUNET_SYSERR;
214 sqlite3_exec (plugin->dbh,
215 "PRAGMA temp_store=MEMORY",
219 sqlite3_exec (plugin->dbh,
220 "PRAGMA synchronous=NORMAL",
224 sqlite3_exec (plugin->dbh,
225 "PRAGMA legacy_file_format=OFF",
229 sqlite3_exec (plugin->dbh,
230 "PRAGMA auto_vacuum=INCREMENTAL",
234 sqlite3_exec (plugin->dbh,
235 "PRAGMA encoding=\"UTF-8\"",
239 sqlite3_exec (plugin->dbh,
240 "PRAGMA locking_mode=EXCLUSIVE",
244 sqlite3_exec (plugin->dbh,
245 "PRAGMA page_size=4092",
250 sqlite3_busy_timeout (plugin->dbh,
256 sq_prepare (plugin->dbh,
257 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
259 if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
261 sqlite3_exec (plugin->dbh,
262 "CREATE TABLE ns096blocks ("
263 " query BLOB NOT NULL,"
264 " block BLOB NOT NULL,"
265 " expiration_time INT8 NOT NULL"
270 GNUNET_ERROR_TYPE_ERROR,
272 sqlite3_finalize (stmt);
273 return GNUNET_SYSERR;
275 sqlite3_finalize (stmt);
276 create_indices (plugin->dbh);
279 sq_prepare (plugin->dbh,
280 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
281 &plugin->cache_block)) ||
283 sq_prepare (plugin->dbh,
284 "DELETE FROM ns096blocks WHERE expiration_time<?",
285 &plugin->expire_blocks)) ||
287 sq_prepare (plugin->dbh,
288 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
289 &plugin->delete_block)) ||
291 sq_prepare (plugin->dbh,
292 "SELECT block FROM ns096blocks WHERE query=? "
293 "ORDER BY expiration_time DESC LIMIT 1",
294 &plugin->lookup_block) )
298 GNUNET_ERROR_TYPE_ERROR,
300 return GNUNET_SYSERR;
307 * Shutdown database connection and associate data
309 * @param plugin the plugin context (state for this module)
312 database_shutdown (struct Plugin *plugin)
317 if (NULL != plugin->cache_block)
318 sqlite3_finalize (plugin->cache_block);
319 if (NULL != plugin->lookup_block)
320 sqlite3_finalize (plugin->lookup_block);
321 if (NULL != plugin->expire_blocks)
322 sqlite3_finalize (plugin->expire_blocks);
323 if (NULL != plugin->delete_block)
324 sqlite3_finalize (plugin->delete_block);
325 result = sqlite3_close (plugin->dbh);
326 if (result == SQLITE_BUSY)
328 LOG (GNUNET_ERROR_TYPE_WARNING,
329 _("Tried to close sqlite without finalizing all prepared statements.\n"));
330 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
333 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
334 "Closing statement %p\n", stmt);
335 result = sqlite3_finalize (stmt);
336 if (result != SQLITE_OK)
337 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
338 "Failed to close statement %p: %d\n", stmt, result);
339 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
341 result = sqlite3_close (plugin->dbh);
343 if (SQLITE_OK != result)
344 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
346 GNUNET_free_non_null (plugin->fn);
351 * Removes any expired block.
353 * @param plugin the plugin
356 namecache_sqlite_expire_blocks (struct Plugin *plugin)
358 struct GNUNET_TIME_Absolute now;
359 struct GNUNET_SQ_QueryParam params[] = {
360 GNUNET_SQ_query_param_absolute_time (&now),
361 GNUNET_SQ_query_param_end
365 now = GNUNET_TIME_absolute_get ();
367 GNUNET_SQ_bind (plugin->expire_blocks,
370 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
371 "sqlite3_bind_XXXX");
372 GNUNET_SQ_reset (plugin->dbh,
373 plugin->expire_blocks);
376 n = sqlite3_step (plugin->expire_blocks);
377 GNUNET_SQ_reset (plugin->dbh,
378 plugin->expire_blocks);
382 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
384 "Records expired\n");
388 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
393 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
401 * Cache a block in the datastore.
403 * @param cls closure (internal context for the plugin)
404 * @param block block to cache
405 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
408 namecache_sqlite_cache_block (void *cls,
409 const struct GNUNET_GNSRECORD_Block *block)
411 struct Plugin *plugin = cls;
412 struct GNUNET_HashCode query;
413 struct GNUNET_TIME_Absolute expiration;
414 size_t block_size = ntohl (block->purpose.size) +
415 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
416 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
417 struct GNUNET_SQ_QueryParam del_params[] = {
418 GNUNET_SQ_query_param_auto_from_type (&query),
419 GNUNET_SQ_query_param_absolute_time (&expiration),
420 GNUNET_SQ_query_param_end
422 struct GNUNET_SQ_QueryParam ins_params[] = {
423 GNUNET_SQ_query_param_auto_from_type (&query),
424 GNUNET_SQ_query_param_fixed_size (block,
426 GNUNET_SQ_query_param_absolute_time (&expiration),
427 GNUNET_SQ_query_param_end
431 namecache_sqlite_expire_blocks (plugin);
432 GNUNET_CRYPTO_hash (&block->derived_key,
433 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
435 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
436 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
437 "Caching new version of block %s (expires %s)\n",
439 GNUNET_STRINGS_absolute_time_to_string (expiration));
440 if (block_size > 64 * 65536)
443 return GNUNET_SYSERR;
446 /* delete old version of the block */
448 GNUNET_SQ_bind (plugin->delete_block,
451 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
452 "sqlite3_bind_XXXX");
453 GNUNET_SQ_reset (plugin->dbh,
454 plugin->delete_block);
455 return GNUNET_SYSERR;
457 n = sqlite3_step (plugin->delete_block);
461 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
463 "Old block deleted\n");
467 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
472 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
476 GNUNET_SQ_reset (plugin->dbh,
477 plugin->delete_block);
479 /* insert new version of the block */
481 GNUNET_SQ_bind (plugin->cache_block,
485 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
486 "sqlite3_bind_XXXX");
487 GNUNET_SQ_reset (plugin->dbh,
488 plugin->cache_block);
489 return GNUNET_SYSERR;
492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
493 "Caching block under derived key `%s'\n",
494 GNUNET_h2s_full (&query));
495 n = sqlite3_step (plugin->cache_block);
496 GNUNET_SQ_reset (plugin->dbh,
497 plugin->cache_block);
501 LOG (GNUNET_ERROR_TYPE_DEBUG,
506 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
511 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
513 return GNUNET_SYSERR;
519 * Get the block for a particular zone and label in the
520 * datastore. Will return at most one result to the iterator.
522 * @param cls closure (internal context for the plugin)
523 * @param query hash of public key derived from the zone and the label
524 * @param iter function to call with the result
525 * @param iter_cls closure for @a iter
526 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
529 namecache_sqlite_lookup_block (void *cls,
530 const struct GNUNET_HashCode *query,
531 GNUNET_NAMECACHE_BlockCallback iter,
534 struct Plugin *plugin = cls;
538 const struct GNUNET_GNSRECORD_Block *block;
539 struct GNUNET_SQ_QueryParam params[] = {
540 GNUNET_SQ_query_param_auto_from_type (query),
541 GNUNET_SQ_query_param_end
543 struct GNUNET_SQ_ResultSpec rs[] = {
544 GNUNET_SQ_result_spec_variable_size ((void **) &block,
546 GNUNET_SQ_result_spec_end
550 GNUNET_SQ_bind (plugin->lookup_block,
554 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
555 "sqlite3_bind_XXXX");
556 GNUNET_SQ_reset (plugin->dbh,
557 plugin->lookup_block);
558 return GNUNET_SYSERR;
562 (sret = sqlite3_step (plugin->lookup_block)))
565 GNUNET_SQ_extract_result (plugin->lookup_block,
571 else if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) ||
572 (ntohl (block->purpose.size) +
573 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
574 sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
577 GNUNET_SQ_cleanup_result (rs);
582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
583 "Found block under derived key `%s'\n",
584 GNUNET_h2s_full (query));
587 GNUNET_SQ_cleanup_result (rs);
593 if (SQLITE_DONE != sret)
596 GNUNET_ERROR_TYPE_ERROR,
602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
603 "No block found under derived key `%s'\n",
604 GNUNET_h2s_full (query));
607 GNUNET_SQ_reset (plugin->dbh,
608 plugin->lookup_block);
614 * Entry point for the plugin.
616 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
617 * @return NULL on error, otherwise the plugin context
620 libgnunet_plugin_namecache_sqlite_init (void *cls)
622 static struct Plugin plugin;
623 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
624 struct GNUNET_NAMECACHE_PluginFunctions *api;
626 if (NULL != plugin.cfg)
627 return NULL; /* can only initialize once! */
628 memset (&plugin, 0, sizeof (struct Plugin));
630 if (GNUNET_OK != database_setup (&plugin))
632 database_shutdown (&plugin);
635 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
637 api->cache_block = &namecache_sqlite_cache_block;
638 api->lookup_block = &namecache_sqlite_lookup_block;
639 LOG (GNUNET_ERROR_TYPE_INFO,
640 _("Sqlite database running\n"));
646 * Exit point from the plugin.
648 * @param cls the plugin context (as returned by "init")
649 * @return always NULL
652 libgnunet_plugin_namecache_sqlite_done (void *cls)
654 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
655 struct Plugin *plugin = api->cls;
657 database_shutdown (plugin);
660 LOG (GNUNET_ERROR_TYPE_DEBUG,
661 "sqlite plugin is finished\n");
665 /* end of plugin_namecache_sqlite.c */