include plugin in gnunet-transport output
[oweals/gnunet.git] / src / datastore / plugin_datastore_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * (C) 2009, 2011 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 datastore/plugin_datastore_sqlite.c
23  * @brief sqlite-based datastore backend
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_datastore_plugin.h"
29 #include <sqlite3.h>
30
31 /**
32  * Enable or disable logging debug messages.
33  */
34 #define DEBUG_SQLITE GNUNET_EXTRA_LOGGING
35
36 /**
37  * We allocate items on the stack at times.  To prevent a stack
38  * overflow, we impose a limit on the maximum size for the data per
39  * item.  64k should be enough.
40  */
41 #define MAX_ITEM_SIZE 65536
42
43 /**
44  * After how many ms "busy" should a DB operation fail for good?
45  * A low value makes sure that we are more responsive to requests
46  * (especially PUTs).  A high value guarantees a higher success
47  * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
48  *
49  * The default value of 250ms should ensure that users do not experience
50  * huge latencies while at the same time allowing operations to succeed
51  * with reasonable probability.
52  */
53 #define BUSY_TIMEOUT_MS 250
54
55
56 /**
57  * Log an error message at log-level 'level' that indicates
58  * a failure of the command 'cmd' on file 'filename'
59  * with the message given by strerror(errno).
60  */
61 #define LOG_SQLITE(db, msg, level, cmd) do { GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); if (msg != NULL) GNUNET_asprintf(msg, _("`%s' failed at %s:%u with error: %s"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
62
63
64
65 /**
66  * Context for all functions in this plugin.
67  */
68 struct Plugin
69 {
70   /**
71    * Our execution environment.
72    */
73   struct GNUNET_DATASTORE_PluginEnvironment *env;
74
75   /**
76    * Database filename.
77    */
78   char *fn;
79
80   /**
81    * Native SQLite database handle.
82    */
83   sqlite3 *dbh;
84
85   /**
86    * Precompiled SQL for deletion.
87    */
88   sqlite3_stmt *delRow;
89
90   /**
91    * Precompiled SQL for update.
92    */
93   sqlite3_stmt *updPrio;
94
95   /**
96    * Get maximum repl value in database.
97    */
98   sqlite3_stmt *maxRepl;
99
100   /**
101    * Precompiled SQL for replication decrement.
102    */
103   sqlite3_stmt *updRepl;
104
105   /**
106    * Precompiled SQL for replication selection.
107    */
108   sqlite3_stmt *selRepl;
109
110   /**
111    * Precompiled SQL for expiration selection.
112    */
113   sqlite3_stmt *selExpi;
114
115   /**
116    * Precompiled SQL for expiration selection.
117    */
118   sqlite3_stmt *selZeroAnon;
119
120   /**
121    * Precompiled SQL for insertion.
122    */
123   sqlite3_stmt *insertContent;
124
125   /**
126    * Should the database be dropped on shutdown?
127    */
128   int drop_on_shutdown;
129
130 };
131
132
133 /**
134  * @brief Prepare a SQL statement
135  *
136  * @param dbh handle to the database
137  * @param zSql SQL statement, UTF-8 encoded
138  * @param ppStmt set to the prepared statement
139  * @return 0 on success
140  */
141 static int
142 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
143 {
144   char *dummy;
145   int result;
146
147   result =
148       sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
149                           (const char **) &dummy);
150 #if DEBUG_SQLITE && 0
151   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
152                    "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
153 #endif
154   return result;
155 }
156
157
158 /**
159  * Create our database indices.
160  *
161  * @param dbh handle to the database
162  */
163 static void
164 create_indices (sqlite3 * dbh)
165 {
166   /* create indices */
167   if ((SQLITE_OK !=
168        sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)",
169                      NULL, NULL, NULL)) ||
170       (SQLITE_OK !=
171        sqlite3_exec (dbh,
172                      "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)",
173                      NULL, NULL, NULL)) ||
174       (SQLITE_OK !=
175        sqlite3_exec (dbh,
176                      "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)",
177                      NULL, NULL, NULL)) ||
178       (SQLITE_OK !=
179        sqlite3_exec (dbh,
180                      "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
181                      NULL, NULL, NULL)) ||
182       (SQLITE_OK !=
183        sqlite3_exec (dbh,
184                      "CREATE INDEX IF NOT EXISTS idx_anon_type_hash ON gn090 (anonLevel ASC,type,hash)",
185                      NULL, NULL, NULL)) ||
186       (SQLITE_OK !=
187        sqlite3_exec (dbh,
188                      "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire ASC)",
189                      NULL, NULL, NULL)) ||
190       (SQLITE_OK !=
191        sqlite3_exec (dbh,
192                      "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
193                      NULL, NULL, NULL)) ||
194       (SQLITE_OK !=
195        sqlite3_exec (dbh,
196                      "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
197                      NULL, NULL, NULL)))
198     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
199                      "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
200 }
201
202
203 #if 0
204 #define CHECK(a) GNUNET_break(a)
205 #define ENULL NULL
206 #else
207 #define ENULL &e
208 #define ENULL_DEFINED 1
209 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
210 #endif
211
212
213 /**
214  * Initialize the database connections and associated
215  * data structures (create tables and indices
216  * as needed as well).
217  *
218  * @param cfg our configuration
219  * @param plugin the plugin context (state for this module)
220  * @return GNUNET_OK on success
221  */
222 static int
223 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
224                 struct Plugin *plugin)
225 {
226   sqlite3_stmt *stmt;
227   char *afsdir;
228
229 #if ENULL_DEFINED
230   char *e;
231 #endif
232
233   if (GNUNET_OK !=
234       GNUNET_CONFIGURATION_get_value_filename (cfg, "datastore-sqlite",
235                                                "FILENAME", &afsdir))
236   {
237     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
238                      _
239                      ("Option `%s' in section `%s' missing in configuration!\n"),
240                      "FILENAME", "datastore-sqlite");
241     return GNUNET_SYSERR;
242   }
243   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
244   {
245     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
246     {
247       GNUNET_break (0);
248       GNUNET_free (afsdir);
249       return GNUNET_SYSERR;
250     }
251     /* database is new or got deleted, reset payload to zero! */
252     plugin->env->duc (plugin->env->cls, 0);
253   }
254 #ifdef ENABLE_NLS
255   plugin->fn =
256       GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
257 #else
258   plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8");       /* good luck */
259 #endif
260   GNUNET_free (afsdir);
261
262   /* Open database and precompile statements */
263   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
264   {
265     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
266                      _("Unable to initialize SQLite: %s.\n"),
267                      sqlite3_errmsg (plugin->dbh));
268     return GNUNET_SYSERR;
269   }
270   CHECK (SQLITE_OK ==
271          sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
272                        ENULL));
273   CHECK (SQLITE_OK ==
274          sqlite3_exec (plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL,
275                        ENULL));
276   CHECK (SQLITE_OK ==
277          sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
278                        ENULL));
279   CHECK (SQLITE_OK ==
280          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
281                        NULL, ENULL));
282   CHECK (SQLITE_OK ==
283          sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
284                        ENULL));
285   CHECK (SQLITE_OK ==
286          sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
287                        ENULL));
288   CHECK (SQLITE_OK ==
289          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
290                        ENULL));
291
292   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
293
294
295   /* We have to do it here, because otherwise precompiling SQL might fail */
296   CHECK (SQLITE_OK ==
297          sq_prepare (plugin->dbh,
298                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
299                      &stmt));
300   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
301       (sqlite3_exec
302        (plugin->dbh,
303         "CREATE TABLE gn090 (" "  repl INT4 NOT NULL DEFAULT 0,"
304         "  type INT4 NOT NULL DEFAULT 0," "  prio INT4 NOT NULL DEFAULT 0,"
305         "  anonLevel INT4 NOT NULL DEFAULT 0,"
306         "  expire INT8 NOT NULL DEFAULT 0," "  rvalue INT8 NOT NULL,"
307         "  hash TEXT NOT NULL DEFAULT ''," "  vhash TEXT NOT NULL DEFAULT '',"
308         "  value BLOB NOT NULL DEFAULT '')", NULL, NULL, NULL) != SQLITE_OK))
309   {
310     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
311     sqlite3_finalize (stmt);
312     return GNUNET_SYSERR;
313   }
314   sqlite3_finalize (stmt);
315   create_indices (plugin->dbh);
316
317   if ((sq_prepare
318        (plugin->dbh,
319         "UPDATE gn090 "
320         "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
321         &plugin->updPrio) != SQLITE_OK) ||
322       (sq_prepare
323        (plugin->dbh,
324         "UPDATE gn090 " "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
325         &plugin->updRepl) != SQLITE_OK) ||
326       (sq_prepare
327        (plugin->dbh,
328         "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
329 #if SQLITE_VERSION_NUMBER >= 3007000
330         "INDEXED BY idx_repl_rvalue "
331 #endif
332         "WHERE repl=?2 AND " " (rvalue>=?1 OR "
333         "  NOT EXISTS (SELECT 1 FROM gn090 "
334 #if SQLITE_VERSION_NUMBER >= 3007000
335         "INDEXED BY idx_repl_rvalue "
336 #endif
337         "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
338         "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
339       (sq_prepare (plugin->dbh, "SELECT MAX(repl) FROM gn090"
340 #if SQLITE_VERSION_NUMBER >= 3007000
341                    " INDEXED BY idx_repl_rvalue"
342 #endif
343                    "", &plugin->maxRepl) != SQLITE_OK) ||
344       (sq_prepare
345        (plugin->dbh,
346         "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
347 #if SQLITE_VERSION_NUMBER >= 3007000
348         "INDEXED BY idx_expire "
349 #endif
350         "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
351         "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
352       (sq_prepare
353        (plugin->dbh,
354         "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
355 #if SQLITE_VERSION_NUMBER >= 3007000
356         "INDEXED BY idx_anon_type_hash "
357 #endif
358         "WHERE (anonLevel = 0 AND type=?1) "
359         "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
360         &plugin->selZeroAnon) != SQLITE_OK) ||
361       (sq_prepare
362        (plugin->dbh,
363         "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
364         "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
365         &plugin->insertContent) != SQLITE_OK) ||
366       (sq_prepare
367        (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
368         &plugin->delRow) != SQLITE_OK))
369   {
370     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
371     return GNUNET_SYSERR;
372   }
373
374   return GNUNET_OK;
375 }
376
377
378 /**
379  * Shutdown database connection and associate data
380  * structures.
381  * @param plugin the plugin context (state for this module)
382  */
383 static void
384 database_shutdown (struct Plugin *plugin)
385 {
386   int result;
387
388 #if SQLITE_VERSION_NUMBER >= 3007000
389   sqlite3_stmt *stmt;
390 #endif
391
392   if (plugin->delRow != NULL)
393     sqlite3_finalize (plugin->delRow);
394   if (plugin->updPrio != NULL)
395     sqlite3_finalize (plugin->updPrio);
396   if (plugin->updRepl != NULL)
397     sqlite3_finalize (plugin->updRepl);
398   if (plugin->selRepl != NULL)
399     sqlite3_finalize (plugin->selRepl);
400   if (plugin->maxRepl != NULL)
401     sqlite3_finalize (plugin->maxRepl);
402   if (plugin->selExpi != NULL)
403     sqlite3_finalize (plugin->selExpi);
404   if (plugin->selZeroAnon != NULL)
405     sqlite3_finalize (plugin->selZeroAnon);
406   if (plugin->insertContent != NULL)
407     sqlite3_finalize (plugin->insertContent);
408   result = sqlite3_close (plugin->dbh);
409 #if SQLITE_VERSION_NUMBER >= 3007000
410   if (result == SQLITE_BUSY)
411   {
412     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
413                      _
414                      ("Tried to close sqlite without finalizing all prepared statements.\n"));
415     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
416     while (stmt != NULL)
417     {
418 #if DEBUG_SQLITE
419       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
420                        "Closing statement %p\n", stmt);
421 #endif
422       result = sqlite3_finalize (stmt);
423 #if DEBUG_SQLITE
424       if (result != SQLITE_OK)
425         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
426                          "Failed to close statement %p: %d\n", stmt, result);
427 #endif
428       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
429     }
430     result = sqlite3_close (plugin->dbh);
431   }
432 #endif
433   if (SQLITE_OK != result)
434     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
435
436   GNUNET_free_non_null (plugin->fn);
437 }
438
439
440 /**
441  * Delete the database entry with the given
442  * row identifier.
443  *
444  * @param plugin the plugin context (state for this module)
445  * @param rid the ID of the row to delete
446  */
447 static int
448 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
449 {
450   if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
451   {
452     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
453                 "sqlite3_bind_XXXX");
454     if (SQLITE_OK != sqlite3_reset (plugin->delRow))
455       LOG_SQLITE (plugin, NULL,
456                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
457                   "sqlite3_reset");
458     return GNUNET_SYSERR;
459   }
460   if (SQLITE_DONE != sqlite3_step (plugin->delRow))
461   {
462     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
463                 "sqlite3_step");
464     if (SQLITE_OK != sqlite3_reset (plugin->delRow))
465       LOG_SQLITE (plugin, NULL,
466                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
467                   "sqlite3_reset");
468     return GNUNET_SYSERR;
469   }
470   if (SQLITE_OK != sqlite3_reset (plugin->delRow))
471     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
472                 "sqlite3_reset");
473   return GNUNET_OK;
474 }
475
476
477 /**
478  * Store an item in the datastore.
479  *
480  * @param cls closure
481  * @param key key for the item
482  * @param size number of bytes in data
483  * @param data content stored
484  * @param type type of the content
485  * @param priority priority of the content
486  * @param anonymity anonymity-level for the content
487  * @param replication replication-level for the content
488  * @param expiration expiration time for the content
489  * @param msg set to an error message
490  * @return GNUNET_OK on success
491  */
492 static int
493 sqlite_plugin_put (void *cls, const GNUNET_HashCode * key, uint32_t size,
494                    const void *data, enum GNUNET_BLOCK_Type type,
495                    uint32_t priority, uint32_t anonymity, uint32_t replication,
496                    struct GNUNET_TIME_Absolute expiration, char **msg)
497 {
498   struct Plugin *plugin = cls;
499   int n;
500   int ret;
501   sqlite3_stmt *stmt;
502   GNUNET_HashCode vhash;
503   uint64_t rvalue;
504
505   if (size > MAX_ITEM_SIZE)
506     return GNUNET_SYSERR;
507 #if DEBUG_SQLITE
508   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
509                    "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
510                    type, GNUNET_h2s (key), priority,
511                    (unsigned long long)
512                    GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
513                    (long long) expiration.abs_value);
514 #endif
515   GNUNET_CRYPTO_hash (data, size, &vhash);
516   stmt = plugin->insertContent;
517   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
518   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
519       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
520       (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
521       (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
522       (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
523       (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
524       (SQLITE_OK !=
525        sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
526                           SQLITE_TRANSIENT)) ||
527       (SQLITE_OK !=
528        sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
529                           SQLITE_TRANSIENT)) ||
530       (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
531   {
532     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
533                 "sqlite3_bind_XXXX");
534     if (SQLITE_OK != sqlite3_reset (stmt))
535       LOG_SQLITE (plugin, NULL,
536                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
537                   "sqlite3_reset");
538     return GNUNET_SYSERR;
539   }
540   n = sqlite3_step (stmt);
541   switch (n)
542   {
543   case SQLITE_DONE:
544     plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
545 #if DEBUG_SQLITE
546     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
547                      "Stored new entry (%u bytes)\n",
548                      size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
549 #endif
550     ret = GNUNET_OK;
551     break;
552   case SQLITE_BUSY:
553     GNUNET_break (0);
554     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
555                 "sqlite3_step");
556     ret = GNUNET_SYSERR;
557     break;
558   default:
559     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
560                 "sqlite3_step");
561     if (SQLITE_OK != sqlite3_reset (stmt))
562       LOG_SQLITE (plugin, NULL,
563                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
564                   "sqlite3_reset");
565     database_shutdown (plugin);
566     database_setup (plugin->env->cfg, plugin);
567     return GNUNET_SYSERR;
568   }
569   if (SQLITE_OK != sqlite3_reset (stmt))
570     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
571                 "sqlite3_reset");
572   return ret;
573 }
574
575
576 /**
577  * Update the priority for a particular key in the datastore.  If
578  * the expiration time in value is different than the time found in
579  * the datastore, the higher value should be kept.  For the
580  * anonymity level, the lower value is to be used.  The specified
581  * priority should be added to the existing priority, ignoring the
582  * priority in value.
583  *
584  * Note that it is possible for multiple values to match this put.
585  * In that case, all of the respective values are updated.
586  *
587  * @param cls the plugin context (state for this module)
588  * @param uid unique identifier of the datum
589  * @param delta by how much should the priority
590  *     change?  If priority + delta < 0 the
591  *     priority should be set to 0 (never go
592  *     negative).
593  * @param expire new expiration time should be the
594  *     MAX of any existing expiration time and
595  *     this value
596  * @param msg set to an error message
597  * @return GNUNET_OK on success
598  */
599 static int
600 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
601                       struct GNUNET_TIME_Absolute expire, char **msg)
602 {
603   struct Plugin *plugin = cls;
604   int n;
605
606   if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
607       (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
608       || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
609   {
610     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
611                 "sqlite3_bind_XXXX");
612     if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
613       LOG_SQLITE (plugin, NULL,
614                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
615                   "sqlite3_reset");
616     return GNUNET_SYSERR;
617
618   }
619   n = sqlite3_step (plugin->updPrio);
620   if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
621     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
622                 "sqlite3_reset");
623   switch (n)
624   {
625   case SQLITE_DONE:
626 #if DEBUG_SQLITE
627     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
628 #endif
629     return GNUNET_OK;
630   case SQLITE_BUSY:
631     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
632                 "sqlite3_step");
633     return GNUNET_NO;
634   default:
635     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
636                 "sqlite3_step");
637     return GNUNET_SYSERR;
638   }
639 }
640
641
642 /**
643  * Execute statement that gets a row and call the callback
644  * with the result.  Resets the statement afterwards.
645  *
646  * @param plugin the plugin
647  * @param stmt the statement
648  * @param proc processor to call
649  * @param proc_cls closure for 'proc'
650  */
651 static void
652 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
653              PluginDatumProcessor proc, void *proc_cls)
654 {
655   int n;
656   struct GNUNET_TIME_Absolute expiration;
657   unsigned long long rowid;
658   unsigned int size;
659   int ret;
660
661   n = sqlite3_step (stmt);
662   switch (n)
663   {
664   case SQLITE_ROW:
665     size = sqlite3_column_bytes (stmt, 5);
666     rowid = sqlite3_column_int64 (stmt, 6);
667     if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
668     {
669       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
670                        _
671                        ("Invalid data in database.  Trying to fix (by deletion).\n"));
672       if (SQLITE_OK != sqlite3_reset (stmt))
673         LOG_SQLITE (plugin, NULL,
674                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
675                     "sqlite3_reset");
676       if (GNUNET_OK == delete_by_rowid (plugin, rowid))
677         plugin->env->duc (plugin->env->cls,
678                           -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
679       break;
680     }
681     expiration.abs_value = sqlite3_column_int64 (stmt, 3);
682 #if DEBUG_SQLITE
683     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
684                      "Found reply in database with expiration %llu\n",
685                      (unsigned long long) expiration.abs_value);
686 #endif
687     ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
688                 size, sqlite3_column_blob (stmt, 5) /* data */ ,
689                 sqlite3_column_int (stmt, 0) /* type */ ,
690                 sqlite3_column_int (stmt, 1) /* priority */ ,
691                 sqlite3_column_int (stmt, 2) /* anonymity */ ,
692                 expiration, rowid);
693     if (SQLITE_OK != sqlite3_reset (stmt))
694       LOG_SQLITE (plugin, NULL,
695                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
696                   "sqlite3_reset");
697     if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
698       plugin->env->duc (plugin->env->cls,
699                         -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
700     return;
701   case SQLITE_DONE:
702     /* database must be empty */
703     if (SQLITE_OK != sqlite3_reset (stmt))
704       LOG_SQLITE (plugin, NULL,
705                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
706                   "sqlite3_reset");
707     break;
708   case SQLITE_BUSY:
709   case SQLITE_ERROR:
710   case SQLITE_MISUSE:
711   default:
712     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
713                 "sqlite3_step");
714     if (SQLITE_OK != sqlite3_reset (stmt))
715       LOG_SQLITE (plugin, NULL,
716                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
717                   "sqlite3_reset");
718     GNUNET_break (0);
719     database_shutdown (plugin);
720     database_setup (plugin->env->cfg, plugin);
721     break;
722   }
723   if (SQLITE_OK != sqlite3_reset (stmt))
724     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
725                 "sqlite3_reset");
726   proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
727 }
728
729
730
731 /**
732  * Select a subset of the items in the datastore and call
733  * the given processor for the item.
734  *
735  * @param cls our plugin context
736  * @param offset offset of the result (modulo num-results);
737  *               specific ordering does not matter for the offset
738  * @param type entries of which type should be considered?
739  *        Use 0 for any type.
740  * @param proc function to call on each matching value;
741  *        will be called once with a NULL value at the end
742  * @param proc_cls closure for proc
743  */
744 static void
745 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
746                                   enum GNUNET_BLOCK_Type type,
747                                   PluginDatumProcessor proc, void *proc_cls)
748 {
749   struct Plugin *plugin = cls;
750   sqlite3_stmt *stmt;
751
752   GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
753   stmt = plugin->selZeroAnon;
754   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
755       (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
756   {
757     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
758                 "sqlite3_bind_XXXX");
759     if (SQLITE_OK != sqlite3_reset (stmt))
760       LOG_SQLITE (plugin, NULL,
761                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
762                   "sqlite3_reset");
763     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
764     return;
765   }
766   execute_get (plugin, stmt, proc, proc_cls);
767 }
768
769
770
771 /**
772  * Get results for a particular key in the datastore.
773  *
774  * @param cls closure
775  * @param offset offset (mod count).
776  * @param key key to match, never NULL
777  * @param vhash hash of the value, maybe NULL (to
778  *        match all values that have the right key).
779  *        Note that for DBlocks there is no difference
780  *        betwen key and vhash, but for other blocks
781  *        there may be!
782  * @param type entries of which type are relevant?
783  *     Use 0 for any type.
784  * @param proc function to call on each matching value;
785  *        will be called once with a NULL value at the end
786  * @param proc_cls closure for proc
787  */
788 static void
789 sqlite_plugin_get_key (void *cls, uint64_t offset, const GNUNET_HashCode * key,
790                        const GNUNET_HashCode * vhash,
791                        enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
792                        void *proc_cls)
793 {
794   struct Plugin *plugin = cls;
795   int ret;
796   int total;
797   int limit_off;
798   unsigned int sqoff;
799   sqlite3_stmt *stmt;
800   char scratch[256];
801
802   GNUNET_assert (proc != NULL);
803   GNUNET_assert (key != NULL);
804   GNUNET_snprintf (scratch, sizeof (scratch),
805                    "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
806                    vhash == NULL ? "" : " AND vhash=?",
807                    type == 0 ? "" : " AND type=?");
808   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
809   {
810     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
811                 "sqlite_prepare");
812     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
813     return;
814   }
815   sqoff = 1;
816   ret =
817       sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
818                          SQLITE_TRANSIENT);
819   if ((vhash != NULL) && (ret == SQLITE_OK))
820     ret =
821         sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
822                            SQLITE_TRANSIENT);
823   if ((type != 0) && (ret == SQLITE_OK))
824     ret = sqlite3_bind_int (stmt, sqoff++, type);
825   if (SQLITE_OK != ret)
826   {
827     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
828     sqlite3_finalize (stmt);
829     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
830     return;
831   }
832   ret = sqlite3_step (stmt);
833   if (ret != SQLITE_ROW)
834   {
835     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
836                 "sqlite_step");
837     sqlite3_finalize (stmt);
838     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
839     return;
840   }
841   total = sqlite3_column_int (stmt, 0);
842   sqlite3_finalize (stmt);
843   if (0 == total)
844   {
845     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
846     return;
847   }
848   limit_off = (int) (offset % total);
849   if (limit_off < 0)
850     limit_off += total;
851   GNUNET_snprintf (scratch, sizeof (scratch),
852                    "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
853                    "FROM gn090 WHERE hash=?%s%s "
854                    "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
855                    vhash == NULL ? "" : " AND vhash=?",
856                    type == 0 ? "" : " AND type=?");
857   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
858   {
859     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
860                 "sqlite_prepare");
861     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
862     return;
863   }
864   sqoff = 1;
865   ret =
866       sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
867                          SQLITE_TRANSIENT);
868   if ((vhash != NULL) && (ret == SQLITE_OK))
869     ret =
870         sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
871                            SQLITE_TRANSIENT);
872   if ((type != 0) && (ret == SQLITE_OK))
873     ret = sqlite3_bind_int (stmt, sqoff++, type);
874   if (ret == SQLITE_OK)
875     ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
876   if (ret != SQLITE_OK)
877   {
878     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
879                 "sqlite_bind");
880     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
881     return;
882   }
883   execute_get (plugin, stmt, proc, proc_cls);
884   sqlite3_finalize (stmt);
885 }
886
887
888
889 /**
890  * Context for 'repl_proc' function.
891  */
892 struct ReplCtx
893 {
894
895   /**
896    * Function to call for the result (or the NULL).
897    */
898   PluginDatumProcessor proc;
899
900   /**
901    * Closure for proc.
902    */
903   void *proc_cls;
904
905   /**
906    * UID to use.
907    */
908   uint64_t uid;
909
910   /**
911    * Yes if UID was set.
912    */
913   int have_uid;
914 };
915
916
917 /**
918  * Wrapper for the processor for 'sqlite_plugin_replication_get'.
919  * Decrements the replication counter and calls the original
920  * processor.
921  *
922  * @param cls closure
923  * @param key key for the content
924  * @param size number of bytes in data
925  * @param data content stored
926  * @param type type of the content
927  * @param priority priority of the content
928  * @param anonymity anonymity-level for the content
929  * @param expiration expiration time for the content
930  * @param uid unique identifier for the datum;
931  *        maybe 0 if no unique identifier is available
932  *
933  * @return GNUNET_OK for normal return,
934  *         GNUNET_NO to delete the item
935  */
936 static int
937 repl_proc (void *cls, const GNUNET_HashCode * key, uint32_t size,
938            const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
939            uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
940            uint64_t uid)
941 {
942   struct ReplCtx *rc = cls;
943   int ret;
944
945   ret =
946       rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
947                 expiration, uid);
948   if (key != NULL)
949   {
950     rc->uid = uid;
951     rc->have_uid = GNUNET_YES;
952   }
953   return ret;
954 }
955
956
957 /**
958  * Get a random item for replication.  Returns a single random item
959  * from those with the highest replication counters.  The item's
960  * replication counter is decremented by one IF it was positive before.
961  * Call 'proc' with all values ZERO or NULL if the datastore is empty.
962  *
963  * @param cls closure
964  * @param proc function to call the value (once only).
965  * @param proc_cls closure for proc
966  */
967 static void
968 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
969                                void *proc_cls)
970 {
971   struct Plugin *plugin = cls;
972   struct ReplCtx rc;
973   uint64_t rvalue;
974   uint32_t repl;
975   sqlite3_stmt *stmt;
976
977 #if DEBUG_SQLITE
978   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
979                    "Getting random block based on replication order.\n");
980 #endif
981   rc.have_uid = GNUNET_NO;
982   rc.proc = proc;
983   rc.proc_cls = proc_cls;
984   stmt = plugin->maxRepl;
985   if (SQLITE_ROW != sqlite3_step (stmt))
986   {
987     if (SQLITE_OK != sqlite3_reset (stmt))
988       LOG_SQLITE (plugin, NULL,
989                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
990                   "sqlite3_reset");
991     /* DB empty */
992     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
993     return;
994   }
995   repl = sqlite3_column_int (stmt, 0);
996   if (SQLITE_OK != sqlite3_reset (stmt))
997     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
998                 "sqlite3_reset");
999   stmt = plugin->selRepl;
1000   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1001   if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1002   {
1003     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1004                 "sqlite3_bind_XXXX");
1005     if (SQLITE_OK != sqlite3_reset (stmt))
1006       LOG_SQLITE (plugin, NULL,
1007                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1008                   "sqlite3_reset");
1009     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1010     return;
1011   }
1012   if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1013   {
1014     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1015                 "sqlite3_bind_XXXX");
1016     if (SQLITE_OK != sqlite3_reset (stmt))
1017       LOG_SQLITE (plugin, NULL,
1018                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1019                   "sqlite3_reset");
1020     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1021     return;
1022   }
1023   execute_get (plugin, stmt, &repl_proc, &rc);
1024   if (GNUNET_YES == rc.have_uid)
1025   {
1026     if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1027     {
1028       LOG_SQLITE (plugin, NULL,
1029                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1030                   "sqlite3_bind_XXXX");
1031       if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1032         LOG_SQLITE (plugin, NULL,
1033                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1034                     "sqlite3_reset");
1035       return;
1036     }
1037     if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1038       LOG_SQLITE (plugin, NULL,
1039                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1040                   "sqlite3_step");
1041     if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1042       LOG_SQLITE (plugin, NULL,
1043                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1044                   "sqlite3_reset");
1045   }
1046 }
1047
1048
1049
1050 /**
1051  * Get a random item that has expired or has low priority.
1052  * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1053  *
1054  * @param cls closure
1055  * @param proc function to call the value (once only).
1056  * @param proc_cls closure for proc
1057  */
1058 static void
1059 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1060                               void *proc_cls)
1061 {
1062   struct Plugin *plugin = cls;
1063   sqlite3_stmt *stmt;
1064   struct GNUNET_TIME_Absolute now;
1065
1066 #if DEBUG_SQLITE
1067   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1068                    "Getting random block based on expiration and priority order.\n");
1069 #endif
1070   now = GNUNET_TIME_absolute_get ();
1071   stmt = plugin->selExpi;
1072   if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1073   {
1074     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1075                 "sqlite3_bind_XXXX");
1076     if (SQLITE_OK != sqlite3_reset (stmt))
1077       LOG_SQLITE (plugin, NULL,
1078                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1079                   "sqlite3_reset");
1080     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1081     return;
1082   }
1083   execute_get (plugin, stmt, proc, proc_cls);
1084 }
1085
1086
1087
1088 /**
1089  * Get all of the keys in the datastore.
1090  *
1091  * @param cls closure
1092  * @param proc function to call on each key
1093  * @param proc_cls closure for proc
1094  */
1095 static void
1096 sqlite_plugin_get_keys (void *cls,
1097                         PluginKeyProcessor proc,
1098                         void *proc_cls)
1099 {
1100   struct Plugin *plugin = cls;
1101   const GNUNET_HashCode *key;
1102   sqlite3_stmt *stmt;
1103   int ret;
1104
1105   GNUNET_assert (proc != NULL);
1106   if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1107   {
1108     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1109                 "sqlite_prepare");
1110     return;
1111   }
1112   while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1113   {
1114     key = sqlite3_column_blob (stmt, 1);
1115     if (sizeof (GNUNET_HashCode) == sqlite3_column_bytes (stmt, 1))
1116       proc (proc_cls, key, 1);
1117   }
1118   if (SQLITE_DONE != ret)
1119     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1120   sqlite3_finalize (stmt);
1121 }
1122
1123
1124 /**
1125  * Drop database.
1126  *
1127  * @param cls our plugin context
1128  */
1129 static void
1130 sqlite_plugin_drop (void *cls)
1131 {
1132   struct Plugin *plugin = cls;
1133
1134   plugin->drop_on_shutdown = GNUNET_YES;
1135 }
1136
1137
1138 /**
1139  * Get an estimate of how much space the database is
1140  * currently using.
1141  *
1142  * @param cls the 'struct Plugin'
1143  * @return the size of the database on disk (estimate)
1144  */
1145 static unsigned long long
1146 sqlite_plugin_estimate_size (void *cls)
1147 {
1148   struct Plugin *plugin = cls;
1149   sqlite3_stmt *stmt;
1150   uint64_t pages;
1151   uint64_t page_size;
1152
1153 #if ENULL_DEFINED
1154   char *e;
1155 #endif
1156
1157   if (SQLITE_VERSION_NUMBER < 3006000)
1158   {
1159     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1160                      _
1161                      ("sqlite version to old to determine size, assuming zero\n"));
1162     return 0;
1163   }
1164   CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1165   CHECK (SQLITE_OK ==
1166          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1167                        NULL, ENULL));
1168   CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1169   if (SQLITE_ROW == sqlite3_step (stmt))
1170     pages = sqlite3_column_int64 (stmt, 0);
1171   else
1172     pages = 0;
1173   sqlite3_finalize (stmt);
1174   CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1175   CHECK (SQLITE_ROW == sqlite3_step (stmt));
1176   page_size = sqlite3_column_int64 (stmt, 0);
1177   sqlite3_finalize (stmt);
1178   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1179               _
1180               ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1181               (unsigned long long) pages, (unsigned long long) page_size);
1182   return pages * page_size;
1183 }
1184
1185
1186 /**
1187  * Entry point for the plugin.
1188  *
1189  * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1190  * @return NULL on error, othrewise the plugin context
1191  */
1192 void *
1193 libgnunet_plugin_datastore_sqlite_init (void *cls)
1194 {
1195   static struct Plugin plugin;
1196   struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1197   struct GNUNET_DATASTORE_PluginFunctions *api;
1198
1199   if (plugin.env != NULL)
1200     return NULL;                /* can only initialize once! */
1201   memset (&plugin, 0, sizeof (struct Plugin));
1202   plugin.env = env;
1203   if (GNUNET_OK != database_setup (env->cfg, &plugin))
1204   {
1205     database_shutdown (&plugin);
1206     return NULL;
1207   }
1208   api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1209   api->cls = &plugin;
1210   api->estimate_size = &sqlite_plugin_estimate_size;
1211   api->put = &sqlite_plugin_put;
1212   api->update = &sqlite_plugin_update;
1213   api->get_key = &sqlite_plugin_get_key;
1214   api->get_replication = &sqlite_plugin_get_replication;
1215   api->get_expiration = &sqlite_plugin_get_expiration;
1216   api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1217   api->get_keys = &sqlite_plugin_get_keys;
1218   api->drop = &sqlite_plugin_drop;
1219   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1220                    _("Sqlite database running\n"));
1221   return api;
1222 }
1223
1224
1225 /**
1226  * Exit point from the plugin.
1227  *
1228  * @param cls the plugin context (as returned by "init")
1229  * @return always NULL
1230  */
1231 void *
1232 libgnunet_plugin_datastore_sqlite_done (void *cls)
1233 {
1234   char *fn;
1235   struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1236   struct Plugin *plugin = api->cls;
1237
1238 #if DEBUG_SQLITE
1239   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1240                    "sqlite plugin is done\n");
1241 #endif
1242
1243   fn = NULL;
1244   if (plugin->drop_on_shutdown)
1245     fn = GNUNET_strdup (plugin->fn);
1246 #if DEBUG_SQLITE
1247   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1248                    "Shutting down database\n");
1249 #endif
1250   database_shutdown (plugin);
1251   plugin->env = NULL;
1252   GNUNET_free (api);
1253   if (fn != NULL)
1254   {
1255     if (0 != UNLINK (fn))
1256       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1257     GNUNET_free (fn);
1258   }
1259 #if DEBUG_SQLITE
1260   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1261                    "sqlite plugin is finished\n");
1262 #endif
1263   return NULL;
1264 }
1265
1266 /* end of plugin_datastore_sqlite.c */