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