90b33d8779aab12a1ce3846e3803a23df148bb36
[oweals/gnunet.git] / src / datacache / plugin_datacache_sqlite.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2006, 2009, 2015 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 datacache/plugin_datacache_sqlite.c
23  * @brief sqlite for an implementation of a database backend for the datacache
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_datacache_plugin.h"
29 #include <sqlite3.h>
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "datacache-sqlite", __VA_ARGS__)
32
33 #define LOG_STRERROR_FILE(kind,op,fn) GNUNET_log_from_strerror_file (kind, "datacache-sqlite", op, fn)
34
35
36 /**
37  * How much overhead do we assume per entry in the
38  * datacache?
39  */
40 #define OVERHEAD (sizeof(struct GNUNET_HashCode) + 32)
41
42 /**
43  * Context for all functions in this plugin.
44  */
45 struct Plugin
46 {
47   /**
48    * Our execution environment.
49    */
50   struct GNUNET_DATACACHE_PluginEnvironment *env;
51
52   /**
53    * Handle to the sqlite database.
54    */
55   sqlite3 *dbh;
56
57   /**
58    * Filename used for the DB.
59    */
60   char *fn;
61
62   /**
63    * Number of key-value pairs in the database.
64    */
65   unsigned int num_items;
66 };
67
68
69 /**
70  * Log an error message at log-level 'level' that indicates
71  * a failure of the command 'cmd' on file 'filename'
72  * with the message given by strerror(errno).
73  */
74 #define LOG_SQLITE(db, level, cmd) do { LOG (level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db)); } while(0)
75
76
77 #define SQLITE3_EXEC(db, cmd) do { emsg = NULL; if (SQLITE_OK != sqlite3_exec(db, cmd, NULL, NULL, &emsg)) { LOG (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_exec", __FILE__, __LINE__, emsg); sqlite3_free(emsg); } } while(0)
78
79
80 /**
81  * @brief Prepare a SQL statement
82  */
83 static int
84 sq_prepare (sqlite3 * dbh, const char *zSql,    /* SQL statement, UTF-8 encoded */
85             sqlite3_stmt ** ppStmt)
86 {                               /* OUT: Statement handle */
87   char *dummy;
88
89   return sqlite3_prepare (dbh, zSql, strlen (zSql), ppStmt,
90                           (const char **) &dummy);
91 }
92
93
94 /**
95  * Store an item in the datastore.
96  *
97  * @param cls closure (our "struct Plugin")
98  * @param key key to store data under
99  * @param size number of bytes in data
100  * @param data data to store
101  * @param type type of the value
102  * @param discard_time when to discard the value in any case
103  * @param path_info_len number of entries in @a path_info
104  * @param path_info array of peers that have processed the request
105  * @return 0 if duplicate, -1 on error, number of bytes used otherwise
106  */
107 static ssize_t
108 sqlite_plugin_put (void *cls,
109                    const struct GNUNET_HashCode *key,
110                    size_t size, const char *data,
111                    enum GNUNET_BLOCK_Type type,
112                    struct GNUNET_TIME_Absolute discard_time,
113                    unsigned int path_info_len,
114                    const struct GNUNET_PeerIdentity *path_info)
115 {
116   struct Plugin *plugin = cls;
117   sqlite3_stmt *stmt;
118   int64_t dval;
119
120   LOG (GNUNET_ERROR_TYPE_DEBUG,
121        "Processing `%s' of %u bytes with key `%4s' and expiration %s\n",
122        "PUT", (unsigned int) size, GNUNET_h2s (key),
123        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (discard_time), GNUNET_YES));
124   dval = (int64_t) discard_time.abs_value_us;
125   if (dval < 0)
126     dval = INT64_MAX;
127   if (sq_prepare
128       (plugin->dbh,
129        "INSERT INTO ds090 (type, expire, key, value, path) VALUES (?, ?, ?, ?, ?)",
130        &stmt) != SQLITE_OK)
131   {
132     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
133                 "sq_prepare");
134     return -1;
135   }
136   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
137       (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, dval)) ||
138       (SQLITE_OK !=
139        sqlite3_bind_blob (stmt, 3,
140                           key, sizeof (struct GNUNET_HashCode),
141                           SQLITE_TRANSIENT)) ||
142       (SQLITE_OK != sqlite3_bind_blob (stmt, 4,
143                                        data, size,
144                                        SQLITE_TRANSIENT)) ||
145       (SQLITE_OK != sqlite3_bind_blob (stmt, 5,
146                                        path_info,
147                                        path_info_len * sizeof (struct GNUNET_PeerIdentity),
148                                        SQLITE_TRANSIENT)))
149   {
150     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
151                 "sqlite3_bind_xxx");
152     sqlite3_finalize (stmt);
153     return -1;
154   }
155   if (SQLITE_DONE != sqlite3_step (stmt))
156   {
157     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
158                 "sqlite3_step");
159     sqlite3_finalize (stmt);
160     return -1;
161   }
162   plugin->num_items++;
163   if (SQLITE_OK != sqlite3_finalize (stmt))
164     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
165                 "sqlite3_finalize");
166   return size + OVERHEAD;
167 }
168
169
170 /**
171  * Iterate over the results for a particular key
172  * in the datastore.
173  *
174  * @param cls closure (our "struct Plugin")
175  * @param key
176  * @param type entries of which type are relevant?
177  * @param iter maybe NULL (to just count)
178  * @param iter_cls closure for iter
179  * @return the number of results found
180  */
181 static unsigned int
182 sqlite_plugin_get (void *cls, const struct GNUNET_HashCode * key,
183                    enum GNUNET_BLOCK_Type type, GNUNET_DATACACHE_Iterator iter,
184                    void *iter_cls)
185 {
186   struct Plugin *plugin = cls;
187   sqlite3_stmt *stmt;
188   struct GNUNET_TIME_Absolute now;
189   struct GNUNET_TIME_Absolute exp;
190   unsigned int size;
191   const char *dat;
192   unsigned int cnt;
193   unsigned int off;
194   unsigned int total;
195   unsigned int psize;
196   char scratch[256];
197   int64_t ntime;
198   const struct GNUNET_PeerIdentity *path;
199
200   now = GNUNET_TIME_absolute_get ();
201   LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' for key `%4s'\n", "GET",
202        GNUNET_h2s (key));
203   if (sq_prepare
204       (plugin->dbh,
205        "SELECT count(*) FROM ds090 WHERE key=? AND type=? AND expire >= ?",
206        &stmt) != SQLITE_OK)
207   {
208     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
209                 "sq_prepare");
210     return 0;
211   }
212   ntime = (int64_t) now.abs_value_us;
213   GNUNET_assert (ntime >= 0);
214   if ((SQLITE_OK !=
215        sqlite3_bind_blob (stmt, 1, key, sizeof (struct GNUNET_HashCode),
216                           SQLITE_TRANSIENT)) ||
217       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
218       (SQLITE_OK != sqlite3_bind_int64 (stmt, 3, now.abs_value_us)))
219   {
220     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
221                 "sqlite3_bind_xxx");
222     sqlite3_finalize (stmt);
223     return 0;
224   }
225
226   if (SQLITE_ROW != sqlite3_step (stmt))
227   {
228     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
229                 "sqlite_step");
230     sqlite3_finalize (stmt);
231     LOG (GNUNET_ERROR_TYPE_DEBUG,
232          "No content found when processing `%s' for key `%4s'\n", "GET",
233          GNUNET_h2s (key));
234     return 0;
235   }
236   total = sqlite3_column_int (stmt, 0);
237   sqlite3_finalize (stmt);
238   if ((total == 0) || (iter == NULL))
239   {
240     if (0 == total)
241       LOG (GNUNET_ERROR_TYPE_DEBUG,
242            "No content found when processing `%s' for key `%4s'\n", "GET",
243            GNUNET_h2s (key));
244     return total;
245   }
246
247   cnt = 0;
248   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
249   while (cnt < total)
250   {
251     off = (off + 1) % total;
252     GNUNET_snprintf (scratch, sizeof (scratch),
253                      "SELECT value,expire,path FROM ds090 WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET %u",
254                      off);
255     if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
256     {
257       LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
258                   "sq_prepare");
259       return cnt;
260     }
261     if ((SQLITE_OK !=
262          sqlite3_bind_blob (stmt, 1, key, sizeof (struct GNUNET_HashCode),
263                             SQLITE_TRANSIENT)) ||
264         (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
265         (SQLITE_OK != sqlite3_bind_int64 (stmt, 3, now.abs_value_us)))
266     {
267       LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
268                   "sqlite3_bind_xxx");
269       sqlite3_finalize (stmt);
270       return cnt;
271     }
272     if (sqlite3_step (stmt) != SQLITE_ROW)
273       break;
274     size = sqlite3_column_bytes (stmt, 0);
275     dat = sqlite3_column_blob (stmt, 0);
276     exp.abs_value_us = sqlite3_column_int64 (stmt, 1);
277     psize = sqlite3_column_bytes (stmt, 2);
278     if (0 != psize % sizeof (struct GNUNET_PeerIdentity))
279     {
280       GNUNET_break (0);
281       psize = 0;
282     }
283     psize /= sizeof (struct GNUNET_PeerIdentity);
284     if (0 != psize)
285       path = sqlite3_column_blob (stmt, 2);
286     else
287       path = NULL;
288     ntime = (int64_t) exp.abs_value_us;
289     if (ntime == INT64_MAX)
290       exp = GNUNET_TIME_UNIT_FOREVER_ABS;
291     cnt++;
292     LOG (GNUNET_ERROR_TYPE_DEBUG,
293          "Found %u-byte result when processing `%s' for key `%4s'\n",
294          (unsigned int) size, "GET", GNUNET_h2s (key));
295     if (GNUNET_OK != iter (iter_cls, key, size, dat, type, exp, psize, path))
296     {
297       sqlite3_finalize (stmt);
298       break;
299     }
300     sqlite3_finalize (stmt);
301   }
302   return cnt;
303 }
304
305
306 /**
307  * Delete the entry with the lowest expiration value
308  * from the datacache right now.
309  *
310  * @param cls closure (our "struct Plugin")
311  * @return GNUNET_OK on success, GNUNET_SYSERR on error
312  */
313 static int
314 sqlite_plugin_del (void *cls)
315 {
316   struct Plugin *plugin = cls;
317   unsigned long long rowid;
318   unsigned int dsize;
319   sqlite3_stmt *stmt;
320   sqlite3_stmt *dstmt;
321   struct GNUNET_HashCode hc;
322
323   LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s'\n", "DEL");
324   stmt = NULL;
325   dstmt = NULL;
326   if (sq_prepare
327       (plugin->dbh,
328        "SELECT _ROWID_,key,value FROM ds090 ORDER BY expire ASC LIMIT 1",
329        &stmt) != SQLITE_OK)
330   {
331     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
332                 "sq_prepare");
333     if (stmt != NULL)
334       (void) sqlite3_finalize (stmt);
335     return GNUNET_SYSERR;
336   }
337   if (SQLITE_ROW != sqlite3_step (stmt))
338   {
339     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
340                 "sqlite3_step");
341     (void) sqlite3_finalize (stmt);
342     return GNUNET_SYSERR;
343   }
344   rowid = sqlite3_column_int64 (stmt, 0);
345   GNUNET_assert (sqlite3_column_bytes (stmt, 1) == sizeof (struct GNUNET_HashCode));
346   memcpy (&hc, sqlite3_column_blob (stmt, 1), sizeof (struct GNUNET_HashCode));
347   dsize = sqlite3_column_bytes (stmt, 2);
348   if (SQLITE_OK != sqlite3_finalize (stmt))
349     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
350                 "sqlite3_step");
351   if (sq_prepare (plugin->dbh, "DELETE FROM ds090 WHERE _ROWID_=?", &dstmt) !=
352       SQLITE_OK)
353   {
354     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
355                 "sq_prepare");
356     if (stmt != NULL)
357       (void) sqlite3_finalize (stmt);
358     return GNUNET_SYSERR;
359   }
360   if (SQLITE_OK != sqlite3_bind_int64 (dstmt, 1, rowid))
361   {
362     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
363                 "sqlite3_bind");
364     (void) sqlite3_finalize (dstmt);
365     return GNUNET_SYSERR;
366   }
367   if (sqlite3_step (dstmt) != SQLITE_DONE)
368   {
369     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
370                 "sqlite3_step");
371     (void) sqlite3_finalize (dstmt);
372     return GNUNET_SYSERR;
373   }
374   plugin->num_items--;
375   plugin->env->delete_notify (plugin->env->cls, &hc, dsize + OVERHEAD);
376   if (SQLITE_OK != sqlite3_finalize (dstmt))
377     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
378                 "sqlite3_finalize");
379   return GNUNET_OK;
380 }
381
382
383 /**
384  * Entry point for the plugin.
385  *
386  * @param cls closure (the "struct GNUNET_DATACACHE_PluginEnvironmnet")
387  * @return the plugin's closure (our "struct Plugin")
388  */
389 void *
390 libgnunet_plugin_datacache_sqlite_init (void *cls)
391 {
392   struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
393   struct GNUNET_DATACACHE_PluginFunctions *api;
394   struct Plugin *plugin;
395   char *fn;
396   char *fn_utf8;
397   sqlite3 *dbh;
398   char *emsg;
399
400   if (GNUNET_YES ==
401       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
402                                             "datacache-sqlite",
403                                             "IN_MEMORY"))
404   {
405     if (SQLITE_OK != sqlite3_open (":memory:", &dbh))
406       return NULL;
407     fn_utf8 = NULL;
408   }
409   else
410   {
411     fn = GNUNET_DISK_mktemp ("gnunet-datacache");
412     if (fn == NULL)
413       {
414         GNUNET_break (0);
415         return NULL;
416       }
417     /* fn should be UTF-8-encoded. If it isn't, it's a bug. */
418     fn_utf8 = GNUNET_strdup (fn);
419     if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
420     {
421       GNUNET_free (fn);
422       GNUNET_free (fn_utf8);
423       return NULL;
424     }
425     GNUNET_free (fn);
426   }
427
428   SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
429   SQLITE3_EXEC (dbh, "PRAGMA locking_mode=EXCLUSIVE");
430   SQLITE3_EXEC (dbh, "PRAGMA journal_mode=OFF");
431   SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
432   SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
433   if (GNUNET_YES ==
434       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
435                                             "datacache-sqlite",
436                                             "IN_MEMORY"))
437     SQLITE3_EXEC (dbh, "PRAGMA sqlite_temp_store=3");
438
439   SQLITE3_EXEC (dbh,
440                 "CREATE TABLE ds090 (" "  type INTEGER NOT NULL DEFAULT 0,"
441                 "  expire INTEGER NOT NULL DEFAULT 0,"
442                 "  key BLOB NOT NULL DEFAULT '',"
443                 "  value BLOB NOT NULL DEFAULT '',"
444                 "  path BLOB DEFAULT '')");
445   SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
446   SQLITE3_EXEC (dbh, "CREATE INDEX idx_expire ON ds090 (expire)");
447   plugin = GNUNET_new (struct Plugin);
448   plugin->env = env;
449   plugin->dbh = dbh;
450   plugin->fn = fn_utf8;
451   api = GNUNET_new (struct GNUNET_DATACACHE_PluginFunctions);
452   api->cls = plugin;
453   api->get = &sqlite_plugin_get;
454   api->put = &sqlite_plugin_put;
455   api->del = &sqlite_plugin_del;
456   LOG (GNUNET_ERROR_TYPE_INFO, _("Sqlite datacache running\n"));
457   return api;
458 }
459
460
461 /**
462  * Exit point from the plugin.
463  *
464  * @param cls closure (our "struct Plugin")
465  * @return NULL
466  */
467 void *
468 libgnunet_plugin_datacache_sqlite_done (void *cls)
469 {
470   struct GNUNET_DATACACHE_PluginFunctions *api = cls;
471   struct Plugin *plugin = api->cls;
472   int result;
473
474 #if SQLITE_VERSION_NUMBER >= 3007000
475   sqlite3_stmt *stmt;
476 #endif
477
478 #if !WINDOWS || defined(__CYGWIN__)
479   if ( (NULL != plugin->fn) &&
480        (0 != UNLINK (plugin->fn)) )
481     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn);
482   GNUNET_free_non_null (plugin->fn);
483 #endif
484   result = sqlite3_close (plugin->dbh);
485 #if SQLITE_VERSION_NUMBER >= 3007000
486   if (result == SQLITE_BUSY)
487   {
488     LOG (GNUNET_ERROR_TYPE_WARNING,
489          _
490          ("Tried to close sqlite without finalizing all prepared statements.\n"));
491     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
492     while (stmt != NULL)
493     {
494       LOG (GNUNET_ERROR_TYPE_DEBUG, "Closing statement %p\n", stmt);
495       result = sqlite3_finalize (stmt);
496       if (result != SQLITE_OK)
497         LOG (GNUNET_ERROR_TYPE_WARNING, _("Failed to close statement %p: %d\n"),
498              stmt, result);
499       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
500     }
501     result = sqlite3_close (plugin->dbh);
502   }
503 #endif
504   if (SQLITE_OK != result)
505     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
506
507 #if WINDOWS && !defined(__CYGWIN__)
508   if ( (NULL != plugin->fn) &&
509        (0 != UNLINK (plugin->fn)) )
510     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn);
511   GNUNET_free_non_null (plugin->fn);
512 #endif
513   GNUNET_free (plugin);
514   GNUNET_free (api);
515   return NULL;
516 }
517
518
519
520 /* end of plugin_datacache_sqlite.c */