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