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
28 #include "gnunet_sq_lib.h"
29 #include "gnunet_namecache_plugin.h"
30 #include "gnunet_namecache_service.h"
31 #include "gnunet_gnsrecord_lib.h"
32 #include "namecache.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, "namecache-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, "namecache-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 for caching a block
79 sqlite3_stmt *cache_block;
82 * Precompiled SQL for deleting an older block
84 sqlite3_stmt *delete_block;
87 * Precompiled SQL for looking up a block
89 sqlite3_stmt *lookup_block;
92 * Precompiled SQL for removing expired blocks
94 sqlite3_stmt *expire_blocks;
101 * @brief Prepare a SQL statement
103 * @param dbh handle to the database
104 * @param zSql SQL statement, UTF-8 encoded
105 * @param ppStmt set to the prepared statement
106 * @return 0 on success
109 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
115 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
116 (const char **) &dummy);
117 LOG (GNUNET_ERROR_TYPE_DEBUG,
118 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
124 * Create our database indices.
126 * @param dbh handle to the database
129 create_indices (sqlite3 * dbh)
133 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_query_hash ON ns096blocks (query,expiration_time)",
134 NULL, NULL, NULL)) ||
136 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_block_expiration ON ns096blocks (expiration_time)",
138 LOG (GNUNET_ERROR_TYPE_ERROR,
139 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
144 #define CHECK(a) GNUNET_break(a)
148 #define ENULL_DEFINED 1
149 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
154 * Initialize the database connections and associated
155 * data structures (create tables and indices
156 * as needed as well).
158 * @param plugin the plugin context (state for this module)
159 * @return #GNUNET_OK on success
162 database_setup (struct Plugin *plugin)
171 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namecache-sqlite",
172 "FILENAME", &afsdir))
174 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
175 "namecache-sqlite", "FILENAME");
176 return GNUNET_SYSERR;
178 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
180 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
183 GNUNET_free (afsdir);
184 return GNUNET_SYSERR;
187 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
190 /* Open database and precompile statements */
191 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
193 LOG (GNUNET_ERROR_TYPE_ERROR,
194 _("Unable to initialize SQLite: %s.\n"),
195 sqlite3_errmsg (plugin->dbh));
196 return GNUNET_SYSERR;
199 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
202 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
205 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
208 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
211 sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
214 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
217 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
220 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
225 sq_prepare (plugin->dbh,
226 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
228 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
231 "CREATE TABLE ns096blocks ("
232 " query BLOB NOT NULL DEFAULT '',"
233 " block BLOB NOT NULL DEFAULT '',"
234 " expiration_time INT8 NOT NULL DEFAULT 0"
236 NULL, NULL, NULL) != SQLITE_OK))
238 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
239 sqlite3_finalize (stmt);
240 return GNUNET_SYSERR;
242 sqlite3_finalize (stmt);
243 create_indices (plugin->dbh);
246 sq_prepare (plugin->dbh,
247 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
248 &plugin->cache_block)) ||
250 sq_prepare (plugin->dbh,
251 "DELETE FROM ns096blocks WHERE expiration_time<?",
252 &plugin->expire_blocks)) ||
254 sq_prepare (plugin->dbh,
255 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
256 &plugin->delete_block)) ||
258 sq_prepare (plugin->dbh,
259 "SELECT block FROM ns096blocks WHERE query=? "
260 "ORDER BY expiration_time DESC LIMIT 1",
261 &plugin->lookup_block) )
265 GNUNET_ERROR_TYPE_ERROR,
267 return GNUNET_SYSERR;
274 * Shutdown database connection and associate data
276 * @param plugin the plugin context (state for this module)
279 database_shutdown (struct Plugin *plugin)
284 if (NULL != plugin->cache_block)
285 sqlite3_finalize (plugin->cache_block);
286 if (NULL != plugin->lookup_block)
287 sqlite3_finalize (plugin->lookup_block);
288 if (NULL != plugin->expire_blocks)
289 sqlite3_finalize (plugin->expire_blocks);
290 if (NULL != plugin->delete_block)
291 sqlite3_finalize (plugin->delete_block);
292 result = sqlite3_close (plugin->dbh);
293 if (result == SQLITE_BUSY)
295 LOG (GNUNET_ERROR_TYPE_WARNING,
296 _("Tried to close sqlite without finalizing all prepared statements.\n"));
297 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
300 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
301 "Closing statement %p\n", stmt);
302 result = sqlite3_finalize (stmt);
303 if (result != SQLITE_OK)
304 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
305 "Failed to close statement %p: %d\n", stmt, result);
306 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
308 result = sqlite3_close (plugin->dbh);
310 if (SQLITE_OK != result)
311 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
313 GNUNET_free_non_null (plugin->fn);
318 * Removes any expired block.
320 * @param plugin the plugin
323 namecache_sqlite_expire_blocks (struct Plugin *plugin)
325 struct GNUNET_TIME_Absolute now;
326 struct GNUNET_SQ_QueryParam params[] = {
327 GNUNET_SQ_query_param_absolute_time (&now),
328 GNUNET_SQ_query_param_end
332 now = GNUNET_TIME_absolute_get ();
334 GNUNET_SQ_bind (plugin->expire_blocks,
337 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
338 "sqlite3_bind_XXXX");
339 GNUNET_SQ_reset (plugin->dbh,
340 plugin->expire_blocks);
343 n = sqlite3_step (plugin->expire_blocks);
344 GNUNET_SQ_reset (plugin->dbh,
345 plugin->expire_blocks);
349 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
351 "Records expired\n");
355 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
360 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
368 * Cache a block in the datastore.
370 * @param cls closure (internal context for the plugin)
371 * @param block block to cache
372 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
375 namecache_sqlite_cache_block (void *cls,
376 const struct GNUNET_GNSRECORD_Block *block)
378 struct Plugin *plugin = cls;
379 struct GNUNET_HashCode query;
380 struct GNUNET_TIME_Absolute expiration;
381 size_t block_size = ntohl (block->purpose.size) +
382 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
383 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
384 struct GNUNET_SQ_QueryParam del_params[] = {
385 GNUNET_SQ_query_param_auto_from_type (&query),
386 GNUNET_SQ_query_param_absolute_time (&expiration),
387 GNUNET_SQ_query_param_end
389 struct GNUNET_SQ_QueryParam ins_params[] = {
390 GNUNET_SQ_query_param_auto_from_type (&query),
391 GNUNET_SQ_query_param_fixed_size (block,
393 GNUNET_SQ_query_param_absolute_time (&expiration),
394 GNUNET_SQ_query_param_end
398 namecache_sqlite_expire_blocks (plugin);
399 GNUNET_CRYPTO_hash (&block->derived_key,
400 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
402 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
403 if (block_size > 64 * 65536)
406 return GNUNET_SYSERR;
409 /* delete old version of the block */
411 GNUNET_SQ_bind (plugin->delete_block,
414 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415 "sqlite3_bind_XXXX");
416 GNUNET_SQ_reset (plugin->dbh,
417 plugin->delete_block);
418 return GNUNET_SYSERR;
420 n = sqlite3_step (plugin->delete_block);
424 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
426 "Old block deleted\n");
430 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
435 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
439 GNUNET_SQ_reset (plugin->dbh,
440 plugin->delete_block);
442 /* insert new version of the block */
444 GNUNET_SQ_bind (plugin->cache_block,
448 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
449 "sqlite3_bind_XXXX");
450 GNUNET_SQ_reset (plugin->dbh,
451 plugin->cache_block);
452 return GNUNET_SYSERR;
455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
456 "Caching block under derived key `%s'\n",
457 GNUNET_h2s_full (&query));
458 n = sqlite3_step (plugin->cache_block);
459 GNUNET_SQ_reset (plugin->dbh,
460 plugin->cache_block);
464 LOG (GNUNET_ERROR_TYPE_DEBUG,
469 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
474 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
476 return GNUNET_SYSERR;
482 * Get the block for a particular zone and label in the
483 * datastore. Will return at most one result to the iterator.
485 * @param cls closure (internal context for the plugin)
486 * @param query hash of public key derived from the zone and the label
487 * @param iter function to call with the result
488 * @param iter_cls closure for @a iter
489 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
492 namecache_sqlite_lookup_block (void *cls,
493 const struct GNUNET_HashCode *query,
494 GNUNET_NAMECACHE_BlockCallback iter,
497 struct Plugin *plugin = cls;
501 const struct GNUNET_GNSRECORD_Block *block;
502 struct GNUNET_SQ_QueryParam params[] = {
503 GNUNET_SQ_query_param_auto_from_type (query),
504 GNUNET_SQ_query_param_end
506 struct GNUNET_SQ_ResultSpec rs[] = {
507 GNUNET_SQ_result_spec_variable_size ((void **) &block,
509 GNUNET_SQ_result_spec_end
513 GNUNET_SQ_bind (plugin->lookup_block,
517 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
518 "sqlite3_bind_XXXX");
519 GNUNET_SQ_reset (plugin->dbh,
520 plugin->lookup_block);
521 return GNUNET_SYSERR;
525 (sret = sqlite3_step (plugin->lookup_block)))
528 GNUNET_SQ_extract_result (plugin->lookup_block,
534 else if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) ||
535 (ntohl (block->purpose.size) +
536 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
537 sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
540 GNUNET_SQ_cleanup_result (rs);
545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
546 "Found block under derived key `%s'\n",
547 GNUNET_h2s_full (query));
550 GNUNET_SQ_cleanup_result (rs);
556 if (SQLITE_DONE != sret)
559 GNUNET_ERROR_TYPE_ERROR,
565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
566 "No block found under derived key `%s'\n",
567 GNUNET_h2s_full (query));
570 GNUNET_SQ_reset (plugin->dbh,
571 plugin->lookup_block);
577 * Entry point for the plugin.
579 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
580 * @return NULL on error, otherwise the plugin context
583 libgnunet_plugin_namecache_sqlite_init (void *cls)
585 static struct Plugin plugin;
586 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
587 struct GNUNET_NAMECACHE_PluginFunctions *api;
589 if (NULL != plugin.cfg)
590 return NULL; /* can only initialize once! */
591 memset (&plugin, 0, sizeof (struct Plugin));
593 if (GNUNET_OK != database_setup (&plugin))
595 database_shutdown (&plugin);
598 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
600 api->cache_block = &namecache_sqlite_cache_block;
601 api->lookup_block = &namecache_sqlite_lookup_block;
602 LOG (GNUNET_ERROR_TYPE_INFO,
603 _("Sqlite database running\n"));
609 * Exit point from the plugin.
611 * @param cls the plugin context (as returned by "init")
612 * @return always NULL
615 libgnunet_plugin_namecache_sqlite_done (void *cls)
617 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
618 struct Plugin *plugin = api->cls;
620 database_shutdown (plugin);
623 LOG (GNUNET_ERROR_TYPE_DEBUG,
624 "sqlite plugin is finished\n");
628 /* end of plugin_namecache_sqlite.c */