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