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