uncrustify as demanded.
[oweals/gnunet.git] / src / peerstore / plugin_peerstore_sqlite.c
1 /*
2  * This file is part of GNUnet
3  * Copyright (C) 2013, 2017 GNUnet e.V.
4  *
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.
9  *
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.
14  *
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/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19  */
20
21 /**
22  * @file peerstore/plugin_peerstore_sqlite.c
23  * @brief sqlite-based peerstore backend
24  * @author Omar Tarabai
25  * @author Christian Grothoff
26  */
27
28 #include "platform.h"
29 #include "gnunet_peerstore_plugin.h"
30 #include "gnunet_peerstore_service.h"
31 #include "gnunet_sq_lib.h"
32 #include "peerstore.h"
33 #include <sqlite3.h>
34
35 /**
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).
40  *
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.
44  */
45 #define BUSY_TIMEOUT_MS 1000
46
47 /**
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).
51  */
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)
53
54 #define LOG(kind, ...) GNUNET_log_from(kind, "peerstore-sqlite", __VA_ARGS__)
55
56 /**
57  * Context for all functions in this plugin.
58  */
59 struct Plugin {
60   /**
61    * Configuration handle
62    */
63   const struct GNUNET_CONFIGURATION_Handle *cfg;
64
65   /**
66    * Database filename.
67    */
68   char *fn;
69
70   /**
71    * Native SQLite database handle.
72    */
73   sqlite3 *dbh;
74
75   /**
76    * Precompiled SQL for inserting into peerstoredata
77    */
78   sqlite3_stmt *insert_peerstoredata;
79
80   /**
81    * Precompiled SQL for selecting from peerstoredata
82    */
83   sqlite3_stmt *select_peerstoredata;
84
85   /**
86    * Precompiled SQL for selecting from peerstoredata
87    */
88   sqlite3_stmt *select_peerstoredata_by_pid;
89
90   /**
91    * Precompiled SQL for selecting from peerstoredata
92    */
93   sqlite3_stmt *select_peerstoredata_by_key;
94
95   /**
96    * Precompiled SQL for selecting from peerstoredata
97    */
98   sqlite3_stmt *select_peerstoredata_by_all;
99
100   /**
101    * Precompiled SQL for deleting expired
102    * records from peerstoredata
103    */
104   sqlite3_stmt *expire_peerstoredata;
105
106   /**
107    * Precompiled SQL for deleting records
108    * with given key
109    */
110   sqlite3_stmt *delete_peerstoredata;
111 };
112
113
114 /**
115  * Delete records with the given key
116  *
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
122  */
123 static int
124 peerstore_sqlite_delete_records(void *cls,
125                                 const char *sub_system,
126                                 const struct GNUNET_PeerIdentity *peer,
127                                 const char *key)
128 {
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
136   };
137   int ret;
138
139   if (GNUNET_OK !=
140       GNUNET_SQ_bind(stmt,
141                      params))
142     {
143       LOG_SQLITE(plugin,
144                  GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
145                  "sqlite3_bind");
146       GNUNET_SQ_reset(plugin->dbh,
147                       stmt);
148       return GNUNET_SYSERR;
149     }
150   if (SQLITE_DONE !=
151       sqlite3_step(stmt))
152     {
153       LOG_SQLITE(plugin,
154                  GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
155                  "sqlite3_step");
156       ret = GNUNET_SYSERR;
157     }
158   else
159     {
160       ret = sqlite3_changes(plugin->dbh);
161     }
162   GNUNET_SQ_reset(plugin->dbh,
163                   stmt);
164   return ret;
165 }
166
167
168 /**
169  * Delete expired records (expiry < now)
170  *
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
176  * called
177  */
178 static int
179 peerstore_sqlite_expire_records(void *cls, struct GNUNET_TIME_Absolute now,
180                                 GNUNET_PEERSTORE_Continuation cont,
181                                 void *cont_cls)
182 {
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
188   };
189
190   if (GNUNET_OK !=
191       GNUNET_SQ_bind(stmt,
192                      params))
193     {
194       LOG_SQLITE(plugin,
195                  GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
196                  "sqlite3_bind");
197       GNUNET_SQ_reset(plugin->dbh,
198                       stmt);
199       return GNUNET_SYSERR;
200     }
201   if (SQLITE_DONE != sqlite3_step(stmt))
202     {
203       LOG_SQLITE(plugin,
204                  GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
205                  "sqlite3_step");
206       GNUNET_SQ_reset(plugin->dbh,
207                       stmt);
208       return GNUNET_SYSERR;
209     }
210   if (NULL != cont)
211     cont(cont_cls,
212          sqlite3_changes(plugin->dbh));
213   GNUNET_SQ_reset(plugin->dbh,
214                   stmt);
215   return GNUNET_OK;
216 }
217
218
219 /**
220  * Iterate over the records given an optional peer id
221  * and/or key.
222  *
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
228  * by a NULL result
229  * @param iter_cls closure for @a iter
230  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
231  * called
232  */
233 static int
234 peerstore_sqlite_iterate_records(void *cls,
235                                  const char *sub_system,
236                                  const struct GNUNET_PeerIdentity *peer,
237                                  const char *key,
238                                  GNUNET_PEERSTORE_Processor iter,
239                                  void *iter_cls)
240 {
241   struct Plugin *plugin = cls;
242   sqlite3_stmt *stmt;
243   int err = 0;
244   int sret;
245   struct GNUNET_PEERSTORE_Record rec;
246
247   LOG(GNUNET_ERROR_TYPE_DEBUG,
248       "Executing iterate request on sqlite db.\n");
249   if (NULL == peer)
250     {
251       if (NULL == key)
252         {
253           struct GNUNET_SQ_QueryParam params[] = {
254             GNUNET_SQ_query_param_string(sub_system),
255             GNUNET_SQ_query_param_end
256           };
257
258           stmt = plugin->select_peerstoredata;
259           err = GNUNET_SQ_bind(stmt,
260                                params);
261         }
262       else
263         {
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
268           };
269
270           stmt = plugin->select_peerstoredata_by_key;
271           err = GNUNET_SQ_bind(stmt,
272                                params);
273         }
274     }
275   else
276     {
277       if (NULL == key)
278         {
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
283           };
284
285           stmt = plugin->select_peerstoredata_by_pid;
286           err = GNUNET_SQ_bind(stmt,
287                                params);
288         }
289       else
290         {
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
296           };
297
298           stmt = plugin->select_peerstoredata_by_all;
299           err = GNUNET_SQ_bind(stmt,
300                                params);
301         }
302     }
303
304   if (GNUNET_OK != err)
305     {
306       LOG_SQLITE(plugin,
307                  GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
308                  "sqlite3_bind_XXXX");
309       GNUNET_SQ_reset(plugin->dbh,
310                       stmt);
311       return GNUNET_SYSERR;
312     }
313
314   err = 0;
315   while (SQLITE_ROW == (sret = sqlite3_step(stmt)))
316     {
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
326       };
327
328       if (GNUNET_OK !=
329           GNUNET_SQ_extract_result(stmt,
330                                    rs))
331         {
332           GNUNET_break(0);
333           break;
334         }
335       if (NULL != iter)
336         iter(iter_cls,
337              &rec,
338              NULL);
339       GNUNET_SQ_cleanup_result(rs);
340     }
341   if (SQLITE_DONE != sret)
342     {
343       LOG_SQLITE(plugin,
344                  GNUNET_ERROR_TYPE_ERROR,
345                  "sqlite_step");
346       err = 1;
347     }
348   GNUNET_SQ_reset(plugin->dbh,
349                   stmt);
350   if (NULL != iter)
351     iter(iter_cls,
352          NULL,
353          err ? "sqlite error" : NULL);
354   return GNUNET_OK;
355 }
356
357
358 /**
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.
362  *
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
374  */
375 static int
376 peerstore_sqlite_store_record(void *cls,
377                               const char *sub_system,
378                               const struct GNUNET_PeerIdentity *peer,
379                               const char *key,
380                               const void *value,
381                               size_t size,
382                               struct GNUNET_TIME_Absolute expiry,
383                               enum GNUNET_PEERSTORE_StoreOption options,
384                               GNUNET_PEERSTORE_Continuation cont,
385                               void *cont_cls)
386 {
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
396   };
397
398   if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
399     {
400       peerstore_sqlite_delete_records(cls,
401                                       sub_system,
402                                       peer,
403                                       key);
404     }
405   if (GNUNET_OK !=
406       GNUNET_SQ_bind(stmt,
407                      params))
408     LOG_SQLITE(plugin,
409                GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
410                "sqlite3_bind");
411   else if (SQLITE_DONE != sqlite3_step(stmt))
412     {
413       LOG_SQLITE(plugin,
414                  GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415                  "sqlite3_step");
416     }
417   GNUNET_SQ_reset(plugin->dbh,
418                   stmt);
419   if (NULL != cont)
420     cont(cont_cls,
421          GNUNET_OK);
422   return GNUNET_OK;
423 }
424
425
426 /**
427  * @brief Prepare a SQL statement
428  *
429  * @param dbh handle to the database
430  * @param sql SQL statement, UTF-8 encoded
431  * @return 0 on success
432  */
433 static int
434 sql_exec(sqlite3 *dbh,
435          const char *sql)
436 {
437   int result;
438
439   result = sqlite3_exec(dbh,
440                         sql,
441                         NULL,
442                         NULL,
443                         NULL);
444   LOG(GNUNET_ERROR_TYPE_DEBUG,
445       "Executed `%s' / %d\n",
446       sql,
447       result);
448   if (SQLITE_OK != result)
449     LOG(GNUNET_ERROR_TYPE_ERROR,
450         _("Error executing SQL query: %s\n  %s\n"),
451         sqlite3_errmsg(dbh),
452         sql);
453   return result;
454 }
455
456
457 /**
458  * @brief Prepare a SQL statement
459  *
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
464  */
465 static int
466 sql_prepare(sqlite3 *dbh,
467             const char *sql,
468             sqlite3_stmt ** stmt)
469 {
470   char *tail;
471   int result;
472
473   result = sqlite3_prepare_v2(dbh,
474                               sql,
475                               strlen(sql),
476                               stmt,
477                               (const char **)&tail);
478   LOG(GNUNET_ERROR_TYPE_DEBUG,
479       "Prepared `%s' / %p: %d\n",
480       sql,
481       *stmt,
482       result);
483   if (SQLITE_OK != result)
484     LOG(GNUNET_ERROR_TYPE_ERROR,
485         _("Error preparing SQL query: %s\n  %s\n"),
486         sqlite3_errmsg(dbh),
487         sql);
488   return result;
489 }
490
491
492 /**
493  * Initialize the database connections and associated
494  * data structures (create tables and indices
495  * as needed as well).
496  *
497  * @param plugin the plugin context (state for this module)
498  * @return #GNUNET_OK on success
499  */
500 static int
501 database_setup(struct Plugin *plugin)
502 {
503   char *filename;
504
505   if (GNUNET_OK !=
506       GNUNET_CONFIGURATION_get_value_filename(plugin->cfg,
507                                               "peerstore-sqlite",
508                                               "FILENAME",
509                                               &filename))
510     {
511       GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
512                                 "peerstore-sqlite",
513                                 "FILENAME");
514       return GNUNET_SYSERR;
515     }
516   if (GNUNET_OK != GNUNET_DISK_file_test(filename))
517     {
518       if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(filename))
519         {
520           GNUNET_break(0);
521           GNUNET_free(filename);
522           return GNUNET_SYSERR;
523         }
524     }
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,
529                                 &plugin->dbh))
530     {
531       LOG(GNUNET_ERROR_TYPE_ERROR,
532           _("Unable to initialize SQLite: %s.\n"),
533           sqlite3_errmsg(plugin->dbh));
534       return GNUNET_SYSERR;
535     }
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,
549                        BUSY_TIMEOUT_MS);
550   /* Create tables */
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" ");");
558   /* Create Indices */
559   if (SQLITE_OK !=
560       sqlite3_exec(plugin->dbh,
561                    "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
562                    NULL,
563                    NULL,
564                    NULL))
565     {
566       LOG(GNUNET_ERROR_TYPE_ERROR,
567           _("Unable to create indices: %s.\n"),
568           sqlite3_errmsg(plugin->dbh));
569       return GNUNET_SYSERR;
570     }
571   /* Prepare statements */
572
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 = ?"
584               " AND peer_id = ?",
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 = ?"
589               " AND key = ?",
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"
598               " WHERE expiry < ?",
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);
605   return GNUNET_OK;
606 }
607
608
609 /**
610  * Shutdown database connection and associate data
611  * structures.
612  * @param plugin the plugin context (state for this module)
613  */
614 static void
615 database_shutdown(struct Plugin *plugin)
616 {
617   int result;
618   sqlite3_stmt *stmt;
619
620   while (NULL != (stmt = sqlite3_next_stmt(plugin->dbh,
621                                            NULL)))
622     {
623       result = sqlite3_finalize(stmt);
624       if (SQLITE_OK != result)
625         LOG(GNUNET_ERROR_TYPE_WARNING,
626             "Failed to close statement %p: %d\n",
627             stmt,
628             result);
629     }
630   if (SQLITE_OK != sqlite3_close(plugin->dbh))
631     LOG_SQLITE(plugin,
632                GNUNET_ERROR_TYPE_ERROR,
633                "sqlite3_close");
634   GNUNET_free_non_null(plugin->fn);
635 }
636
637
638 /**
639  * Entry point for the plugin.
640  *
641  * @param cls The struct GNUNET_CONFIGURATION_Handle.
642  * @return NULL on error, otherwise the plugin context
643  */
644 void *
645 libgnunet_plugin_peerstore_sqlite_init(void *cls)
646 {
647   static struct Plugin plugin;
648   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
649   struct GNUNET_PEERSTORE_PluginFunctions *api;
650
651   if (NULL != plugin.cfg)
652     return NULL;                /* can only initialize once! */
653   memset(&plugin,
654          0,
655          sizeof(struct Plugin));
656   plugin.cfg = cfg;
657   if (GNUNET_OK != database_setup(&plugin))
658     {
659       database_shutdown(&plugin);
660       return NULL;
661     }
662   api = GNUNET_new(struct GNUNET_PEERSTORE_PluginFunctions);
663   api->cls = &plugin;
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");
669   return api;
670 }
671
672
673 /**
674  * Exit point from the plugin.
675  *
676  * @param cls The plugin context (as returned by "init")
677  * @return Always NULL
678  */
679 void *
680 libgnunet_plugin_peerstore_sqlite_done(void *cls)
681 {
682   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
683   struct Plugin *plugin = api->cls;
684
685   database_shutdown(plugin);
686   plugin->cfg = NULL;
687   GNUNET_free(api);
688   LOG(GNUNET_ERROR_TYPE_DEBUG,
689       "Sqlite plugin is finished\n");
690   return NULL;
691 }
692
693 /* end of plugin_peerstore_sqlite.c */