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