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