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