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.
61 * Configuration handle
63 const struct GNUNET_CONFIGURATION_Handle *cfg;
71 * Native SQLite database handle.
76 * Precompiled SQL for inserting into peerstoredata
78 sqlite3_stmt *insert_peerstoredata;
81 * Precompiled SQL for selecting from peerstoredata
83 sqlite3_stmt *select_peerstoredata;
86 * Precompiled SQL for selecting from peerstoredata
88 sqlite3_stmt *select_peerstoredata_by_pid;
91 * Precompiled SQL for selecting from peerstoredata
93 sqlite3_stmt *select_peerstoredata_by_key;
96 * Precompiled SQL for selecting from peerstoredata
98 sqlite3_stmt *select_peerstoredata_by_all;
101 * Precompiled SQL for deleting expired
102 * records from peerstoredata
104 sqlite3_stmt *expire_peerstoredata;
107 * Precompiled SQL for deleting records
110 sqlite3_stmt *delete_peerstoredata;
115 * Delete records with the given key
117 * @param cls closure (internal context for the plugin)
118 * @param sub_system name of sub system
119 * @param peer Peer identity (can be NULL)
120 * @param key entry key string (can be NULL)
121 * @return number of deleted records, #GNUNE_SYSERR on error
124 peerstore_sqlite_delete_records(void *cls,
125 const char *sub_system,
126 const struct GNUNET_PeerIdentity *peer,
129 struct Plugin *plugin = cls;
130 sqlite3_stmt *stmt = plugin->delete_peerstoredata;
131 struct GNUNET_SQ_QueryParam params[] = {
132 GNUNET_SQ_query_param_string(sub_system),
133 GNUNET_SQ_query_param_auto_from_type(peer),
134 GNUNET_SQ_query_param_string(key),
135 GNUNET_SQ_query_param_end
144 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
146 GNUNET_SQ_reset(plugin->dbh,
148 return GNUNET_SYSERR;
154 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
160 ret = sqlite3_changes(plugin->dbh);
162 GNUNET_SQ_reset(plugin->dbh,
169 * Delete expired records (expiry < now)
171 * @param cls closure (internal context for the plugin)
172 * @param now time to use as reference
173 * @param cont continuation called with the number of records expired
174 * @param cont_cls continuation closure
175 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and cont is not
179 peerstore_sqlite_expire_records(void *cls, struct GNUNET_TIME_Absolute now,
180 GNUNET_PEERSTORE_Continuation cont,
183 struct Plugin *plugin = cls;
184 sqlite3_stmt *stmt = plugin->expire_peerstoredata;
185 struct GNUNET_SQ_QueryParam params[] = {
186 GNUNET_SQ_query_param_absolute_time(&now),
187 GNUNET_SQ_query_param_end
195 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
197 GNUNET_SQ_reset(plugin->dbh,
199 return GNUNET_SYSERR;
201 if (SQLITE_DONE != sqlite3_step(stmt))
204 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
206 GNUNET_SQ_reset(plugin->dbh,
208 return GNUNET_SYSERR;
212 sqlite3_changes(plugin->dbh));
213 GNUNET_SQ_reset(plugin->dbh,
220 * Iterate over the records given an optional peer id
223 * @param cls closure (internal context for the plugin)
224 * @param sub_system name of sub system
225 * @param peer Peer identity (can be NULL)
226 * @param key entry key string (can be NULL)
227 * @param iter function to call asynchronously with the results, terminated
229 * @param iter_cls closure for @a iter
230 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
234 peerstore_sqlite_iterate_records(void *cls,
235 const char *sub_system,
236 const struct GNUNET_PeerIdentity *peer,
238 GNUNET_PEERSTORE_Processor iter,
241 struct Plugin *plugin = cls;
245 struct GNUNET_PEERSTORE_Record rec;
247 LOG(GNUNET_ERROR_TYPE_DEBUG,
248 "Executing iterate request on sqlite db.\n");
253 struct GNUNET_SQ_QueryParam params[] = {
254 GNUNET_SQ_query_param_string(sub_system),
255 GNUNET_SQ_query_param_end
258 stmt = plugin->select_peerstoredata;
259 err = GNUNET_SQ_bind(stmt,
264 struct GNUNET_SQ_QueryParam params[] = {
265 GNUNET_SQ_query_param_string(sub_system),
266 GNUNET_SQ_query_param_string(key),
267 GNUNET_SQ_query_param_end
270 stmt = plugin->select_peerstoredata_by_key;
271 err = GNUNET_SQ_bind(stmt,
279 struct GNUNET_SQ_QueryParam params[] = {
280 GNUNET_SQ_query_param_string(sub_system),
281 GNUNET_SQ_query_param_auto_from_type(peer),
282 GNUNET_SQ_query_param_end
285 stmt = plugin->select_peerstoredata_by_pid;
286 err = GNUNET_SQ_bind(stmt,
291 struct GNUNET_SQ_QueryParam params[] = {
292 GNUNET_SQ_query_param_string(sub_system),
293 GNUNET_SQ_query_param_auto_from_type(peer),
294 GNUNET_SQ_query_param_string(key),
295 GNUNET_SQ_query_param_end
298 stmt = plugin->select_peerstoredata_by_all;
299 err = GNUNET_SQ_bind(stmt,
304 if (GNUNET_OK != err)
307 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
308 "sqlite3_bind_XXXX");
309 GNUNET_SQ_reset(plugin->dbh,
311 return GNUNET_SYSERR;
315 while (SQLITE_ROW == (sret = sqlite3_step(stmt)))
317 LOG(GNUNET_ERROR_TYPE_DEBUG,
318 "Returning a matched record.\n");
319 struct GNUNET_SQ_ResultSpec rs[] = {
320 GNUNET_SQ_result_spec_string(&rec.sub_system),
321 GNUNET_SQ_result_spec_auto_from_type(&rec.peer),
322 GNUNET_SQ_result_spec_string(&rec.key),
323 GNUNET_SQ_result_spec_variable_size(&rec.value, &rec.value_size),
324 GNUNET_SQ_result_spec_absolute_time(&rec.expiry),
325 GNUNET_SQ_result_spec_end
329 GNUNET_SQ_extract_result(stmt,
339 GNUNET_SQ_cleanup_result(rs);
341 if (SQLITE_DONE != sret)
344 GNUNET_ERROR_TYPE_ERROR,
348 GNUNET_SQ_reset(plugin->dbh,
353 err ? "sqlite error" : NULL);
359 * Store a record in the peerstore.
360 * Key is the combination of sub system and peer identity.
361 * One key can store multiple values.
363 * @param cls closure (internal context for the plugin)
364 * @param sub_system name of the GNUnet sub system responsible
365 * @param peer peer identity
366 * @param key record key string
367 * @param value value to be stored
368 * @param size size of value to be stored
369 * @param expiry absolute time after which the record is (possibly) deleted
370 * @param options options related to the store operation
371 * @param cont continuation called when record is stored
372 * @param cont_cls continuation closure
373 * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called
376 peerstore_sqlite_store_record(void *cls,
377 const char *sub_system,
378 const struct GNUNET_PeerIdentity *peer,
382 struct GNUNET_TIME_Absolute expiry,
383 enum GNUNET_PEERSTORE_StoreOption options,
384 GNUNET_PEERSTORE_Continuation cont,
387 struct Plugin *plugin = cls;
388 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
389 struct GNUNET_SQ_QueryParam params[] = {
390 GNUNET_SQ_query_param_string(sub_system),
391 GNUNET_SQ_query_param_auto_from_type(peer),
392 GNUNET_SQ_query_param_string(key),
393 GNUNET_SQ_query_param_fixed_size(value, size),
394 GNUNET_SQ_query_param_absolute_time(&expiry),
395 GNUNET_SQ_query_param_end
398 if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
400 peerstore_sqlite_delete_records(cls,
409 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
411 else if (SQLITE_DONE != sqlite3_step(stmt))
414 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
417 GNUNET_SQ_reset(plugin->dbh,
427 * @brief Prepare a SQL statement
429 * @param dbh handle to the database
430 * @param sql SQL statement, UTF-8 encoded
431 * @return 0 on success
434 sql_exec(sqlite3 *dbh,
439 result = sqlite3_exec(dbh,
444 LOG(GNUNET_ERROR_TYPE_DEBUG,
445 "Executed `%s' / %d\n",
448 if (SQLITE_OK != result)
449 LOG(GNUNET_ERROR_TYPE_ERROR,
450 _("Error executing SQL query: %s\n %s\n"),
458 * @brief Prepare a SQL statement
460 * @param dbh handle to the database
461 * @param sql SQL statement, UTF-8 encoded
462 * @param stmt set to the prepared statement
463 * @return 0 on success
466 sql_prepare(sqlite3 *dbh,
468 sqlite3_stmt ** stmt)
473 result = sqlite3_prepare_v2(dbh,
477 (const char **)&tail);
478 LOG(GNUNET_ERROR_TYPE_DEBUG,
479 "Prepared `%s' / %p: %d\n",
483 if (SQLITE_OK != result)
484 LOG(GNUNET_ERROR_TYPE_ERROR,
485 _("Error preparing SQL query: %s\n %s\n"),
493 * Initialize the database connections and associated
494 * data structures (create tables and indices
495 * as needed as well).
497 * @param plugin the plugin context (state for this module)
498 * @return #GNUNET_OK on success
501 database_setup(struct Plugin *plugin)
506 GNUNET_CONFIGURATION_get_value_filename(plugin->cfg,
511 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
514 return GNUNET_SYSERR;
516 if (GNUNET_OK != GNUNET_DISK_file_test(filename))
518 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(filename))
521 GNUNET_free(filename);
522 return GNUNET_SYSERR;
525 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
526 plugin->fn = filename;
527 /* Open database and precompile statements */
528 if (SQLITE_OK != sqlite3_open(plugin->fn,
531 LOG(GNUNET_ERROR_TYPE_ERROR,
532 _("Unable to initialize SQLite: %s.\n"),
533 sqlite3_errmsg(plugin->dbh));
534 return GNUNET_SYSERR;
536 sql_exec(plugin->dbh,
537 "PRAGMA temp_store=MEMORY");
538 sql_exec(plugin->dbh,
539 "PRAGMA synchronous=OFF");
540 sql_exec(plugin->dbh,
541 "PRAGMA legacy_file_format=OFF");
542 sql_exec(plugin->dbh,
543 "PRAGMA auto_vacuum=INCREMENTAL");
544 sql_exec(plugin->dbh,
545 "PRAGMA encoding=\"UTF-8\"");
546 sql_exec(plugin->dbh,
547 "PRAGMA page_size=4096");
548 sqlite3_busy_timeout(plugin->dbh,
551 sql_exec(plugin->dbh,
552 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
553 " sub_system TEXT NOT NULL,\n"
554 " peer_id BLOB NOT NULL,\n"
555 " key TEXT NOT NULL,\n"
556 " value BLOB NULL,\n"
557 " expiry INT8 NOT NULL" ");");
560 sqlite3_exec(plugin->dbh,
561 "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
566 LOG(GNUNET_ERROR_TYPE_ERROR,
567 _("Unable to create indices: %s.\n"),
568 sqlite3_errmsg(plugin->dbh));
569 return GNUNET_SYSERR;
571 /* Prepare statements */
573 sql_prepare(plugin->dbh,
574 "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)"
575 " VALUES (?,?,?,?,?);",
576 &plugin->insert_peerstoredata);
577 sql_prepare(plugin->dbh,
578 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
579 " WHERE sub_system = ?",
580 &plugin->select_peerstoredata);
581 sql_prepare(plugin->dbh,
582 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
583 " WHERE sub_system = ?"
585 &plugin->select_peerstoredata_by_pid);
586 sql_prepare(plugin->dbh,
587 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
588 " WHERE sub_system = ?"
590 &plugin->select_peerstoredata_by_key);
591 sql_prepare(plugin->dbh,
592 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
593 " WHERE sub_system = ?"
594 " AND peer_id = ?" " AND key = ?",
595 &plugin->select_peerstoredata_by_all);
596 sql_prepare(plugin->dbh,
597 "DELETE FROM peerstoredata"
599 &plugin->expire_peerstoredata);
600 sql_prepare(plugin->dbh,
601 "DELETE FROM peerstoredata"
602 " WHERE sub_system = ?"
603 " AND peer_id = ?" " AND key = ?",
604 &plugin->delete_peerstoredata);
610 * Shutdown database connection and associate data
612 * @param plugin the plugin context (state for this module)
615 database_shutdown(struct Plugin *plugin)
620 while (NULL != (stmt = sqlite3_next_stmt(plugin->dbh,
623 result = sqlite3_finalize(stmt);
624 if (SQLITE_OK != result)
625 LOG(GNUNET_ERROR_TYPE_WARNING,
626 "Failed to close statement %p: %d\n",
630 if (SQLITE_OK != sqlite3_close(plugin->dbh))
632 GNUNET_ERROR_TYPE_ERROR,
634 GNUNET_free_non_null(plugin->fn);
639 * Entry point for the plugin.
641 * @param cls The struct GNUNET_CONFIGURATION_Handle.
642 * @return NULL on error, otherwise the plugin context
645 libgnunet_plugin_peerstore_sqlite_init(void *cls)
647 static struct Plugin plugin;
648 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
649 struct GNUNET_PEERSTORE_PluginFunctions *api;
651 if (NULL != plugin.cfg)
652 return NULL; /* can only initialize once! */
655 sizeof(struct Plugin));
657 if (GNUNET_OK != database_setup(&plugin))
659 database_shutdown(&plugin);
662 api = GNUNET_new(struct GNUNET_PEERSTORE_PluginFunctions);
664 api->store_record = &peerstore_sqlite_store_record;
665 api->iterate_records = &peerstore_sqlite_iterate_records;
666 api->expire_records = &peerstore_sqlite_expire_records;
667 LOG(GNUNET_ERROR_TYPE_DEBUG,
668 "Sqlite plugin is running\n");
674 * Exit point from the plugin.
676 * @param cls The plugin context (as returned by "init")
677 * @return Always NULL
680 libgnunet_plugin_peerstore_sqlite_done(void *cls)
682 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
683 struct Plugin *plugin = api->cls;
685 database_shutdown(plugin);
688 LOG(GNUNET_ERROR_TYPE_DEBUG,
689 "Sqlite plugin is finished\n");
693 /* end of plugin_peerstore_sqlite.c */