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, "peerstore-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, "peerstore-sqlite", __VA_ARGS__)
57 * Context for all functions in this plugin.
63 * Configuration handle
65 const struct GNUNET_CONFIGURATION_Handle *cfg;
73 * Native SQLite database handle.
78 * Precompiled SQL for inserting into peerstoredata
80 sqlite3_stmt *insert_peerstoredata;
83 * Precompiled SQL for selecting from peerstoredata
85 sqlite3_stmt *select_peerstoredata;
88 * Precompiled SQL for selecting from peerstoredata
90 sqlite3_stmt *select_peerstoredata_by_pid;
93 * Precompiled SQL for selecting from peerstoredata
95 sqlite3_stmt *select_peerstoredata_by_key;
98 * Precompiled SQL for selecting from peerstoredata
100 sqlite3_stmt *select_peerstoredata_by_all;
103 * Precompiled SQL for deleting expired
104 * records from peerstoredata
106 sqlite3_stmt *expire_peerstoredata;
109 * Precompiled SQL for deleting records
112 sqlite3_stmt *delete_peerstoredata;
118 * Delete records with the given key
120 * @param cls closure (internal context for the plugin)
121 * @param sub_system name of sub system
122 * @param peer Peer identity (can be NULL)
123 * @param key entry key string (can be NULL)
124 * @return number of deleted records, #GNUNE_SYSERR on error
127 peerstore_sqlite_delete_records (void *cls,
128 const char *sub_system,
129 const struct GNUNET_PeerIdentity *peer,
132 struct Plugin *plugin = cls;
133 sqlite3_stmt *stmt = plugin->delete_peerstoredata;
134 struct GNUNET_SQ_QueryParam params[] = {
135 GNUNET_SQ_query_param_string (sub_system),
136 GNUNET_SQ_query_param_auto_from_type (peer),
137 GNUNET_SQ_query_param_string (key),
138 GNUNET_SQ_query_param_end
143 GNUNET_SQ_bind (stmt,
147 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
149 GNUNET_SQ_reset (plugin->dbh,
151 return GNUNET_SYSERR;
157 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
163 ret = sqlite3_changes (plugin->dbh);
165 GNUNET_SQ_reset (plugin->dbh,
172 * Delete expired records (expiry < now)
174 * @param cls closure (internal context for the plugin)
175 * @param now time to use as reference
176 * @param cont continuation called with the number of records expired
177 * @param cont_cls continuation closure
178 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and cont is not
182 peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now,
183 GNUNET_PEERSTORE_Continuation cont,
186 struct Plugin *plugin = cls;
187 sqlite3_stmt *stmt = plugin->expire_peerstoredata;
188 struct GNUNET_SQ_QueryParam params[] = {
189 GNUNET_SQ_query_param_absolute_time (&now),
190 GNUNET_SQ_query_param_end
194 GNUNET_SQ_bind (stmt,
198 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
200 GNUNET_SQ_reset (plugin->dbh,
202 return GNUNET_SYSERR;
204 if (SQLITE_DONE != sqlite3_step (stmt))
207 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
209 GNUNET_SQ_reset (plugin->dbh,
211 return GNUNET_SYSERR;
215 sqlite3_changes (plugin->dbh));
216 GNUNET_SQ_reset (plugin->dbh,
223 * Iterate over the records given an optional peer id
226 * @param cls closure (internal context for the plugin)
227 * @param sub_system name of sub system
228 * @param peer Peer identity (can be NULL)
229 * @param key entry key string (can be NULL)
230 * @param iter function to call asynchronously with the results, terminated
232 * @param iter_cls closure for @a iter
233 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
237 peerstore_sqlite_iterate_records (void *cls,
238 const char *sub_system,
239 const struct GNUNET_PeerIdentity *peer,
241 GNUNET_PEERSTORE_Processor iter,
244 struct Plugin *plugin = cls;
248 struct GNUNET_PEERSTORE_Record rec;
250 LOG (GNUNET_ERROR_TYPE_DEBUG,
251 "Executing iterate request on sqlite db.\n");
256 struct GNUNET_SQ_QueryParam params[] = {
257 GNUNET_SQ_query_param_string (sub_system),
258 GNUNET_SQ_query_param_end
261 stmt = plugin->select_peerstoredata;
262 err = GNUNET_SQ_bind (stmt,
267 struct GNUNET_SQ_QueryParam params[] = {
268 GNUNET_SQ_query_param_string (sub_system),
269 GNUNET_SQ_query_param_string (key),
270 GNUNET_SQ_query_param_end
273 stmt = plugin->select_peerstoredata_by_key;
274 err = GNUNET_SQ_bind (stmt,
282 struct GNUNET_SQ_QueryParam params[] = {
283 GNUNET_SQ_query_param_string (sub_system),
284 GNUNET_SQ_query_param_auto_from_type (peer),
285 GNUNET_SQ_query_param_end
288 stmt = plugin->select_peerstoredata_by_pid;
289 err = GNUNET_SQ_bind (stmt,
294 struct GNUNET_SQ_QueryParam params[] = {
295 GNUNET_SQ_query_param_string (sub_system),
296 GNUNET_SQ_query_param_auto_from_type (peer),
297 GNUNET_SQ_query_param_string (key),
298 GNUNET_SQ_query_param_end
301 stmt = plugin->select_peerstoredata_by_all;
302 err = GNUNET_SQ_bind (stmt,
307 if (GNUNET_OK != err)
310 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
311 "sqlite3_bind_XXXX");
312 GNUNET_SQ_reset (plugin->dbh,
314 return GNUNET_SYSERR;
318 while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
320 LOG (GNUNET_ERROR_TYPE_DEBUG,
321 "Returning a matched record.\n");
322 struct GNUNET_SQ_ResultSpec rs[] = {
323 GNUNET_SQ_result_spec_string (&rec.sub_system),
324 GNUNET_SQ_result_spec_auto_from_type (&rec.peer),
325 GNUNET_SQ_result_spec_string (&rec.key),
326 GNUNET_SQ_result_spec_variable_size (&rec.value, &rec.value_size),
327 GNUNET_SQ_result_spec_absolute_time (&rec.expiry),
328 GNUNET_SQ_result_spec_end
332 GNUNET_SQ_extract_result (stmt,
342 GNUNET_SQ_cleanup_result (rs);
344 if (SQLITE_DONE != sret)
347 GNUNET_ERROR_TYPE_ERROR,
351 GNUNET_SQ_reset (plugin->dbh,
356 err ? "sqlite error" : NULL);
362 * Store a record in the peerstore.
363 * Key is the combination of sub system and peer identity.
364 * One key can store multiple values.
366 * @param cls closure (internal context for the plugin)
367 * @param sub_system name of the GNUnet sub system responsible
368 * @param peer peer identity
369 * @param key record key string
370 * @param value value to be stored
371 * @param size size of value to be stored
372 * @param expiry absolute time after which the record is (possibly) deleted
373 * @param options options related to the store operation
374 * @param cont continuation called when record is stored
375 * @param cont_cls continuation closure
376 * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called
379 peerstore_sqlite_store_record (void *cls,
380 const char *sub_system,
381 const struct GNUNET_PeerIdentity *peer,
385 struct GNUNET_TIME_Absolute expiry,
386 enum GNUNET_PEERSTORE_StoreOption options,
387 GNUNET_PEERSTORE_Continuation cont,
390 struct Plugin *plugin = cls;
391 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
392 struct GNUNET_SQ_QueryParam params[] = {
393 GNUNET_SQ_query_param_string (sub_system),
394 GNUNET_SQ_query_param_auto_from_type (peer),
395 GNUNET_SQ_query_param_string (key),
396 GNUNET_SQ_query_param_fixed_size (value, size),
397 GNUNET_SQ_query_param_absolute_time (&expiry),
398 GNUNET_SQ_query_param_end
401 if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
403 peerstore_sqlite_delete_records (cls,
409 GNUNET_SQ_bind (stmt,
412 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
414 else if (SQLITE_DONE != sqlite3_step (stmt))
417 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
420 GNUNET_SQ_reset (plugin->dbh,
430 * @brief Prepare a SQL statement
432 * @param dbh handle to the database
433 * @param sql SQL statement, UTF-8 encoded
434 * @return 0 on success
437 sql_exec (sqlite3 *dbh,
442 result = sqlite3_exec (dbh,
447 LOG (GNUNET_ERROR_TYPE_DEBUG,
448 "Executed `%s' / %d\n",
451 if (SQLITE_OK != result)
452 LOG (GNUNET_ERROR_TYPE_ERROR,
453 _("Error executing SQL query: %s\n %s\n"),
454 sqlite3_errmsg (dbh),
461 * @brief Prepare a SQL statement
463 * @param dbh handle to the database
464 * @param sql SQL statement, UTF-8 encoded
465 * @param stmt set to the prepared statement
466 * @return 0 on success
469 sql_prepare (sqlite3 *dbh,
471 sqlite3_stmt ** stmt)
476 result = sqlite3_prepare_v2 (dbh,
480 (const char **) &tail);
481 LOG (GNUNET_ERROR_TYPE_DEBUG,
482 "Prepared `%s' / %p: %d\n",
486 if (SQLITE_OK != result)
487 LOG (GNUNET_ERROR_TYPE_ERROR,
488 _("Error preparing SQL query: %s\n %s\n"),
489 sqlite3_errmsg (dbh),
496 * Initialize the database connections and associated
497 * data structures (create tables and indices
498 * as needed as well).
500 * @param plugin the plugin context (state for this module)
501 * @return #GNUNET_OK on success
504 database_setup (struct Plugin *plugin)
509 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
514 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
517 return GNUNET_SYSERR;
519 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
521 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
524 GNUNET_free (filename);
525 return GNUNET_SYSERR;
528 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
529 plugin->fn = filename;
530 /* Open database and precompile statements */
531 if (SQLITE_OK != sqlite3_open (plugin->fn,
534 LOG (GNUNET_ERROR_TYPE_ERROR,
535 _("Unable to initialize SQLite: %s.\n"),
536 sqlite3_errmsg (plugin->dbh));
537 return GNUNET_SYSERR;
539 sql_exec (plugin->dbh,
540 "PRAGMA temp_store=MEMORY");
541 sql_exec (plugin->dbh,
542 "PRAGMA synchronous=OFF");
543 sql_exec (plugin->dbh,
544 "PRAGMA legacy_file_format=OFF");
545 sql_exec (plugin->dbh,
546 "PRAGMA auto_vacuum=INCREMENTAL");
547 sql_exec (plugin->dbh,
548 "PRAGMA encoding=\"UTF-8\"");
549 sql_exec (plugin->dbh,
550 "PRAGMA page_size=4096");
551 sqlite3_busy_timeout (plugin->dbh,
554 sql_exec (plugin->dbh,
555 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
556 " sub_system TEXT NOT NULL,\n"
557 " peer_id BLOB NOT NULL,\n"
558 " key TEXT NOT NULL,\n"
559 " value BLOB NULL,\n"
560 " expiry INT8 NOT NULL" ");");
563 sqlite3_exec (plugin->dbh,
564 "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
569 LOG (GNUNET_ERROR_TYPE_ERROR,
570 _("Unable to create indices: %s.\n"),
571 sqlite3_errmsg (plugin->dbh));
572 return GNUNET_SYSERR;
574 /* Prepare statements */
576 sql_prepare (plugin->dbh,
577 "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)"
578 " VALUES (?,?,?,?,?);",
579 &plugin->insert_peerstoredata);
580 sql_prepare (plugin->dbh,
581 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
582 " WHERE sub_system = ?",
583 &plugin->select_peerstoredata);
584 sql_prepare (plugin->dbh,
585 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
586 " WHERE sub_system = ?"
588 &plugin->select_peerstoredata_by_pid);
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_key);
594 sql_prepare (plugin->dbh,
595 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
596 " WHERE sub_system = ?"
597 " AND peer_id = ?" " AND key = ?",
598 &plugin->select_peerstoredata_by_all);
599 sql_prepare (plugin->dbh,
600 "DELETE FROM peerstoredata"
602 &plugin->expire_peerstoredata);
603 sql_prepare (plugin->dbh,
604 "DELETE FROM peerstoredata"
605 " WHERE sub_system = ?"
606 " AND peer_id = ?" " AND key = ?",
607 &plugin->delete_peerstoredata);
613 * Shutdown database connection and associate data
615 * @param plugin the plugin context (state for this module)
618 database_shutdown (struct Plugin *plugin)
623 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh,
626 result = sqlite3_finalize (stmt);
627 if (SQLITE_OK != result)
628 LOG (GNUNET_ERROR_TYPE_WARNING,
629 "Failed to close statement %p: %d\n",
633 if (SQLITE_OK != sqlite3_close (plugin->dbh))
635 GNUNET_ERROR_TYPE_ERROR,
637 GNUNET_free_non_null (plugin->fn);
642 * Entry point for the plugin.
644 * @param cls The struct GNUNET_CONFIGURATION_Handle.
645 * @return NULL on error, otherwise the plugin context
648 libgnunet_plugin_peerstore_sqlite_init (void *cls)
650 static struct Plugin plugin;
651 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
652 struct GNUNET_PEERSTORE_PluginFunctions *api;
654 if (NULL != plugin.cfg)
655 return NULL; /* can only initialize once! */
658 sizeof (struct Plugin));
660 if (GNUNET_OK != database_setup (&plugin))
662 database_shutdown (&plugin);
665 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
667 api->store_record = &peerstore_sqlite_store_record;
668 api->iterate_records = &peerstore_sqlite_iterate_records;
669 api->expire_records = &peerstore_sqlite_expire_records;
670 LOG (GNUNET_ERROR_TYPE_DEBUG,
671 "Sqlite plugin is running\n");
677 * Exit point from the plugin.
679 * @param cls The plugin context (as returned by "init")
680 * @return Always NULL
683 libgnunet_plugin_peerstore_sqlite_done (void *cls)
685 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
686 struct Plugin *plugin = api->cls;
688 database_shutdown (plugin);
691 LOG (GNUNET_ERROR_TYPE_DEBUG,
692 "Sqlite plugin is finished\n");
696 /* end of plugin_peerstore_sqlite.c */