2726eef3d8a9dace771143c828fbd8f7cabbd85d
[oweals/gnunet.git] / src / peerstore / plugin_peerstore_sqlite.c
1 /*
2  * This file is part of GNUnet
3  * (C) 2013 Christian Grothoff (and other contributing authors)
4  *
5  * GNUnet is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published
7  * by the Free Software Foundation; either version 3, or (at your
8  * 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  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with GNUnet; see the file COPYING.  If not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file peerstore/plugin_peerstore_sqlite.c
23  * @brief sqlite-based peerstore backend
24  * @author Omar Tarabai
25  */
26
27 #include "platform.h"
28 #include "gnunet_peerstore_plugin.h"
29 #include "gnunet_peerstore_service.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  * 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
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
132   if((SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
133       || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC))
134       || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)))
135   {
136     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind");
137   }
138   else if (SQLITE_DONE != sqlite3_step (stmt))
139   {
140     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
141                 "sqlite3_step");
142   }
143   if (SQLITE_OK != sqlite3_reset (stmt))
144   {
145     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
146                 "sqlite3_reset");
147     return 0;
148   }
149   return sqlite3_changes(plugin->dbh);
150 }
151
152 /**
153  * Delete expired records (expiry < now)
154  *
155  * @param cls closure (internal context for the plugin)
156  * @param now time to use as reference
157  * @return number of records deleted
158  */
159 static int
160 peerstore_sqlite_expire_records(void *cls,
161     struct GNUNET_TIME_Absolute now)
162 {
163   struct Plugin *plugin = cls;
164   sqlite3_stmt *stmt = plugin->expire_peerstoredata;
165
166   if(SQLITE_OK != sqlite3_bind_int64(stmt, 1, (sqlite3_uint64)now.abs_value_us))
167   {
168     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind");
169   }
170   else if (SQLITE_DONE != sqlite3_step (stmt))
171   {
172     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
173                 "sqlite3_step");
174   }
175   if (SQLITE_OK != sqlite3_reset (stmt))
176   {
177     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
178                 "sqlite3_reset");
179     return 0;
180   }
181   return sqlite3_changes(plugin->dbh);
182
183 }
184
185 /**
186  * Iterate over the records given an optional peer id
187  * and/or key.
188  *
189  * @param cls closure (internal context for the plugin)
190  * @param sub_system name of sub system
191  * @param peer Peer identity (can be NULL)
192  * @param key entry key string (can be NULL)
193  * @param iter function to call with the result
194  * @param iter_cls closure for @a iter
195  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
196  */
197 static int
198 peerstore_sqlite_iterate_records (void *cls,
199     const char *sub_system,
200     const struct GNUNET_PeerIdentity *peer,
201     const char *key,
202     GNUNET_PEERSTORE_Processor iter, void *iter_cls)
203 {
204   struct Plugin *plugin = cls;
205   sqlite3_stmt *stmt;
206   int err = 0;
207   int sret;
208   struct GNUNET_PEERSTORE_Record *ret;
209
210   LOG(GNUNET_ERROR_TYPE_DEBUG, "Executing iterate request on sqlite db.\n");
211   if(NULL == peer && NULL == key)
212   {
213     stmt = plugin->select_peerstoredata;
214     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
215   }
216   else if(NULL == key)
217   {
218     stmt = plugin->select_peerstoredata_by_pid;
219     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
220         || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC));
221   }
222   else if(NULL == peer)
223   {
224     stmt = plugin->select_peerstoredata_by_key;
225     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
226         || (SQLITE_OK != sqlite3_bind_text(stmt, 2, key, strlen(key) + 1, SQLITE_STATIC));
227   }
228   else
229   {
230     stmt = plugin->select_peerstoredata_by_all;
231     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
232             || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC))
233             || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
234   }
235
236   if (err)
237   {
238     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
239     "sqlite3_bind_XXXX");
240     if (SQLITE_OK != sqlite3_reset (stmt))
241       LOG_SQLITE (plugin,
242       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
243       "sqlite3_reset");
244     return GNUNET_SYSERR;
245   }
246   while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
247   {
248     LOG(GNUNET_ERROR_TYPE_DEBUG, "Returning a matched record.\n");
249     ret = GNUNET_new(struct GNUNET_PEERSTORE_Record);
250     ret->sub_system = (char *)sqlite3_column_text(stmt, 0);
251     ret->peer = (struct GNUNET_PeerIdentity *)sqlite3_column_blob(stmt, 1);
252     ret->key = (char *)sqlite3_column_text(stmt, 2);
253     ret->value = (void *)sqlite3_column_blob(stmt, 3);
254     ret->value_size = sqlite3_column_bytes(stmt, 3);
255     ret->expiry = GNUNET_new(struct GNUNET_TIME_Absolute);
256     ret->expiry->abs_value_us = (uint64_t)sqlite3_column_int64(stmt, 4);
257     if (NULL != iter)
258       iter (iter_cls,
259           ret,
260           NULL);
261     GNUNET_free(ret->expiry);
262     GNUNET_free(ret);
263   }
264   if (SQLITE_DONE != sret)
265   {
266     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
267     err = 1;
268   }
269   if (SQLITE_OK != sqlite3_reset (stmt))
270   {
271     LOG_SQLITE (plugin,
272     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
273     "sqlite3_reset");
274     err = 1;
275   }
276   if(err)
277     return GNUNET_SYSERR;
278   return GNUNET_OK;
279 }
280
281 /**
282  * Store a record in the peerstore.
283  * Key is the combination of sub system and peer identity.
284  * One key can store multiple values.
285  *
286  * @param cls closure (internal context for the plugin)
287  * @param sub_system name of the GNUnet sub system responsible
288  * @param peer peer identity
289  * @param key record key string
290  * @param value value to be stored
291  * @param size size of value to be stored
292  * @param expiry absolute time after which the record is (possibly) deleted
293  * @param options options related to the store operation
294  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
295  */
296 static int
297 peerstore_sqlite_store_record (void *cls,
298                                const char *sub_system,
299                                const struct GNUNET_PeerIdentity *peer,
300                                const char *key,
301                                const void *value,
302                                size_t size,
303                                struct GNUNET_TIME_Absolute expiry,
304                                enum GNUNET_PEERSTORE_StoreOption options)
305 {
306   struct Plugin *plugin = cls;
307   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
308
309   if(GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
310   {
311     peerstore_sqlite_delete_records(cls, sub_system, peer, key);
312   }
313   if(SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
314       || SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
315       || SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)
316       || SQLITE_OK != sqlite3_bind_blob(stmt, 4, value, size, SQLITE_STATIC)
317       || SQLITE_OK != sqlite3_bind_int64(stmt, 5, (sqlite3_uint64)expiry.abs_value_us))
318     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
319                     "sqlite3_bind");
320   else if (SQLITE_DONE != sqlite3_step (stmt))
321   {
322     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
323                 "sqlite3_step");
324   }
325   if (SQLITE_OK != sqlite3_reset (stmt))
326   {
327     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
328                 "sqlite3_reset");
329     return GNUNET_SYSERR;
330   }
331
332   return GNUNET_OK;
333 }
334
335
336 /**
337  * @brief Prepare a SQL statement
338  *
339  * @param dbh handle to the database
340  * @param sql SQL statement, UTF-8 encoded
341  * @return 0 on success
342  */
343 static int
344 sql_exec (sqlite3 *dbh, const char *sql)
345 {
346   int result;
347
348   result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
349   LOG (GNUNET_ERROR_TYPE_DEBUG,
350        "Executed `%s' / %d\n", sql, result);
351   if (result != SQLITE_OK)
352     LOG (GNUNET_ERROR_TYPE_ERROR,
353    _("Error executing SQL query: %s\n  %s\n"),
354    sqlite3_errmsg (dbh), sql);
355   return result;
356 }
357
358 /**
359  * @brief Prepare a SQL statement
360  *
361  * @param dbh handle to the database
362  * @param sql SQL statement, UTF-8 encoded
363  * @param stmt set to the prepared statement
364  * @return 0 on success
365  */
366 static int
367 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
368 {
369   char *tail;
370   int result;
371
372   result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
373                                (const char **) &tail);
374   LOG (GNUNET_ERROR_TYPE_DEBUG,
375        "Prepared `%s' / %p: %d\n", sql, *stmt, result);
376   if (result != SQLITE_OK)
377     LOG (GNUNET_ERROR_TYPE_ERROR,
378    _("Error preparing SQL query: %s\n  %s\n"),
379    sqlite3_errmsg (dbh), sql);
380   return result;
381 }
382
383 /**
384  * sqlite3 custom function for comparison of uint64_t values
385  * since it is not supported by default
386  */
387 void sqlite3_lessthan(sqlite3_context* ctx, int dummy,
388     sqlite3_value** values)
389 {
390   uint64_t v1;
391   uint64_t v2;
392
393   v1 = (uint64_t)sqlite3_value_int64(values[0]);
394   v2 = (uint64_t)sqlite3_value_int64(values[1]);
395   sqlite3_result_int(ctx, v1 < v2);
396 }
397
398 /**
399  * Initialize the database connections and associated
400  * data structures (create tables and indices
401  * as needed as well).
402  *
403  * @param plugin the plugin context (state for this module)
404  * @return GNUNET_OK on success
405  */
406 static int
407 database_setup (struct Plugin *plugin)
408 {
409   char *filename;
410
411   if (GNUNET_OK !=
412       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
413                                                "FILENAME", &filename))
414   {
415     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
416              "peerstore-sqlite", "FILENAME");
417     return GNUNET_SYSERR;
418   }
419   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
420   {
421     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
422     {
423       GNUNET_break (0);
424       GNUNET_free (filename);
425       return GNUNET_SYSERR;
426     }
427   }
428   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
429   plugin->fn = filename;
430
431   /* Open database and precompile statements */
432   if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
433   {
434     LOG (GNUNET_ERROR_TYPE_ERROR,
435    _("Unable to initialize SQLite: %s.\n"),
436    sqlite3_errmsg (plugin->dbh));
437     return GNUNET_SYSERR;
438   }
439
440   sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
441   sql_exec (plugin->dbh, "PRAGMA synchronous=OFF");
442   sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
443   sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
444   sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
445   sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
446   sql_exec (plugin->dbh, "PRAGMA page_size=4096");
447
448   sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
449
450   /* Create tables */
451
452   sql_exec (plugin->dbh,
453       "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
454       "  sub_system TEXT NOT NULL,\n"
455       "  peer_id BLOB NOT NULL,\n"
456       "  key TEXT NOT NULL,\n"
457       "  value BLOB NULL,\n"
458       "  expiry sqlite3_uint64 NOT NULL"
459       ");");
460
461   sqlite3_create_function(plugin->dbh, "UINT64_LT", 2, SQLITE_UTF8, NULL, &sqlite3_lessthan, NULL, NULL);
462
463   /* Create Indices */
464   if (SQLITE_OK !=
465       sqlite3_exec(plugin->dbh,
466         "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
467         NULL, NULL, NULL))
468   {
469     LOG (GNUNET_ERROR_TYPE_ERROR,
470      _("Unable to create indices: %s.\n"),
471      sqlite3_errmsg (plugin->dbh));
472       return GNUNET_SYSERR;
473   }
474
475   /* Prepare statements */
476
477   sql_prepare (plugin->dbh,
478       "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry) VALUES (?,?,?,?,?);",
479       &plugin->insert_peerstoredata);
480   sql_prepare(plugin->dbh,
481       "SELECT * FROM peerstoredata"
482       " WHERE sub_system = ?",
483       &plugin->select_peerstoredata);
484   sql_prepare(plugin->dbh,
485       "SELECT * FROM peerstoredata"
486       " WHERE sub_system = ?"
487       " AND peer_id = ?",
488       &plugin->select_peerstoredata_by_pid);
489   sql_prepare(plugin->dbh,
490       "SELECT * FROM peerstoredata"
491       " WHERE sub_system = ?"
492       " AND key = ?",
493       &plugin->select_peerstoredata_by_key);
494   sql_prepare(plugin->dbh,
495       "SELECT * FROM peerstoredata"
496       " WHERE sub_system = ?"
497       " AND peer_id = ?"
498       " AND key = ?",
499       &plugin->select_peerstoredata_by_all);
500   sql_prepare(plugin->dbh,
501       "DELETE FROM peerstoredata"
502       " WHERE UINT64_LT(expiry, ?)",
503       &plugin->expire_peerstoredata);
504   sql_prepare(plugin->dbh,
505       "DELETE FROM peerstoredata"
506       " WHERE sub_system = ?"
507       " AND peer_id = ?"
508       " AND key = ?",
509       &plugin->delete_peerstoredata);
510
511   return GNUNET_OK;
512 }
513
514 /**
515  * Shutdown database connection and associate data
516  * structures.
517  * @param plugin the plugin context (state for this module)
518  */
519 static void
520 database_shutdown (struct Plugin *plugin)
521 {
522   int result;
523   sqlite3_stmt *stmt;
524   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
525   {
526     result = sqlite3_finalize (stmt);
527     if (SQLITE_OK != result)
528       LOG (GNUNET_ERROR_TYPE_WARNING,
529            "Failed to close statement %p: %d\n", stmt, result);
530   }
531   if (SQLITE_OK != sqlite3_close (plugin->dbh))
532     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
533
534   GNUNET_free_non_null (plugin->fn);
535 }
536
537 /**
538  * Entry point for the plugin.
539  *
540  * @param cls The struct GNUNET_CONFIGURATION_Handle.
541  * @return NULL on error, otherwise the plugin context
542  */
543 void *
544 libgnunet_plugin_peerstore_sqlite_init (void *cls)
545 {
546   static struct Plugin plugin;
547   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
548   struct GNUNET_PEERSTORE_PluginFunctions *api;
549
550   if (NULL != plugin.cfg)
551     return NULL;                /* can only initialize once! */
552   memset (&plugin, 0, sizeof (struct Plugin));
553   plugin.cfg = cfg;
554   if (GNUNET_OK != database_setup (&plugin))
555   {
556     database_shutdown (&plugin);
557     return NULL;
558   }
559   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
560   api->cls = &plugin;
561   api->store_record = &peerstore_sqlite_store_record;
562   api->iterate_records = &peerstore_sqlite_iterate_records;
563   api->expire_records = &peerstore_sqlite_expire_records;
564   LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
565   return api;
566 }
567
568 /**
569  * Exit point from the plugin.
570  *
571  * @param cls The plugin context (as returned by "init")
572  * @return Always NULL
573  */
574 void *
575 libgnunet_plugin_peerstore_sqlite_done (void *cls)
576 {
577   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
578   struct Plugin *plugin = api->cls;
579
580   database_shutdown (plugin);
581   plugin->cfg = NULL;
582   GNUNET_free (api);
583   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
584   return NULL;
585
586 }
587
588 /* end of plugin_peerstore_sqlite.c */