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 count_changes=OFF", NULL, NULL,
219 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
222 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
227 sq_prepare (plugin->dbh,
228 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
230 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
233 "CREATE TABLE ns096blocks ("
234 " query BLOB NOT NULL DEFAULT '',"
235 " block BLOB NOT NULL DEFAULT '',"
236 " expiration_time INT8 NOT NULL DEFAULT 0"
238 NULL, NULL, NULL) != SQLITE_OK))
240 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
241 sqlite3_finalize (stmt);
242 return GNUNET_SYSERR;
244 sqlite3_finalize (stmt);
245 create_indices (plugin->dbh);
249 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
250 &plugin->cache_block) != SQLITE_OK) ||
253 "DELETE FROM ns096blocks WHERE expiration_time<?",
254 &plugin->expire_blocks) != SQLITE_OK) ||
257 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
258 &plugin->delete_block) != SQLITE_OK) ||
261 "SELECT block FROM ns096blocks WHERE query=? ORDER BY expiration_time DESC LIMIT 1",
262 &plugin->lookup_block) != SQLITE_OK)
265 LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
266 return GNUNET_SYSERR;
273 * Shutdown database connection and associate data
275 * @param plugin the plugin context (state for this module)
278 database_shutdown (struct Plugin *plugin)
283 if (NULL != plugin->cache_block)
284 sqlite3_finalize (plugin->cache_block);
285 if (NULL != plugin->lookup_block)
286 sqlite3_finalize (plugin->lookup_block);
287 if (NULL != plugin->expire_blocks)
288 sqlite3_finalize (plugin->expire_blocks);
289 if (NULL != plugin->delete_block)
290 sqlite3_finalize (plugin->delete_block);
291 result = sqlite3_close (plugin->dbh);
292 if (result == SQLITE_BUSY)
294 LOG (GNUNET_ERROR_TYPE_WARNING,
295 _("Tried to close sqlite without finalizing all prepared statements.\n"));
296 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
299 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
300 "Closing statement %p\n", stmt);
301 result = sqlite3_finalize (stmt);
302 if (result != SQLITE_OK)
303 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
304 "Failed to close statement %p: %d\n", stmt, result);
305 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
307 result = sqlite3_close (plugin->dbh);
309 if (SQLITE_OK != result)
310 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
312 GNUNET_free_non_null (plugin->fn);
317 * Removes any expired block.
319 * @param plugin the plugin
322 namecache_sqlite_expire_blocks (struct Plugin *plugin)
324 struct GNUNET_TIME_Absolute now;
327 now = GNUNET_TIME_absolute_get ();
328 if (SQLITE_OK != sqlite3_bind_int64 (plugin->expire_blocks,
329 1, now.abs_value_us))
331 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
332 "sqlite3_bind_XXXX");
333 if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
335 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
339 n = sqlite3_step (plugin->expire_blocks);
340 if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
341 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
346 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Records expired\n");
349 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
353 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
361 * Cache a block in the datastore.
363 * @param cls closure (internal context for the plugin)
364 * @param block block to cache
365 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
368 namecache_sqlite_cache_block (void *cls,
369 const struct GNUNET_GNSRECORD_Block *block)
371 struct Plugin *plugin = cls;
372 struct GNUNET_HashCode query;
373 struct GNUNET_TIME_Absolute expiration;
378 namecache_sqlite_expire_blocks (plugin);
379 GNUNET_CRYPTO_hash (&block->derived_key,
380 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
382 expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
383 dval = (int64_t) expiration.abs_value_us;
386 block_size = ntohl (block->purpose.size) +
387 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
388 sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
389 if (block_size > 64 * 65536)
392 return GNUNET_SYSERR;
395 /* delete old version of the block */
397 sqlite3_bind_blob (plugin->delete_block, 1,
398 &query, sizeof (struct GNUNET_HashCode),
401 sqlite3_bind_int64 (plugin->delete_block,
404 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
405 "sqlite3_bind_XXXX");
406 if (SQLITE_OK != sqlite3_reset (plugin->delete_block))
408 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
410 return GNUNET_SYSERR;
412 n = sqlite3_step (plugin->delete_block);
416 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Old block deleted\n");
419 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
423 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
427 if (SQLITE_OK != sqlite3_reset (plugin->delete_block))
428 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
431 /* insert new version of the block */
433 sqlite3_bind_blob (plugin->cache_block, 1,
434 &query, sizeof (struct GNUNET_HashCode),
437 sqlite3_bind_blob (plugin->cache_block, 2,
441 sqlite3_bind_int64 (plugin->cache_block, 3,
445 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
446 "sqlite3_bind_XXXX");
447 if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
449 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
451 return GNUNET_SYSERR;
454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
455 "Caching block under derived key `%s'\n",
456 GNUNET_h2s_full (&query));
457 n = sqlite3_step (plugin->cache_block);
458 if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
459 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
464 LOG (GNUNET_ERROR_TYPE_DEBUG,
468 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
472 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
474 return GNUNET_SYSERR;
480 * Get the block for a particular zone and label in the
481 * datastore. Will return at most one result to the iterator.
483 * @param cls closure (internal context for the plugin)
484 * @param query hash of public key derived from the zone and the label
485 * @param iter function to call with the result
486 * @param iter_cls closure for @a iter
487 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
490 namecache_sqlite_lookup_block (void *cls,
491 const struct GNUNET_HashCode *query,
492 GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls)
494 struct Plugin *plugin = cls;
498 const struct GNUNET_GNSRECORD_Block *block;
500 if (SQLITE_OK != sqlite3_bind_blob (plugin->lookup_block, 1,
501 query, sizeof (struct GNUNET_HashCode),
504 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
505 "sqlite3_bind_XXXX");
506 if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
508 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
510 return GNUNET_SYSERR;
513 if (SQLITE_ROW == (sret = sqlite3_step (plugin->lookup_block)))
515 block = sqlite3_column_blob (plugin->lookup_block, 0);
516 block_size = sqlite3_column_bytes (plugin->lookup_block, 0);
517 if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) ||
518 (ntohl (block->purpose.size) +
519 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
520 sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528 "Found block under derived key `%s'\n",
529 GNUNET_h2s_full (query));
530 iter (iter_cls, block);
536 if (SQLITE_DONE != sret)
538 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
544 "No block found under derived key `%s'\n",
545 GNUNET_h2s_full (query));
548 if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
550 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
557 * Entry point for the plugin.
559 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
560 * @return NULL on error, otherwise the plugin context
563 libgnunet_plugin_namecache_sqlite_init (void *cls)
565 static struct Plugin plugin;
566 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
567 struct GNUNET_NAMECACHE_PluginFunctions *api;
569 if (NULL != plugin.cfg)
570 return NULL; /* can only initialize once! */
571 memset (&plugin, 0, sizeof (struct Plugin));
573 if (GNUNET_OK != database_setup (&plugin))
575 database_shutdown (&plugin);
578 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
580 api->cache_block = &namecache_sqlite_cache_block;
581 api->lookup_block = &namecache_sqlite_lookup_block;
582 LOG (GNUNET_ERROR_TYPE_INFO,
583 _("Sqlite database running\n"));
589 * Exit point from the plugin.
591 * @param cls the plugin context (as returned by "init")
592 * @return always NULL
595 libgnunet_plugin_namecache_sqlite_done (void *cls)
597 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
598 struct Plugin *plugin = api->cls;
600 database_shutdown (plugin);
603 LOG (GNUNET_ERROR_TYPE_DEBUG,
604 "sqlite plugin is finished\n");
608 /* end of plugin_namecache_sqlite.c */