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