when zone does not match, do not run through the loop anyway
[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
19 /**
20  * @file peerstore/plugin_peerstore_sqlite.c
21  * @brief sqlite-based peerstore backend
22  * @author Omar Tarabai
23  * @author Christian Grothoff
24  */
25
26 #include "platform.h"
27 #include "gnunet_peerstore_plugin.h"
28 #include "gnunet_peerstore_service.h"
29 #include "gnunet_sq_lib.h"
30 #include "peerstore.h"
31 #include <sqlite3.h>
32
33 /**
34  * After how many ms "busy" should a DB operation fail for good?  A
35  * low value makes sure that we are more responsive to requests
36  * (especially PUTs).  A high value guarantees a higher success rate
37  * (SELECTs in iterate can take several seconds despite LIMIT=1).
38  *
39  * The default value of 1s should ensure that users do not experience
40  * huge latencies while at the same time allowing operations to
41  * succeed with reasonable probability.
42  */
43 #define BUSY_TIMEOUT_MS 1000
44
45 /**
46  * Log an error message at log-level 'level' that indicates
47  * a failure of the command 'cmd' on file 'filename'
48  * with the message given by strerror(errno).
49  */
50 #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)
51
52 #define LOG(kind,...) GNUNET_log_from (kind, "peerstore-sqlite", __VA_ARGS__)
53
54 /**
55  * Context for all functions in this plugin.
56  */
57 struct Plugin
58 {
59
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 /**
116  * Delete records with the given key
117  *
118  * @param cls closure (internal context for the plugin)
119  * @param sub_system name of sub system
120  * @param peer Peer identity (can be NULL)
121  * @param key entry key string (can be NULL)
122  * @return number of deleted records, #GNUNE_SYSERR on error
123  */
124 static int
125 peerstore_sqlite_delete_records (void *cls,
126                                  const char *sub_system,
127                                  const struct GNUNET_PeerIdentity *peer,
128                                  const char *key)
129 {
130   struct Plugin *plugin = cls;
131   sqlite3_stmt *stmt = plugin->delete_peerstoredata;
132   struct GNUNET_SQ_QueryParam params[] = {
133     GNUNET_SQ_query_param_string (sub_system),
134     GNUNET_SQ_query_param_auto_from_type (peer),
135     GNUNET_SQ_query_param_string (key),
136     GNUNET_SQ_query_param_end
137   };
138   int ret;
139
140   if (GNUNET_OK !=
141       GNUNET_SQ_bind (stmt,
142                       params))
143   {
144     LOG_SQLITE (plugin,
145                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
146                 "sqlite3_bind");
147     GNUNET_SQ_reset (plugin->dbh,
148                      stmt);
149     return GNUNET_SYSERR;
150   }
151   if (SQLITE_DONE !=
152       sqlite3_step (stmt))
153   {
154     LOG_SQLITE (plugin,
155                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
156                 "sqlite3_step");
157     ret = GNUNET_SYSERR;
158   }
159   else
160   {
161     ret = sqlite3_changes (plugin->dbh);
162   }
163   GNUNET_SQ_reset (plugin->dbh,
164                    stmt);
165   return ret;
166 }
167
168
169 /**
170  * Delete expired records (expiry < now)
171  *
172  * @param cls closure (internal context for the plugin)
173  * @param now time to use as reference
174  * @param cont continuation called with the number of records expired
175  * @param cont_cls continuation closure
176  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and cont is not
177  * called
178  */
179 static int
180 peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now,
181                                  GNUNET_PEERSTORE_Continuation cont,
182                                  void *cont_cls)
183 {
184   struct Plugin *plugin = cls;
185   sqlite3_stmt *stmt = plugin->expire_peerstoredata;
186   struct GNUNET_SQ_QueryParam params[] = {
187     GNUNET_SQ_query_param_absolute_time (&now),
188     GNUNET_SQ_query_param_end
189   };
190
191   if (GNUNET_OK !=
192       GNUNET_SQ_bind (stmt,
193                       params))
194   {
195     LOG_SQLITE (plugin,
196                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
197                 "sqlite3_bind");
198     GNUNET_SQ_reset (plugin->dbh,
199                      stmt);
200     return GNUNET_SYSERR;
201   }
202   if (SQLITE_DONE != sqlite3_step (stmt))
203   {
204     LOG_SQLITE (plugin,
205                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
206                 "sqlite3_step");
207     GNUNET_SQ_reset (plugin->dbh,
208                      stmt);
209     return GNUNET_SYSERR;
210   }
211   if (NULL != cont)
212     cont (cont_cls,
213           sqlite3_changes (plugin->dbh));
214   GNUNET_SQ_reset (plugin->dbh,
215                    stmt);
216   return GNUNET_OK;
217 }
218
219
220 /**
221  * Iterate over the records given an optional peer id
222  * and/or key.
223  *
224  * @param cls closure (internal context for the plugin)
225  * @param sub_system name of sub system
226  * @param peer Peer identity (can be NULL)
227  * @param key entry key string (can be NULL)
228  * @param iter function to call asynchronously with the results, terminated
229  * by a NULL result
230  * @param iter_cls closure for @a iter
231  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
232  * called
233  */
234 static int
235 peerstore_sqlite_iterate_records (void *cls,
236                                   const char *sub_system,
237                                   const struct GNUNET_PeerIdentity *peer,
238                                   const char *key,
239                                   GNUNET_PEERSTORE_Processor iter,
240                                   void *iter_cls)
241 {
242   struct Plugin *plugin = cls;
243   sqlite3_stmt *stmt;
244   int err = 0;
245   int sret;
246   struct GNUNET_PEERSTORE_Record rec;
247
248   LOG (GNUNET_ERROR_TYPE_DEBUG,
249        "Executing iterate request on sqlite db.\n");
250   if (NULL == peer)
251   {
252     if (NULL == key)
253     {
254       struct GNUNET_SQ_QueryParam params[] = {
255         GNUNET_SQ_query_param_string (sub_system),
256         GNUNET_SQ_query_param_end
257       };
258
259       stmt = plugin->select_peerstoredata;
260       err = GNUNET_SQ_bind (stmt,
261                             params);
262     }
263     else
264     {
265       struct GNUNET_SQ_QueryParam params[] = {
266         GNUNET_SQ_query_param_string (sub_system),
267         GNUNET_SQ_query_param_string (key),
268         GNUNET_SQ_query_param_end
269       };
270
271       stmt = plugin->select_peerstoredata_by_key;
272       err = GNUNET_SQ_bind (stmt,
273                             params);
274     }
275   }
276   else
277   {
278     if (NULL == key)
279     {
280       struct GNUNET_SQ_QueryParam params[] = {
281         GNUNET_SQ_query_param_string (sub_system),
282         GNUNET_SQ_query_param_auto_from_type (peer),
283         GNUNET_SQ_query_param_end
284       };
285
286       stmt = plugin->select_peerstoredata_by_pid;
287       err = GNUNET_SQ_bind (stmt,
288                             params);
289     }
290     else
291     {
292       struct GNUNET_SQ_QueryParam params[] = {
293         GNUNET_SQ_query_param_string (sub_system),
294         GNUNET_SQ_query_param_auto_from_type (peer),
295         GNUNET_SQ_query_param_string (key),
296         GNUNET_SQ_query_param_end
297       };
298
299       stmt = plugin->select_peerstoredata_by_all;
300       err = GNUNET_SQ_bind (stmt,
301                             params);
302     }
303   }
304
305   if (GNUNET_OK != err)
306   {
307     LOG_SQLITE (plugin,
308                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
309                 "sqlite3_bind_XXXX");
310     GNUNET_SQ_reset (plugin->dbh,
311                      stmt);
312     return GNUNET_SYSERR;
313   }
314
315   err = 0;
316   while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
317   {
318     LOG (GNUNET_ERROR_TYPE_DEBUG,
319          "Returning a matched record.\n");
320     struct GNUNET_SQ_ResultSpec rs[] = {
321       GNUNET_SQ_result_spec_string (&rec.sub_system),
322       GNUNET_SQ_result_spec_auto_from_type (&rec.peer),
323       GNUNET_SQ_result_spec_string (&rec.key),
324       GNUNET_SQ_result_spec_variable_size (&rec.value, &rec.value_size),
325       GNUNET_SQ_result_spec_absolute_time (&rec.expiry),
326       GNUNET_SQ_result_spec_end
327     };
328
329     if (GNUNET_OK !=
330         GNUNET_SQ_extract_result (stmt,
331                                   rs))
332     {
333       GNUNET_break (0);
334       break;
335     }
336     if (NULL != iter)
337       iter (iter_cls,
338             &rec,
339             NULL);
340     GNUNET_SQ_cleanup_result (rs);
341   }
342   if (SQLITE_DONE != sret)
343   {
344     LOG_SQLITE (plugin,
345                 GNUNET_ERROR_TYPE_ERROR,
346                 "sqlite_step");
347     err = 1;
348   }
349   GNUNET_SQ_reset (plugin->dbh,
350                    stmt);
351   if (NULL != iter)
352     iter (iter_cls,
353           NULL,
354           err ? "sqlite error" : NULL);
355   return GNUNET_OK;
356 }
357
358
359 /**
360  * Store a record in the peerstore.
361  * Key is the combination of sub system and peer identity.
362  * One key can store multiple values.
363  *
364  * @param cls closure (internal context for the plugin)
365  * @param sub_system name of the GNUnet sub system responsible
366  * @param peer peer identity
367  * @param key record key string
368  * @param value value to be stored
369  * @param size size of value to be stored
370  * @param expiry absolute time after which the record is (possibly) deleted
371  * @param options options related to the store operation
372  * @param cont continuation called when record is stored
373  * @param cont_cls continuation closure
374  * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called
375  */
376 static int
377 peerstore_sqlite_store_record (void *cls,
378                                const char *sub_system,
379                                const struct GNUNET_PeerIdentity *peer,
380                                const char *key,
381                                const void *value,
382                                size_t size,
383                                struct GNUNET_TIME_Absolute expiry,
384                                enum GNUNET_PEERSTORE_StoreOption options,
385                                GNUNET_PEERSTORE_Continuation cont,
386                                void *cont_cls)
387 {
388   struct Plugin *plugin = cls;
389   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
390   struct GNUNET_SQ_QueryParam params[] = {
391     GNUNET_SQ_query_param_string (sub_system),
392     GNUNET_SQ_query_param_auto_from_type (peer),
393     GNUNET_SQ_query_param_string (key),
394     GNUNET_SQ_query_param_fixed_size (value, size),
395     GNUNET_SQ_query_param_absolute_time (&expiry),
396     GNUNET_SQ_query_param_end
397   };
398
399   if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
400   {
401     peerstore_sqlite_delete_records (cls,
402                                      sub_system,
403                                      peer,
404                                      key);
405   }
406   if (GNUNET_OK !=
407       GNUNET_SQ_bind (stmt,
408                       params))
409     LOG_SQLITE (plugin,
410                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
411                 "sqlite3_bind");
412   else if (SQLITE_DONE != sqlite3_step (stmt))
413   {
414     LOG_SQLITE (plugin,
415                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
416                 "sqlite3_step");
417   }
418   GNUNET_SQ_reset (plugin->dbh,
419                    stmt);
420   if (NULL != cont)
421     cont (cont_cls,
422           GNUNET_OK);
423   return GNUNET_OK;
424 }
425
426
427 /**
428  * @brief Prepare a SQL statement
429  *
430  * @param dbh handle to the database
431  * @param sql SQL statement, UTF-8 encoded
432  * @return 0 on success
433  */
434 static int
435 sql_exec (sqlite3 *dbh,
436           const char *sql)
437 {
438   int result;
439
440   result = sqlite3_exec (dbh,
441                          sql,
442                          NULL,
443                          NULL,
444                          NULL);
445   LOG (GNUNET_ERROR_TYPE_DEBUG,
446        "Executed `%s' / %d\n",
447        sql,
448        result);
449   if (SQLITE_OK != result)
450     LOG (GNUNET_ERROR_TYPE_ERROR,
451          _("Error executing SQL query: %s\n  %s\n"),
452          sqlite3_errmsg (dbh),
453          sql);
454   return result;
455 }
456
457
458 /**
459  * @brief Prepare a SQL statement
460  *
461  * @param dbh handle to the database
462  * @param sql SQL statement, UTF-8 encoded
463  * @param stmt set to the prepared statement
464  * @return 0 on success
465  */
466 static int
467 sql_prepare (sqlite3 *dbh,
468              const char *sql,
469              sqlite3_stmt ** stmt)
470 {
471   char *tail;
472   int result;
473
474   result = sqlite3_prepare_v2 (dbh,
475                                sql,
476                                strlen (sql),
477                                stmt,
478                                (const char **) &tail);
479   LOG (GNUNET_ERROR_TYPE_DEBUG,
480        "Prepared `%s' / %p: %d\n",
481        sql,
482        *stmt,
483        result);
484   if (SQLITE_OK != result)
485     LOG (GNUNET_ERROR_TYPE_ERROR,
486          _("Error preparing SQL query: %s\n  %s\n"),
487          sqlite3_errmsg (dbh),
488          sql);
489   return result;
490 }
491
492
493 /**
494  * Initialize the database connections and associated
495  * data structures (create tables and indices
496  * as needed as well).
497  *
498  * @param plugin the plugin context (state for this module)
499  * @return GNUNET_OK on success
500  */
501 static int
502 database_setup (struct Plugin *plugin)
503 {
504   char *filename;
505
506   if (GNUNET_OK !=
507       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
508                                                "peerstore-sqlite",
509                                                "FILENAME",
510                                                &filename))
511   {
512     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
513                                "peerstore-sqlite",
514                                "FILENAME");
515     return GNUNET_SYSERR;
516   }
517   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
518   {
519     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
520     {
521       GNUNET_break (0);
522       GNUNET_free (filename);
523       return GNUNET_SYSERR;
524     }
525   }
526   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
527   plugin->fn = filename;
528   /* Open database and precompile statements */
529   if (SQLITE_OK != sqlite3_open (plugin->fn,
530                                  &plugin->dbh))
531   {
532     LOG (GNUNET_ERROR_TYPE_ERROR,
533          _("Unable to initialize SQLite: %s.\n"),
534          sqlite3_errmsg (plugin->dbh));
535     return GNUNET_SYSERR;
536   }
537   sql_exec (plugin->dbh,
538             "PRAGMA temp_store=MEMORY");
539   sql_exec (plugin->dbh,
540             "PRAGMA synchronous=OFF");
541   sql_exec (plugin->dbh,
542             "PRAGMA legacy_file_format=OFF");
543   sql_exec (plugin->dbh,
544             "PRAGMA auto_vacuum=INCREMENTAL");
545   sql_exec (plugin->dbh,
546             "PRAGMA encoding=\"UTF-8\"");
547   sql_exec (plugin->dbh,
548             "PRAGMA page_size=4096");
549   sqlite3_busy_timeout (plugin->dbh,
550                         BUSY_TIMEOUT_MS);
551   /* Create tables */
552   sql_exec (plugin->dbh,
553             "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
554             "  sub_system TEXT NOT NULL,\n"
555             "  peer_id BLOB NOT NULL,\n"
556             "  key TEXT NOT NULL,\n"
557             "  value BLOB NULL,\n"
558             "  expiry INT8 NOT NULL" ");");
559   /* Create Indices */
560   if (SQLITE_OK !=
561       sqlite3_exec (plugin->dbh,
562                     "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
563                     NULL,
564                     NULL,
565                     NULL))
566   {
567     LOG (GNUNET_ERROR_TYPE_ERROR,
568          _("Unable to create indices: %s.\n"),
569          sqlite3_errmsg (plugin->dbh));
570     return GNUNET_SYSERR;
571   }
572   /* Prepare statements */
573
574   sql_prepare (plugin->dbh,
575                "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)"
576                " VALUES (?,?,?,?,?);",
577                &plugin->insert_peerstoredata);
578   sql_prepare (plugin->dbh,
579                "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
580                " WHERE sub_system = ?",
581                &plugin->select_peerstoredata);
582   sql_prepare (plugin->dbh,
583                "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
584                " WHERE sub_system = ?"
585                " AND peer_id = ?",
586                &plugin->select_peerstoredata_by_pid);
587   sql_prepare (plugin->dbh,
588                "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
589                " WHERE sub_system = ?"
590                " AND key = ?",
591                &plugin->select_peerstoredata_by_key);
592   sql_prepare (plugin->dbh,
593                "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
594                " WHERE sub_system = ?"
595                " AND peer_id = ?" " AND key = ?",
596                &plugin->select_peerstoredata_by_all);
597   sql_prepare (plugin->dbh,
598                "DELETE FROM peerstoredata"
599                " WHERE expiry < ?",
600                &plugin->expire_peerstoredata);
601   sql_prepare (plugin->dbh,
602                "DELETE FROM peerstoredata"
603                " WHERE sub_system = ?"
604                " AND peer_id = ?" " AND key = ?",
605                &plugin->delete_peerstoredata);
606   return GNUNET_OK;
607 }
608
609
610 /**
611  * Shutdown database connection and associate data
612  * structures.
613  * @param plugin the plugin context (state for this module)
614  */
615 static void
616 database_shutdown (struct Plugin *plugin)
617 {
618   int result;
619   sqlite3_stmt *stmt;
620
621   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh,
622                                             NULL)))
623   {
624     result = sqlite3_finalize (stmt);
625     if (SQLITE_OK != result)
626       LOG (GNUNET_ERROR_TYPE_WARNING,
627            "Failed to close statement %p: %d\n",
628            stmt,
629            result);
630   }
631   if (SQLITE_OK != sqlite3_close (plugin->dbh))
632     LOG_SQLITE (plugin,
633                 GNUNET_ERROR_TYPE_ERROR,
634                 "sqlite3_close");
635   GNUNET_free_non_null (plugin->fn);
636 }
637
638
639 /**
640  * Entry point for the plugin.
641  *
642  * @param cls The struct GNUNET_CONFIGURATION_Handle.
643  * @return NULL on error, otherwise the plugin context
644  */
645 void *
646 libgnunet_plugin_peerstore_sqlite_init (void *cls)
647 {
648   static struct Plugin plugin;
649   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
650   struct GNUNET_PEERSTORE_PluginFunctions *api;
651
652   if (NULL != plugin.cfg)
653     return NULL;                /* can only initialize once! */
654   memset (&plugin,
655           0,
656           sizeof (struct Plugin));
657   plugin.cfg = cfg;
658   if (GNUNET_OK != database_setup (&plugin))
659   {
660     database_shutdown (&plugin);
661     return NULL;
662   }
663   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
664   api->cls = &plugin;
665   api->store_record = &peerstore_sqlite_store_record;
666   api->iterate_records = &peerstore_sqlite_iterate_records;
667   api->expire_records = &peerstore_sqlite_expire_records;
668   LOG (GNUNET_ERROR_TYPE_DEBUG,
669        "Sqlite plugin is running\n");
670   return api;
671 }
672
673
674 /**
675  * Exit point from the plugin.
676  *
677  * @param cls The plugin context (as returned by "init")
678  * @return Always NULL
679  */
680 void *
681 libgnunet_plugin_peerstore_sqlite_done (void *cls)
682 {
683   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
684   struct Plugin *plugin = api->cls;
685
686   database_shutdown (plugin);
687   plugin->cfg = NULL;
688   GNUNET_free (api);
689   LOG (GNUNET_ERROR_TYPE_DEBUG,
690        "Sqlite plugin is finished\n");
691   return NULL;
692 }
693
694 /* end of plugin_peerstore_sqlite.c */