sleeep
[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    * Plugin handle.
889    */
890   struct Plugin *plugin;
891   
892   /**
893    * Function to call for the result (or the NULL).
894    */
895   PluginDatumProcessor proc;
896   
897   /**
898    * Closure for proc.
899    */
900   void *proc_cls;
901 };
902
903
904 /**
905  * Wrapper for the processor for 'sqlite_plugin_replication_get'.
906  * Decrements the replication counter and calls the original
907  * processor.
908  *
909  * @param cls closure
910  * @param key key for the content
911  * @param size number of bytes in data
912  * @param data content stored
913  * @param type type of the content
914  * @param priority priority of the content
915  * @param anonymity anonymity-level for the content
916  * @param expiration expiration time for the content
917  * @param uid unique identifier for the datum;
918  *        maybe 0 if no unique identifier is available
919  *
920  * @return GNUNET_OK for normal return,
921  *         GNUNET_NO to delete the item
922  */
923 static int
924 repl_proc (void *cls,
925            const GNUNET_HashCode *key,
926            uint32_t size,
927            const void *data,
928            enum GNUNET_BLOCK_Type type,
929            uint32_t priority,
930            uint32_t anonymity,
931            struct GNUNET_TIME_Absolute expiration, 
932            uint64_t uid)
933 {
934   struct ReplCtx *rc = cls;
935   struct Plugin *plugin = rc->plugin;
936   int ret;
937
938   ret = rc->proc (rc->proc_cls,
939                   key,
940                   size, data, 
941                   type, priority, anonymity, expiration,
942                   uid);
943   if (NULL != key)
944     {
945       sqlite3_bind_int64 (plugin->updRepl, 1, uid);
946       if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
947         {
948           LOG_SQLITE (plugin, NULL,
949                       GNUNET_ERROR_TYPE_ERROR |
950                       GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
951           if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
952             LOG_SQLITE (plugin, NULL,
953                         GNUNET_ERROR_TYPE_ERROR |
954                         GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
955           return GNUNET_SYSERR;
956         }
957       if (SQLITE_OK != sqlite3_reset (plugin->delRow))
958         LOG_SQLITE (plugin, NULL,
959                     GNUNET_ERROR_TYPE_ERROR |
960                     GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
961     }
962   return ret;
963 }
964
965
966 /**
967  * Get a random item for replication.  Returns a single random item
968  * from those with the highest replication counters.  The item's 
969  * replication counter is decremented by one IF it was positive before.
970  * Call 'proc' with all values ZERO or NULL if the datastore is empty.
971  *
972  * @param cls closure
973  * @param proc function to call the value (once only).
974  * @param proc_cls closure for proc
975  */
976 static void
977 sqlite_plugin_get_replication (void *cls,
978                                PluginDatumProcessor proc, void *proc_cls)
979 {
980   struct Plugin *plugin = cls;
981   struct ReplCtx rc;
982
983 #if DEBUG_SQLITE
984   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
985                    "sqlite",
986                    "Getting random block based on replication order.\n");
987 #endif
988   rc.plugin = plugin;
989   rc.proc = proc;
990   rc.proc_cls = proc_cls;
991   execute_get (plugin, plugin->selRepl, &repl_proc, &rc);
992 }
993
994
995
996 /**
997  * Get a random item that has expired or has low priority.
998  * Call 'proc' with all values ZERO or NULL if the datastore is empty.
999  *
1000  * @param cls closure
1001  * @param proc function to call the value (once only).
1002  * @param proc_cls closure for proc
1003  */
1004 static void
1005 sqlite_plugin_get_expiration (void *cls,
1006                               PluginDatumProcessor proc, void *proc_cls)
1007 {
1008   struct Plugin *plugin = cls;
1009   sqlite3_stmt *stmt;
1010   struct GNUNET_TIME_Absolute now;
1011
1012 #if DEBUG_SQLITE
1013   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1014                    "sqlite",
1015                    "Getting random block based on expiration and priority order.\n");
1016 #endif
1017   now = GNUNET_TIME_absolute_get ();
1018   stmt = plugin->selExpi;
1019   if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1020     {
1021       LOG_SQLITE (plugin, NULL,           
1022                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1023       if (SQLITE_OK != sqlite3_reset (stmt))
1024         LOG_SQLITE (plugin, NULL,
1025                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1026       proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 
1027             GNUNET_TIME_UNIT_ZERO_ABS, 0);
1028       return;
1029     }
1030   execute_get (plugin, stmt, proc, proc_cls);
1031 }
1032
1033
1034 /**
1035  * Drop database.
1036  *
1037  * @param cls our plugin context
1038  */
1039 static void 
1040 sqlite_plugin_drop (void *cls)
1041 {
1042   struct Plugin *plugin = cls;
1043   plugin->drop_on_shutdown = GNUNET_YES;
1044 }
1045
1046
1047 /**
1048  * Get an estimate of how much space the database is
1049  * currently using.
1050  *
1051  * @param cls the 'struct Plugin'
1052  * @return the size of the database on disk (estimate)
1053  */
1054 static unsigned long long
1055 sqlite_plugin_estimate_size (void *cls)
1056 {
1057   struct Plugin *plugin = cls;
1058   sqlite3_stmt *stmt;
1059   uint64_t pages;
1060   uint64_t page_size;
1061 #if ENULL_DEFINED
1062   char *e;
1063 #endif
1064
1065   if (SQLITE_VERSION_NUMBER < 3006000)
1066     {
1067       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1068                        "datastore-sqlite",
1069                        _("sqlite version to old to determine size, assuming zero\n"));
1070       return 0;
1071     }
1072   CHECK (SQLITE_OK ==
1073          sqlite3_exec (plugin->dbh,
1074                        "VACUUM", NULL, NULL, ENULL));
1075   CHECK (SQLITE_OK ==
1076          sqlite3_exec (plugin->dbh,
1077                        "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1078   CHECK (SQLITE_OK ==
1079          sq_prepare (plugin->dbh,
1080                      "PRAGMA page_count",
1081                      &stmt));
1082   if (SQLITE_ROW ==
1083       sqlite3_step (stmt))
1084     pages = sqlite3_column_int64 (stmt, 0);
1085   else
1086     pages = 0;
1087   sqlite3_finalize (stmt);
1088   CHECK (SQLITE_OK ==
1089          sq_prepare (plugin->dbh,
1090                      "PRAGMA page_size",
1091                      &stmt));
1092   CHECK (SQLITE_ROW ==
1093          sqlite3_step (stmt));
1094   page_size = sqlite3_column_int64 (stmt, 0);
1095   sqlite3_finalize (stmt);
1096   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1097               _("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1098               (unsigned long long) pages,
1099               (unsigned long long) page_size);
1100   return  pages * page_size;
1101 }
1102                                          
1103
1104 /**
1105  * Entry point for the plugin.
1106  *
1107  * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1108  * @return NULL on error, othrewise the plugin context
1109  */
1110 void *
1111 libgnunet_plugin_datastore_sqlite_init (void *cls)
1112 {
1113   static struct Plugin plugin;
1114   struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1115   struct GNUNET_DATASTORE_PluginFunctions *api;
1116
1117   if (plugin.env != NULL)
1118     return NULL; /* can only initialize once! */
1119   memset (&plugin, 0, sizeof(struct Plugin));
1120   plugin.env = env;
1121   if (GNUNET_OK !=
1122       database_setup (env->cfg, &plugin))
1123     {
1124       database_shutdown (&plugin);
1125       return NULL;
1126     }
1127   api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1128   api->cls = &plugin;
1129   api->estimate_size = &sqlite_plugin_estimate_size;
1130   api->put = &sqlite_plugin_put;
1131   api->update = &sqlite_plugin_update;
1132   api->get_key = &sqlite_plugin_get_key;
1133   api->get_replication = &sqlite_plugin_get_replication;
1134   api->get_expiration = &sqlite_plugin_get_expiration;
1135   api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1136   api->drop = &sqlite_plugin_drop;
1137   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1138                    "sqlite", _("Sqlite database running\n"));
1139   return api;
1140 }
1141
1142
1143 /**
1144  * Exit point from the plugin.
1145  *
1146  * @param cls the plugin context (as returned by "init")
1147  * @return always NULL
1148  */
1149 void *
1150 libgnunet_plugin_datastore_sqlite_done (void *cls)
1151 {
1152   char *fn;
1153   struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1154   struct Plugin *plugin = api->cls;
1155
1156 #if DEBUG_SQLITE
1157   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1158                    "sqlite",
1159                    "sqlite plugin is done\n");
1160 #endif
1161
1162   fn = NULL;
1163   if (plugin->drop_on_shutdown)
1164     fn = GNUNET_strdup (plugin->fn);
1165 #if DEBUG_SQLITE
1166   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1167                    "sqlite",
1168                    "Shutting down database\n");
1169 #endif
1170   database_shutdown (plugin);
1171   plugin->env = NULL; 
1172   GNUNET_free (api);
1173   if (fn != NULL)
1174     {
1175       if (0 != UNLINK(fn))
1176         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1177                                   "unlink",
1178                                   fn);
1179       GNUNET_free (fn);
1180     }
1181 #if DEBUG_SQLITE
1182   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1183                    "sqlite",
1184                    "sqlite plugin is finished\n");
1185 #endif
1186   return NULL;
1187 }
1188
1189 /* end of plugin_datastore_sqlite.c */