Fixed reconnect
[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_NO
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_ "
329         "FROM gn090 "
330 #if SQLITE_VERSION_NUMBER >= 3007000
331         "INDEXED BY idx_repl_rvalue "
332 #endif
333         "WHERE repl=?2 AND "
334         " (rvalue>=?1 OR "
335         "  NOT EXISTS (SELECT 1 FROM gn090 "
336 #if SQLITE_VERSION_NUMBER >= 3007000
337         "INDEXED BY idx_repl_rvalue "
338 #endif
339         "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
340         "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
341       (sq_prepare
342        (plugin->dbh, "SELECT MAX(repl) FROM gn090"
343 #if SQLITE_VERSION_NUMBER >= 3007000
344         " INDEXED BY idx_repl_rvalue"
345 #endif
346         "",
347         &plugin->maxRepl) != SQLITE_OK) ||
348       (sq_prepare
349        (plugin->dbh,
350         "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
351         "FROM gn090 "
352 #if SQLITE_VERSION_NUMBER >= 3007000
353         "INDEXED BY idx_expire "
354 #endif
355         "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
356         "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
357       (sq_prepare
358        (plugin->dbh,
359         "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
360         "FROM gn090 " 
361 #if SQLITE_VERSION_NUMBER >= 3007000
362         "INDEXED BY idx_anon_type_hash " 
363 #endif
364         "WHERE (anonLevel = 0 AND type=?1) "
365         "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
366         &plugin->selZeroAnon) != SQLITE_OK) ||
367       (sq_prepare
368        (plugin->dbh,
369         "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
370         "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
371         &plugin->insertContent) != SQLITE_OK) ||
372       (sq_prepare
373        (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
374         &plugin->delRow) != SQLITE_OK))
375   {
376     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
377     return GNUNET_SYSERR;
378   }
379
380   return GNUNET_OK;
381 }
382
383
384 /**
385  * Shutdown database connection and associate data
386  * structures.
387  * @param plugin the plugin context (state for this module)
388  */
389 static void
390 database_shutdown (struct Plugin *plugin)
391 {
392   int result;
393
394 #if SQLITE_VERSION_NUMBER >= 3007000
395   sqlite3_stmt *stmt;
396 #endif
397
398   if (plugin->delRow != NULL)
399     sqlite3_finalize (plugin->delRow);
400   if (plugin->updPrio != NULL)
401     sqlite3_finalize (plugin->updPrio);
402   if (plugin->updRepl != NULL)
403     sqlite3_finalize (plugin->updRepl);
404   if (plugin->selRepl != NULL)
405     sqlite3_finalize (plugin->selRepl);
406   if (plugin->maxRepl != NULL)
407     sqlite3_finalize (plugin->maxRepl);
408   if (plugin->selExpi != NULL)
409     sqlite3_finalize (plugin->selExpi);
410   if (plugin->selZeroAnon != NULL)
411     sqlite3_finalize (plugin->selZeroAnon);
412   if (plugin->insertContent != NULL)
413     sqlite3_finalize (plugin->insertContent);
414   result = sqlite3_close (plugin->dbh);
415 #if SQLITE_VERSION_NUMBER >= 3007000
416   if (result == SQLITE_BUSY)
417   {
418     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
419                      _
420                      ("Tried to close sqlite without finalizing all prepared statements.\n"));
421     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
422     while (stmt != NULL)
423     {
424 #if DEBUG_SQLITE
425       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
426                        "Closing statement %p\n", stmt);
427 #endif
428       result = sqlite3_finalize (stmt);
429 #if DEBUG_SQLITE
430       if (result != SQLITE_OK)
431         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
432                          "Failed to close statement %p: %d\n", stmt, result);
433 #endif
434       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
435     }
436     result = sqlite3_close (plugin->dbh);
437   }
438 #endif
439   if (SQLITE_OK != result)
440     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
441
442   GNUNET_free_non_null (plugin->fn);
443 }
444
445
446 /**
447  * Delete the database entry with the given
448  * row identifier.
449  *
450  * @param plugin the plugin context (state for this module)
451  * @param rid the ID of the row to delete
452  */
453 static int
454 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
455 {
456   if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
457   {
458     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
459                 "sqlite3_bind_XXXX");
460     if (SQLITE_OK != sqlite3_reset (plugin->delRow))
461       LOG_SQLITE (plugin, NULL,
462                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
463                   "sqlite3_reset");
464     return GNUNET_SYSERR;
465   }
466   if (SQLITE_DONE != sqlite3_step (plugin->delRow))
467   {
468     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
469                 "sqlite3_step");
470     if (SQLITE_OK != sqlite3_reset (plugin->delRow))
471       LOG_SQLITE (plugin, NULL,
472                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
473                   "sqlite3_reset");
474     return GNUNET_SYSERR;
475   }
476   if (SQLITE_OK != sqlite3_reset (plugin->delRow))
477     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
478                 "sqlite3_reset");
479   return GNUNET_OK;
480 }
481
482
483 /**
484  * Store an item in the datastore.
485  *
486  * @param cls closure
487  * @param key key for the item
488  * @param size number of bytes in data
489  * @param data content stored
490  * @param type type of the content
491  * @param priority priority of the content
492  * @param anonymity anonymity-level for the content
493  * @param replication replication-level for the content
494  * @param expiration expiration time for the content
495  * @param msg set to an error message
496  * @return GNUNET_OK on success
497  */
498 static int
499 sqlite_plugin_put (void *cls, const GNUNET_HashCode * key, uint32_t size,
500                    const void *data, enum GNUNET_BLOCK_Type type,
501                    uint32_t priority, uint32_t anonymity, uint32_t replication,
502                    struct GNUNET_TIME_Absolute expiration, char **msg)
503 {
504   struct Plugin *plugin = cls;
505   int n;
506   int ret;
507   sqlite3_stmt *stmt;
508   GNUNET_HashCode vhash;
509   uint64_t rvalue;
510
511   if (size > MAX_ITEM_SIZE)
512     return GNUNET_SYSERR;
513 #if DEBUG_SQLITE
514   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
515                    "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
516                    type, GNUNET_h2s (key), priority,
517                    (unsigned long long)
518                    GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
519                    (long long) expiration.abs_value);
520 #endif
521   GNUNET_CRYPTO_hash (data, size, &vhash);
522   stmt = plugin->insertContent;
523   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
524   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
525       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
526       (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
527       (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
528       (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
529       (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
530       (SQLITE_OK !=
531        sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
532                           SQLITE_TRANSIENT)) ||
533       (SQLITE_OK !=
534        sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
535                           SQLITE_TRANSIENT)) ||
536       (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
537   {
538     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
539                 "sqlite3_bind_XXXX");
540     if (SQLITE_OK != sqlite3_reset (stmt))
541       LOG_SQLITE (plugin, NULL,
542                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
543                   "sqlite3_reset");
544     return GNUNET_SYSERR;
545   }
546   n = sqlite3_step (stmt);
547   switch (n)
548   {
549   case SQLITE_DONE:
550     plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
551 #if DEBUG_SQLITE
552     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
553                      "Stored new entry (%u bytes)\n",
554                      size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
555 #endif
556     ret = GNUNET_OK;
557     break;
558   case SQLITE_BUSY:
559     GNUNET_break (0);
560     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
561                 "sqlite3_step");
562     ret = GNUNET_SYSERR;
563     break;
564   default:
565     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
566                 "sqlite3_step");
567     if (SQLITE_OK != sqlite3_reset (stmt))
568       LOG_SQLITE (plugin, NULL,
569                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
570                   "sqlite3_reset");
571     database_shutdown (plugin);
572     database_setup (plugin->env->cfg, plugin);
573     return GNUNET_SYSERR;
574   }
575   if (SQLITE_OK != sqlite3_reset (stmt))
576     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
577                 "sqlite3_reset");
578   return ret;
579 }
580
581
582 /**
583  * Update the priority for a particular key in the datastore.  If
584  * the expiration time in value is different than the time found in
585  * the datastore, the higher value should be kept.  For the
586  * anonymity level, the lower value is to be used.  The specified
587  * priority should be added to the existing priority, ignoring the
588  * priority in value.
589  *
590  * Note that it is possible for multiple values to match this put.
591  * In that case, all of the respective values are updated.
592  *
593  * @param cls the plugin context (state for this module)
594  * @param uid unique identifier of the datum
595  * @param delta by how much should the priority
596  *     change?  If priority + delta < 0 the
597  *     priority should be set to 0 (never go
598  *     negative).
599  * @param expire new expiration time should be the
600  *     MAX of any existing expiration time and
601  *     this value
602  * @param msg set to an error message
603  * @return GNUNET_OK on success
604  */
605 static int
606 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
607                       struct GNUNET_TIME_Absolute expire, char **msg)
608 {
609   struct Plugin *plugin = cls;
610   int n;
611
612   if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
613       (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
614       || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
615   {
616     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
617                 "sqlite3_bind_XXXX");
618     if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
619       LOG_SQLITE (plugin, NULL,
620                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
621                   "sqlite3_reset");
622     return GNUNET_SYSERR;
623
624   }
625   n = sqlite3_step (plugin->updPrio);
626   if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
627     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
628                 "sqlite3_reset");
629   switch (n)
630   {
631   case SQLITE_DONE:
632 #if DEBUG_SQLITE
633     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
634 #endif
635     return GNUNET_OK;
636   case SQLITE_BUSY:
637     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
638                 "sqlite3_step");
639     return GNUNET_NO;
640   default:
641     LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
642                 "sqlite3_step");
643     return GNUNET_SYSERR;
644   }
645 }
646
647
648 /**
649  * Execute statement that gets a row and call the callback
650  * with the result.  Resets the statement afterwards.
651  *
652  * @param plugin the plugin
653  * @param stmt the statement
654  * @param proc processor to call
655  * @param proc_cls closure for 'proc'
656  */
657 static void
658 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
659              PluginDatumProcessor proc, void *proc_cls)
660 {
661   int n;
662   struct GNUNET_TIME_Absolute expiration;
663   unsigned long long rowid;
664   unsigned int size;
665   int ret;
666
667   n = sqlite3_step (stmt);
668   switch (n)
669   {
670   case SQLITE_ROW:
671     size = sqlite3_column_bytes (stmt, 5);
672     rowid = sqlite3_column_int64 (stmt, 6);
673     if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
674     {
675       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
676                        _
677                        ("Invalid data in database.  Trying to fix (by deletion).\n"));
678       if (SQLITE_OK != sqlite3_reset (stmt))
679         LOG_SQLITE (plugin, NULL,
680                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
681                     "sqlite3_reset");
682       if (GNUNET_OK == delete_by_rowid (plugin, rowid))
683         plugin->env->duc (plugin->env->cls,
684                           -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
685       break;
686     }
687     expiration.abs_value = sqlite3_column_int64 (stmt, 3);
688 #if DEBUG_SQLITE
689     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
690                      "Found reply in database with expiration %llu\n",
691                      (unsigned long long) expiration.abs_value);
692 #endif
693     ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
694                 size, sqlite3_column_blob (stmt, 5) /* data */ ,
695                 sqlite3_column_int (stmt, 0) /* type */ ,
696                 sqlite3_column_int (stmt, 1) /* priority */ ,
697                 sqlite3_column_int (stmt, 2) /* anonymity */ ,
698                 expiration, rowid);
699     if (SQLITE_OK != sqlite3_reset (stmt))
700       LOG_SQLITE (plugin, NULL,
701                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
702                   "sqlite3_reset");
703     if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
704       plugin->env->duc (plugin->env->cls,
705                         -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
706     return;
707   case SQLITE_DONE:
708     /* database must be empty */
709     if (SQLITE_OK != sqlite3_reset (stmt))
710       LOG_SQLITE (plugin, NULL,
711                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
712                   "sqlite3_reset");
713     break;
714   case SQLITE_BUSY:
715   case SQLITE_ERROR:
716   case SQLITE_MISUSE:
717   default:
718     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
719                 "sqlite3_step");
720     if (SQLITE_OK != sqlite3_reset (stmt))
721       LOG_SQLITE (plugin, NULL,
722                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
723                   "sqlite3_reset");
724     GNUNET_break (0);
725     database_shutdown (plugin);
726     database_setup (plugin->env->cfg, plugin);
727     break;
728   }
729   if (SQLITE_OK != sqlite3_reset (stmt))
730     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
731                 "sqlite3_reset");
732   proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
733 }
734
735
736
737 /**
738  * Select a subset of the items in the datastore and call
739  * the given processor for the item.
740  *
741  * @param cls our plugin context
742  * @param offset offset of the result (modulo num-results);
743  *               specific ordering does not matter for the offset
744  * @param type entries of which type should be considered?
745  *        Use 0 for any type.
746  * @param proc function to call on each matching value;
747  *        will be called once with a NULL value at the end
748  * @param proc_cls closure for proc
749  */
750 static void
751 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
752                                   enum GNUNET_BLOCK_Type type,
753                                   PluginDatumProcessor proc, void *proc_cls)
754 {
755   struct Plugin *plugin = cls;
756   sqlite3_stmt *stmt;
757
758   GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
759   stmt = plugin->selZeroAnon;
760   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
761       (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
762   {
763     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
764                 "sqlite3_bind_XXXX");
765     if (SQLITE_OK != sqlite3_reset (stmt))
766       LOG_SQLITE (plugin, NULL,
767                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
768                   "sqlite3_reset");
769     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
770     return;
771   }
772   execute_get (plugin, stmt, proc, proc_cls);
773 }
774
775
776
777 /**
778  * Get results for a particular key in the datastore.
779  *
780  * @param cls closure
781  * @param offset offset (mod count).
782  * @param key key to match, never NULL
783  * @param vhash hash of the value, maybe NULL (to
784  *        match all values that have the right key).
785  *        Note that for DBlocks there is no difference
786  *        betwen key and vhash, but for other blocks
787  *        there may be!
788  * @param type entries of which type are relevant?
789  *     Use 0 for any type.
790  * @param proc function to call on each matching value;
791  *        will be called once with a NULL value at the end
792  * @param proc_cls closure for proc
793  */
794 static void
795 sqlite_plugin_get_key (void *cls, uint64_t offset, const GNUNET_HashCode * key,
796                        const GNUNET_HashCode * vhash,
797                        enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
798                        void *proc_cls)
799 {
800   struct Plugin *plugin = cls;
801   int ret;
802   int total;
803   int limit_off;
804   unsigned int sqoff;
805   sqlite3_stmt *stmt;
806   char scratch[256];
807
808   GNUNET_assert (proc != NULL);
809   GNUNET_assert (key != NULL);
810   GNUNET_snprintf (scratch, sizeof (scratch),
811                    "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
812                    vhash == NULL ? "" : " AND vhash=?",
813                    type == 0 ? "" : " AND type=?");
814   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
815   {
816     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
817                 "sqlite_prepare");
818     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
819     return;
820   }
821   sqoff = 1;
822   ret =
823       sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
824                          SQLITE_TRANSIENT);
825   if ((vhash != NULL) && (ret == SQLITE_OK))
826     ret =
827         sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
828                            SQLITE_TRANSIENT);
829   if ((type != 0) && (ret == SQLITE_OK))
830     ret = sqlite3_bind_int (stmt, sqoff++, type);
831   if (SQLITE_OK != ret)
832   {
833     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
834     sqlite3_finalize (stmt);
835     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
836     return;
837   }
838   ret = sqlite3_step (stmt);
839   if (ret != SQLITE_ROW)
840   {
841     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
842                 "sqlite_step");
843     sqlite3_finalize (stmt);
844     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
845     return;
846   }
847   total = sqlite3_column_int (stmt, 0);
848   sqlite3_finalize (stmt);
849   if (0 == total)
850   {
851     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
852     return;
853   }
854   limit_off = (int) (offset % total);
855   if (limit_off < 0)
856     limit_off += total;
857   GNUNET_snprintf (scratch, sizeof (scratch),
858                    "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
859                    "FROM gn090 WHERE hash=?%s%s "
860                    "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
861                    vhash == NULL ? "" : " AND vhash=?",
862                    type == 0 ? "" : " AND type=?");
863   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
864   {
865     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
866                 "sqlite_prepare");
867     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
868     return;
869   }
870   sqoff = 1;
871   ret =
872       sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
873                          SQLITE_TRANSIENT);
874   if ((vhash != NULL) && (ret == SQLITE_OK))
875     ret =
876         sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
877                            SQLITE_TRANSIENT);
878   if ((type != 0) && (ret == SQLITE_OK))
879     ret = sqlite3_bind_int (stmt, sqoff++, type);
880   if (ret == SQLITE_OK)
881     ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
882   if (ret != SQLITE_OK)
883   {
884     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
885                 "sqlite_bind");
886     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
887     return;
888   }
889   execute_get (plugin, stmt, proc, proc_cls);
890   sqlite3_finalize (stmt);
891 }
892
893
894
895 /**
896  * Context for 'repl_proc' function.
897  */
898 struct ReplCtx
899 {
900
901   /**
902    * Function to call for the result (or the NULL).
903    */
904   PluginDatumProcessor proc;
905
906   /**
907    * Closure for proc.
908    */
909   void *proc_cls;
910
911   /**
912    * UID to use.
913    */
914   uint64_t uid;
915
916   /**
917    * Yes if UID was set.
918    */
919   int have_uid;
920 };
921
922
923 /**
924  * Wrapper for the processor for 'sqlite_plugin_replication_get'.
925  * Decrements the replication counter and calls the original
926  * processor.
927  *
928  * @param cls closure
929  * @param key key for the content
930  * @param size number of bytes in data
931  * @param data content stored
932  * @param type type of the content
933  * @param priority priority of the content
934  * @param anonymity anonymity-level for the content
935  * @param expiration expiration time for the content
936  * @param uid unique identifier for the datum;
937  *        maybe 0 if no unique identifier is available
938  *
939  * @return GNUNET_OK for normal return,
940  *         GNUNET_NO to delete the item
941  */
942 static int
943 repl_proc (void *cls, const GNUNET_HashCode * key, uint32_t size,
944            const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
945            uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
946            uint64_t uid)
947 {
948   struct ReplCtx *rc = cls;
949   int ret;
950
951   ret =
952       rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
953                 expiration, uid);
954   if (key != NULL)
955   {
956     rc->uid = uid;
957     rc->have_uid = GNUNET_YES;
958   }
959   return ret;
960 }
961
962
963 /**
964  * Get a random item for replication.  Returns a single random item
965  * from those with the highest replication counters.  The item's
966  * replication counter is decremented by one IF it was positive before.
967  * Call 'proc' with all values ZERO or NULL if the datastore is empty.
968  *
969  * @param cls closure
970  * @param proc function to call the value (once only).
971  * @param proc_cls closure for proc
972  */
973 static void
974 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
975                                void *proc_cls)
976 {
977   struct Plugin *plugin = cls;
978   struct ReplCtx rc;
979   uint64_t rvalue;
980   uint32_t repl;
981   sqlite3_stmt *stmt;
982
983 #if DEBUG_SQLITE
984   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
985                    "Getting random block based on replication order.\n");
986 #endif
987   rc.have_uid = GNUNET_NO;
988   rc.proc = proc;
989   rc.proc_cls = proc_cls;
990   stmt = plugin->maxRepl;
991   if (SQLITE_ROW != sqlite3_step (stmt))
992   {
993     if (SQLITE_OK != sqlite3_reset (stmt))
994       LOG_SQLITE (plugin, NULL,
995                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
996                   "sqlite3_reset");
997     /* DB empty */
998     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
999     return;
1000   }
1001   repl = sqlite3_column_int (stmt, 0);
1002   if (SQLITE_OK != sqlite3_reset (stmt))
1003     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1004                 "sqlite3_reset");
1005   stmt = plugin->selRepl;
1006   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1007   if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1008   {
1009     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1010                 "sqlite3_bind_XXXX");
1011     if (SQLITE_OK != sqlite3_reset (stmt))
1012       LOG_SQLITE (plugin, NULL,
1013                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1014                   "sqlite3_reset");
1015     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1016     return;
1017   }
1018   if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1019   {
1020     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1021                 "sqlite3_bind_XXXX");
1022     if (SQLITE_OK != sqlite3_reset (stmt))
1023       LOG_SQLITE (plugin, NULL,
1024                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1025                   "sqlite3_reset");
1026     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1027     return;
1028   }
1029   execute_get (plugin, stmt, &repl_proc, &rc);
1030   if (GNUNET_YES == rc.have_uid)
1031   {
1032     if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1033     {
1034       LOG_SQLITE (plugin, NULL,
1035                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1036                   "sqlite3_bind_XXXX");
1037       if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1038         LOG_SQLITE (plugin, NULL,
1039                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1040                     "sqlite3_reset");
1041       return;
1042     }
1043     if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1044       LOG_SQLITE (plugin, NULL,
1045                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1046                   "sqlite3_step");
1047     if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1048       LOG_SQLITE (plugin, NULL,
1049                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1050                   "sqlite3_reset");
1051   }
1052 }
1053
1054
1055
1056 /**
1057  * Get a random item that has expired or has low priority.
1058  * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1059  *
1060  * @param cls closure
1061  * @param proc function to call the value (once only).
1062  * @param proc_cls closure for proc
1063  */
1064 static void
1065 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1066                               void *proc_cls)
1067 {
1068   struct Plugin *plugin = cls;
1069   sqlite3_stmt *stmt;
1070   struct GNUNET_TIME_Absolute now;
1071
1072 #if DEBUG_SQLITE
1073   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1074                    "Getting random block based on expiration and priority order.\n");
1075 #endif
1076   now = GNUNET_TIME_absolute_get ();
1077   stmt = plugin->selExpi;
1078   if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1079   {
1080     LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1081                 "sqlite3_bind_XXXX");
1082     if (SQLITE_OK != sqlite3_reset (stmt))
1083       LOG_SQLITE (plugin, NULL,
1084                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1085                   "sqlite3_reset");
1086     proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1087     return;
1088   }
1089   execute_get (plugin, stmt, proc, proc_cls);
1090 }
1091
1092
1093 /**
1094  * Drop database.
1095  *
1096  * @param cls our plugin context
1097  */
1098 static void
1099 sqlite_plugin_drop (void *cls)
1100 {
1101   struct Plugin *plugin = cls;
1102
1103   plugin->drop_on_shutdown = GNUNET_YES;
1104 }
1105
1106
1107 /**
1108  * Get an estimate of how much space the database is
1109  * currently using.
1110  *
1111  * @param cls the 'struct Plugin'
1112  * @return the size of the database on disk (estimate)
1113  */
1114 static unsigned long long
1115 sqlite_plugin_estimate_size (void *cls)
1116 {
1117   struct Plugin *plugin = cls;
1118   sqlite3_stmt *stmt;
1119   uint64_t pages;
1120   uint64_t page_size;
1121
1122 #if ENULL_DEFINED
1123   char *e;
1124 #endif
1125
1126   if (SQLITE_VERSION_NUMBER < 3006000)
1127   {
1128     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1129                      _
1130                      ("sqlite version to old to determine size, assuming zero\n"));
1131     return 0;
1132   }
1133   CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1134   CHECK (SQLITE_OK ==
1135          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1136                        NULL, ENULL));
1137   CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1138   if (SQLITE_ROW == sqlite3_step (stmt))
1139     pages = sqlite3_column_int64 (stmt, 0);
1140   else
1141     pages = 0;
1142   sqlite3_finalize (stmt);
1143   CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1144   CHECK (SQLITE_ROW == sqlite3_step (stmt));
1145   page_size = sqlite3_column_int64 (stmt, 0);
1146   sqlite3_finalize (stmt);
1147   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1148               _
1149               ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1150               (unsigned long long) pages, (unsigned long long) page_size);
1151   return pages * page_size;
1152 }
1153
1154
1155 /**
1156  * Entry point for the plugin.
1157  *
1158  * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1159  * @return NULL on error, othrewise the plugin context
1160  */
1161 void *
1162 libgnunet_plugin_datastore_sqlite_init (void *cls)
1163 {
1164   static struct Plugin plugin;
1165   struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1166   struct GNUNET_DATASTORE_PluginFunctions *api;
1167
1168   if (plugin.env != NULL)
1169     return NULL;                /* can only initialize once! */
1170   memset (&plugin, 0, sizeof (struct Plugin));
1171   plugin.env = env;
1172   if (GNUNET_OK != database_setup (env->cfg, &plugin))
1173   {
1174     database_shutdown (&plugin);
1175     return NULL;
1176   }
1177   api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1178   api->cls = &plugin;
1179   api->estimate_size = &sqlite_plugin_estimate_size;
1180   api->put = &sqlite_plugin_put;
1181   api->update = &sqlite_plugin_update;
1182   api->get_key = &sqlite_plugin_get_key;
1183   api->get_replication = &sqlite_plugin_get_replication;
1184   api->get_expiration = &sqlite_plugin_get_expiration;
1185   api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1186   api->drop = &sqlite_plugin_drop;
1187   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1188                    _("Sqlite database running\n"));
1189   return api;
1190 }
1191
1192
1193 /**
1194  * Exit point from the plugin.
1195  *
1196  * @param cls the plugin context (as returned by "init")
1197  * @return always NULL
1198  */
1199 void *
1200 libgnunet_plugin_datastore_sqlite_done (void *cls)
1201 {
1202   char *fn;
1203   struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1204   struct Plugin *plugin = api->cls;
1205
1206 #if DEBUG_SQLITE
1207   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1208                    "sqlite plugin is done\n");
1209 #endif
1210
1211   fn = NULL;
1212   if (plugin->drop_on_shutdown)
1213     fn = GNUNET_strdup (plugin->fn);
1214 #if DEBUG_SQLITE
1215   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1216                    "Shutting down database\n");
1217 #endif
1218   database_shutdown (plugin);
1219   plugin->env = NULL;
1220   GNUNET_free (api);
1221   if (fn != NULL)
1222   {
1223     if (0 != UNLINK (fn))
1224       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1225     GNUNET_free (fn);
1226   }
1227 #if DEBUG_SQLITE
1228   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1229                    "sqlite plugin is finished\n");
1230 #endif
1231   return NULL;
1232 }
1233
1234 /* end of plugin_datastore_sqlite.c */