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