2 * This file is part of GNUnet
3 * Copyright (C) 2013, 2017 GNUnet e.V.
5 * GNUnet is free software: you can redistribute it and/or modify it
6 * under the terms of the GNU Affero General Public License as published
7 * by the Free Software Foundation, either version 3 of the License,
8 * or (at your 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 * Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file peerstore/plugin_peerstore_sqlite.c
23 * @brief sqlite-based peerstore backend
24 * @author Omar Tarabai
25 * @author Christian Grothoff
29 #include "gnunet_peerstore_plugin.h"
30 #include "gnunet_peerstore_service.h"
31 #include "gnunet_sq_lib.h"
32 #include "peerstore.h"
36 * After how many ms "busy" should a DB operation fail for good? A
37 * low value makes sure that we are more responsive to requests
38 * (especially PUTs). A high value guarantees a higher success rate
39 * (SELECTs in iterate can take several seconds despite LIMIT=1).
41 * The default value of 1s should ensure that users do not experience
42 * huge latencies while at the same time allowing operations to
43 * succeed with reasonable probability.
45 #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, \
53 "peerstore-sqlite", _ ( \
54 "`%s' failed at %s:%d with error: %s\n"), \
61 #define LOG(kind, ...) GNUNET_log_from (kind, "peerstore-sqlite", __VA_ARGS__)
64 * Context for all functions in this plugin.
69 * Configuration handle
71 const struct GNUNET_CONFIGURATION_Handle *cfg;
79 * Native SQLite database handle.
84 * Precompiled SQL for inserting into peerstoredata
86 sqlite3_stmt *insert_peerstoredata;
89 * Precompiled SQL for selecting from peerstoredata
91 sqlite3_stmt *select_peerstoredata;
94 * Precompiled SQL for selecting from peerstoredata
96 sqlite3_stmt *select_peerstoredata_by_pid;
99 * Precompiled SQL for selecting from peerstoredata
101 sqlite3_stmt *select_peerstoredata_by_key;
104 * Precompiled SQL for selecting from peerstoredata
106 sqlite3_stmt *select_peerstoredata_by_all;
109 * Precompiled SQL for deleting expired
110 * records from peerstoredata
112 sqlite3_stmt *expire_peerstoredata;
115 * Precompiled SQL for deleting records
118 sqlite3_stmt *delete_peerstoredata;
123 * Delete records with the given key
125 * @param cls closure (internal context for the plugin)
126 * @param sub_system name of sub system
127 * @param peer Peer identity (can be NULL)
128 * @param key entry key string (can be NULL)
129 * @return number of deleted records, #GNUNE_SYSERR on error
132 peerstore_sqlite_delete_records (void *cls,
133 const char *sub_system,
134 const struct GNUNET_PeerIdentity *peer,
137 struct Plugin *plugin = cls;
138 sqlite3_stmt *stmt = plugin->delete_peerstoredata;
139 struct GNUNET_SQ_QueryParam params[] = {
140 GNUNET_SQ_query_param_string (sub_system),
141 GNUNET_SQ_query_param_auto_from_type (peer),
142 GNUNET_SQ_query_param_string (key),
143 GNUNET_SQ_query_param_end
148 GNUNET_SQ_bind (stmt,
152 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
154 GNUNET_SQ_reset (plugin->dbh,
156 return GNUNET_SYSERR;
162 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
168 ret = sqlite3_changes (plugin->dbh);
170 GNUNET_SQ_reset (plugin->dbh,
177 * Delete expired records (expiry < now)
179 * @param cls closure (internal context for the plugin)
180 * @param now time to use as reference
181 * @param cont continuation called with the number of records expired
182 * @param cont_cls continuation closure
183 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and cont is not
187 peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now,
188 GNUNET_PEERSTORE_Continuation cont,
191 struct Plugin *plugin = cls;
192 sqlite3_stmt *stmt = plugin->expire_peerstoredata;
193 struct GNUNET_SQ_QueryParam params[] = {
194 GNUNET_SQ_query_param_absolute_time (&now),
195 GNUNET_SQ_query_param_end
199 GNUNET_SQ_bind (stmt,
203 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
205 GNUNET_SQ_reset (plugin->dbh,
207 return GNUNET_SYSERR;
209 if (SQLITE_DONE != sqlite3_step (stmt))
212 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
214 GNUNET_SQ_reset (plugin->dbh,
216 return GNUNET_SYSERR;
220 sqlite3_changes (plugin->dbh));
221 GNUNET_SQ_reset (plugin->dbh,
228 * Iterate over the records given an optional peer id
231 * @param cls closure (internal context for the plugin)
232 * @param sub_system name of sub system
233 * @param peer Peer identity (can be NULL)
234 * @param key entry key string (can be NULL)
235 * @param iter function to call asynchronously with the results, terminated
237 * @param iter_cls closure for @a iter
238 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
242 peerstore_sqlite_iterate_records (void *cls,
243 const char *sub_system,
244 const struct GNUNET_PeerIdentity *peer,
246 GNUNET_PEERSTORE_Processor iter,
249 struct Plugin *plugin = cls;
253 struct GNUNET_PEERSTORE_Record rec;
255 LOG (GNUNET_ERROR_TYPE_DEBUG,
256 "Executing iterate request on sqlite db.\n");
261 struct GNUNET_SQ_QueryParam params[] = {
262 GNUNET_SQ_query_param_string (sub_system),
263 GNUNET_SQ_query_param_end
266 stmt = plugin->select_peerstoredata;
267 err = GNUNET_SQ_bind (stmt,
272 struct GNUNET_SQ_QueryParam params[] = {
273 GNUNET_SQ_query_param_string (sub_system),
274 GNUNET_SQ_query_param_string (key),
275 GNUNET_SQ_query_param_end
278 stmt = plugin->select_peerstoredata_by_key;
279 err = GNUNET_SQ_bind (stmt,
287 struct GNUNET_SQ_QueryParam params[] = {
288 GNUNET_SQ_query_param_string (sub_system),
289 GNUNET_SQ_query_param_auto_from_type (peer),
290 GNUNET_SQ_query_param_end
293 stmt = plugin->select_peerstoredata_by_pid;
294 err = GNUNET_SQ_bind (stmt,
299 struct GNUNET_SQ_QueryParam params[] = {
300 GNUNET_SQ_query_param_string (sub_system),
301 GNUNET_SQ_query_param_auto_from_type (peer),
302 GNUNET_SQ_query_param_string (key),
303 GNUNET_SQ_query_param_end
306 stmt = plugin->select_peerstoredata_by_all;
307 err = GNUNET_SQ_bind (stmt,
312 if (GNUNET_OK != err)
315 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
316 "sqlite3_bind_XXXX");
317 GNUNET_SQ_reset (plugin->dbh,
319 return GNUNET_SYSERR;
323 while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
325 LOG (GNUNET_ERROR_TYPE_DEBUG,
326 "Returning a matched record.\n");
327 struct GNUNET_SQ_ResultSpec rs[] = {
328 GNUNET_SQ_result_spec_string (&rec.sub_system),
329 GNUNET_SQ_result_spec_auto_from_type (&rec.peer),
330 GNUNET_SQ_result_spec_string (&rec.key),
331 GNUNET_SQ_result_spec_variable_size (&rec.value, &rec.value_size),
332 GNUNET_SQ_result_spec_absolute_time (&rec.expiry),
333 GNUNET_SQ_result_spec_end
337 GNUNET_SQ_extract_result (stmt,
347 GNUNET_SQ_cleanup_result (rs);
349 if (SQLITE_DONE != sret)
352 GNUNET_ERROR_TYPE_ERROR,
356 GNUNET_SQ_reset (plugin->dbh,
361 err ? "sqlite error" : NULL);
367 * Store a record in the peerstore.
368 * Key is the combination of sub system and peer identity.
369 * One key can store multiple values.
371 * @param cls closure (internal context for the plugin)
372 * @param sub_system name of the GNUnet sub system responsible
373 * @param peer peer identity
374 * @param key record key string
375 * @param value value to be stored
376 * @param size size of value to be stored
377 * @param expiry absolute time after which the record is (possibly) deleted
378 * @param options options related to the store operation
379 * @param cont continuation called when record is stored
380 * @param cont_cls continuation closure
381 * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called
384 peerstore_sqlite_store_record (void *cls,
385 const char *sub_system,
386 const struct GNUNET_PeerIdentity *peer,
390 struct GNUNET_TIME_Absolute expiry,
391 enum GNUNET_PEERSTORE_StoreOption options,
392 GNUNET_PEERSTORE_Continuation cont,
395 struct Plugin *plugin = cls;
396 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
397 struct GNUNET_SQ_QueryParam params[] = {
398 GNUNET_SQ_query_param_string (sub_system),
399 GNUNET_SQ_query_param_auto_from_type (peer),
400 GNUNET_SQ_query_param_string (key),
401 GNUNET_SQ_query_param_fixed_size (value, size),
402 GNUNET_SQ_query_param_absolute_time (&expiry),
403 GNUNET_SQ_query_param_end
406 if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
408 peerstore_sqlite_delete_records (cls,
414 GNUNET_SQ_bind (stmt,
417 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
419 else if (SQLITE_DONE != sqlite3_step (stmt))
422 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
425 GNUNET_SQ_reset (plugin->dbh,
435 * @brief Prepare a SQL statement
437 * @param dbh handle to the database
438 * @param sql SQL statement, UTF-8 encoded
439 * @return 0 on success
442 sql_exec (sqlite3 *dbh,
447 result = sqlite3_exec (dbh,
452 LOG (GNUNET_ERROR_TYPE_DEBUG,
453 "Executed `%s' / %d\n",
456 if (SQLITE_OK != result)
457 LOG (GNUNET_ERROR_TYPE_ERROR,
458 _ ("Error executing SQL query: %s\n %s\n"),
459 sqlite3_errmsg (dbh),
466 * @brief Prepare a SQL statement
468 * @param dbh handle to the database
469 * @param sql SQL statement, UTF-8 encoded
470 * @param stmt set to the prepared statement
471 * @return 0 on success
474 sql_prepare (sqlite3 *dbh,
481 result = sqlite3_prepare_v2 (dbh,
485 (const char **) &tail);
486 LOG (GNUNET_ERROR_TYPE_DEBUG,
487 "Prepared `%s' / %p: %d\n",
491 if (SQLITE_OK != result)
492 LOG (GNUNET_ERROR_TYPE_ERROR,
493 _ ("Error preparing SQL query: %s\n %s\n"),
494 sqlite3_errmsg (dbh),
501 * Initialize the database connections and associated
502 * data structures (create tables and indices
503 * as needed as well).
505 * @param plugin the plugin context (state for this module)
506 * @return #GNUNET_OK on success
509 database_setup (struct Plugin *plugin)
514 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
519 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
522 return GNUNET_SYSERR;
524 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
526 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
529 GNUNET_free (filename);
530 return GNUNET_SYSERR;
533 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
534 plugin->fn = filename;
535 /* Open database and precompile statements */
536 if (SQLITE_OK != sqlite3_open (plugin->fn,
539 LOG (GNUNET_ERROR_TYPE_ERROR,
540 _ ("Unable to initialize SQLite: %s.\n"),
541 sqlite3_errmsg (plugin->dbh));
542 return GNUNET_SYSERR;
544 sql_exec (plugin->dbh,
545 "PRAGMA temp_store=MEMORY");
546 sql_exec (plugin->dbh,
547 "PRAGMA synchronous=OFF");
548 sql_exec (plugin->dbh,
549 "PRAGMA legacy_file_format=OFF");
550 sql_exec (plugin->dbh,
551 "PRAGMA auto_vacuum=INCREMENTAL");
552 sql_exec (plugin->dbh,
553 "PRAGMA encoding=\"UTF-8\"");
554 sql_exec (plugin->dbh,
555 "PRAGMA page_size=4096");
556 sqlite3_busy_timeout (plugin->dbh,
559 sql_exec (plugin->dbh,
560 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
561 " sub_system TEXT NOT NULL,\n"
562 " peer_id BLOB NOT NULL,\n"
563 " key TEXT NOT NULL,\n"
564 " value BLOB NULL,\n"
565 " expiry INT8 NOT NULL" ");");
568 sqlite3_exec (plugin->dbh,
569 "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
574 LOG (GNUNET_ERROR_TYPE_ERROR,
575 _ ("Unable to create indices: %s.\n"),
576 sqlite3_errmsg (plugin->dbh));
577 return GNUNET_SYSERR;
579 /* Prepare statements */
581 sql_prepare (plugin->dbh,
582 "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)"
583 " VALUES (?,?,?,?,?);",
584 &plugin->insert_peerstoredata);
585 sql_prepare (plugin->dbh,
586 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
587 " WHERE sub_system = ?",
588 &plugin->select_peerstoredata);
589 sql_prepare (plugin->dbh,
590 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
591 " WHERE sub_system = ?"
593 &plugin->select_peerstoredata_by_pid);
594 sql_prepare (plugin->dbh,
595 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
596 " WHERE sub_system = ?"
598 &plugin->select_peerstoredata_by_key);
599 sql_prepare (plugin->dbh,
600 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
601 " WHERE sub_system = ?"
602 " AND peer_id = ?" " AND key = ?",
603 &plugin->select_peerstoredata_by_all);
604 sql_prepare (plugin->dbh,
605 "DELETE FROM peerstoredata"
607 &plugin->expire_peerstoredata);
608 sql_prepare (plugin->dbh,
609 "DELETE FROM peerstoredata"
610 " WHERE sub_system = ?"
611 " AND peer_id = ?" " AND key = ?",
612 &plugin->delete_peerstoredata);
618 * Shutdown database connection and associate data
620 * @param plugin the plugin context (state for this module)
623 database_shutdown (struct Plugin *plugin)
628 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh,
631 result = sqlite3_finalize (stmt);
632 if (SQLITE_OK != result)
633 LOG (GNUNET_ERROR_TYPE_WARNING,
634 "Failed to close statement %p: %d\n",
638 if (SQLITE_OK != sqlite3_close (plugin->dbh))
640 GNUNET_ERROR_TYPE_ERROR,
642 GNUNET_free_non_null (plugin->fn);
647 * Entry point for the plugin.
649 * @param cls The struct GNUNET_CONFIGURATION_Handle.
650 * @return NULL on error, otherwise the plugin context
653 libgnunet_plugin_peerstore_sqlite_init (void *cls)
655 static struct Plugin plugin;
656 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
657 struct GNUNET_PEERSTORE_PluginFunctions *api;
659 if (NULL != plugin.cfg)
660 return NULL; /* can only initialize once! */
663 sizeof(struct Plugin));
665 if (GNUNET_OK != database_setup (&plugin))
667 database_shutdown (&plugin);
670 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
672 api->store_record = &peerstore_sqlite_store_record;
673 api->iterate_records = &peerstore_sqlite_iterate_records;
674 api->expire_records = &peerstore_sqlite_expire_records;
675 LOG (GNUNET_ERROR_TYPE_DEBUG,
676 "Sqlite plugin is running\n");
682 * Exit point from the plugin.
684 * @param cls The plugin context (as returned by "init")
685 * @return Always NULL
688 libgnunet_plugin_peerstore_sqlite_done (void *cls)
690 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
691 struct Plugin *plugin = api->cls;
693 database_shutdown (plugin);
696 LOG (GNUNET_ERROR_TYPE_DEBUG,
697 "Sqlite plugin is finished\n");
702 /* end of plugin_peerstore_sqlite.c */