2 * This file is part of GNUnet
3 * Copyright (C) 2009-2013 GNUnet e.V.
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)
141 "CREATE INDEX IF NOT EXISTS ir_pkey_reverse ON ns097records (zone_private_key,pkey)",
142 NULL, NULL, NULL)) ||
145 "CREATE INDEX IF NOT EXISTS ir_pkey_iter ON ns097records (zone_private_key,rvalue)",
146 NULL, NULL, NULL)) ||
149 "CREATE INDEX IF NOT EXISTS it_iter ON ns097records (rvalue)",
151 LOG (GNUNET_ERROR_TYPE_ERROR,
152 "Failed to create indices: %s\n",
153 sqlite3_errmsg (dbh));
158 #define CHECK(a) GNUNET_break(a)
162 #define ENULL_DEFINED 1
163 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
168 * Initialize the database connections and associated
169 * data structures (create tables and indices
170 * as needed as well).
172 * @param plugin the plugin context (state for this module)
173 * @return #GNUNET_OK on success
176 database_setup (struct Plugin *plugin)
185 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
190 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
193 return GNUNET_SYSERR;
196 GNUNET_DISK_file_test (afsdir))
199 GNUNET_DISK_directory_create_for_file (afsdir))
202 GNUNET_free (afsdir);
203 return GNUNET_SYSERR;
206 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
209 /* Open database and precompile statements */
210 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
212 LOG (GNUNET_ERROR_TYPE_ERROR,
213 _("Unable to initialize SQLite: %s.\n"),
214 sqlite3_errmsg (plugin->dbh));
215 return GNUNET_SYSERR;
218 sqlite3_exec (plugin->dbh,
219 "PRAGMA temp_store=MEMORY", NULL, NULL,
222 sqlite3_exec (plugin->dbh,
223 "PRAGMA synchronous=NORMAL", NULL, NULL,
226 sqlite3_exec (plugin->dbh,
227 "PRAGMA legacy_file_format=OFF", NULL, NULL,
230 sqlite3_exec (plugin->dbh,
231 "PRAGMA auto_vacuum=INCREMENTAL", NULL,
234 sqlite3_exec (plugin->dbh,
235 "PRAGMA encoding=\"UTF-8\"", NULL,
238 sqlite3_exec (plugin->dbh,
239 "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
242 sqlite3_exec (plugin->dbh,
243 "PRAGMA page_size=4092", NULL, NULL,
247 sqlite3_busy_timeout (plugin->dbh,
253 sq_prepare (plugin->dbh,
254 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns097records'",
256 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
259 "CREATE TABLE ns097records ("
260 " zone_private_key BLOB NOT NULL DEFAULT '',"
262 " rvalue INT8 NOT NULL DEFAULT '',"
263 " record_count INT NOT NULL DEFAULT 0,"
264 " record_data BLOB NOT NULL DEFAULT '',"
265 " label TEXT NOT NULL DEFAULT ''"
267 NULL, NULL, NULL) != SQLITE_OK))
269 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR,
271 sqlite3_finalize (stmt);
272 return GNUNET_SYSERR;
274 sqlite3_finalize (stmt);
276 create_indices (plugin->dbh);
280 "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label)"
281 " VALUES (?, ?, ?, ?, ?, ?)",
282 &plugin->store_records) != SQLITE_OK) ||
285 "DELETE FROM ns097records WHERE zone_private_key=? AND label=?",
286 &plugin->delete_records) != SQLITE_OK) ||
289 "SELECT record_count,record_data,label"
290 " FROM ns097records WHERE zone_private_key=? AND pkey=?",
291 &plugin->zone_to_name) != SQLITE_OK) ||
294 "SELECT record_count,record_data,label"
295 " FROM ns097records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
296 &plugin->iterate_zone) != SQLITE_OK) ||
299 "SELECT record_count,record_data,label,zone_private_key"
300 " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET ?",
301 &plugin->iterate_all_zones) != SQLITE_OK) ||
304 "SELECT record_count,record_data,label,zone_private_key"
305 " FROM ns097records WHERE zone_private_key=? AND label=?",
306 &plugin->lookup_label) != SQLITE_OK)
309 LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
310 return GNUNET_SYSERR;
317 * Shutdown database connection and associate data
319 * @param plugin the plugin context (state for this module)
322 database_shutdown (struct Plugin *plugin)
327 if (NULL != plugin->store_records)
328 sqlite3_finalize (plugin->store_records);
329 if (NULL != plugin->delete_records)
330 sqlite3_finalize (plugin->delete_records);
331 if (NULL != plugin->iterate_zone)
332 sqlite3_finalize (plugin->iterate_zone);
333 if (NULL != plugin->iterate_all_zones)
334 sqlite3_finalize (plugin->iterate_all_zones);
335 if (NULL != plugin->zone_to_name)
336 sqlite3_finalize (plugin->zone_to_name);
337 if (NULL != plugin->lookup_label)
338 sqlite3_finalize (plugin->lookup_label);
339 result = sqlite3_close (plugin->dbh);
340 if (result == SQLITE_BUSY)
342 LOG (GNUNET_ERROR_TYPE_WARNING,
343 _("Tried to close sqlite without finalizing all prepared statements.\n"));
344 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
347 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
348 "Closing statement %p\n", stmt);
349 result = sqlite3_finalize (stmt);
350 if (result != SQLITE_OK)
351 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
352 "Failed to close statement %p: %d\n", stmt, result);
353 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
355 result = sqlite3_close (plugin->dbh);
357 if (SQLITE_OK != result)
358 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
360 GNUNET_free_non_null (plugin->fn);
365 * Store a record in the datastore. Removes any existing record in the
366 * same zone with the same name.
368 * @param cls closure (internal context for the plugin)
369 * @param zone_key private key of the zone
370 * @param label name that is being mapped (at most 255 characters long)
371 * @param rd_count number of entries in @a rd array
372 * @param rd array of records with data to store
373 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
376 namestore_sqlite_store_records (void *cls,
377 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
379 unsigned int rd_count,
380 const struct GNUNET_GNSRECORD_Data *rd)
382 struct Plugin *plugin = cls;
384 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
389 memset (&pkey, 0, sizeof (pkey));
390 for (i=0;i<rd_count;i++)
391 if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
393 GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) ==
395 GNUNET_memcpy (&pkey,
400 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
402 data_size = GNUNET_GNSRECORD_records_get_size (rd_count,
404 if (data_size > 64 * 65536)
407 return GNUNET_SYSERR;
410 char data[data_size];
413 GNUNET_GNSRECORD_records_serialize (rd_count,
419 return GNUNET_SYSERR;
422 /* First delete 'old' records */
424 sqlite3_bind_blob (plugin->delete_records,
427 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
430 sqlite3_bind_text (plugin->delete_records,
437 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438 "sqlite3_bind_XXXX");
439 if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
441 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
443 return GNUNET_SYSERR;
446 n = sqlite3_step (plugin->delete_records);
447 if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
448 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
454 sqlite3_bind_blob (plugin->store_records,
457 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
460 sqlite3_bind_blob (plugin->store_records,
463 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
466 sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
468 sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
470 sqlite3_bind_blob (plugin->store_records, 5,
474 sqlite3_bind_text (plugin->store_records, 6,
479 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
480 "sqlite3_bind_XXXX");
481 if (SQLITE_OK != sqlite3_reset (plugin->store_records))
483 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
485 return GNUNET_SYSERR;
487 n = sqlite3_step (plugin->store_records);
488 if (SQLITE_OK != sqlite3_reset (plugin->store_records))
489 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
497 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
499 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record deleted\n");
502 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
506 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
508 return GNUNET_SYSERR;
514 * The given 'sqlite' statement has been prepared to be run.
515 * It will return a record which should be given to the iterator.
516 * Runs the statement and parses the returned record.
518 * @param plugin plugin context
519 * @param stmt to run (and then clean up)
520 * @param zone_key private key of the zone
521 * @param iter iterator to call with the result
522 * @param iter_cls closure for @a iter
523 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
526 get_record_and_call_iterator (struct Plugin *plugin,
528 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
529 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
531 unsigned int record_count;
539 if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
541 record_count = sqlite3_column_int (stmt, 0);
542 data_size = sqlite3_column_bytes (stmt, 1);
543 data = sqlite3_column_blob (stmt, 1);
544 label = (const char*) sqlite3_column_text (stmt, 2);
545 if (NULL == zone_key)
547 /* must be "iterate_all_zones", got one extra return value */
548 if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) !=
549 sqlite3_column_bytes (stmt, 3))
556 zone_key = sqlite3_column_blob (stmt, 3);
559 if (record_count > 64 * 1024)
561 /* sanity check, don't stack allocate far too much just
562 because database might contain a large value here */
568 struct GNUNET_GNSRECORD_Data rd[record_count];
571 GNUNET_GNSRECORD_records_deserialize (data_size, data,
577 else if (NULL != zone_key)
580 iter (iter_cls, zone_key, label, record_count, rd);
587 if (SQLITE_DONE != sret)
588 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
590 if (SQLITE_OK != sqlite3_reset (stmt))
592 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
598 * Lookup records in the datastore for which we are the authority.
600 * @param cls closure (internal context for the plugin)
601 * @param zone private key of the zone
602 * @param label name of the record in the zone
603 * @param iter function to call with the result
604 * @param iter_cls closure for @a iter
605 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
608 namestore_sqlite_lookup_records (void *cls,
609 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label,
610 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
612 struct Plugin *plugin = cls;
618 return GNUNET_SYSERR;
622 stmt = plugin->lookup_label;
623 err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
624 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
626 (SQLITE_OK != sqlite3_bind_text (stmt, 2,
627 label, -1, SQLITE_STATIC)) );
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 * Iterate over the results for a particular key and zone in the
645 * datastore. Will return at most one result to the iterator.
647 * @param cls closure (internal context for the plugin)
648 * @param zone hash of public key of the zone, NULL to iterate over all zones
649 * @param offset offset in the list of all matching records
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_iterate_records (void *cls,
656 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
658 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
660 struct Plugin *plugin = cls;
666 stmt = plugin->iterate_all_zones;
667 err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
672 stmt = plugin->iterate_zone;
673 err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
674 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
676 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
681 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
682 "sqlite3_bind_XXXX");
683 if (SQLITE_OK != sqlite3_reset (stmt))
685 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
687 return GNUNET_SYSERR;
689 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
694 * Look for an existing PKEY delegation record for a given public key.
695 * Returns at most one result to the iterator.
697 * @param cls closure (internal context for the plugin)
698 * @param zone private key of the zone to look up in, never NULL
699 * @param value_zone public key of the target zone (value), never NULL
700 * @param iter function to call with the result
701 * @param iter_cls closure for @a iter
702 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
705 namestore_sqlite_zone_to_name (void *cls,
706 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
707 const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
708 GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
710 struct Plugin *plugin = cls;
713 stmt = plugin->zone_to_name;
714 if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1,
715 zone, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
717 (SQLITE_OK != sqlite3_bind_blob (stmt, 2,
718 value_zone, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
721 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
722 "sqlite3_bind_XXXX");
723 if (SQLITE_OK != sqlite3_reset (stmt))
725 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
727 return GNUNET_SYSERR;
729 LOG (GNUNET_ERROR_TYPE_DEBUG,
730 "Performing reverse lookup for `%s'\n",
731 GNUNET_GNSRECORD_z2s (value_zone));
733 return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
738 * Entry point for the plugin.
740 * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
741 * @return NULL on error, otherwise the plugin context
744 libgnunet_plugin_namestore_sqlite_init (void *cls)
746 static struct Plugin plugin;
747 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
748 struct GNUNET_NAMESTORE_PluginFunctions *api;
750 if (NULL != plugin.cfg)
751 return NULL; /* can only initialize once! */
752 memset (&plugin, 0, sizeof (struct Plugin));
754 if (GNUNET_OK != database_setup (&plugin))
756 database_shutdown (&plugin);
759 api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
761 api->store_records = &namestore_sqlite_store_records;
762 api->iterate_records = &namestore_sqlite_iterate_records;
763 api->zone_to_name = &namestore_sqlite_zone_to_name;
764 api->lookup_records = &namestore_sqlite_lookup_records;
765 LOG (GNUNET_ERROR_TYPE_INFO,
766 _("Sqlite database running\n"));
772 * Exit point from the plugin.
774 * @param cls the plugin context (as returned by "init")
775 * @return always NULL
778 libgnunet_plugin_namestore_sqlite_done (void *cls)
780 struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
781 struct Plugin *plugin = api->cls;
783 database_shutdown (plugin);
786 LOG (GNUNET_ERROR_TYPE_DEBUG,
787 "sqlite plugin is finished\n");
791 /* end of plugin_namestore_sqlite.c */