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 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 count_changes=OFF", NULL, NULL,
230 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
233 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
238 sq_prepare (plugin->dbh,
239 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns097records'",
241 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
244 "CREATE TABLE ns097records ("
245 " zone_private_key BLOB NOT NULL DEFAULT '',"
247 " rvalue INT8 NOT NULL DEFAULT '',"
248 " record_count INT NOT NULL DEFAULT 0,"
249 " record_data BLOB NOT NULL DEFAULT '',"
250 " label TEXT NOT NULL DEFAULT ''"
252 NULL, NULL, NULL) != SQLITE_OK))
254 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
255 sqlite3_finalize (stmt);
256 return GNUNET_SYSERR;
258 sqlite3_finalize (stmt);
260 create_indices (plugin->dbh);
264 "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label)"
265 " VALUES (?, ?, ?, ?, ?, ?)",
266 &plugin->store_records) != SQLITE_OK) ||
269 "DELETE FROM ns097records WHERE zone_private_key=? AND label=?",
270 &plugin->delete_records) != SQLITE_OK) ||
273 "SELECT record_count,record_data,label"
274 " FROM ns097records WHERE zone_private_key=? AND pkey=?",
275 &plugin->zone_to_name) != SQLITE_OK) ||
278 "SELECT record_count,record_data,label"
279 " FROM ns097records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
280 &plugin->iterate_zone) != SQLITE_OK) ||
283 "SELECT record_count,record_data,label,zone_private_key"
284 " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET ?",
285 &plugin->iterate_all_zones) != SQLITE_OK) ||
288 "SELECT record_count,record_data,label,zone_private_key"
289 " FROM ns097records WHERE zone_private_key=? AND label=?",
290 &plugin->lookup_label) != SQLITE_OK)
293 LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
294 return GNUNET_SYSERR;
301 * Shutdown database connection and associate data
303 * @param plugin the plugin context (state for this module)
306 database_shutdown (struct Plugin *plugin)
311 if (NULL != plugin->store_records)
312 sqlite3_finalize (plugin->store_records);
313 if (NULL != plugin->delete_records)
314 sqlite3_finalize (plugin->delete_records);
315 if (NULL != plugin->iterate_zone)
316 sqlite3_finalize (plugin->iterate_zone);
317 if (NULL != plugin->iterate_all_zones)
318 sqlite3_finalize (plugin->iterate_all_zones);
319 if (NULL != plugin->zone_to_name)
320 sqlite3_finalize (plugin->zone_to_name);
321 if (NULL != plugin->zone_to_name)
322 sqlite3_finalize (plugin->lookup_label);
323 result = sqlite3_close (plugin->dbh);
324 if (result == SQLITE_BUSY)
326 LOG (GNUNET_ERROR_TYPE_WARNING,
327 _("Tried to close sqlite without finalizing all prepared statements.\n"));
328 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
331 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
332 "Closing statement %p\n", stmt);
333 result = sqlite3_finalize (stmt);
334 if (result != SQLITE_OK)
335 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
336 "Failed to close statement %p: %d\n", stmt, result);
337 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
339 result = sqlite3_close (plugin->dbh);
341 if (SQLITE_OK != result)
342 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
344 GNUNET_free_non_null (plugin->fn);
349 * Store a record in the datastore. Removes any existing record in the
350 * same zone with the same name.
352 * @param cls closure (internal context for the plugin)
353 * @param zone_key private key of the zone
354 * @param label name that is being mapped (at most 255 characters long)
355 * @param rd_count number of entries in @a rd array
356 * @param rd array of records with data to store
357 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
360 namestore_sqlite_store_records (void *cls,
361 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
363 unsigned int rd_count,
364 const struct GNUNET_GNSRECORD_Data *rd)
366 struct Plugin *plugin = cls;
368 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
373 memset (&pkey, 0, sizeof (pkey));
374 for (i=0;i<rd_count;i++)
375 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
377 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) == rd[i].data_size);
383 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
384 data_size = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
385 if (data_size > 64 * 65536)
388 return GNUNET_SYSERR;
391 char data[data_size];
393 if (data_size != GNUNET_GNSRECORD_records_serialize (rd_count, rd,
397 return GNUNET_SYSERR;
400 /* First delete 'old' records */
401 if ((SQLITE_OK != sqlite3_bind_blob (plugin->delete_records, 1,
402 zone_key, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), SQLITE_STATIC)) ||
403 (SQLITE_OK != sqlite3_bind_text (plugin->delete_records, 2, label, -1, SQLITE_STATIC)))
406 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
407 "sqlite3_bind_XXXX");
408 if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
410 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
412 return GNUNET_SYSERR;
415 n = sqlite3_step (plugin->delete_records);
416 if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
417 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
422 if ((SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 1,
423 zone_key, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), SQLITE_STATIC)) ||
424 (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 2,
425 &pkey, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), SQLITE_STATIC)) ||
426 (SQLITE_OK != sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
427 (SQLITE_OK != sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
428 (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 5, data, data_size, SQLITE_STATIC)) ||
429 (SQLITE_OK != sqlite3_bind_text (plugin->store_records, 6, label, -1, SQLITE_STATIC)))
432 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
433 "sqlite3_bind_XXXX");
434 if (SQLITE_OK != sqlite3_reset (plugin->store_records))
436 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438 return GNUNET_SYSERR;
440 n = sqlite3_step (plugin->store_records);
441 if (SQLITE_OK != sqlite3_reset (plugin->store_records))
442 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
450 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
452 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record deleted\n");
455 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
459 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
461 return GNUNET_SYSERR;
467 * The given 'sqlite' statement has been prepared to be run.
468 * It will return a record which should be given to the iterator.
469 * Runs the statement and parses the returned record.
471 * @param plugin plugin context
472 * @param stmt to run (and then clean up)
473 * @param zone_key private key of the zone
474 * @param iter iterator to call with the result
475 * @param iter_cls closure for @a iter
476 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
479 get_record_and_call_iterator (struct Plugin *plugin,
481 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
482 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
484 unsigned int record_count;
492 if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
494 record_count = sqlite3_column_int (stmt, 0);
495 data_size = sqlite3_column_bytes (stmt, 1);
496 data = sqlite3_column_blob (stmt, 1);
497 label = (const char*) sqlite3_column_text (stmt, 2);
498 if (NULL == zone_key)
500 /* must be "iterate_all_zones", got one extra return value */
501 if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) !=
502 sqlite3_column_bytes (stmt, 3))
509 zone_key = sqlite3_column_blob (stmt, 3);
512 if (record_count > 64 * 1024)
514 /* sanity check, don't stack allocate far too much just
515 because database might contain a large value here */
521 struct GNUNET_GNSRECORD_Data rd[record_count];
524 GNUNET_GNSRECORD_records_deserialize (data_size, data,
530 else if (NULL != zone_key)
533 iter (iter_cls, zone_key, label, record_count, rd);
540 if (SQLITE_DONE != sret)
541 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
543 if (SQLITE_OK != sqlite3_reset (stmt))
545 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
551 * Lookup records in the datastore for which we are the authority.
553 * @param cls closure (internal context for the plugin)
554 * @param zone private key of the zone
555 * @param label name of the record in the zone
556 * @param iter function to call with the result
557 * @param iter_cls closure for @a iter
558 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
561 namestore_sqlite_lookup_records (void *cls,
562 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label,
563 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
565 struct Plugin *plugin = cls;
571 return GNUNET_SYSERR;
575 stmt = plugin->lookup_label;
576 err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
577 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
579 (SQLITE_OK != sqlite3_bind_text (stmt, 2,
580 label, -1, SQLITE_STATIC)) );
584 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
585 "sqlite3_bind_XXXX");
586 if (SQLITE_OK != sqlite3_reset (stmt))
588 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
590 return GNUNET_SYSERR;
592 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
597 * Iterate over the results for a particular key and zone in the
598 * datastore. Will return at most one result to the iterator.
600 * @param cls closure (internal context for the plugin)
601 * @param zone hash of public key of the zone, NULL to iterate over all zones
602 * @param offset offset in the list of all matching records
603 * @param iter function to call with the result
604 * @param iter_cls closure for @a iter
605 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
608 namestore_sqlite_iterate_records (void *cls,
609 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
611 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
613 struct Plugin *plugin = cls;
619 stmt = plugin->iterate_all_zones;
620 err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
625 stmt = plugin->iterate_zone;
626 err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
627 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
629 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
634 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
635 "sqlite3_bind_XXXX");
636 if (SQLITE_OK != sqlite3_reset (stmt))
638 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
640 return GNUNET_SYSERR;
642 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
647 * Look for an existing PKEY delegation record for a given public key.
648 * Returns at most one result to the iterator.
650 * @param cls closure (internal context for the plugin)
651 * @param zone private key of the zone to look up in, never NULL
652 * @param value_zone public key of the target zone (value), never NULL
653 * @param iter function to call with the result
654 * @param iter_cls closure for @a iter
655 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
658 namestore_sqlite_zone_to_name (void *cls,
659 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
660 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
661 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
663 struct Plugin *plugin = cls;
666 stmt = plugin->zone_to_name;
667 if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
668 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
670 (SQLITE_OK != sqlite3_bind_blob (stmt, 2,
671 value_zone, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
674 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
675 "sqlite3_bind_XXXX");
676 if (SQLITE_OK != sqlite3_reset (stmt))
678 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
680 return GNUNET_SYSERR;
682 LOG (GNUNET_ERROR_TYPE_DEBUG,
683 "Performing reverse lookup for `%s'\n",
684 GNUNET_GNSRECORD_z2s (value_zone));
686 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
691 * Entry point for the plugin.
693 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
694 * @return NULL on error, otherwise the plugin context
697 libgnunet_plugin_namestore_sqlite_init (void *cls)
699 static struct Plugin plugin;
700 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
701 struct GNUNET_NAMESTORE_PluginFunctions *api;
703 if (NULL != plugin.cfg)
704 return NULL; /* can only initialize once! */
705 memset (&plugin, 0, sizeof (struct Plugin));
707 if (GNUNET_OK != database_setup (&plugin))
709 database_shutdown (&plugin);
712 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
714 api->store_records = &namestore_sqlite_store_records;
715 api->iterate_records = &namestore_sqlite_iterate_records;
716 api->zone_to_name = &namestore_sqlite_zone_to_name;
717 api->lookup_records = &namestore_sqlite_lookup_records;
718 LOG (GNUNET_ERROR_TYPE_INFO,
719 _("Sqlite database running\n"));
725 * Exit point from the plugin.
727 * @param cls the plugin context (as returned by "init")
728 * @return always NULL
731 libgnunet_plugin_namestore_sqlite_done (void *cls)
733 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
734 struct Plugin *plugin = api->cls;
736 database_shutdown (plugin);
739 LOG (GNUNET_ERROR_TYPE_DEBUG,
740 "sqlite plugin is finished\n");
744 /* end of plugin_namestore_sqlite.c */