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)
139 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_query_hash ON ns096blocks (query,expiration_time)",
140 NULL, NULL, NULL)) ||
142 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_block_expiration ON ns096blocks (expiration_time)",
144 LOG (GNUNET_ERROR_TYPE_ERROR,
145 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
150 #define CHECK(a) GNUNET_break(a)
154 #define ENULL_DEFINED 1
155 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
160 * Initialize the database connections and associated
161 * data structures (create tables and indices
162 * as needed as well).
164 * @param plugin the plugin context (state for this module)
165 * @return #GNUNET_OK on success
168 database_setup (struct Plugin *plugin)
177 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
182 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
185 return GNUNET_SYSERR;
188 GNUNET_DISK_file_test (afsdir))
191 GNUNET_DISK_directory_create_for_file (afsdir))
194 GNUNET_free (afsdir);
195 return GNUNET_SYSERR;
198 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
201 /* Open database and precompile statements */
203 sqlite3_open (plugin->fn, &plugin->dbh))
205 LOG (GNUNET_ERROR_TYPE_ERROR,
206 _("Unable to initialize SQLite: %s.\n"),
207 sqlite3_errmsg (plugin->dbh));
208 return GNUNET_SYSERR;
211 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
214 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
217 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
220 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
223 sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
226 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
229 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
232 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
237 sq_prepare (plugin->dbh,
238 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
240 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
243 "CREATE TABLE ns096blocks ("
244 " query BLOB NOT NULL,"
245 " block BLOB NOT NULL,"
246 " expiration_time INT8 NOT NULL"
248 NULL, NULL, NULL) != SQLITE_OK))
250 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
251 sqlite3_finalize (stmt);
252 return GNUNET_SYSERR;
254 sqlite3_finalize (stmt);
255 create_indices (plugin->dbh);
258 sq_prepare (plugin->dbh,
259 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
260 &plugin->cache_block)) ||
262 sq_prepare (plugin->dbh,
263 "DELETE FROM ns096blocks WHERE expiration_time<?",
264 &plugin->expire_blocks)) ||
266 sq_prepare (plugin->dbh,
267 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
268 &plugin->delete_block)) ||
270 sq_prepare (plugin->dbh,
271 "SELECT block FROM ns096blocks WHERE query=? "
272 "ORDER BY expiration_time DESC LIMIT 1",
273 &plugin->lookup_block) )
277 GNUNET_ERROR_TYPE_ERROR,
279 return GNUNET_SYSERR;
286 * Shutdown database connection and associate data
288 * @param plugin the plugin context (state for this module)
291 database_shutdown (struct Plugin *plugin)
296 if (NULL != plugin->cache_block)
297 sqlite3_finalize (plugin->cache_block);
298 if (NULL != plugin->lookup_block)
299 sqlite3_finalize (plugin->lookup_block);
300 if (NULL != plugin->expire_blocks)
301 sqlite3_finalize (plugin->expire_blocks);
302 if (NULL != plugin->delete_block)
303 sqlite3_finalize (plugin->delete_block);
304 result = sqlite3_close (plugin->dbh);
305 if (result == SQLITE_BUSY)
307 LOG (GNUNET_ERROR_TYPE_WARNING,
308 _("Tried to close sqlite without finalizing all prepared statements.\n"));
309 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
312 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
313 "Closing statement %p\n", stmt);
314 result = sqlite3_finalize (stmt);
315 if (result != SQLITE_OK)
316 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
317 "Failed to close statement %p: %d\n", stmt, result);
318 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
320 result = sqlite3_close (plugin->dbh);
322 if (SQLITE_OK != result)
323 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
325 GNUNET_free_non_null (plugin->fn);
330 * Removes any expired block.
332 * @param plugin the plugin
335 namecache_sqlite_expire_blocks (struct Plugin *plugin)
337 struct GNUNET_TIME_Absolute now;
338 struct GNUNET_SQ_QueryParam params[] = {
339 GNUNET_SQ_query_param_absolute_time (&now),
340 GNUNET_SQ_query_param_end
344 now = GNUNET_TIME_absolute_get ();
346 GNUNET_SQ_bind (plugin->expire_blocks,
349 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
350 "sqlite3_bind_XXXX");
351 GNUNET_SQ_reset (plugin->dbh,
352 plugin->expire_blocks);
355 n = sqlite3_step (plugin->expire_blocks);
356 GNUNET_SQ_reset (plugin->dbh,
357 plugin->expire_blocks);
361 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
363 "Records expired\n");
367 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
372 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
380 * Cache a block in the datastore.
382 * @param cls closure (internal context for the plugin)
383 * @param block block to cache
384 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
387 namecache_sqlite_cache_block (void *cls,
388 const struct GNUNET_GNSRECORD_Block *block)
390 struct Plugin *plugin = cls;
391 struct GNUNET_HashCode query;
392 struct GNUNET_TIME_Absolute expiration;
393 size_t block_size = ntohl (block->purpose.size) +
394 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
395 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
396 struct GNUNET_SQ_QueryParam del_params[] = {
397 GNUNET_SQ_query_param_auto_from_type (&query),
398 GNUNET_SQ_query_param_absolute_time (&expiration),
399 GNUNET_SQ_query_param_end
401 struct GNUNET_SQ_QueryParam ins_params[] = {
402 GNUNET_SQ_query_param_auto_from_type (&query),
403 GNUNET_SQ_query_param_fixed_size (block,
405 GNUNET_SQ_query_param_absolute_time (&expiration),
406 GNUNET_SQ_query_param_end
410 namecache_sqlite_expire_blocks (plugin);
411 GNUNET_CRYPTO_hash (&block->derived_key,
412 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
414 fprintf (stderr, // GNUNET_log (GNUNET_ERROR_TYPE_INFO,
415 "Caching new version of block %s (expires %s)\n",
417 GNUNET_STRINGS_absolute_time_to_string (expiration));
418 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
419 if (block_size > 64 * 65536)
422 return GNUNET_SYSERR;
425 /* delete old version of the block */
427 GNUNET_SQ_bind (plugin->delete_block,
430 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
431 "sqlite3_bind_XXXX");
432 GNUNET_SQ_reset (plugin->dbh,
433 plugin->delete_block);
434 return GNUNET_SYSERR;
436 n = sqlite3_step (plugin->delete_block);
440 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
442 "Old block deleted\n");
446 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
451 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
455 GNUNET_SQ_reset (plugin->dbh,
456 plugin->delete_block);
458 /* insert new version of the block */
460 GNUNET_SQ_bind (plugin->cache_block,
464 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
465 "sqlite3_bind_XXXX");
466 GNUNET_SQ_reset (plugin->dbh,
467 plugin->cache_block);
468 return GNUNET_SYSERR;
471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
472 "Caching block under derived key `%s'\n",
473 GNUNET_h2s_full (&query));
474 n = sqlite3_step (plugin->cache_block);
475 GNUNET_SQ_reset (plugin->dbh,
476 plugin->cache_block);
480 LOG (GNUNET_ERROR_TYPE_DEBUG,
485 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
490 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
492 return GNUNET_SYSERR;
498 * Get the block for a particular zone and label in the
499 * datastore. Will return at most one result to the iterator.
501 * @param cls closure (internal context for the plugin)
502 * @param query hash of public key derived from the zone and the label
503 * @param iter function to call with the result
504 * @param iter_cls closure for @a iter
505 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
508 namecache_sqlite_lookup_block (void *cls,
509 const struct GNUNET_HashCode *query,
510 GNUNET_NAMECACHE_BlockCallback iter,
513 struct Plugin *plugin = cls;
517 const struct GNUNET_GNSRECORD_Block *block;
518 struct GNUNET_SQ_QueryParam params[] = {
519 GNUNET_SQ_query_param_auto_from_type (query),
520 GNUNET_SQ_query_param_end
522 struct GNUNET_SQ_ResultSpec rs[] = {
523 GNUNET_SQ_result_spec_variable_size ((void **) &block,
525 GNUNET_SQ_result_spec_end
529 GNUNET_SQ_bind (plugin->lookup_block,
533 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
534 "sqlite3_bind_XXXX");
535 GNUNET_SQ_reset (plugin->dbh,
536 plugin->lookup_block);
537 return GNUNET_SYSERR;
541 (sret = sqlite3_step (plugin->lookup_block)))
544 GNUNET_SQ_extract_result (plugin->lookup_block,
550 else if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) ||
551 (ntohl (block->purpose.size) +
552 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
553 sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
556 GNUNET_SQ_cleanup_result (rs);
561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
562 "Found block under derived key `%s'\n",
563 GNUNET_h2s_full (query));
566 GNUNET_SQ_cleanup_result (rs);
572 if (SQLITE_DONE != sret)
575 GNUNET_ERROR_TYPE_ERROR,
581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582 "No block found under derived key `%s'\n",
583 GNUNET_h2s_full (query));
586 GNUNET_SQ_reset (plugin->dbh,
587 plugin->lookup_block);
593 * Entry point for the plugin.
595 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
596 * @return NULL on error, otherwise the plugin context
599 libgnunet_plugin_namecache_sqlite_init (void *cls)
601 static struct Plugin plugin;
602 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
603 struct GNUNET_NAMECACHE_PluginFunctions *api;
605 if (NULL != plugin.cfg)
606 return NULL; /* can only initialize once! */
607 memset (&plugin, 0, sizeof (struct Plugin));
609 if (GNUNET_OK != database_setup (&plugin))
611 database_shutdown (&plugin);
614 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
616 api->cache_block = &namecache_sqlite_cache_block;
617 api->lookup_block = &namecache_sqlite_lookup_block;
618 LOG (GNUNET_ERROR_TYPE_INFO,
619 _("Sqlite database running\n"));
625 * Exit point from the plugin.
627 * @param cls the plugin context (as returned by "init")
628 * @return always NULL
631 libgnunet_plugin_namecache_sqlite_done (void *cls)
633 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
634 struct Plugin *plugin = api->cls;
636 database_shutdown (plugin);
639 LOG (GNUNET_ERROR_TYPE_DEBUG,
640 "sqlite plugin is finished\n");
644 /* end of plugin_namecache_sqlite.c */