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