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