5493dbb905916df3cc90b5ba0e37edd1a832c642
[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 2, 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 key key to store data under
90  * @param size number of bytes in data
91  * @param data data to store
92  * @param type type of the value
93  * @param discard_time when to discard the value in any case
94  * @return 0 on error, number of bytes used otherwise
95  */
96 static uint32_t 
97 sqlite_plugin_put (void *cls,
98                    const GNUNET_HashCode * key,
99                    uint32_t size,
100                    const char *data,
101                    uint32_t type,
102                    struct GNUNET_TIME_Absolute discard_time)
103 {
104   struct Plugin *plugin = cls;
105   sqlite3_stmt *stmt;
106
107 #if DEBUG_DATACACHE_SQLITE
108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
109               "Processing `%s' of %u bytes with key `%4s' and expiration %llums\n",
110               "PUT",
111               (unsigned int) size,
112               GNUNET_h2s (key),
113               (unsigned long long) GNUNET_TIME_absolute_get_remaining (discard_time).value);
114 #endif
115   if (sq_prepare (plugin->dbh,
116                   "INSERT INTO ds090 "
117                   "(type, expire, key, value) "
118                   "VALUES (?, ?, ?, ?)", &stmt) != SQLITE_OK)
119     {
120       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
121                   _("`%s' failed at %s:%d with error: %s\n"),
122                   "sq_prepare", __FILE__, __LINE__, 
123                   sqlite3_errmsg (plugin->dbh));
124       return 0;
125     }
126   if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
127        (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, discard_time.value)) ||
128        (SQLITE_OK != sqlite3_bind_blob (stmt, 3, key, sizeof (GNUNET_HashCode),
129                                         SQLITE_TRANSIENT)) ||
130        (SQLITE_OK != sqlite3_bind_blob (stmt, 4, data, size, SQLITE_TRANSIENT)))
131     {
132       LOG_SQLITE (plugin->dbh,
133                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
134                   "sqlite3_bind_xxx");
135       sqlite3_finalize (stmt);
136       return 0;
137     }
138   if (SQLITE_DONE != sqlite3_step (stmt))
139     {
140       LOG_SQLITE (plugin->dbh,
141                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
142                   "sqlite3_step");
143       sqlite3_finalize (stmt);
144       return 0;
145     }
146   if (SQLITE_OK != sqlite3_finalize (stmt))
147     LOG_SQLITE (plugin->dbh,
148                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
149                 "sqlite3_finalize");
150   return size + OVERHEAD;
151 }
152
153
154 /**
155  * Iterate over the results for a particular key
156  * in the datastore.
157  *
158  * @param key
159  * @param type entries of which type are relevant?
160  * @param iter maybe NULL (to just count)
161  * @return the number of results found
162  */
163 static unsigned int 
164 sqlite_plugin_get (void *cls,
165                    const GNUNET_HashCode * key,
166                    uint32_t type,
167                    GNUNET_DATACACHE_Iterator iter,
168                    void *iter_cls)
169 {
170   struct Plugin *plugin = cls;
171   sqlite3_stmt *stmt;
172   struct GNUNET_TIME_Absolute now;
173   struct GNUNET_TIME_Absolute exp;
174   unsigned int size;
175   const char *dat;
176   unsigned int cnt;
177   unsigned int off;
178   unsigned int total;
179   char scratch[256];
180
181   now = GNUNET_TIME_absolute_get ();
182 #if DEBUG_DATACACHE_SQLITE
183   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
184               "Processing `%s' for key `%4s'\n",
185               "GET",
186               GNUNET_h2s (key));
187 #endif
188   if (sq_prepare (plugin->dbh,
189                   "SELECT count(*) FROM ds090 WHERE key=? AND type=? AND expire >= ?",
190                   &stmt) != SQLITE_OK)
191     {
192       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
193                   _("`%s' failed at %s:%d with error: %s\n"),
194                   "sq_prepare", __FILE__, __LINE__, 
195                   sqlite3_errmsg (plugin->dbh));
196       return 0;
197     }
198   sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
199                      SQLITE_TRANSIENT);
200   sqlite3_bind_int (stmt, 2, type);
201   sqlite3_bind_int64 (stmt, 3, now.value);
202   if (SQLITE_ROW != sqlite3_step (stmt))
203     {
204       LOG_SQLITE (plugin->dbh,
205                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
206                   "sqlite_step");
207       sqlite3_finalize (stmt);
208       return 0;
209     }
210   total = sqlite3_column_int (stmt, 0);
211   sqlite3_finalize (stmt);
212   if ( (total == 0) || (iter == NULL) )
213     return total;    
214
215   cnt = 0;
216   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
217   while (cnt < total)
218     {
219       off = (off + 1) % total;
220       GNUNET_snprintf (scratch, 
221                        sizeof(scratch),
222                        "SELECT value,expire FROM ds090 WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET %u",
223                        off);
224       if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
225         {
226           GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
227                       _("`%s' failed at %s:%d with error: %s\n"),
228                       "sq_prepare", __FILE__, __LINE__,
229                       sqlite3_errmsg (plugin->dbh));
230           return cnt;
231         }
232       sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
233                          SQLITE_TRANSIENT);
234       sqlite3_bind_int (stmt, 2, type);
235       sqlite3_bind_int64 (stmt, 3, now.value);
236       if (sqlite3_step (stmt) != SQLITE_ROW)
237         break;
238       size = sqlite3_column_bytes (stmt, 0);
239       dat = sqlite3_column_blob (stmt, 0);
240       exp.value = sqlite3_column_int64 (stmt, 1);
241       cnt++;
242       if (GNUNET_OK != iter (iter_cls,
243                              exp,
244                              key, 
245                              size,
246                              dat,
247                              type))
248         {
249           sqlite3_finalize (stmt);
250           break;
251         }
252       sqlite3_finalize (stmt);
253     }
254   return cnt;
255 }
256
257
258 /**
259  * Delete the entry with the lowest expiration value
260  * from the datacache right now.
261  * 
262  * @return GNUNET_OK on success, GNUNET_SYSERR on error
263  */ 
264 static int 
265 sqlite_plugin_del (void *cls)
266 {
267   struct Plugin *plugin = cls;
268   unsigned int dsize;
269   unsigned int dtype;
270   sqlite3_stmt *stmt;
271   sqlite3_stmt *dstmt;
272
273 #if DEBUG_DATACACHE_SQLITE
274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
275               "Processing `%s'\n",
276               "DEL");
277 #endif
278   stmt = NULL;
279   dstmt = NULL;
280   if ((sq_prepare (plugin->dbh,
281                    "SELECT type, key, value FROM ds090 ORDER BY expire ASC LIMIT 1",
282                    &stmt) != SQLITE_OK) ||
283       (sq_prepare (plugin->dbh,
284                    "DELETE FROM ds090 "
285                    "WHERE key=? AND value=? AND type=?",
286                    &dstmt) != SQLITE_OK))
287     {
288       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
289                   _("`%s' failed at %s:%d with error: %s\n"),
290                   "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
291       if (dstmt != NULL)
292         sqlite3_finalize (dstmt);
293       if (stmt != NULL)
294         sqlite3_finalize (stmt);
295       return GNUNET_SYSERR;
296     }
297   if (SQLITE_ROW != sqlite3_step (stmt))
298     {
299       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
300                   _("`%s' failed at %s:%d with error: %s\n"),
301                   "sqlite3_step", __FILE__, __LINE__,
302                   sqlite3_errmsg (plugin->dbh));
303       sqlite3_finalize (dstmt);
304       sqlite3_finalize (stmt);
305       return GNUNET_SYSERR;
306     }
307   dtype = sqlite3_column_int (stmt, 0);
308   GNUNET_break (sqlite3_column_bytes (stmt, 1) == sizeof (GNUNET_HashCode));
309   dsize = sqlite3_column_bytes (stmt, 2);
310   sqlite3_bind_blob (dstmt,
311                      1, sqlite3_column_blob (stmt, 1),
312                      sizeof (GNUNET_HashCode),
313                      SQLITE_TRANSIENT);
314   sqlite3_bind_blob (dstmt,
315                      2, sqlite3_column_blob (stmt, 2),
316                      dsize,
317                      SQLITE_TRANSIENT);
318   sqlite3_bind_int (dstmt, 3, dtype);
319   if (sqlite3_step (dstmt) != SQLITE_DONE)
320     {
321       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
322                   _("`%s' failed at %s:%d with error: %s\n"),
323                   "sqlite3_step", __FILE__, __LINE__,
324                   sqlite3_errmsg (plugin->dbh));    
325       sqlite3_finalize (dstmt);
326       sqlite3_finalize (stmt);
327       return GNUNET_SYSERR;
328     }
329   plugin->env->delete_notify (plugin->env->cls,
330                               sqlite3_column_blob (stmt, 1),
331                               dsize + OVERHEAD);
332   sqlite3_finalize (dstmt);
333   sqlite3_finalize (stmt);
334   return GNUNET_OK;
335 }
336
337
338 /**
339  * Entry point for the plugin.
340  */
341 void *
342 libgnunet_plugin_datacache_sqlite_init (void *cls)
343 {
344   struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
345   struct GNUNET_DATACACHE_PluginFunctions *api;
346   struct Plugin *plugin;
347   char *fn;
348   char *fn_utf8;
349   int fd;
350   sqlite3 *dbh;
351   char *tmpl;
352   const char *tmpdir;
353   char *emsg;
354
355   tmpdir = getenv ("TMPDIR");
356   tmpdir = tmpdir ? tmpdir : "/tmp";
357
358 #define TEMPLATE "/gnunet-dstoreXXXXXX"
359   tmpl = GNUNET_malloc (strlen (tmpdir) + sizeof (TEMPLATE) + 1);
360   strcpy (tmpl, tmpdir);
361   strcat (tmpl, TEMPLATE);
362 #undef TEMPLATE
363 #ifdef MINGW
364   fn = (char *) GNUNET_malloc (MAX_PATH + 1);
365   plibc_conv_to_win_path (tmpl, fn);
366   GNUNET_free (tmpl);
367 #else
368   fn = tmpl;
369 #endif
370   fd = mkstemp (fn);
371   if (fd == -1)
372     {
373       GNUNET_break (0);
374       GNUNET_free (fn);
375       return NULL;
376     }
377   CLOSE (fd);
378   fn_utf8 = GNUNET_STRINGS_to_utf8 (fn, strlen (fn),
379 #ifdef ENABLE_NLS
380                                     nl_langinfo (CODESET)
381 #else
382                                     "UTF-8"      /* good luck */
383 #endif
384     );
385   if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
386     {
387       GNUNET_free (fn);
388       GNUNET_free (fn_utf8);
389       return NULL;
390     }
391   GNUNET_free (fn);
392
393   SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
394   SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
395   SQLITE3_EXEC (dbh, "PRAGMA count_changes=OFF");
396   SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
397   SQLITE3_EXEC (dbh,
398                 "CREATE TABLE ds090 ("
399                 "  type INTEGER NOT NULL DEFAULT 0,"
400                 "  expire INTEGER NOT NULL DEFAULT 0,"
401                 "  key BLOB NOT NULL DEFAULT '',"
402                 "  value BLOB NOT NULL DEFAULT '')");
403   SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
404   plugin = GNUNET_malloc (sizeof (struct Plugin));
405   plugin->env = env;
406   plugin->dbh = dbh;
407   plugin->fn = fn_utf8;
408   api = GNUNET_malloc (sizeof (struct GNUNET_DATACACHE_PluginFunctions));
409   api->cls = plugin;
410   api->get = &sqlite_plugin_get;
411   api->put = &sqlite_plugin_put;
412   api->del = &sqlite_plugin_del;
413   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
414                    "sqlite", _("Sqlite datacache running\n"));
415   return api;
416 }
417
418
419 /**
420  * Exit point from the plugin.
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   UNLINK (plugin->fn);
429   GNUNET_free (plugin->fn);
430   sqlite3_close (plugin->dbh);
431   GNUNET_free (plugin);
432   GNUNET_free (api);
433   return NULL;
434 }
435
436
437
438 /* end of plugin_datacache_sqlite.c */
439