2 * This file is part of GNUnet
3 * (C) 2009, 2011, 2012 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 namestore/plugin_namestore_sqlite.c
23 * @brief sqlite-based namestore backend
24 * @author Christian Grothoff
28 #include "gnunet_namestore_plugin.h"
32 * After how many ms "busy" should a DB operation fail for good?
33 * A low value makes sure that we are more responsive to requests
34 * (especially PUTs). A high value guarantees a higher success
35 * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
37 * The default value of 1s should ensure that users do not experience
38 * huge latencies while at the same time allowing operations to succeed
39 * with reasonable probability.
41 #define BUSY_TIMEOUT_MS 1000
45 * Log an error message at log-level 'level' that indicates
46 * a failure of the command 'cmd' on file 'filename'
47 * with the message given by strerror(errno).
49 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "namestore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
51 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-sqlite", __VA_ARGS__)
55 * Context for all functions in this plugin.
60 const struct GNUNET_CONFIGURATION_Handle *cfg;
68 * Native SQLite database handle.
73 * Precompiled SQL for put record
75 sqlite3_stmt *put_records;
78 * Precompiled SQL for remove record
80 sqlite3_stmt *remove_records;
83 * Precompiled SQL for iterate over all records.
85 sqlite3_stmt *iterate_all;
88 * Precompiled SQL for iterate records with same name.
90 sqlite3_stmt *iterate_by_name;
93 * Precompiled SQL for iterate records with same zone.
95 sqlite3_stmt *iterate_by_zone;
98 * Precompiled SQL for iterate records with same name and zone.
100 sqlite3_stmt *iterate_records;
103 * Precompiled SQL for delete zone
105 sqlite3_stmt *delete_zone;
111 * @brief Prepare a SQL statement
113 * @param dbh handle to the database
114 * @param zSql SQL statement, UTF-8 encoded
115 * @param ppStmt set to the prepared statement
116 * @return 0 on success
119 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
125 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
126 (const char **) &dummy);
127 LOG (GNUNET_ERROR_TYPE_DEBUG,
128 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
134 * Create our database indices.
136 * @param dbh handle to the database
139 create_indices (sqlite3 * dbh)
143 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone_name_rv ON ns090records (zone_hash,record_name_hash,rvalue)",
144 NULL, NULL, NULL)) ||
146 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone_rv ON ns090records (zone_hash,rvalue)",
147 NULL, NULL, NULL)) ||
149 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_zone ON ns090records (zone_hash)",
150 NULL, NULL, NULL)) ||
152 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_name_rv ON ns090records (record_name_hash,rvalue)",
153 NULL, NULL, NULL)) ||
155 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_rv ON ns090records (rvalue)",
157 LOG (GNUNET_ERROR_TYPE_ERROR,
158 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
163 #define CHECK(a) GNUNET_break(a)
167 #define ENULL_DEFINED 1
168 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
173 * Initialize the database connections and associated
174 * data structures (create tables and indices
175 * as needed as well).
177 * @param plugin the plugin context (state for this module)
178 * @return GNUNET_OK on success
181 database_setup (struct Plugin *plugin)
190 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namestore-sqlite",
191 "FILENAME", &afsdir))
193 LOG (GNUNET_ERROR_TYPE_ERROR,
194 _ ("Option `%s' in section `%s' missing in configuration!\n"),
195 "FILENAME", "namestore-sqlite");
196 return GNUNET_SYSERR;
198 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
200 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
203 GNUNET_free (afsdir);
204 return GNUNET_SYSERR;
209 GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
211 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8"); /* good luck */
213 GNUNET_free (afsdir);
215 /* Open database and precompile statements */
216 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
218 LOG (GNUNET_ERROR_TYPE_ERROR,
219 _("Unable to initialize SQLite: %s.\n"),
220 sqlite3_errmsg (plugin->dbh));
221 return GNUNET_SYSERR;
224 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
227 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
230 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
233 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
236 sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
239 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
242 sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
245 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
248 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
253 sq_prepare (plugin->dbh,
254 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns090records'",
256 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
259 "CREATE TABLE ns090records ("
260 " zone_hash BLOB NOT NULL DEFAULT '',"
261 " record_data BLOB NOT NULL DEFAULT ''"
262 " block_expiration_time INT8 NOT NULL DEFAULT 0,"
263 " record_name TEXT NOT NULL DEFAULT '',"
264 " record_name_hash BLOB NOT NULL DEFAULT '',"
265 " rvalue INT8 NOT NULL DEFAULT ''"
267 NULL, NULL, NULL) != SQLITE_OK))
269 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
270 sqlite3_finalize (stmt);
271 return GNUNET_SYSERR;
273 sqlite3_finalize (stmt);
275 create_indices (plugin->dbh);
277 #define ALL "zone_hash, record_name, record_data, block_expiration_time"
280 "INSERT INTO ns090records (" ALL ", record_name_hash, rvalue) VALUES "
281 "(?, ?, ?, ?, ?, ?)",
282 &plugin->put_records) != SQLITE_OK) ||
285 "DELETE FROM ns090records WHERE zone_hash=? AND record_name_hash=?",
286 &plugin->remove_records) != SQLITE_OK) ||
290 "FROM ns090records WHERE zone_hash=? AND record_name_hash=? ORDER BY rvalue OFFSET ? LIMIT 1",
291 &plugin->iterate_records) != SQLITE_OK) ||
295 "FROM ns090records WHERE zone_hash=? ORDER BY rvalue OFFSET ? LIMIT 1",
296 &plugin->iterate_by_zone) != SQLITE_OK) ||
300 "FROM ns090records WHERE record_name_hash=? ORDER BY rvalue OFFSET ? LIMIT 1",
301 &plugin->iterate_by_name) != SQLITE_OK) ||
305 "FROM ns090records ORDER BY rvalue OFFSET ? LIMIT 1",
306 &plugin->iterate_all) != SQLITE_OK) ||
309 "DELETE FROM ns090records WHERE zone_hash=?",
310 &plugin->delete_zone) != SQLITE_OK) )
312 LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
313 return GNUNET_SYSERR;
321 * Shutdown database connection and associate data
323 * @param plugin the plugin context (state for this module)
326 database_shutdown (struct Plugin *plugin)
331 if (NULL != plugin->put_records)
332 sqlite3_finalize (plugin->put_records);
333 if (NULL != plugin->remove_records)
334 sqlite3_finalize (plugin->remove_records);
335 if (NULL != plugin->iterate_records)
336 sqlite3_finalize (plugin->iterate_records);
337 if (NULL != plugin->iterate_records)
338 sqlite3_finalize (plugin->iterate_by_zone);
339 if (NULL != plugin->iterate_records)
340 sqlite3_finalize (plugin->iterate_by_name);
341 if (NULL != plugin->iterate_records)
342 sqlite3_finalize (plugin->iterate_all);
343 if (NULL != plugin->delete_zone)
344 sqlite3_finalize (plugin->delete_zone);
345 result = sqlite3_close (plugin->dbh);
346 if (result == SQLITE_BUSY)
348 LOG (GNUNET_ERROR_TYPE_WARNING,
349 _("Tried to close sqlite without finalizing all prepared statements.\n"));
350 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
353 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
354 "Closing statement %p\n", stmt);
355 result = sqlite3_finalize (stmt);
356 if (result != SQLITE_OK)
357 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
358 "Failed to close statement %p: %d\n", stmt, result);
359 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
361 result = sqlite3_close (plugin->dbh);
363 if (SQLITE_OK != result)
364 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
366 GNUNET_free_non_null (plugin->fn);
371 * Store a record in the datastore.
373 * @param cls closure (internal context for the plugin)
374 * @param zone hash of the public key of the zone
375 * @param name name that is being mapped (at most 255 characters long)
376 * @param record_type type of the record (A, AAAA, PKEY, etc.)
377 * @param loc location of the signature for the record
378 * @param expiration expiration time for the content
379 * @param flags flags for the content
380 * @param data_size number of bytes in data
381 * @param data value, semantics depend on 'record_type' (see RFCs for DNS and
382 * GNS specification for GNS extensions)
383 * @return GNUNET_OK on success
386 namestore_sqlite_put_records (void *cls,
387 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
388 struct GNUNET_TIME_Absolute expire,
390 unsigned int rd_count,
391 const struct GNUNET_NAMESTORE_RecordData *rd,
392 const struct GNUNET_CRYPTO_RsaSignature *signature)
395 struct Plugin *plugin = cls;
400 name_len = strlen (name);
401 GNUNET_CRYPTO_hash (name, name_len, &nh);
402 if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
403 (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 2, loc->revision)) ||
404 (SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 3, &nh, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
405 (SQLITE_OK != sqlite3_bind_text (plugin->put_record, 4, name, -1, SQLITE_STATIC)) ||
406 (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 5, record_type)) ||
407 (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 6, loc->depth)) ||
408 (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 7, loc->offset)) ||
409 (SQLITE_OK != sqlite3_bind_int64 (plugin->put_record, 8, expiration.abs_value)) ||
410 (SQLITE_OK != sqlite3_bind_int (plugin->put_record, 9, flags)) ||
411 (SQLITE_OK != sqlite3_bind_blob (plugin->put_record, 10, data, data_size, SQLITE_STATIC)) )
414 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415 "sqlite3_bind_XXXX");
416 if (SQLITE_OK != sqlite3_reset (plugin->put_record))
418 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
420 return GNUNET_SYSERR;
423 n = sqlite3_step (plugin->put_record);
424 if (SQLITE_OK != sqlite3_reset (plugin->put_record))
425 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
430 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
433 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
437 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
439 return GNUNET_SYSERR;
442 return GNUNET_SYSERR;
447 * Store a Merkle tree node in the datastore.
449 * @param cls closure (internal context for the plugin)
450 * @param zone hash of public key of the zone
451 * @param loc location in the B-tree
452 * @param ploc parent's location in the B-tree (must have depth = loc.depth + 1), NULL for root
453 * @param num_entries number of entries at this node in the B-tree
454 * @param entries the 'num_entries' entries to store (hashes over the
456 * @return GNUNET_OK on success
459 namestore_sqlite_remove_records (void *cls,
460 const GNUNET_HashCode *zone,
464 struct Plugin *plugin = cls;
467 if ( (loc->revision != ploc->revision) ||
468 (loc->depth + 1 != ploc->depth) ||
472 return GNUNET_SYSERR;
474 if ((SQLITE_OK != sqlite3_bind_blob (plugin->put_node, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC)) ||
475 (SQLITE_OK != sqlite3_bind_int (plugin->put_node, 2, loc->revision)) ||
476 (SQLITE_OK != sqlite3_bind_int (plugin->put_node, 3, loc->depth)) ||
477 (SQLITE_OK != sqlite3_bind_int64 (plugin->put_node, 4, loc->offset)) ||
478 (SQLITE_OK != sqlite3_bind_int64 (plugin->put_node, 5, ploc->offset)) ||
479 (SQLITE_OK != sqlite3_bind_blob (plugin->put_node, 6, entries, num_entries * sizeof (GNUNET_HashCode), SQLITE_STATIC)) )
481 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
482 "sqlite3_bind_XXXX");
483 if (SQLITE_OK != sqlite3_reset (plugin->put_node))
485 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
487 return GNUNET_SYSERR;
490 n = sqlite3_step (plugin->put_node);
491 if (SQLITE_OK != sqlite3_reset (plugin->put_node))
492 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
497 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Node stored\n");
500 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
504 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
506 return GNUNET_SYSERR;
509 return GNUNET_SYSERR;
514 * Iterate over the results for a particular key and zone in the
515 * datastore. Will only query the latest revision known for the
516 * zone (as adding a new zone revision will cause the plugin to
517 * delete all records from previous revisions).
519 * @param cls closure (internal context for the plugin)
520 * @param zone hash of public key of the zone, NULL to iterate over all zones
521 * @param name_hash hash of name, NULL to iterate over all records of the zone
522 * @param offset offset in the list of all matching records
523 * @param iter maybe NULL (to just count)
524 * @param iter_cls closure for iter
525 * @return GNUNET_OK on success, GNUNET_NO if there were no results, GNUNET_SYSERR on error
528 namestore_sqlite_iterate_records (void *cls,
529 const GNUNET_HashCode *zone,
530 const GNUNET_HashCode *name_hash,
532 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
535 struct Plugin *plugin = cls;
538 struct GNUNET_TIME_Absolute expiration;
539 uint32_t record_type;
540 enum GNUNET_NAMESTORE_RecordFlags flags;
543 struct GNUNET_NAMESTORE_SignatureLocation loc;
546 if ((SQLITE_OK != sqlite3_bind_blob (plugin->iterate_records, 1,
547 zone, sizeof (GNUNET_HashCode),
549 (SQLITE_OK != sqlite3_bind_blob (plugin->iterate_records, 2,
550 name_hash, sizeof (GNUNET_HashCode),
553 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
554 "sqlite3_bind_XXXX");
555 if (SQLITE_OK != sqlite3_reset (plugin->iterate_records))
557 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
559 return GNUNET_SYSERR;
562 while (SQLITE_ROW == (sret = sqlite3_step (plugin->iterate_records)))
566 continue; /* FIXME: just counting can be done more cheaply... */
567 loc.revision = sqlite3_column_int (plugin->iterate_records, 0);
568 name = (const char*) sqlite3_column_text (plugin->iterate_records, 1);
569 record_type = sqlite3_column_int (plugin->iterate_records, 2);
570 loc.depth = sqlite3_column_int (plugin->iterate_records, 3);
571 loc.offset = sqlite3_column_int64 (plugin->iterate_records, 4);
572 expiration.abs_value = (uint64_t) sqlite3_column_int64 (plugin->iterate_records, 5);
573 flags = (enum GNUNET_NAMESTORE_RecordFlags) sqlite3_column_int (plugin->iterate_records, 6);
574 data = sqlite3_column_blob (plugin->iterate_records, 7);
575 data_size = sqlite3_column_bytes (plugin->iterate_records, 7);
576 iter (iter_cls, zone,
577 &loc, name, record_type,
578 expiration, flags, data_size, data);
580 if (SQLITE_DONE != sret)
581 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
582 if (SQLITE_OK != sqlite3_reset (plugin->iterate_records))
584 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
588 return GNUNET_SYSERR;
593 * Delete an entire zone (all records). Not used in normal operation.
595 * @param cls closure (internal context for the plugin)
596 * @param zone zone to delete
599 namestore_sqlite_delete_zone (void *cls,
600 const GNUNET_HashCode *zone)
602 struct Plugin *plugin = cls;
603 sqlite3_stmt *stmt = plugin->delete_zone;
606 if (SQLITE_OK != sqlite3_bind_blob (stmt, 1, zone, sizeof (GNUNET_HashCode), SQLITE_STATIC))
608 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
609 "sqlite3_bind_XXXX");
610 if (SQLITE_OK != sqlite3_reset (stmt))
612 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
616 n = sqlite3_step (stmt);
617 if (SQLITE_OK != sqlite3_reset (stmt))
618 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
623 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Values deleted\n");
626 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
630 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
638 * Entry point for the plugin.
640 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
641 * @return NULL on error, othrewise the plugin context
644 libgnunet_plugin_namestore_sqlite_init (void *cls)
646 static struct Plugin plugin;
647 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
648 struct GNUNET_NAMESTORE_PluginFunctions *api;
650 if (NULL != plugin.cfg)
651 return NULL; /* can only initialize once! */
652 memset (&plugin, 0, sizeof (struct Plugin));
654 if (GNUNET_OK != database_setup (&plugin))
656 database_shutdown (&plugin);
659 api = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_PluginFunctions));
661 api->put_records = &namestore_sqlite_put_records;
662 api->remove_records = &namestore_sqlite_remove_records;
663 api->iterate_records = &namestore_sqlite_iterate_records;
664 api->delete_zone = &namestore_sqlite_delete_zone;
665 LOG (GNUNET_ERROR_TYPE_INFO,
666 _("Sqlite database running\n"));
672 * Exit point from the plugin.
674 * @param cls the plugin context (as returned by "init")
675 * @return always NULL
678 libgnunet_plugin_namestore_sqlite_done (void *cls)
680 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
681 struct Plugin *plugin = api->cls;
683 LOG (GNUNET_ERROR_TYPE_DEBUG,
684 "sqlite plugin is done\n");
685 database_shutdown (plugin);
688 LOG (GNUNET_ERROR_TYPE_DEBUG,
689 "sqlite plugin is finished\n");
693 /* end of plugin_namestore_sqlite.c */