2 * This file is part of GNUnet
3 * Copyright (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., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
22 * @file namestore/plugin_namestore_sqlite.c
23 * @brief sqlite-based namestore backend
24 * @author Christian Grothoff
28 #include "gnunet_namestore_plugin.h"
29 #include "gnunet_namestore_service.h"
30 #include "gnunet_gnsrecord_lib.h"
31 #include "namestore.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, "namestore-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, "namestore-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 to store records.
78 sqlite3_stmt *store_records;
81 * Precompiled SQL to deltete existing records.
83 sqlite3_stmt *delete_records;
86 * Precompiled SQL for iterate records within a zone.
88 sqlite3_stmt *iterate_zone;
91 * Precompiled SQL for iterate all records within all zones.
93 sqlite3_stmt *iterate_all_zones;
96 * Precompiled SQL to for reverse lookup based on PKEY.
98 sqlite3_stmt *zone_to_name;
101 * Precompiled SQL to lookup records based on label.
103 sqlite3_stmt *lookup_label;
108 * @brief Prepare a SQL statement
110 * @param dbh handle to the database
111 * @param zSql SQL statement, UTF-8 encoded
112 * @param ppStmt set to the prepared statement
113 * @return 0 on success
116 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
122 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
123 (const char **) &dummy);
124 LOG (GNUNET_ERROR_TYPE_DEBUG,
125 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
131 * Create our database indices.
133 * @param dbh handle to the database
136 create_indices (sqlite3 * dbh)
140 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_pkey_reverse ON ns097records (zone_private_key,pkey)",
141 NULL, NULL, NULL)) ||
143 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_pkey_iter ON ns097records (zone_private_key,rvalue)",
144 NULL, NULL, NULL)) ||
146 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS it_iter ON ns097records (rvalue)",
148 LOG (GNUNET_ERROR_TYPE_ERROR,
149 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
154 #define CHECK(a) GNUNET_break(a)
158 #define ENULL_DEFINED 1
159 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
164 * Initialize the database connections and associated
165 * data structures (create tables and indices
166 * as needed as well).
168 * @param plugin the plugin context (state for this module)
169 * @return #GNUNET_OK on success
172 database_setup (struct Plugin *plugin)
181 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namestore-sqlite",
182 "FILENAME", &afsdir))
184 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
185 "namestore-sqlite", "FILENAME");
186 return GNUNET_SYSERR;
188 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
190 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
193 GNUNET_free (afsdir);
194 return GNUNET_SYSERR;
197 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
200 /* Open database and precompile statements */
201 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
203 LOG (GNUNET_ERROR_TYPE_ERROR,
204 _("Unable to initialize SQLite: %s.\n"),
205 sqlite3_errmsg (plugin->dbh));
206 return GNUNET_SYSERR;
209 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
212 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
215 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
218 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
221 sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
224 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
227 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
230 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
235 sq_prepare (plugin->dbh,
236 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns097records'",
238 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
241 "CREATE TABLE ns097records ("
242 " zone_private_key BLOB NOT NULL DEFAULT '',"
244 " rvalue INT8 NOT NULL DEFAULT '',"
245 " record_count INT NOT NULL DEFAULT 0,"
246 " record_data BLOB NOT NULL DEFAULT '',"
247 " label TEXT NOT NULL DEFAULT ''"
249 NULL, NULL, NULL) != SQLITE_OK))
251 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
252 sqlite3_finalize (stmt);
253 return GNUNET_SYSERR;
255 sqlite3_finalize (stmt);
257 create_indices (plugin->dbh);
261 "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label)"
262 " VALUES (?, ?, ?, ?, ?, ?)",
263 &plugin->store_records) != SQLITE_OK) ||
266 "DELETE FROM ns097records WHERE zone_private_key=? AND label=?",
267 &plugin->delete_records) != SQLITE_OK) ||
270 "SELECT record_count,record_data,label"
271 " FROM ns097records WHERE zone_private_key=? AND pkey=?",
272 &plugin->zone_to_name) != SQLITE_OK) ||
275 "SELECT record_count,record_data,label"
276 " FROM ns097records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
277 &plugin->iterate_zone) != SQLITE_OK) ||
280 "SELECT record_count,record_data,label,zone_private_key"
281 " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET ?",
282 &plugin->iterate_all_zones) != SQLITE_OK) ||
285 "SELECT record_count,record_data,label,zone_private_key"
286 " FROM ns097records WHERE zone_private_key=? AND label=?",
287 &plugin->lookup_label) != SQLITE_OK)
290 LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
291 return GNUNET_SYSERR;
298 * Shutdown database connection and associate data
300 * @param plugin the plugin context (state for this module)
303 database_shutdown (struct Plugin *plugin)
308 if (NULL != plugin->store_records)
309 sqlite3_finalize (plugin->store_records);
310 if (NULL != plugin->delete_records)
311 sqlite3_finalize (plugin->delete_records);
312 if (NULL != plugin->iterate_zone)
313 sqlite3_finalize (plugin->iterate_zone);
314 if (NULL != plugin->iterate_all_zones)
315 sqlite3_finalize (plugin->iterate_all_zones);
316 if (NULL != plugin->zone_to_name)
317 sqlite3_finalize (plugin->zone_to_name);
318 if (NULL != plugin->zone_to_name)
319 sqlite3_finalize (plugin->lookup_label);
320 result = sqlite3_close (plugin->dbh);
321 if (result == SQLITE_BUSY)
323 LOG (GNUNET_ERROR_TYPE_WARNING,
324 _("Tried to close sqlite without finalizing all prepared statements.\n"));
325 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
328 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
329 "Closing statement %p\n", stmt);
330 result = sqlite3_finalize (stmt);
331 if (result != SQLITE_OK)
332 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
333 "Failed to close statement %p: %d\n", stmt, result);
334 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
336 result = sqlite3_close (plugin->dbh);
338 if (SQLITE_OK != result)
339 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
341 GNUNET_free_non_null (plugin->fn);
346 * Store a record in the datastore. Removes any existing record in the
347 * same zone with the same name.
349 * @param cls closure (internal context for the plugin)
350 * @param zone_key private key of the zone
351 * @param label name that is being mapped (at most 255 characters long)
352 * @param rd_count number of entries in @a rd array
353 * @param rd array of records with data to store
354 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
357 namestore_sqlite_store_records (void *cls,
358 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
360 unsigned int rd_count,
361 const struct GNUNET_GNSRECORD_Data *rd)
363 struct Plugin *plugin = cls;
365 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
370 memset (&pkey, 0, sizeof (pkey));
371 for (i=0;i<rd_count;i++)
372 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
374 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) == rd[i].data_size);
380 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
381 data_size = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
382 if (data_size > 64 * 65536)
385 return GNUNET_SYSERR;
388 char data[data_size];
390 if (data_size != GNUNET_GNSRECORD_records_serialize (rd_count, rd,
394 return GNUNET_SYSERR;
397 /* First delete 'old' records */
398 if ((SQLITE_OK != sqlite3_bind_blob (plugin->delete_records, 1,
399 zone_key, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), SQLITE_STATIC)) ||
400 (SQLITE_OK != sqlite3_bind_text (plugin->delete_records, 2, label, -1, SQLITE_STATIC)))
403 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
404 "sqlite3_bind_XXXX");
405 if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
407 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
409 return GNUNET_SYSERR;
412 n = sqlite3_step (plugin->delete_records);
413 if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
414 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
419 if ((SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 1,
420 zone_key, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), SQLITE_STATIC)) ||
421 (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 2,
422 &pkey, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), SQLITE_STATIC)) ||
423 (SQLITE_OK != sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
424 (SQLITE_OK != sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
425 (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 5, data, data_size, SQLITE_STATIC)) ||
426 (SQLITE_OK != sqlite3_bind_text (plugin->store_records, 6, label, -1, SQLITE_STATIC)))
429 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
430 "sqlite3_bind_XXXX");
431 if (SQLITE_OK != sqlite3_reset (plugin->store_records))
433 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
435 return GNUNET_SYSERR;
437 n = sqlite3_step (plugin->store_records);
438 if (SQLITE_OK != sqlite3_reset (plugin->store_records))
439 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
447 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
449 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record deleted\n");
452 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
456 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
458 return GNUNET_SYSERR;
464 * The given 'sqlite' statement has been prepared to be run.
465 * It will return a record which should be given to the iterator.
466 * Runs the statement and parses the returned record.
468 * @param plugin plugin context
469 * @param stmt to run (and then clean up)
470 * @param zone_key private key of the zone
471 * @param iter iterator to call with the result
472 * @param iter_cls closure for @a iter
473 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
476 get_record_and_call_iterator (struct Plugin *plugin,
478 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
479 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
481 unsigned int record_count;
489 if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
491 record_count = sqlite3_column_int (stmt, 0);
492 data_size = sqlite3_column_bytes (stmt, 1);
493 data = sqlite3_column_blob (stmt, 1);
494 label = (const char*) sqlite3_column_text (stmt, 2);
495 if (NULL == zone_key)
497 /* must be "iterate_all_zones", got one extra return value */
498 if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) !=
499 sqlite3_column_bytes (stmt, 3))
506 zone_key = sqlite3_column_blob (stmt, 3);
509 if (record_count > 64 * 1024)
511 /* sanity check, don't stack allocate far too much just
512 because database might contain a large value here */
518 struct GNUNET_GNSRECORD_Data rd[record_count];
521 GNUNET_GNSRECORD_records_deserialize (data_size, data,
527 else if (NULL != zone_key)
530 iter (iter_cls, zone_key, label, record_count, rd);
537 if (SQLITE_DONE != sret)
538 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
540 if (SQLITE_OK != sqlite3_reset (stmt))
542 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
548 * Lookup records in the datastore for which we are the authority.
550 * @param cls closure (internal context for the plugin)
551 * @param zone private key of the zone
552 * @param label name of the record in the zone
553 * @param iter function to call with the result
554 * @param iter_cls closure for @a iter
555 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
558 namestore_sqlite_lookup_records (void *cls,
559 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label,
560 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
562 struct Plugin *plugin = cls;
568 return GNUNET_SYSERR;
572 stmt = plugin->lookup_label;
573 err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
574 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
576 (SQLITE_OK != sqlite3_bind_text (stmt, 2,
577 label, -1, SQLITE_STATIC)) );
581 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
582 "sqlite3_bind_XXXX");
583 if (SQLITE_OK != sqlite3_reset (stmt))
585 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
587 return GNUNET_SYSERR;
589 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
594 * Iterate over the results for a particular key and zone in the
595 * datastore. Will return at most one result to the iterator.
597 * @param cls closure (internal context for the plugin)
598 * @param zone hash of public key of the zone, NULL to iterate over all zones
599 * @param offset offset in the list of all matching records
600 * @param iter function to call with the result
601 * @param iter_cls closure for @a iter
602 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
605 namestore_sqlite_iterate_records (void *cls,
606 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
608 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
610 struct Plugin *plugin = cls;
616 stmt = plugin->iterate_all_zones;
617 err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
622 stmt = plugin->iterate_zone;
623 err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
624 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
626 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
631 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
632 "sqlite3_bind_XXXX");
633 if (SQLITE_OK != sqlite3_reset (stmt))
635 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
637 return GNUNET_SYSERR;
639 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
644 * Look for an existing PKEY delegation record for a given public key.
645 * Returns at most one result to the iterator.
647 * @param cls closure (internal context for the plugin)
648 * @param zone private key of the zone to look up in, never NULL
649 * @param value_zone public key of the target zone (value), never NULL
650 * @param iter function to call with the result
651 * @param iter_cls closure for @a iter
652 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
655 namestore_sqlite_zone_to_name (void *cls,
656 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
657 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
658 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
660 struct Plugin *plugin = cls;
663 stmt = plugin->zone_to_name;
664 if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
665 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
667 (SQLITE_OK != sqlite3_bind_blob (stmt, 2,
668 value_zone, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
671 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
672 "sqlite3_bind_XXXX");
673 if (SQLITE_OK != sqlite3_reset (stmt))
675 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
677 return GNUNET_SYSERR;
679 LOG (GNUNET_ERROR_TYPE_DEBUG,
680 "Performing reverse lookup for `%s'\n",
681 GNUNET_GNSRECORD_z2s (value_zone));
683 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
688 * Entry point for the plugin.
690 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
691 * @return NULL on error, otherwise the plugin context
694 libgnunet_plugin_namestore_sqlite_init (void *cls)
696 static struct Plugin plugin;
697 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
698 struct GNUNET_NAMESTORE_PluginFunctions *api;
700 if (NULL != plugin.cfg)
701 return NULL; /* can only initialize once! */
702 memset (&plugin, 0, sizeof (struct Plugin));
704 if (GNUNET_OK != database_setup (&plugin))
706 database_shutdown (&plugin);
709 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
711 api->store_records = &namestore_sqlite_store_records;
712 api->iterate_records = &namestore_sqlite_iterate_records;
713 api->zone_to_name = &namestore_sqlite_zone_to_name;
714 api->lookup_records = &namestore_sqlite_lookup_records;
715 LOG (GNUNET_ERROR_TYPE_INFO,
716 _("Sqlite database running\n"));
722 * Exit point from the plugin.
724 * @param cls the plugin context (as returned by "init")
725 * @return always NULL
728 libgnunet_plugin_namestore_sqlite_done (void *cls)
730 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
731 struct Plugin *plugin = api->cls;
733 database_shutdown (plugin);
736 LOG (GNUNET_ERROR_TYPE_DEBUG,
737 "sqlite plugin is finished\n");
741 /* end of plugin_namestore_sqlite.c */