2 * This file is part of GNUnet
3 * (C) 2009-2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
22 * @file namecache/plugin_namecache_sqlite.c
23 * @brief sqlite-based namecache backend
24 * @author Christian Grothoff
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, const char *zSql, sqlite3_stmt ** ppStmt)
114 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
115 (const char **) &dummy);
116 LOG (GNUNET_ERROR_TYPE_DEBUG,
117 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
123 * Create our database indices.
125 * @param dbh handle to the database
128 create_indices (sqlite3 * dbh)
132 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_query_hash ON ns096blocks (query,expiration_time)",
133 NULL, NULL, NULL)) ||
135 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_block_expiration ON ns096blocks (expiration_time)",
137 LOG (GNUNET_ERROR_TYPE_ERROR,
138 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
143 #define CHECK(a) GNUNET_break(a)
147 #define ENULL_DEFINED 1
148 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
153 * Initialize the database connections and associated
154 * data structures (create tables and indices
155 * as needed as well).
157 * @param plugin the plugin context (state for this module)
158 * @return #GNUNET_OK on success
161 database_setup (struct Plugin *plugin)
170 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namecache-sqlite",
171 "FILENAME", &afsdir))
173 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
174 "namecache-sqlite", "FILENAME");
175 return GNUNET_SYSERR;
177 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
179 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
182 GNUNET_free (afsdir);
183 return GNUNET_SYSERR;
186 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
189 /* Open database and precompile statements */
190 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
192 LOG (GNUNET_ERROR_TYPE_ERROR,
193 _("Unable to initialize SQLite: %s.\n"),
194 sqlite3_errmsg (plugin->dbh));
195 return GNUNET_SYSERR;
198 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
201 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
204 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
207 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
210 sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
213 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
216 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
219 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
224 sq_prepare (plugin->dbh,
225 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
227 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
230 "CREATE TABLE ns096blocks ("
231 " query BLOB NOT NULL DEFAULT '',"
232 " block BLOB NOT NULL DEFAULT '',"
233 " expiration_time INT8 NOT NULL DEFAULT 0"
235 NULL, NULL, NULL) != SQLITE_OK))
237 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
238 sqlite3_finalize (stmt);
239 return GNUNET_SYSERR;
241 sqlite3_finalize (stmt);
242 create_indices (plugin->dbh);
246 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
247 &plugin->cache_block) != SQLITE_OK) ||
250 "DELETE FROM ns096blocks WHERE expiration_time<?",
251 &plugin->expire_blocks) != SQLITE_OK) ||
254 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
255 &plugin->delete_block) != SQLITE_OK) ||
258 "SELECT block FROM ns096blocks WHERE query=? ORDER BY expiration_time DESC LIMIT 1",
259 &plugin->lookup_block) != SQLITE_OK)
262 LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
263 return GNUNET_SYSERR;
270 * Shutdown database connection and associate data
272 * @param plugin the plugin context (state for this module)
275 database_shutdown (struct Plugin *plugin)
280 if (NULL != plugin->cache_block)
281 sqlite3_finalize (plugin->cache_block);
282 if (NULL != plugin->lookup_block)
283 sqlite3_finalize (plugin->lookup_block);
284 if (NULL != plugin->expire_blocks)
285 sqlite3_finalize (plugin->expire_blocks);
286 if (NULL != plugin->delete_block)
287 sqlite3_finalize (plugin->delete_block);
288 result = sqlite3_close (plugin->dbh);
289 if (result == SQLITE_BUSY)
291 LOG (GNUNET_ERROR_TYPE_WARNING,
292 _("Tried to close sqlite without finalizing all prepared statements.\n"));
293 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
296 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
297 "Closing statement %p\n", stmt);
298 result = sqlite3_finalize (stmt);
299 if (result != SQLITE_OK)
300 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
301 "Failed to close statement %p: %d\n", stmt, result);
302 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
304 result = sqlite3_close (plugin->dbh);
306 if (SQLITE_OK != result)
307 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
309 GNUNET_free_non_null (plugin->fn);
314 * Removes any expired block.
316 * @param plugin the plugin
319 namecache_sqlite_expire_blocks (struct Plugin *plugin)
321 struct GNUNET_TIME_Absolute now;
324 now = GNUNET_TIME_absolute_get ();
325 if (SQLITE_OK != sqlite3_bind_int64 (plugin->expire_blocks,
326 1, now.abs_value_us))
328 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
329 "sqlite3_bind_XXXX");
330 if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
332 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
336 n = sqlite3_step (plugin->expire_blocks);
337 if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
338 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
343 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Records expired\n");
346 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
350 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
358 * Cache a block in the datastore.
360 * @param cls closure (internal context for the plugin)
361 * @param block block to cache
362 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
365 namecache_sqlite_cache_block (void *cls,
366 const struct GNUNET_GNSRECORD_Block *block)
368 struct Plugin *plugin = cls;
369 struct GNUNET_HashCode query;
370 struct GNUNET_TIME_Absolute expiration;
375 namecache_sqlite_expire_blocks (plugin);
376 GNUNET_CRYPTO_hash (&block->derived_key,
377 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
379 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
380 dval = (int64_t) expiration.abs_value_us;
383 block_size = ntohl (block->purpose.size) +
384 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
385 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
386 if (block_size > 64 * 65536)
389 return GNUNET_SYSERR;
392 /* delete old version of the block */
394 sqlite3_bind_blob (plugin->delete_block, 1,
395 &query, sizeof (struct GNUNET_HashCode),
398 sqlite3_bind_int64 (plugin->delete_block,
401 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
402 "sqlite3_bind_XXXX");
403 if (SQLITE_OK != sqlite3_reset (plugin->delete_block))
405 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
407 return GNUNET_SYSERR;
409 n = sqlite3_step (plugin->delete_block);
413 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Old block deleted\n");
416 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
420 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
424 if (SQLITE_OK != sqlite3_reset (plugin->delete_block))
425 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
428 /* insert new version of the block */
430 sqlite3_bind_blob (plugin->cache_block, 1,
431 &query, sizeof (struct GNUNET_HashCode),
434 sqlite3_bind_blob (plugin->cache_block, 2,
438 sqlite3_bind_int64 (plugin->cache_block, 3,
442 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
443 "sqlite3_bind_XXXX");
444 if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
446 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
448 return GNUNET_SYSERR;
451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
452 "Caching block under derived key `%s'\n",
453 GNUNET_h2s_full (&query));
454 n = sqlite3_step (plugin->cache_block);
455 if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
456 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
461 LOG (GNUNET_ERROR_TYPE_DEBUG,
465 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
469 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
471 return GNUNET_SYSERR;
477 * Get the block for a particular zone and label in the
478 * datastore. Will return at most one result to the iterator.
480 * @param cls closure (internal context for the plugin)
481 * @param query hash of public key derived from the zone and the label
482 * @param iter function to call with the result
483 * @param iter_cls closure for @a iter
484 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
487 namecache_sqlite_lookup_block (void *cls,
488 const struct GNUNET_HashCode *query,
489 GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls)
491 struct Plugin *plugin = cls;
495 const struct GNUNET_GNSRECORD_Block *block;
497 if (SQLITE_OK != sqlite3_bind_blob (plugin->lookup_block, 1,
498 query, sizeof (struct GNUNET_HashCode),
501 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
502 "sqlite3_bind_XXXX");
503 if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
505 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
507 return GNUNET_SYSERR;
510 if (SQLITE_ROW == (sret = sqlite3_step (plugin->lookup_block)))
512 block = sqlite3_column_blob (plugin->lookup_block, 0);
513 block_size = sqlite3_column_bytes (plugin->lookup_block, 0);
514 if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) ||
515 (ntohl (block->purpose.size) +
516 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
517 sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
524 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
525 "Found block under derived key `%s'\n",
526 GNUNET_h2s_full (query));
527 iter (iter_cls, block);
533 if (SQLITE_DONE != sret)
535 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
541 "No block found under derived key `%s'\n",
542 GNUNET_h2s_full (query));
545 if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
547 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
554 * Entry point for the plugin.
556 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
557 * @return NULL on error, otherwise the plugin context
560 libgnunet_plugin_namecache_sqlite_init (void *cls)
562 static struct Plugin plugin;
563 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
564 struct GNUNET_NAMECACHE_PluginFunctions *api;
566 if (NULL != plugin.cfg)
567 return NULL; /* can only initialize once! */
568 memset (&plugin, 0, sizeof (struct Plugin));
570 if (GNUNET_OK != database_setup (&plugin))
572 database_shutdown (&plugin);
575 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
577 api->cache_block = &namecache_sqlite_cache_block;
578 api->lookup_block = &namecache_sqlite_lookup_block;
579 LOG (GNUNET_ERROR_TYPE_INFO,
580 _("Sqlite database running\n"));
586 * Exit point from the plugin.
588 * @param cls the plugin context (as returned by "init")
589 * @return always NULL
592 libgnunet_plugin_namecache_sqlite_done (void *cls)
594 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
595 struct Plugin *plugin = api->cls;
597 database_shutdown (plugin);
600 LOG (GNUNET_ERROR_TYPE_DEBUG,
601 "sqlite plugin is finished\n");
605 /* end of plugin_namecache_sqlite.c */