-copied block-related functions from namestore to namecache
[oweals/gnunet.git] / src / namecache / plugin_namecache_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * (C) 2009-2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18   * Boston, MA 02111-1307, 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 count_changes=OFF", NULL, NULL,
217                        ENULL));
218   CHECK (SQLITE_OK ==
219          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
220                        ENULL));
221
222   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
223
224
225   /* Create tables */
226   CHECK (SQLITE_OK ==
227          sq_prepare (plugin->dbh,
228                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
229                      &stmt));
230   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
231       (sqlite3_exec
232        (plugin->dbh,
233         "CREATE TABLE ns096blocks ("
234         " query BLOB NOT NULL DEFAULT '',"
235         " block BLOB NOT NULL DEFAULT '',"
236         " expiration_time INT8 NOT NULL DEFAULT 0"
237         ")",
238         NULL, NULL, NULL) != SQLITE_OK))
239   {
240     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
241     sqlite3_finalize (stmt);
242     return GNUNET_SYSERR;
243   }
244   sqlite3_finalize (stmt);
245   create_indices (plugin->dbh);
246
247   if ((sq_prepare
248        (plugin->dbh,
249         "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
250         &plugin->cache_block) != SQLITE_OK) ||
251       (sq_prepare
252        (plugin->dbh,
253         "DELETE FROM ns096blocks WHERE expiration_time<?",
254         &plugin->expire_blocks) != SQLITE_OK) ||
255       (sq_prepare
256        (plugin->dbh,
257         "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
258         &plugin->delete_block) != SQLITE_OK) ||
259       (sq_prepare
260        (plugin->dbh,
261         "SELECT block FROM ns096blocks WHERE query=? ORDER BY expiration_time DESC LIMIT 1",
262         &plugin->lookup_block) != SQLITE_OK)
263       )
264   {
265     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
266     return GNUNET_SYSERR;
267   }
268   return GNUNET_OK;
269 }
270
271
272 /**
273  * Shutdown database connection and associate data
274  * structures.
275  * @param plugin the plugin context (state for this module)
276  */
277 static void
278 database_shutdown (struct Plugin *plugin)
279 {
280   int result;
281   sqlite3_stmt *stmt;
282
283   if (NULL != plugin->cache_block)
284     sqlite3_finalize (plugin->cache_block);
285   if (NULL != plugin->lookup_block)
286     sqlite3_finalize (plugin->lookup_block);
287   if (NULL != plugin->expire_blocks)
288     sqlite3_finalize (plugin->expire_blocks);
289   if (NULL != plugin->delete_block)
290     sqlite3_finalize (plugin->delete_block);
291   result = sqlite3_close (plugin->dbh);
292   if (result == SQLITE_BUSY)
293   {
294     LOG (GNUNET_ERROR_TYPE_WARNING,
295          _("Tried to close sqlite without finalizing all prepared statements.\n"));
296     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
297     while (stmt != NULL)
298     {
299       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
300                        "Closing statement %p\n", stmt);
301       result = sqlite3_finalize (stmt);
302       if (result != SQLITE_OK)
303         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
304                          "Failed to close statement %p: %d\n", stmt, result);
305       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
306     }
307     result = sqlite3_close (plugin->dbh);
308   }
309   if (SQLITE_OK != result)
310     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
311
312   GNUNET_free_non_null (plugin->fn);
313 }
314
315
316 /**
317  * Removes any expired block.
318  *
319  * @param plugin the plugin
320  */
321 static void
322 namecache_sqlite_expire_blocks (struct Plugin *plugin)
323 {
324   struct GNUNET_TIME_Absolute now;
325   int n;
326
327   now = GNUNET_TIME_absolute_get ();
328   if (SQLITE_OK != sqlite3_bind_int64 (plugin->expire_blocks,
329                                        1, now.abs_value_us))
330   {
331     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
332                 "sqlite3_bind_XXXX");
333     if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
334       LOG_SQLITE (plugin,
335                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
336                   "sqlite3_reset");
337     return;
338   }
339   n = sqlite3_step (plugin->expire_blocks);
340   if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
341     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
342                 "sqlite3_reset");
343   switch (n)
344   {
345   case SQLITE_DONE:
346     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Records expired\n");
347     return;
348   case SQLITE_BUSY:
349     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
350                 "sqlite3_step");
351     return;
352   default:
353     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
354                 "sqlite3_step");
355     return;
356   }
357 }
358
359
360 /**
361  * Cache a block in the datastore.
362  *
363  * @param cls closure (internal context for the plugin)
364  * @param block block to cache
365  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
366  */
367 static int
368 namecache_sqlite_cache_block (void *cls,
369                               const struct GNUNET_NAMESTORE_Block *block)
370 {
371   struct Plugin *plugin = cls;
372   struct GNUNET_HashCode query;
373   struct GNUNET_TIME_Absolute expiration;
374   int64_t dval;
375   size_t block_size;
376   int n;
377
378   namecache_sqlite_expire_blocks (plugin);
379   GNUNET_CRYPTO_hash (&block->derived_key,
380                       sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
381                       &query);
382   expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
383   dval = (int64_t) expiration.abs_value_us;
384   if (dval < 0)
385     dval = INT64_MAX;
386   block_size = ntohl (block->purpose.size) +
387     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
388     sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
389   if (block_size > 64 * 65536)
390   {
391     GNUNET_break (0);
392     return GNUNET_SYSERR;
393   }
394
395   /* delete old version of the block */
396   if ( (SQLITE_OK !=
397         sqlite3_bind_blob (plugin->delete_block, 1,
398                            &query, sizeof (struct GNUNET_HashCode),
399                            SQLITE_STATIC)) ||
400        (SQLITE_OK !=
401         sqlite3_bind_int64 (plugin->delete_block,
402                             2, dval)) )
403   {
404     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
405                 "sqlite3_bind_XXXX");
406     if (SQLITE_OK != sqlite3_reset (plugin->delete_block))
407       LOG_SQLITE (plugin,
408                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
409                   "sqlite3_reset");
410     return GNUNET_SYSERR;
411   }
412   n = sqlite3_step (plugin->delete_block);
413   switch (n)
414   {
415   case SQLITE_DONE:
416     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Old block deleted\n");
417     break;
418   case SQLITE_BUSY:
419     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
420                 "sqlite3_step");
421     break;
422   default:
423     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
424                 "sqlite3_step");
425     break;
426   }
427   if (SQLITE_OK != sqlite3_reset (plugin->delete_block))
428     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
429                 "sqlite3_reset");
430
431   /* insert new version of the block */
432   if ((SQLITE_OK !=
433        sqlite3_bind_blob (plugin->cache_block, 1,
434                           &query, sizeof (struct GNUNET_HashCode),
435                           SQLITE_STATIC)) ||
436       (SQLITE_OK !=
437        sqlite3_bind_blob (plugin->cache_block, 2,
438                           block, block_size,
439                           SQLITE_STATIC)) ||
440       (SQLITE_OK !=
441        sqlite3_bind_int64 (plugin->cache_block, 3,
442                            dval)))
443   {
444     LOG_SQLITE (plugin,
445                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
446                 "sqlite3_bind_XXXX");
447     if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
448       LOG_SQLITE (plugin,
449                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
450                   "sqlite3_reset");
451     return GNUNET_SYSERR;
452
453   }
454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
455               "Caching block under derived key `%s'\n",
456               GNUNET_h2s_full (&query));
457   n = sqlite3_step (plugin->cache_block);
458   if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
459     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
460                 "sqlite3_reset");
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, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
469                 "sqlite3_step");
470     return GNUNET_NO;
471   default:
472     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
473                 "sqlite3_step");
474     return GNUNET_SYSERR;
475   }
476 }
477
478
479 /**
480  * Get the block for a particular zone and label in the
481  * datastore.  Will return at most one result to the iterator.
482  *
483  * @param cls closure (internal context for the plugin)
484  * @param query hash of public key derived from the zone and the label
485  * @param iter function to call with the result
486  * @param iter_cls closure for @a iter
487  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
488  */
489 static int
490 namecache_sqlite_lookup_block (void *cls,
491                                const struct GNUNET_HashCode *query,
492                                GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls)
493 {
494   struct Plugin *plugin = cls;
495   int ret;
496   int sret;
497   size_t block_size;
498   const struct GNUNET_NAMESTORE_Block *block;
499
500   if (SQLITE_OK != sqlite3_bind_blob (plugin->lookup_block, 1,
501                                       query, sizeof (struct GNUNET_HashCode),
502                                       SQLITE_STATIC))
503   {
504     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
505                 "sqlite3_bind_XXXX");
506     if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
507       LOG_SQLITE (plugin,
508                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
509                   "sqlite3_reset");
510     return GNUNET_SYSERR;
511   }
512   ret = GNUNET_NO;
513   if (SQLITE_ROW == (sret = sqlite3_step (plugin->lookup_block)))
514   {
515     block = sqlite3_column_blob (plugin->lookup_block, 0);
516     block_size = sqlite3_column_bytes (plugin->lookup_block, 0);
517     if ( (block_size < sizeof (struct GNUNET_NAMESTORE_Block)) ||
518          (ntohl (block->purpose.size) +
519           sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
520           sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) )
521     {
522       GNUNET_break (0);
523       ret = GNUNET_SYSERR;
524     }
525     else
526     {
527       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528                   "Found block under derived key `%s'\n",
529                   GNUNET_h2s_full (query));
530       iter (iter_cls, block);
531       ret = GNUNET_YES;
532     }
533   }
534   else
535   {
536     if (SQLITE_DONE != sret)
537     {
538       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
539       ret = GNUNET_SYSERR;
540     }
541     else
542     {
543       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
544                   "No block found under derived key `%s'\n",
545                   GNUNET_h2s_full (query));
546     }
547   }
548   if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
549     LOG_SQLITE (plugin,
550                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
551                 "sqlite3_reset");
552   return ret;
553 }
554
555
556 /**
557  * Entry point for the plugin.
558  *
559  * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
560  * @return NULL on error, otherwise the plugin context
561  */
562 void *
563 libgnunet_plugin_namecache_sqlite_init (void *cls)
564 {
565   static struct Plugin plugin;
566   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
567   struct GNUNET_NAMECACHE_PluginFunctions *api;
568
569   if (NULL != plugin.cfg)
570     return NULL;                /* can only initialize once! */
571   memset (&plugin, 0, sizeof (struct Plugin));
572   plugin.cfg = cfg;
573   if (GNUNET_OK != database_setup (&plugin))
574   {
575     database_shutdown (&plugin);
576     return NULL;
577   }
578   api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
579   api->cls = &plugin;
580   api->cache_block = &namecache_sqlite_cache_block;
581   api->lookup_block = &namecache_sqlite_lookup_block;
582   LOG (GNUNET_ERROR_TYPE_INFO,
583        _("Sqlite database running\n"));
584   return api;
585 }
586
587
588 /**
589  * Exit point from the plugin.
590  *
591  * @param cls the plugin context (as returned by "init")
592  * @return always NULL
593  */
594 void *
595 libgnunet_plugin_namecache_sqlite_done (void *cls)
596 {
597   struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
598   struct Plugin *plugin = api->cls;
599
600   database_shutdown (plugin);
601   plugin->cfg = NULL;
602   GNUNET_free (api);
603   LOG (GNUNET_ERROR_TYPE_DEBUG,
604        "sqlite plugin is finished\n");
605   return NULL;
606 }
607
608 /* end of plugin_namecache_sqlite.c */