7a19ba82714b98e9b53a6916f378b7a9739a0d2e
[oweals/gnunet.git] / src / identity-provider / plugin_identity_provider_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * Copyright (C) 2009-2017 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18   * Boston, MA 02110-1301, USA.
19   */
20
21 /**
22  * @file identity-provider/plugin_identity_provider_sqlite.c
23  * @brief sqlite-based idp backend
24  * @author Martin Schanzenbach
25  */
26
27 #include "platform.h"
28 #include "gnunet_identity_provider_service.h"
29 #include "gnunet_identity_provider_plugin.h"
30 #include "gnunet_sq_lib.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 /**
47  * Log an error message at log-level 'level' that indicates
48  * a failure of the command 'cmd' on file 'filename'
49  * with the message given by strerror(errno).
50  */
51 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "identity-provider", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
52
53 #define LOG(kind,...) GNUNET_log_from (kind, "identity-provider-sqlite", __VA_ARGS__)
54
55
56 /**
57  * Context for all functions in this plugin.
58  */
59 struct Plugin
60 {
61
62   const struct GNUNET_CONFIGURATION_Handle *cfg;
63
64   /**
65    * Database filename.
66    */
67   char *fn;
68
69   /**
70    * Native SQLite database handle.
71    */
72   sqlite3 *dbh;
73
74   /**
75    * Precompiled SQL to store ticket.
76    */
77   sqlite3_stmt *store_ticket;
78
79   /**
80    * Precompiled SQL to delete existing ticket.
81    */
82   sqlite3_stmt *delete_ticket;
83
84   /**
85    * Precompiled SQL to iterate tickets.
86    */
87   sqlite3_stmt *iterate_tickets;
88
89   /**
90    * Precompiled SQL to iterate tickets by audience.
91    */
92   sqlite3_stmt *iterate_tickets_by_audience;
93 };
94
95
96 /**
97  * @brief Prepare a SQL statement
98  *
99  * @param dbh handle to the database
100  * @param zSql SQL statement, UTF-8 encoded
101  * @param ppStmt set to the prepared statement
102  * @return 0 on success
103  */
104 static int
105 sq_prepare (sqlite3 *dbh,
106             const char *zSql,
107             sqlite3_stmt **ppStmt)
108 {
109   char *dummy;
110   int result;
111
112   result =
113       sqlite3_prepare_v2 (dbh,
114                           zSql,
115                           strlen (zSql),
116                           ppStmt,
117                           (const char **) &dummy);
118   LOG (GNUNET_ERROR_TYPE_DEBUG,
119        "Prepared `%s' / %p: %d\n",
120        zSql,
121        *ppStmt,
122        result);
123   return result;
124 }
125
126 /**
127  * Create our database indices.
128  *
129  * @param dbh handle to the database
130  */
131 static void
132 create_indices (sqlite3 * dbh)
133 {
134   /* create indices */
135   if ( (SQLITE_OK !=
136         sqlite3_exec (dbh,
137                       "CREATE INDEX IF NOT EXISTS identity_reverse ON identity001tickets (identity,audience)",
138                       NULL, NULL, NULL)) ||
139        (SQLITE_OK !=
140         sqlite3_exec (dbh,
141                       "CREATE INDEX IF NOT EXISTS it_iter ON identity001tickets (rnd)",
142                       NULL, NULL, NULL)) )
143     LOG (GNUNET_ERROR_TYPE_ERROR,
144          "Failed to create indices: %s\n",
145          sqlite3_errmsg (dbh));
146 }
147
148
149
150 #if 0
151 #define CHECK(a) GNUNET_break(a)
152 #define ENULL NULL
153 #else
154 #define ENULL &e
155 #define ENULL_DEFINED 1
156 #define CHECK(a) if (! (a)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
157 #endif
158
159
160 /**
161  * Initialize the database connections and associated
162  * data structures (create tables and indices
163  * as needed as well).
164  *
165  * @param plugin the plugin context (state for this module)
166  * @return #GNUNET_OK on success
167  */
168 static int
169 database_setup (struct Plugin *plugin)
170 {
171   sqlite3_stmt *stmt;
172   char *afsdir;
173 #if ENULL_DEFINED
174   char *e;
175 #endif
176
177   if (GNUNET_OK !=
178       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
179                                                "identity-provider-sqlite",
180                                                "FILENAME",
181                                                &afsdir))
182   {
183     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
184                                "identity-provider-sqlite",
185                                "FILENAME");
186     return GNUNET_SYSERR;
187   }
188   if (GNUNET_OK !=
189       GNUNET_DISK_file_test (afsdir))
190   {
191     if (GNUNET_OK !=
192         GNUNET_DISK_directory_create_for_file (afsdir))
193     {
194       GNUNET_break (0);
195       GNUNET_free (afsdir);
196       return GNUNET_SYSERR;
197     }
198   }
199   /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
200   plugin->fn = afsdir;
201
202   /* Open database and precompile statements */
203   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
204   {
205     LOG (GNUNET_ERROR_TYPE_ERROR,
206          _("Unable to initialize SQLite: %s.\n"),
207          sqlite3_errmsg (plugin->dbh));
208     return GNUNET_SYSERR;
209   }
210   CHECK (SQLITE_OK ==
211          sqlite3_exec (plugin->dbh,
212                        "PRAGMA temp_store=MEMORY", NULL, NULL,
213                        ENULL));
214   CHECK (SQLITE_OK ==
215          sqlite3_exec (plugin->dbh,
216                        "PRAGMA synchronous=NORMAL", NULL, NULL,
217                        ENULL));
218   CHECK (SQLITE_OK ==
219          sqlite3_exec (plugin->dbh,
220                        "PRAGMA legacy_file_format=OFF", NULL, NULL,
221                        ENULL));
222   CHECK (SQLITE_OK ==
223          sqlite3_exec (plugin->dbh,
224                        "PRAGMA auto_vacuum=INCREMENTAL", NULL,
225                        NULL, ENULL));
226   CHECK (SQLITE_OK ==
227          sqlite3_exec (plugin->dbh,
228                        "PRAGMA encoding=\"UTF-8\"", NULL,
229                        NULL, ENULL));
230   CHECK (SQLITE_OK ==
231          sqlite3_exec (plugin->dbh,
232                        "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
233                        ENULL));
234   CHECK (SQLITE_OK ==
235          sqlite3_exec (plugin->dbh,
236                        "PRAGMA page_size=4092", NULL, NULL,
237                        ENULL));
238
239   CHECK (SQLITE_OK ==
240          sqlite3_busy_timeout (plugin->dbh,
241                                BUSY_TIMEOUT_MS));
242
243
244   /* Create table */
245   CHECK (SQLITE_OK ==
246          sq_prepare (plugin->dbh,
247                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'identity001tickets'",
248                      &stmt));
249   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
250       (sqlite3_exec
251        (plugin->dbh,
252         "CREATE TABLE identity001tickets ("
253         " identity BLOB NOT NULL DEFAULT '',"
254         " audience BLOB NOT NULL DEFAULT '',"
255               " rnd INT8 NOT NULL DEFAULT ''"
256         ")",
257         NULL, NULL, NULL) != SQLITE_OK))
258   {
259     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR,
260                 "sqlite3_exec");
261     sqlite3_finalize (stmt);
262     return GNUNET_SYSERR;
263   }
264   sqlite3_finalize (stmt);
265
266   create_indices (plugin->dbh);
267
268   if ( (SQLITE_OK !=
269         sq_prepare (plugin->dbh,
270                     "INSERT INTO identity001tickets (identity, audience, rnd)"
271                     " VALUES (?, ?, ?)",
272                     &plugin->store_ticket)) ||
273        (SQLITE_OK !=
274         sq_prepare (plugin->dbh,
275                     "DELETE FROM identity001tickets WHERE identity=? AND rnd=?",
276                     &plugin->delete_ticket)) ||
277        (SQLITE_OK !=
278         sq_prepare (plugin->dbh,
279                     "SELECT identity,audience,rnd"
280                     " FROM identity001tickets WHERE identity=?"
281                     " ORDER BY rnd LIMIT 1 OFFSET ?",
282                     &plugin->iterate_tickets)) ||
283        (SQLITE_OK !=
284         sq_prepare (plugin->dbh,
285                     "SELECT identity,audience,rnd"
286                     " FROM identity001tickets WHERE audience=?"
287                     " ORDER BY rnd LIMIT 1 OFFSET ?",
288                     &plugin->iterate_tickets_by_audience)) ) 
289   {
290     LOG_SQLITE (plugin,
291                 GNUNET_ERROR_TYPE_ERROR,
292                 "precompiling");
293     return GNUNET_SYSERR;
294   }
295   return GNUNET_OK;
296 }
297
298
299 /**
300  * Shutdown database connection and associate data
301  * structures.
302  * @param plugin the plugin context (state for this module)
303  */
304 static void
305 database_shutdown (struct Plugin *plugin)
306 {
307   int result;
308   sqlite3_stmt *stmt;
309
310   if (NULL != plugin->store_ticket)
311     sqlite3_finalize (plugin->store_ticket);
312   if (NULL != plugin->delete_ticket)
313     sqlite3_finalize (plugin->delete_ticket);
314   if (NULL != plugin->iterate_tickets)
315     sqlite3_finalize (plugin->iterate_tickets);
316   if (NULL != plugin->iterate_tickets_by_audience)
317     sqlite3_finalize (plugin->iterate_tickets_by_audience);
318   result = sqlite3_close (plugin->dbh);
319   if (result == SQLITE_BUSY)
320   {
321     LOG (GNUNET_ERROR_TYPE_WARNING,
322          _("Tried to close sqlite without finalizing all prepared statements.\n"));
323     stmt = sqlite3_next_stmt (plugin->dbh,
324                               NULL);
325     while (NULL != stmt)
326     {
327       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
328                        "sqlite",
329                        "Closing statement %p\n",
330                        stmt);
331       result = sqlite3_finalize (stmt);
332       if (result != SQLITE_OK)
333         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
334                          "sqlite",
335                          "Failed to close statement %p: %d\n",
336                          stmt,
337                          result);
338       stmt = sqlite3_next_stmt (plugin->dbh,
339                                 NULL);
340     }
341     result = sqlite3_close (plugin->dbh);
342   }
343   if (SQLITE_OK != result)
344     LOG_SQLITE (plugin,
345                 GNUNET_ERROR_TYPE_ERROR,
346                 "sqlite3_close");
347
348   GNUNET_free_non_null (plugin->fn);
349 }
350
351
352 /**
353  * Store a ticket in the database.
354  *
355  * @param cls closure (internal context for the plugin)
356  * @param ticket the ticket to persist
357  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
358  */
359 static int
360 identity_provider_sqlite_store_ticket (void *cls,
361                                         const struct GNUNET_IDENTITY_PROVIDER_Ticket2 *ticket)
362 {
363   struct Plugin *plugin = cls;
364   int n;
365
366   { 
367     /* First delete duplicates */
368     struct GNUNET_SQ_QueryParam dparams[] = {
369       GNUNET_SQ_query_param_auto_from_type (&ticket->identity),
370       GNUNET_SQ_query_param_uint64 (&ticket->rnd),
371       GNUNET_SQ_query_param_end
372     };
373     if (GNUNET_OK !=
374         GNUNET_SQ_bind (plugin->delete_ticket,
375                         dparams))
376     {
377       LOG_SQLITE (plugin,
378                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
379                   "sqlite3_bind_XXXX");
380       GNUNET_SQ_reset (plugin->dbh,
381                        plugin->delete_ticket);
382       return GNUNET_SYSERR;
383     }
384     n = sqlite3_step (plugin->delete_ticket);
385     GNUNET_SQ_reset (plugin->dbh,
386                      plugin->delete_ticket);
387
388     struct GNUNET_SQ_QueryParam sparams[] = {
389       GNUNET_SQ_query_param_auto_from_type (&ticket->identity),
390       GNUNET_SQ_query_param_auto_from_type (&ticket->audience),
391       GNUNET_SQ_query_param_uint64 (&ticket->rnd),
392       GNUNET_SQ_query_param_end
393     };
394
395     if (GNUNET_OK !=
396         GNUNET_SQ_bind (plugin->store_ticket,
397                         sparams))
398     {
399       LOG_SQLITE (plugin,
400                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
401                   "sqlite3_bind_XXXX");
402       GNUNET_SQ_reset (plugin->dbh,
403                        plugin->store_ticket);
404       return GNUNET_SYSERR;
405     }
406     n = sqlite3_step (plugin->store_ticket);
407     GNUNET_SQ_reset (plugin->dbh,
408                      plugin->store_ticket);
409   }
410   switch (n)
411   {
412     case SQLITE_DONE:
413       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
414                        "sqlite",
415                        "Ticket stored\n");
416       return GNUNET_OK;
417     case SQLITE_BUSY:
418       LOG_SQLITE (plugin,
419                   GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
420                   "sqlite3_step");
421       return GNUNET_NO;
422     default:
423       LOG_SQLITE (plugin,
424                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
425                   "sqlite3_step");
426       return GNUNET_SYSERR;
427   }
428 }
429
430
431 /**
432  * Store a ticket in the database.
433  *
434  * @param cls closure (internal context for the plugin)
435  * @param ticket the ticket to delete
436  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
437  */
438 static int
439 identity_provider_sqlite_delete_ticket (void *cls,
440                                         const struct GNUNET_IDENTITY_PROVIDER_Ticket2 *ticket)
441 {
442   struct Plugin *plugin = cls;
443   int n;
444
445   {  
446     struct GNUNET_SQ_QueryParam sparams[] = {
447       GNUNET_SQ_query_param_auto_from_type (&ticket->identity),
448       GNUNET_SQ_query_param_uint64 (&ticket->rnd),
449       GNUNET_SQ_query_param_end
450     };
451
452     if (GNUNET_OK !=
453         GNUNET_SQ_bind (plugin->delete_ticket,
454                         sparams))
455     {
456       LOG_SQLITE (plugin,
457                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
458                   "sqlite3_bind_XXXX");
459       GNUNET_SQ_reset (plugin->dbh,
460                        plugin->store_ticket);
461       return GNUNET_SYSERR;
462     }
463     n = sqlite3_step (plugin->delete_ticket);
464     GNUNET_SQ_reset (plugin->dbh,
465                      plugin->delete_ticket);
466   }
467   switch (n)
468   {
469     case SQLITE_DONE:
470       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
471                        "sqlite",
472                        "Ticket deleted\n");
473       return GNUNET_OK;
474     case SQLITE_BUSY:
475       LOG_SQLITE (plugin,
476                   GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
477                   "sqlite3_step");
478       return GNUNET_NO;
479     default:
480       LOG_SQLITE (plugin,
481                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
482                   "sqlite3_step");
483       return GNUNET_SYSERR;
484   }
485 }
486
487
488 /**
489  * The given 'sqlite' statement has been prepared to be run.
490  * It will return a record which should be given to the iterator.
491  * Runs the statement and parses the returned record.
492  *
493  * @param plugin plugin context
494  * @param stmt to run (and then clean up)
495  * @param iter iterator to call with the result
496  * @param iter_cls closure for @a iter
497  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
498  */
499 static int
500 get_ticket_and_call_iterator (struct Plugin *plugin,
501                               sqlite3_stmt *stmt,
502                               GNUNET_IDENTITY_PROVIDER_TicketIterator iter,
503                               void *iter_cls)
504 {
505   struct GNUNET_IDENTITY_PROVIDER_Ticket2 ticket;
506   int ret;
507   int sret;
508
509   ret = GNUNET_NO;
510   if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
511   {
512     struct GNUNET_SQ_ResultSpec rs[] = {
513       GNUNET_SQ_result_spec_auto_from_type (&ticket.identity),
514       GNUNET_SQ_result_spec_auto_from_type (&ticket.audience),
515       GNUNET_SQ_result_spec_uint64 (&ticket.rnd),
516       GNUNET_SQ_result_spec_end
517
518     };
519     ret = GNUNET_SQ_extract_result (stmt,
520                                     rs);
521     if (GNUNET_OK != ret)
522     {
523       GNUNET_break (0);
524       ret = GNUNET_SYSERR;
525     }
526     else
527     {
528         if (NULL != iter)
529           iter (iter_cls,
530                 &ticket);
531         ret = GNUNET_YES;
532     }
533     GNUNET_SQ_cleanup_result (rs);
534   }
535   else
536   {
537     if (SQLITE_DONE != sret)
538       LOG_SQLITE (plugin,
539                   GNUNET_ERROR_TYPE_ERROR,
540                   "sqlite_step");
541   }
542   GNUNET_SQ_reset (plugin->dbh,
543                    stmt);
544   return ret;
545 }
546
547 /**
548  * Iterate over the results for a particular key and zone in the
549  * datastore.  Will return at most one result to the iterator.
550  *
551  * @param cls closure (internal context for the plugin)
552  * @param identity the issuing identity or audience (depending on audience switch)
553  * @param audience GNUNET_YES if identity is audience
554  * @param offset offset in the list of all matching records
555  * @param iter function to call with the result
556  * @param iter_cls closure for @a iter
557  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
558  */
559 static int
560 identity_provider_sqlite_iterate_tickets (void *cls,
561                                           const struct GNUNET_CRYPTO_EcdsaPublicKey *identity,
562                                           int audience,
563                                           uint64_t offset,
564                                           GNUNET_IDENTITY_PROVIDER_TicketIterator iter,
565                                           void *iter_cls)
566 {
567   struct Plugin *plugin = cls;
568   sqlite3_stmt *stmt;
569   int err;
570
571   if (NULL == identity)
572   {
573     GNUNET_break (0);
574     return GNUNET_SYSERR;
575   }
576   struct GNUNET_SQ_QueryParam params[] = {
577     GNUNET_SQ_query_param_auto_from_type (identity),
578     GNUNET_SQ_query_param_uint64 (&offset),
579     GNUNET_SQ_query_param_end
580   };
581   if (GNUNET_YES == audience)
582   {
583     stmt = plugin->iterate_tickets_by_audience;
584     err = GNUNET_SQ_bind (stmt,
585                           params);
586   }
587   else
588   {
589     stmt = plugin->iterate_tickets;
590     err = GNUNET_SQ_bind (stmt,
591                           params);
592   }
593   if (GNUNET_OK != err)
594   {
595     LOG_SQLITE (plugin,
596                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
597                 "sqlite3_bind_XXXX");
598     GNUNET_SQ_reset (plugin->dbh,
599                      stmt);
600     return GNUNET_SYSERR;
601   }
602   return get_ticket_and_call_iterator (plugin,
603                                        stmt,
604                                        iter,
605                                        iter_cls);
606 }
607
608
609 /**
610  * Entry point for the plugin.
611  *
612  * @param cls the "struct GNUNET_IDENTITY_PROVIDER_PluginEnvironment*"
613  * @return NULL on error, otherwise the plugin context
614  */
615 void *
616 libgnunet_plugin_identity_provider_sqlite_init (void *cls)
617 {
618   static struct Plugin plugin;
619   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
620   struct GNUNET_IDENTITY_PROVIDER_PluginFunctions *api;
621
622   if (NULL != plugin.cfg)
623     return NULL;                /* can only initialize once! */
624   memset (&plugin, 0, sizeof (struct Plugin));
625   plugin.cfg = cfg;
626   if (GNUNET_OK != database_setup (&plugin))
627   {
628     database_shutdown (&plugin);
629     return NULL;
630   }
631   api = GNUNET_new (struct GNUNET_IDENTITY_PROVIDER_PluginFunctions);
632   api->cls = &plugin;
633   api->store_ticket = &identity_provider_sqlite_store_ticket;
634   api->delete_ticket = &identity_provider_sqlite_delete_ticket;
635   api->iterate_tickets = &identity_provider_sqlite_iterate_tickets;
636   LOG (GNUNET_ERROR_TYPE_INFO,
637        _("Sqlite database running\n"));
638   return api;
639 }
640
641
642 /**
643  * Exit point from the plugin.
644  *
645  * @param cls the plugin context (as returned by "init")
646  * @return always NULL
647  */
648 void *
649 libgnunet_plugin_identity_provider_sqlite_done (void *cls)
650 {
651   struct GNUNET_IDENTITY_PROVIDER_PluginFunctions *api = cls;
652   struct Plugin *plugin = api->cls;
653
654   database_shutdown (plugin);
655   plugin->cfg = NULL;
656   GNUNET_free (api);
657   LOG (GNUNET_ERROR_TYPE_DEBUG,
658        "sqlite plugin is finished\n");
659   return NULL;
660 }
661
662 /* end of plugin_identity_provider_sqlite.c */