converting datacache to sqlite, fixing misc. issues in libgnunetsq
[oweals/gnunet.git] / src / datacache / plugin_datacache_sqlite.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2006, 2009, 2015 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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 "gnunet_sq_lib.h"
30 #include <sqlite3.h>
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "datacache-sqlite", __VA_ARGS__)
33
34 #define LOG_STRERROR_FILE(kind,op,fn) GNUNET_log_from_strerror_file (kind, "datacache-sqlite", op, fn)
35
36
37 /**
38  * How much overhead do we assume per entry in the
39  * datacache?
40  */
41 #define OVERHEAD (sizeof(struct GNUNET_HashCode) + 32)
42
43 /**
44  * Context for all functions in this plugin.
45  */
46 struct Plugin
47 {
48   /**
49    * Our execution environment.
50    */
51   struct GNUNET_DATACACHE_PluginEnvironment *env;
52
53   /**
54    * Handle to the sqlite database.
55    */
56   sqlite3 *dbh;
57
58   /**
59    * Filename used for the DB.
60    */
61   char *fn;
62
63   /**
64    * Prepared statement for #sqlite_plugin_put.
65    */
66   sqlite3_stmt *insert_stmt;
67
68   /**
69    * Prepared statement for #sqlite_plugin_get.
70    */
71   sqlite3_stmt *get_count_stmt;
72
73   /**
74    * Prepared statement for #sqlite_plugin_get.
75    */
76   sqlite3_stmt *get_stmt;
77
78   /**
79    * Prepared statement for #sqlite_plugin_del.
80    */
81   sqlite3_stmt *del_select_stmt;
82
83   /**
84    * Prepared statement for #sqlite_plugin_del.
85    */
86   sqlite3_stmt *del_stmt;
87
88   /**
89    * Prepared statement for #sqlite_plugin_get_random.
90    */
91   sqlite3_stmt *get_random_stmt;
92
93   /**
94    * Prepared statement for #sqlite_plugin_get_closest.
95    */
96   sqlite3_stmt *get_closest_stmt;
97
98   /**
99    * Number of key-value pairs in the database.
100    */
101   unsigned int num_items;
102 };
103
104
105 /**
106  * Log an error message at log-level @a level that indicates
107  * a failure of the command @a cmd with the error from the database @a db
108  *
109  * @param db database handle
110  * @param level log level
111  * @param cmd failed command
112  */
113 #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)
114
115
116 /**
117  * Execute SQL statement.
118  *
119  * @param db database handle
120  * @param cmd SQL command to execute
121  */
122 #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)
123
124
125 /**
126  * @brief Prepare a SQL statement
127  *
128  * @param dbh database handle
129  * @param zsql SQL statement text
130  * @param[out] ppStmt set to the prepared statement
131  * @return 0 on success
132  */
133 static int
134 sq_prepare (sqlite3 *dbh,
135             const char *zSql,    /* SQL statement, UTF-8 encoded */
136             sqlite3_stmt **ppStmt)
137 {                               /* OUT: Statement handle */
138   char *dummy;
139
140   return sqlite3_prepare (dbh,
141                           zSql, strlen (zSql),
142                           ppStmt,
143                           (const char **) &dummy);
144 }
145
146
147 /**
148  * Store an item in the datastore.
149  *
150  * @param cls closure (our `struct Plugin`)
151  * @param key key to store @a data under
152  * @param size number of bytes in @a data
153  * @param data data to store
154  * @param type type of the value
155  * @param discard_time when to discard the value in any case
156  * @param path_info_len number of entries in @a path_info
157  * @param path_info array of peers that have processed the request
158  * @return 0 if duplicate, -1 on error, number of bytes used otherwise
159  */
160 static ssize_t
161 sqlite_plugin_put (void *cls,
162                    const struct GNUNET_HashCode *key,
163                    size_t size,
164                    const char *data,
165                    enum GNUNET_BLOCK_Type type,
166                    struct GNUNET_TIME_Absolute discard_time,
167                    unsigned int path_info_len,
168                    const struct GNUNET_PeerIdentity *path_info)
169 {
170   struct Plugin *plugin = cls;
171   uint32_t type32 = type;
172   struct GNUNET_SQ_QueryParam params[] = {
173     GNUNET_SQ_query_param_uint32 (&type32),
174     GNUNET_SQ_query_param_absolute_time (&discard_time),
175     GNUNET_SQ_query_param_auto_from_type (key),
176     GNUNET_SQ_query_param_fixed_size (data, size),
177     GNUNET_SQ_query_param_fixed_size (path_info,
178                                       path_info_len * sizeof (struct GNUNET_PeerIdentity)),
179     GNUNET_SQ_query_param_end
180   };
181
182   LOG (GNUNET_ERROR_TYPE_DEBUG,
183        "Processing PUT of %u bytes with key `%s' and expiration %s\n",
184        (unsigned int) size,
185        GNUNET_h2s (key),
186        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (discard_time),
187                                                GNUNET_YES));
188   if (GNUNET_OK !=
189       GNUNET_SQ_bind (plugin->insert_stmt,
190                       params))
191   {
192     LOG_SQLITE (plugin->dbh,
193                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
194                 "sqlite3_bind_xxx");
195     GNUNET_SQ_reset (plugin->dbh,
196                      plugin->insert_stmt);
197     return -1;
198   }
199   if (SQLITE_DONE !=
200       sqlite3_step (plugin->insert_stmt))
201   {
202     LOG_SQLITE (plugin->dbh,
203                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
204                 "sqlite3_step");
205     GNUNET_SQ_reset (plugin->dbh,
206                      plugin->insert_stmt);
207     return -1;
208   }
209   plugin->num_items++;
210   GNUNET_SQ_reset (plugin->dbh,
211                    plugin->insert_stmt);
212   return size + OVERHEAD;
213 }
214
215
216 /**
217  * Iterate over the results for a particular key
218  * in the datastore.
219  *
220  * @param cls closure (our `struct Plugin`)
221  * @param key
222  * @param type entries of which type are relevant?
223  * @param iter maybe NULL (to just count)
224  * @param iter_cls closure for @a iter
225  * @return the number of results found
226  */
227 static unsigned int
228 sqlite_plugin_get (void *cls,
229                    const struct GNUNET_HashCode *key,
230                    enum GNUNET_BLOCK_Type type,
231                    GNUNET_DATACACHE_Iterator iter,
232                    void *iter_cls)
233 {
234   struct Plugin *plugin = cls;
235   uint32_t type32 = type;
236   struct GNUNET_TIME_Absolute now;
237   struct GNUNET_TIME_Absolute exp;
238   size_t size;
239   void *dat;
240   unsigned int cnt;
241   uint32_t off;
242   unsigned int total;
243   size_t psize;
244   struct GNUNET_PeerIdentity *path;
245   struct GNUNET_SQ_QueryParam params_count[] = {
246     GNUNET_SQ_query_param_auto_from_type (key),
247     GNUNET_SQ_query_param_uint32 (&type32),
248     GNUNET_SQ_query_param_absolute_time (&now),
249     GNUNET_SQ_query_param_end
250   };
251   struct GNUNET_SQ_QueryParam params_select[] = {
252     GNUNET_SQ_query_param_auto_from_type (key),
253     GNUNET_SQ_query_param_uint32 (&type32),
254     GNUNET_SQ_query_param_absolute_time (&now),
255     GNUNET_SQ_query_param_uint32 (&off),
256     GNUNET_SQ_query_param_end
257   };
258   struct GNUNET_SQ_ResultSpec rs[] = {
259     GNUNET_SQ_result_spec_variable_size (&dat,
260                                          &size),
261     GNUNET_SQ_result_spec_absolute_time (&exp),
262     GNUNET_SQ_result_spec_variable_size ((void **) &path,
263                                          &psize),
264     GNUNET_SQ_result_spec_end
265   };
266
267   now = GNUNET_TIME_absolute_get ();
268   LOG (GNUNET_ERROR_TYPE_DEBUG,
269        "Processing GET for key `%s'\n",
270        GNUNET_h2s (key));
271
272   if (GNUNET_OK !=
273       GNUNET_SQ_bind (plugin->get_count_stmt,
274                       params_count))
275   {
276     LOG_SQLITE (plugin->dbh,
277                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
278                 "sqlite3_bind_xxx");
279     GNUNET_SQ_reset (plugin->dbh,
280                      plugin->get_count_stmt);
281     return 0;
282   }
283   if (SQLITE_ROW !=
284       sqlite3_step (plugin->get_count_stmt))
285   {
286     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
287                 "sqlite_step");
288     GNUNET_SQ_reset (plugin->dbh,
289                      plugin->get_count_stmt);
290     LOG (GNUNET_ERROR_TYPE_DEBUG,
291          "No content found when processing GET for key `%s'\n",
292          GNUNET_h2s (key));
293     return 0;
294   }
295   total = sqlite3_column_int (plugin->get_count_stmt,
296                               0);
297   GNUNET_SQ_reset (plugin->dbh,
298                    plugin->get_count_stmt);
299   if ( (0 == total) ||
300        (NULL == iter) )
301   {
302     if (0 == total)
303       LOG (GNUNET_ERROR_TYPE_DEBUG,
304            "No content found when processing GET for key `%s'\n",
305            GNUNET_h2s (key));
306     return total;
307   }
308
309   cnt = 0;
310   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
311                                   total);
312   while (cnt < total)
313   {
314     off = (off + 1) % total;
315     if (GNUNET_OK !=
316         GNUNET_SQ_bind (plugin->get_stmt,
317                         params_select))
318     {
319       LOG_SQLITE (plugin->dbh,
320                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
321                   "sqlite3_bind_xxx");
322       GNUNET_SQ_reset (plugin->dbh,
323                        plugin->get_stmt);
324       return cnt;
325     }
326     if (SQLITE_ROW !=
327         sqlite3_step (plugin->get_stmt))
328       break;
329     if (GNUNET_OK !=
330         GNUNET_SQ_extract_result (plugin->get_stmt,
331                                   rs))
332     {
333       GNUNET_break (0);
334       GNUNET_SQ_reset (plugin->dbh,
335                        plugin->get_stmt);
336       break;
337     }
338     if (0 != psize % sizeof (struct GNUNET_PeerIdentity))
339     {
340       GNUNET_break (0);
341       psize = 0;
342       path = NULL;
343     }
344     psize /= sizeof (struct GNUNET_PeerIdentity);
345     cnt++;
346     LOG (GNUNET_ERROR_TYPE_DEBUG,
347          "Found %u-byte result when processing GET for key `%s'\n",
348          (unsigned int) size,
349          GNUNET_h2s (key));
350     if (GNUNET_OK != iter (iter_cls,
351                            key,
352                            size,
353                            dat,
354                            type,
355                            exp,
356                            psize,
357                            path))
358     {
359       GNUNET_SQ_cleanup_result (rs);
360       GNUNET_SQ_reset (plugin->dbh,
361                        plugin->get_stmt);
362       break;
363     }
364     GNUNET_SQ_cleanup_result (rs);
365     GNUNET_SQ_reset (plugin->dbh,
366                      plugin->get_stmt);
367   }
368   GNUNET_SQ_reset (plugin->dbh,
369                    plugin->get_stmt);
370   return cnt;
371 }
372
373
374 /**
375  * Delete the entry with the lowest expiration value
376  * from the datacache right now.
377  *
378  * @param cls closure (our `struct Plugin`)
379  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
380  */
381 static int
382 sqlite_plugin_del (void *cls)
383 {
384   struct Plugin *plugin = cls;
385   uint64_t rowid;
386   void *data;
387   size_t dsize;
388   struct GNUNET_HashCode hc;
389   struct GNUNET_SQ_ResultSpec rs[] = {
390     GNUNET_SQ_result_spec_uint64 (&rowid),
391     GNUNET_SQ_result_spec_auto_from_type (&hc),
392     GNUNET_SQ_result_spec_variable_size ((void **) &data,
393                                          &dsize),
394     GNUNET_SQ_result_spec_end
395   };
396   struct GNUNET_SQ_QueryParam params[] = {
397     GNUNET_SQ_query_param_uint64 (&rowid),
398     GNUNET_SQ_query_param_end
399   };
400
401   LOG (GNUNET_ERROR_TYPE_DEBUG,
402        "Processing DEL\n");
403   if (SQLITE_ROW !=
404       sqlite3_step (plugin->del_select_stmt))
405   {
406     LOG_SQLITE (plugin->dbh,
407                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
408                 "sqlite3_step");
409     GNUNET_SQ_reset (plugin->dbh,
410                      plugin->del_select_stmt);
411     return GNUNET_SYSERR;
412   }
413   if (GNUNET_OK !=
414       GNUNET_SQ_extract_result (plugin->del_select_stmt,
415                                 rs))
416   {
417     GNUNET_break (0);
418     GNUNET_SQ_reset (plugin->dbh,
419                      plugin->del_select_stmt);
420     return GNUNET_SYSERR;
421   }
422   GNUNET_SQ_cleanup_result (rs);
423   GNUNET_SQ_reset (plugin->dbh,
424                    plugin->del_select_stmt);
425   if (GNUNET_OK !=
426       GNUNET_SQ_bind (plugin->del_stmt,
427                       params))
428   {
429     LOG_SQLITE (plugin->dbh,
430                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
431                 "sqlite3_bind");
432     GNUNET_SQ_reset (plugin->dbh,
433                      plugin->del_stmt);
434     return GNUNET_SYSERR;
435   }
436   if (SQLITE_DONE !=
437       sqlite3_step (plugin->del_stmt))
438   {
439     LOG_SQLITE (plugin->dbh,
440                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
441                 "sqlite3_step");
442     GNUNET_SQ_reset (plugin->dbh,
443                      plugin->del_stmt);
444     return GNUNET_SYSERR;
445   }
446   plugin->num_items--;
447   plugin->env->delete_notify (plugin->env->cls,
448                               &hc,
449                               dsize + OVERHEAD);
450   GNUNET_SQ_reset (plugin->dbh,
451                    plugin->del_stmt);
452   return GNUNET_OK;
453 }
454
455
456 /**
457  * Obtain a random key-value pair from the datacache.
458  *
459  * @param cls closure (our `struct Plugin`)
460  * @param iter maybe NULL (to just count)
461  * @param iter_cls closure for @a iter
462  * @return the number of results found, zero (datacache empty) or one
463  */
464 static unsigned int
465 sqlite_plugin_get_random (void *cls,
466                           GNUNET_DATACACHE_Iterator iter,
467                           void *iter_cls)
468 {
469   struct Plugin *plugin = cls;
470   struct GNUNET_TIME_Absolute exp;
471   size_t size;
472   void *dat;
473   uint32_t off;
474   size_t psize;
475   uint32_t type;
476   struct GNUNET_PeerIdentity *path;
477   struct GNUNET_HashCode key;
478   struct GNUNET_SQ_QueryParam params[] = {
479     GNUNET_SQ_query_param_uint32 (&off),
480     GNUNET_SQ_query_param_end
481   };
482   struct GNUNET_SQ_ResultSpec rs[] = {
483     GNUNET_SQ_result_spec_variable_size (&dat,
484                                          &size),
485     GNUNET_SQ_result_spec_absolute_time (&exp),
486     GNUNET_SQ_result_spec_variable_size ((void **) &path,
487                                          &psize),
488     GNUNET_SQ_result_spec_auto_from_type (&key),
489     GNUNET_SQ_result_spec_uint32 (&type),
490     GNUNET_SQ_result_spec_end
491   };
492
493   if (0 == plugin->num_items)
494     return 0;
495   if (NULL == iter)
496     return 1;
497   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
498                                   plugin->num_items);
499   if (GNUNET_OK !=
500       GNUNET_SQ_bind (plugin->get_random_stmt,
501                       params))
502   {
503     return 0;
504   }
505   if (SQLITE_ROW !=
506       sqlite3_step (plugin->get_random_stmt))
507   {
508     GNUNET_break (0);
509     GNUNET_SQ_reset (plugin->dbh,
510                      plugin->get_random_stmt);
511     return 0;
512   }
513   if (GNUNET_OK !=
514       GNUNET_SQ_extract_result (plugin->get_random_stmt,
515                                 rs))
516   {
517     GNUNET_break (0);
518     GNUNET_SQ_reset (plugin->dbh,
519                      plugin->get_random_stmt);
520     return 0;
521   }
522   if (0 != psize % sizeof (struct GNUNET_PeerIdentity))
523   {
524     GNUNET_break (0);
525     psize = 0;
526     path = NULL;
527   }
528   psize /= sizeof (struct GNUNET_PeerIdentity);
529   LOG (GNUNET_ERROR_TYPE_DEBUG,
530        "Found %u-byte result with key %s when processing GET-RANDOM\n",
531        (unsigned int) size,
532        GNUNET_h2s (&key));
533   (void) iter (iter_cls,
534                &key,
535                size,
536                dat,
537                (enum GNUNET_BLOCK_Type) type,
538                exp,
539                psize,
540                path);
541   GNUNET_SQ_cleanup_result (rs);
542   GNUNET_SQ_reset (plugin->dbh,
543                    plugin->get_random_stmt);
544   return 1;
545 }
546
547
548 /**
549  * Iterate over the results that are "close" to a particular key in
550  * the datacache.  "close" is defined as numerically larger than @a
551  * key (when interpreted as a circular address space), with small
552  * distance.
553  *
554  * @param cls closure (internal context for the plugin)
555  * @param key area of the keyspace to look into
556  * @param num_results number of results that should be returned to @a iter
557  * @param iter maybe NULL (to just count)
558  * @param iter_cls closure for @a iter
559  * @return the number of results found
560  */
561 static unsigned int
562 sqlite_plugin_get_closest (void *cls,
563                            const struct GNUNET_HashCode *key,
564                            unsigned int num_results,
565                            GNUNET_DATACACHE_Iterator iter,
566                            void *iter_cls)
567 {
568   struct Plugin *plugin = cls;
569   uint32_t num_results32 = num_results;
570   struct GNUNET_TIME_Absolute now;
571   struct GNUNET_TIME_Absolute exp;
572   size_t size;
573   void *dat;
574   unsigned int cnt;
575   size_t psize;
576   uint32_t type;
577   struct GNUNET_HashCode hc;
578   struct GNUNET_PeerIdentity *path;
579   struct GNUNET_SQ_QueryParam params[] = {
580     GNUNET_SQ_query_param_auto_from_type (key),
581     GNUNET_SQ_query_param_absolute_time (&now),
582     GNUNET_SQ_query_param_uint32 (&num_results32),
583     GNUNET_SQ_query_param_end
584   };
585   struct GNUNET_SQ_ResultSpec rs[] = {
586     GNUNET_SQ_result_spec_variable_size (&dat,
587                                          &size),
588     GNUNET_SQ_result_spec_absolute_time (&exp),
589     GNUNET_SQ_result_spec_variable_size ((void **) &path,
590                                          &psize),
591     GNUNET_SQ_result_spec_uint32 (&type),
592     GNUNET_SQ_result_spec_auto_from_type (&hc),
593     GNUNET_SQ_result_spec_end
594   };
595
596   now = GNUNET_TIME_absolute_get ();
597   LOG (GNUNET_ERROR_TYPE_DEBUG,
598        "Processing GET_CLOSEST for key `%s'\n",
599        GNUNET_h2s (key));
600   if (GNUNET_OK !=
601       GNUNET_SQ_bind (plugin->get_closest_stmt,
602                       params))
603   {
604     LOG_SQLITE (plugin->dbh,
605                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
606                 "sqlite3_bind_xxx");
607     GNUNET_SQ_reset (plugin->dbh,
608                      plugin->get_closest_stmt);
609     return 0;
610   }
611   cnt = 0;
612   while (SQLITE_ROW ==
613          sqlite3_step (plugin->get_closest_stmt))
614   {
615     if (GNUNET_OK !=
616         GNUNET_SQ_extract_result (plugin->get_closest_stmt,
617                                   rs))
618     {
619       GNUNET_break (0);
620       break;
621     }
622     if (0 != psize % sizeof (struct GNUNET_PeerIdentity))
623     {
624       GNUNET_break (0);
625       psize = 0;
626       path = NULL;
627     }
628     psize /= sizeof (struct GNUNET_PeerIdentity);
629     cnt++;
630     LOG (GNUNET_ERROR_TYPE_DEBUG,
631          "Found %u-byte result at %s when processing GET_CLOSE\n",
632          (unsigned int) size,
633          GNUNET_h2s (&hc));
634     if (GNUNET_OK != iter (iter_cls,
635                            &hc,
636                            size,
637                            dat,
638                            type,
639                            exp,
640                            psize,
641                            path))
642     {
643       GNUNET_SQ_cleanup_result (rs);
644       break;
645     }
646     GNUNET_SQ_cleanup_result (rs);
647   }
648   GNUNET_SQ_reset (plugin->dbh,
649                    plugin->get_closest_stmt);
650   return cnt;
651 }
652
653
654 /**
655  * Entry point for the plugin.
656  *
657  * @param cls closure (the `struct GNUNET_DATACACHE_PluginEnvironment`)
658  * @return the plugin's closure (our `struct Plugin`)
659  */
660 void *
661 libgnunet_plugin_datacache_sqlite_init (void *cls)
662 {
663   struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
664   struct GNUNET_DATACACHE_PluginFunctions *api;
665   struct Plugin *plugin;
666   char *fn;
667   char *fn_utf8;
668   sqlite3 *dbh;
669   char *emsg;
670
671   if (GNUNET_YES ==
672       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
673                                             "datacache-sqlite",
674                                             "IN_MEMORY"))
675   {
676     if (SQLITE_OK != sqlite3_open (":memory:", &dbh))
677       return NULL;
678     fn_utf8 = NULL;
679   }
680   else
681   {
682     fn = GNUNET_DISK_mktemp ("gnunet-datacache");
683     if (fn == NULL)
684       {
685         GNUNET_break (0);
686         return NULL;
687       }
688     /* fn should be UTF-8-encoded. If it isn't, it's a bug. */
689     fn_utf8 = GNUNET_strdup (fn);
690     if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
691     {
692       GNUNET_free (fn);
693       GNUNET_free (fn_utf8);
694       return NULL;
695     }
696     GNUNET_free (fn);
697   }
698
699   SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
700   SQLITE3_EXEC (dbh, "PRAGMA locking_mode=EXCLUSIVE");
701   SQLITE3_EXEC (dbh, "PRAGMA journal_mode=OFF");
702   SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
703   SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
704   if (GNUNET_YES ==
705       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
706                                             "datacache-sqlite",
707                                             "IN_MEMORY"))
708     SQLITE3_EXEC (dbh, "PRAGMA sqlite_temp_store=3");
709
710   SQLITE3_EXEC (dbh,
711                 "CREATE TABLE ds090 (" "  type INTEGER NOT NULL DEFAULT 0,"
712                 "  expire INTEGER NOT NULL DEFAULT 0,"
713                 "  key BLOB NOT NULL DEFAULT '',"
714                 "  value BLOB NOT NULL DEFAULT '',"
715                 "  path BLOB DEFAULT '')");
716   SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
717   SQLITE3_EXEC (dbh, "CREATE INDEX idx_expire ON ds090 (expire)");
718   plugin = GNUNET_new (struct Plugin);
719   plugin->env = env;
720   plugin->dbh = dbh;
721   plugin->fn = fn_utf8;
722
723   if ( (SQLITE_OK !=
724         sq_prepare (plugin->dbh,
725                     "INSERT INTO ds090 (type, expire, key, value, path) "
726                     "VALUES (?, ?, ?, ?, ?)",
727                     &plugin->insert_stmt)) ||
728        (SQLITE_OK !=
729         sq_prepare (plugin->dbh,
730                     "SELECT count(*) FROM ds090 "
731                     "WHERE key=? AND type=? AND expire >= ?",
732                     &plugin->get_count_stmt)) ||
733        (SQLITE_OK !=
734         sq_prepare (plugin->dbh,
735                     "SELECT value,expire,path FROM ds090 "
736                     "WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET ?",
737                     &plugin->get_stmt)) ||
738        (SQLITE_OK !=
739         sq_prepare (plugin->dbh,
740                     "SELECT _ROWID_,key,value FROM ds090 ORDER BY expire ASC LIMIT 1",
741                     &plugin->del_select_stmt)) ||
742        (SQLITE_OK !=
743         sq_prepare (plugin->dbh,
744                     "DELETE FROM ds090 WHERE _ROWID_=?",
745                     &plugin->del_stmt)) ||
746        (SQLITE_OK !=
747         sq_prepare (plugin->dbh,
748                     "SELECT value,expire,path,key,type FROM ds090 "
749                     "ORDER BY key LIMIT 1 OFFSET ?",
750                     &plugin->get_random_stmt)) ||
751        (SQLITE_OK !=
752         sq_prepare (plugin->dbh,
753                     "SELECT value,expire,path,type,key FROM ds090 "
754                     "WHERE key>=? AND expire >= ? ORDER BY KEY ASC LIMIT ?",
755                     &plugin->get_closest_stmt))
756        )
757   {
758     LOG_SQLITE (plugin->dbh,
759                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
760                 "sq_prepare");
761     (void) sqlite3_close (plugin->dbh);
762     GNUNET_free (plugin);
763     return NULL;
764   }
765
766   api = GNUNET_new (struct GNUNET_DATACACHE_PluginFunctions);
767   api->cls = plugin;
768   api->get = &sqlite_plugin_get;
769   api->put = &sqlite_plugin_put;
770   api->del = &sqlite_plugin_del;
771   api->get_random = &sqlite_plugin_get_random;
772   api->get_closest = &sqlite_plugin_get_closest;
773   LOG (GNUNET_ERROR_TYPE_INFO,
774        "Sqlite datacache running\n");
775   return api;
776 }
777
778
779 /**
780  * Exit point from the plugin.
781  *
782  * @param cls closure (our `struct Plugin`)
783  * @return NULL
784  */
785 void *
786 libgnunet_plugin_datacache_sqlite_done (void *cls)
787 {
788   struct GNUNET_DATACACHE_PluginFunctions *api = cls;
789   struct Plugin *plugin = api->cls;
790   int result;
791
792 #if SQLITE_VERSION_NUMBER >= 3007000
793   sqlite3_stmt *stmt;
794 #endif
795
796 #if !WINDOWS || defined(__CYGWIN__)
797   if ( (NULL != plugin->fn) &&
798        (0 != UNLINK (plugin->fn)) )
799     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
800                        "unlink",
801                        plugin->fn);
802   GNUNET_free_non_null (plugin->fn);
803 #endif
804   sqlite3_finalize (plugin->insert_stmt);
805   sqlite3_finalize (plugin->get_count_stmt);
806   sqlite3_finalize (plugin->get_stmt);
807   sqlite3_finalize (plugin->del_select_stmt);
808   sqlite3_finalize (plugin->del_stmt);
809   sqlite3_finalize (plugin->get_random_stmt);
810   sqlite3_finalize (plugin->get_closest_stmt);
811   result = sqlite3_close (plugin->dbh);
812 #if SQLITE_VERSION_NUMBER >= 3007000
813   if (SQLITE_BUSY == result)
814   {
815     LOG (GNUNET_ERROR_TYPE_WARNING,
816          _("Tried to close sqlite without finalizing all prepared statements.\n"));
817     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
818     while (NULL != stmt)
819     {
820       result = sqlite3_finalize (stmt);
821       if (result != SQLITE_OK)
822         LOG (GNUNET_ERROR_TYPE_WARNING,
823              "Failed to close statement %p: %d\n",
824              stmt,
825              result);
826       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
827     }
828     result = sqlite3_close (plugin->dbh);
829   }
830 #endif
831   if (SQLITE_OK != result)
832     LOG_SQLITE (plugin->dbh,
833                 GNUNET_ERROR_TYPE_ERROR,
834                 "sqlite3_close");
835
836 #if WINDOWS && !defined(__CYGWIN__)
837   if ( (NULL != plugin->fn) &&
838        (0 != UNLINK (plugin->fn)) )
839     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
840                        "unlink",
841                        plugin->fn);
842   GNUNET_free_non_null (plugin->fn);
843 #endif
844   GNUNET_free (plugin);
845   GNUNET_free (api);
846   return NULL;
847 }
848
849
850
851 /* end of plugin_datacache_sqlite.c */