fixing issue pointed out by amatus
[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 "plugin_datacache.h"
29 #include <sqlite3.h>
30
31 #define DEBUG_DATACACHE_SQLITE GNUNET_NO
32
33 /**
34  * How much overhead do we assume per entry in the
35  * datacache?
36  */
37 #define OVERHEAD (sizeof(GNUNET_HashCode) + 32)
38
39 /**
40  * Context for all functions in this plugin.
41  */
42 struct Plugin 
43 {
44   /**
45    * Our execution environment.
46    */
47   struct GNUNET_DATACACHE_PluginEnvironment *env;
48
49   /**
50    * Handle to the sqlite database.
51    */
52   sqlite3 *dbh;
53
54   /**
55    * Filename used for the DB.
56    */ 
57   char *fn;
58 };
59
60
61 /**
62  * Log an error message at log-level 'level' that indicates
63  * a failure of the command 'cmd' on file 'filename'
64  * with the message given by strerror(errno).
65  */
66 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db)); } while(0)
67
68
69 #define SQLITE3_EXEC(db, cmd) do { emsg = NULL; if (SQLITE_OK != sqlite3_exec(db, cmd, NULL, NULL, &emsg)) { GNUNET_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)
70
71
72 /**
73  * @brief Prepare a SQL statement
74  */
75 static int
76 sq_prepare (sqlite3 * dbh, const char *zSql,    /* SQL statement, UTF-8 encoded */
77             sqlite3_stmt ** ppStmt)
78 {                               /* OUT: Statement handle */
79   char *dummy;
80   return sqlite3_prepare (dbh,
81                           zSql,
82                           strlen (zSql), ppStmt, (const char **) &dummy);
83 }
84
85
86 /**
87  * Store an item in the datastore.
88  *
89  * @param cls closure (our "struct Plugin")
90  * @param key key to store data under
91  * @param size number of bytes in data
92  * @param data data to store
93  * @param type type of the value
94  * @param discard_time when to discard the value in any case
95  * @return 0 on error, number of bytes used otherwise
96  */
97 static size_t 
98 sqlite_plugin_put (void *cls,
99                    const GNUNET_HashCode * key,
100                    size_t size,
101                    const char *data,
102                    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 #if DEBUG_DATACACHE_SQLITE
110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
111               "Processing `%s' of %u bytes with key `%4s' and expiration %llums\n",
112               "PUT",
113               (unsigned int) size,
114               GNUNET_h2s (key),
115               (unsigned long long) GNUNET_TIME_absolute_get_remaining (discard_time).value);
116 #endif
117   dval = (int64_t) discard_time.value;
118   if (dval < 0)    
119     dval = INT64_MAX;    
120   if (sq_prepare (plugin->dbh,
121                   "INSERT INTO ds090 "
122                   "(type, expire, key, value) "
123                   "VALUES (?, ?, ?, ?)", &stmt) != SQLITE_OK)
124     {
125       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
126                   _("`%s' failed at %s:%d with error: %s\n"),
127                   "sq_prepare", __FILE__, __LINE__, 
128                   sqlite3_errmsg (plugin->dbh));
129       return 0;
130     }
131   if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
132        (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, dval)) ||
133        (SQLITE_OK != sqlite3_bind_blob (stmt, 3, key, sizeof (GNUNET_HashCode),
134                                         SQLITE_TRANSIENT)) ||
135        (SQLITE_OK != sqlite3_bind_blob (stmt, 4, data, size, SQLITE_TRANSIENT)))
136     {
137       LOG_SQLITE (plugin->dbh,
138                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
139                   "sqlite3_bind_xxx");
140       sqlite3_finalize (stmt);
141       return 0;
142     }
143   if (SQLITE_DONE != sqlite3_step (stmt))
144     {
145       LOG_SQLITE (plugin->dbh,
146                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
147                   "sqlite3_step");
148       sqlite3_finalize (stmt);
149       return 0;
150     }
151   if (SQLITE_OK != sqlite3_finalize (stmt))
152     LOG_SQLITE (plugin->dbh,
153                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
154                 "sqlite3_finalize");
155   return size + OVERHEAD;
156 }
157
158
159 /**
160  * Iterate over the results for a particular key
161  * in the datastore.
162  *
163  * @param cls closure (our "struct Plugin")
164  * @param key
165  * @param type entries of which type are relevant?
166  * @param iter maybe NULL (to just count)
167  * @param iter_cls closure for iter
168  * @return the number of results found
169  */
170 static unsigned int 
171 sqlite_plugin_get (void *cls,
172                    const GNUNET_HashCode * key,
173                    enum GNUNET_BLOCK_Type type,
174                    GNUNET_DATACACHE_Iterator iter,
175                    void *iter_cls)
176 {
177   struct Plugin *plugin = cls;
178   sqlite3_stmt *stmt;
179   struct GNUNET_TIME_Absolute now;
180   struct GNUNET_TIME_Absolute exp;
181   unsigned int size;
182   const char *dat;
183   unsigned int cnt;
184   unsigned int off;
185   unsigned int total;
186   char scratch[256];
187   int64_t ntime;
188
189   now = GNUNET_TIME_absolute_get ();
190 #if DEBUG_DATACACHE_SQLITE
191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
192               "Processing `%s' for key `%4s'\n",
193               "GET",
194               GNUNET_h2s (key));
195 #endif
196   if (sq_prepare (plugin->dbh,
197                   "SELECT count(*) FROM ds090 WHERE key=? AND type=? AND expire >= ?",
198                   &stmt) != SQLITE_OK)
199     {
200       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
201                   _("`%s' failed at %s:%d with error: %s\n"),
202                   "sq_prepare", __FILE__, __LINE__, 
203                   sqlite3_errmsg (plugin->dbh));
204       return 0;
205     }
206   sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
207                      SQLITE_TRANSIENT);
208   sqlite3_bind_int (stmt, 2, type);
209   ntime = (int64_t) now.value;
210   GNUNET_assert (ntime >= 0);
211   sqlite3_bind_int64 (stmt, 3, now.value);
212   if (SQLITE_ROW != sqlite3_step (stmt))
213     {
214       LOG_SQLITE (plugin->dbh,
215                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
216                   "sqlite_step");
217       sqlite3_finalize (stmt);
218       return 0;
219     }
220   total = sqlite3_column_int (stmt, 0);
221   sqlite3_finalize (stmt);
222   if ( (total == 0) || (iter == NULL) )
223     return total;    
224
225   cnt = 0;
226   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
227   while (cnt < total)
228     {
229       off = (off + 1) % total;
230       GNUNET_snprintf (scratch, 
231                        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           GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
237                       _("`%s' failed at %s:%d with error: %s\n"),
238                       "sq_prepare", __FILE__, __LINE__,
239                       sqlite3_errmsg (plugin->dbh));
240           return cnt;
241         }
242       sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
243                          SQLITE_TRANSIENT);
244       sqlite3_bind_int (stmt, 2, type);
245       sqlite3_bind_int64 (stmt, 3, now.value);
246       if (sqlite3_step (stmt) != SQLITE_ROW)
247         break;
248       size = sqlite3_column_bytes (stmt, 0);
249       dat = sqlite3_column_blob (stmt, 0);
250       exp.value = sqlite3_column_int64 (stmt, 1);
251       ntime = (int64_t) exp.value;
252       if (ntime == INT64_MAX)
253         exp = GNUNET_TIME_UNIT_FOREVER_ABS;
254       cnt++;
255       if (GNUNET_OK != iter (iter_cls,
256                              exp,
257                              key, 
258                              size,
259                              dat,
260                              type))
261         {
262           sqlite3_finalize (stmt);
263           break;
264         }
265       sqlite3_finalize (stmt);
266     }
267   return cnt;
268 }
269
270
271 /**
272  * Delete the entry with the lowest expiration value
273  * from the datacache right now.
274  * 
275  * @param cls closure (our "struct Plugin")
276  * @return GNUNET_OK on success, GNUNET_SYSERR on error
277  */ 
278 static int 
279 sqlite_plugin_del (void *cls)
280 {
281   struct Plugin *plugin = cls;
282   unsigned int dsize;
283   unsigned int dtype;
284   sqlite3_stmt *stmt;
285   sqlite3_stmt *dstmt;
286
287 #if DEBUG_DATACACHE_SQLITE
288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
289               "Processing `%s'\n",
290               "DEL");
291 #endif
292   stmt = NULL;
293   dstmt = NULL;
294   if ((sq_prepare (plugin->dbh,
295                    "SELECT type, key, value FROM ds090 ORDER BY expire ASC LIMIT 1",
296                    &stmt) != SQLITE_OK) ||
297       (sq_prepare (plugin->dbh,
298                    "DELETE FROM ds090 "
299                    "WHERE key=? AND value=? AND type=?",
300                    &dstmt) != SQLITE_OK))
301     {
302       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
303                   _("`%s' failed at %s:%d with error: %s\n"),
304                   "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
305       if (dstmt != NULL)
306         sqlite3_finalize (dstmt);
307       if (stmt != NULL)
308         sqlite3_finalize (stmt);
309       return GNUNET_SYSERR;
310     }
311   if (SQLITE_ROW != sqlite3_step (stmt))
312     {
313       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
314                   _("`%s' failed at %s:%d with error: %s\n"),
315                   "sqlite3_step", __FILE__, __LINE__,
316                   sqlite3_errmsg (plugin->dbh));
317       sqlite3_finalize (dstmt);
318       sqlite3_finalize (stmt);
319       return GNUNET_SYSERR;
320     }
321   dtype = sqlite3_column_int (stmt, 0);
322   GNUNET_break (sqlite3_column_bytes (stmt, 1) == sizeof (GNUNET_HashCode));
323   dsize = sqlite3_column_bytes (stmt, 2);
324   sqlite3_bind_blob (dstmt,
325                      1, sqlite3_column_blob (stmt, 1),
326                      sizeof (GNUNET_HashCode),
327                      SQLITE_TRANSIENT);
328   sqlite3_bind_blob (dstmt,
329                      2, sqlite3_column_blob (stmt, 2),
330                      dsize,
331                      SQLITE_TRANSIENT);
332   sqlite3_bind_int (dstmt, 3, dtype);
333   if (sqlite3_step (dstmt) != SQLITE_DONE)
334     {
335       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
336                   _("`%s' failed at %s:%d with error: %s\n"),
337                   "sqlite3_step", __FILE__, __LINE__,
338                   sqlite3_errmsg (plugin->dbh));    
339       sqlite3_finalize (dstmt);
340       sqlite3_finalize (stmt);
341       return GNUNET_SYSERR;
342     }
343   plugin->env->delete_notify (plugin->env->cls,
344                               sqlite3_column_blob (stmt, 1),
345                               dsize + OVERHEAD);
346   sqlite3_finalize (dstmt);
347   sqlite3_finalize (stmt);
348   return GNUNET_OK;
349 }
350
351
352 /**
353  * Entry point for the plugin.
354  *
355  * @param cls closure (the "struct GNUNET_DATACACHE_PluginEnvironmnet")
356  * @return the plugin's closure (our "struct Plugin")
357  */
358 void *
359 libgnunet_plugin_datacache_sqlite_init (void *cls)
360 {
361   struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
362   struct GNUNET_DATACACHE_PluginFunctions *api;
363   struct Plugin *plugin;
364   char *fn;
365   char *fn_utf8;
366   sqlite3 *dbh;
367   char *emsg;
368
369   fn = GNUNET_DISK_mktemp ("gnunet-datacache");
370   if (fn == NULL)
371     {
372       GNUNET_break (0);
373       return NULL;
374     }
375   fn_utf8 = GNUNET_STRINGS_to_utf8 (fn, strlen (fn),
376 #ifdef ENABLE_NLS
377                                     nl_langinfo (CODESET)
378 #else
379                                     "UTF-8"      /* good luck */
380 #endif
381     );
382   if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
383     {
384       GNUNET_free (fn);
385       GNUNET_free (fn_utf8);
386       return NULL;
387     }
388   GNUNET_free (fn);
389
390   SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
391   SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
392   SQLITE3_EXEC (dbh, "PRAGMA count_changes=OFF");
393   SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
394   SQLITE3_EXEC (dbh,
395                 "CREATE TABLE ds090 ("
396                 "  type INTEGER NOT NULL DEFAULT 0,"
397                 "  expire INTEGER NOT NULL DEFAULT 0,"
398                 "  key BLOB NOT NULL DEFAULT '',"
399                 "  value BLOB NOT NULL DEFAULT '')");
400   SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
401   plugin = GNUNET_malloc (sizeof (struct Plugin));
402   plugin->env = env;
403   plugin->dbh = dbh;
404   plugin->fn = fn_utf8;
405   api = GNUNET_malloc (sizeof (struct GNUNET_DATACACHE_PluginFunctions));
406   api->cls = plugin;
407   api->get = &sqlite_plugin_get;
408   api->put = &sqlite_plugin_put;
409   api->del = &sqlite_plugin_del;
410   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
411                    "sqlite", _("Sqlite datacache running\n"));
412   return api;
413 }
414
415
416 /**
417  * Exit point from the plugin.
418  *
419  * @param cls closure (our "struct Plugin")
420  * @return NULL
421  */
422 void *
423 libgnunet_plugin_datacache_sqlite_done (void *cls)
424 {
425   struct GNUNET_DATACACHE_PluginFunctions *api = cls;
426   struct Plugin *plugin = api->cls;
427
428   if (0 != UNLINK (plugin->fn))
429     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
430                               "unlink", 
431                               plugin->fn);
432   GNUNET_free (plugin->fn);
433   sqlite3_close (plugin->dbh);
434   GNUNET_free (plugin);
435   GNUNET_free (api);
436   return NULL;
437 }
438
439
440
441 /* end of plugin_datacache_sqlite.c */
442