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