print
[oweals/gnunet.git] / src / datastore / plugin_datastore_sqlite.c
1  /*
2      This file is part of GNUnet
3      (C) 2009 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 2, 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_statistics_service.h"
29 #include "plugin_datastore.h"
30 #include <sqlite3.h>
31
32 #define DEBUG_SQLITE GNUNET_YES
33
34 /**
35  * After how many payload-changing operations
36  * do we sync our statistics?
37  */
38 #define MAX_STAT_SYNC_LAG 50
39
40 #define QUOTA_STAT_NAME gettext_noop ("file-sharing datastore utilization (in bytes)")
41
42
43 /**
44  * Die with an error message that indicates
45  * a failure of the command 'cmd' with the message given
46  * by strerror(errno).
47  */
48 #define DIE_SQLITE(db, cmd) do { GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); abort(); } while(0)
49
50 /**
51  * Log an error message at log-level 'level' that indicates
52  * a failure of the command 'cmd' on file 'filename'
53  * with the message given by strerror(errno).
54  */
55 #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 with error: %s\n"), cmd, sqlite3_errmsg(db->dbh)); } while(0)
56
57 #define SELECT_IT_LOW_PRIORITY_1 \
58   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio = ? AND hash > ?) "\
59   "ORDER BY hash ASC LIMIT 1"
60
61 #define SELECT_IT_LOW_PRIORITY_2 \
62   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio > ?) "\
63   "ORDER BY prio ASC, hash ASC LIMIT 1"
64
65 #define SELECT_IT_NON_ANONYMOUS_1 \
66   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio = ? AND hash < ? AND anonLevel = 0 AND expire > %llu) "\
67   " ORDER BY hash DESC LIMIT 1"
68
69 #define SELECT_IT_NON_ANONYMOUS_2 \
70   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio < ? AND anonLevel = 0 AND expire > %llu)"\
71   " ORDER BY prio DESC, hash DESC LIMIT 1"
72
73 #define SELECT_IT_EXPIRATION_TIME_1 \
74   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire = ? AND hash > ?) "\
75   " ORDER BY hash ASC LIMIT 1"
76
77 #define SELECT_IT_EXPIRATION_TIME_2 \
78   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire > ?) "\
79   " ORDER BY expire ASC, hash ASC LIMIT 1"
80
81 #define SELECT_IT_MIGRATION_ORDER_1 \
82   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire = ? AND hash < ?) "\
83   " ORDER BY hash DESC LIMIT 1"
84
85 #define SELECT_IT_MIGRATION_ORDER_2 \
86   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire < ? AND expire > %llu) "\
87   " ORDER BY expire DESC, hash DESC LIMIT 1"
88
89 /**
90  * After how many ms "busy" should a DB operation fail for good?
91  * A low value makes sure that we are more responsive to requests
92  * (especially PUTs).  A high value guarantees a higher success
93  * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
94  *
95  * The default value of 250ms should ensure that users do not experience
96  * huge latencies while at the same time allowing operations to succeed
97  * with reasonable probability.
98  */
99 #define BUSY_TIMEOUT_MS 250
100
101
102 /**
103  * Context for all functions in this plugin.
104  */
105 struct Plugin 
106 {
107   /**
108    * Our execution environment.
109    */
110   struct GNUNET_DATASTORE_PluginEnvironment *env;
111
112   /**
113    * Database filename.
114    */
115   char *fn;
116
117   /**
118    * Native SQLite database handle.
119    */
120   sqlite3 *dbh;
121
122   /**
123    * Precompiled SQL for update.
124    */
125   sqlite3_stmt *updPrio;
126
127   /**
128    * Precompiled SQL for insertion.
129    */
130   sqlite3_stmt *insertContent;
131
132   /**
133    * Handle to the statistics service.
134    */
135   struct GNUNET_STATISTICS_Handle *statistics;
136   
137   /**
138    * How much data are we currently storing
139    * in the database?
140    */
141   unsigned long long payload;
142
143   /**
144    * Number of updates that were made to the
145    * payload value since we last synchronized
146    * it with the statistics service.
147    */
148   unsigned int lastSync;
149
150   /**
151    * Should the database be dropped on shutdown?
152    */
153   int drop_on_shutdown;
154 };
155
156
157 /**
158  * @brief Prepare a SQL statement
159  *
160  * @param zSql SQL statement, UTF-8 encoded
161  */
162 static int
163 sq_prepare (sqlite3 * dbh, const char *zSql,
164             sqlite3_stmt ** ppStmt)
165 {
166   char *dummy;
167   return sqlite3_prepare (dbh,
168                           zSql,
169                           strlen (zSql), ppStmt, (const char **) &dummy);
170 }
171
172
173 /**
174  * Create our database indices.
175  */
176 static void
177 create_indices (sqlite3 * dbh)
178 {
179   /* create indices */
180   sqlite3_exec (dbh,
181                 "CREATE INDEX idx_hash ON gn080 (hash)", NULL, NULL, NULL);
182   sqlite3_exec (dbh,
183                 "CREATE INDEX idx_hash_vhash ON gn080 (hash,vhash)", NULL,
184                 NULL, NULL);
185   sqlite3_exec (dbh, "CREATE INDEX idx_prio ON gn080 (prio)", NULL, NULL,
186                 NULL);
187   sqlite3_exec (dbh, "CREATE INDEX idx_expire ON gn080 (expire)", NULL, NULL,
188                 NULL);
189   sqlite3_exec (dbh, "CREATE INDEX idx_comb3 ON gn080 (prio,anonLevel)", NULL,
190                 NULL, NULL);
191   sqlite3_exec (dbh, "CREATE INDEX idx_comb4 ON gn080 (prio,hash,anonLevel)",
192                 NULL, NULL, NULL);
193   sqlite3_exec (dbh, "CREATE INDEX idx_comb7 ON gn080 (expire,hash)", NULL,
194                 NULL, NULL);
195 }
196
197
198
199 #if 1
200 #define CHECK(a) GNUNET_break(a)
201 #define ENULL NULL
202 #else
203 #define ENULL &e
204 #define ENULL_DEFINED 1
205 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERRROR, "%s\n", e); sqlite3_free(e); }
206 #endif
207
208
209
210
211 /**
212  * Initialize the database connections and associated
213  * data structures (create tables and indices
214  * as needed as well).
215  *
216  * @return GNUNET_OK on success
217  */
218 static int
219 database_setup (struct GNUNET_CONFIGURATION_Handle *cfg,
220                 struct Plugin *plugin)
221 {
222   sqlite3_stmt *stmt;
223   char *afsdir;
224 #if ENULL_DEFINED
225   char *e;
226 #endif
227   
228   if (GNUNET_OK != 
229       GNUNET_CONFIGURATION_get_value_filename (cfg,
230                                                "datastore-sqlite",
231                                                "FILENAME",
232                                                &afsdir))
233     {
234       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
235                        "sqlite",
236                        _("Option `%s' in section `%s' missing in configuration!\n"),
237                        "FILENAME",
238                        "datastore-sqlite");
239       return GNUNET_SYSERR;
240     }
241   if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
242     {
243       GNUNET_break (0);
244       GNUNET_free (afsdir);
245       return GNUNET_SYSERR;
246     }
247   plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
248 #ifdef ENABLE_NLS
249                                               nl_langinfo (CODESET)
250 #else
251                                               "UTF-8"   /* good luck */
252 #endif
253                                               );
254   GNUNET_free (afsdir);
255   
256   /* Open database and precompile statements */
257   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
258     {
259       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
260                        "sqlite",
261                        _("Unable to initialize SQLite: %s.\n"),
262                        sqlite3_errmsg (plugin->dbh));
263       return GNUNET_SYSERR;
264     }
265   CHECK (SQLITE_OK ==
266          sqlite3_exec (plugin->dbh,
267                        "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
268   CHECK (SQLITE_OK ==
269          sqlite3_exec (plugin->dbh,
270                        "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
271   CHECK (SQLITE_OK ==
272          sqlite3_exec (plugin->dbh,
273                        "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
274   CHECK (SQLITE_OK ==
275          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL, ENULL));
276
277   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
278
279
280   /* We have to do it here, because otherwise precompiling SQL might fail */
281   CHECK (SQLITE_OK ==
282          sq_prepare (plugin->dbh,
283                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn080'",
284                      &stmt));
285   if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
286        (sqlite3_exec (plugin->dbh,
287                       "CREATE TABLE gn080 ("
288                       "  size INT4 NOT NULL DEFAULT 0,"
289                       "  type INT4 NOT NULL DEFAULT 0,"
290                       "  prio INT4 NOT NULL DEFAULT 0,"
291                       "  anonLevel INT4 NOT NULL DEFAULT 0,"
292                       "  expire INT8 NOT NULL DEFAULT 0,"
293                       "  hash TEXT NOT NULL DEFAULT '',"
294                       "  vhash TEXT NOT NULL DEFAULT '',"
295                       "  value BLOB NOT NULL DEFAULT '')", NULL, NULL,
296                       NULL) != SQLITE_OK) )
297     {
298       LOG_SQLITE (plugin, NULL,
299                   GNUNET_ERROR_TYPE_ERROR, 
300                   "sqlite3_exec");
301       sqlite3_finalize (stmt);
302       return GNUNET_SYSERR;
303     }
304   sqlite3_finalize (stmt);
305   create_indices (plugin->dbh);
306
307   CHECK (SQLITE_OK ==
308          sq_prepare (plugin->dbh,
309                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn071'",
310                      &stmt));
311   if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
312        (sqlite3_exec (plugin->dbh,
313                       "CREATE TABLE gn071 ("
314                       "  key TEXT NOT NULL DEFAULT '',"
315                       "  value INTEGER NOT NULL DEFAULT 0)", NULL, NULL,
316                       NULL) != SQLITE_OK) )
317     {
318       LOG_SQLITE (plugin, NULL,
319                   GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
320       sqlite3_finalize (stmt);
321       return GNUNET_SYSERR;
322     }
323   sqlite3_finalize (stmt);
324
325   if ((sq_prepare (plugin->dbh,
326                    "UPDATE gn080 SET prio = prio + ?, expire = MAX(expire,?) WHERE "
327                    "_ROWID_ = ?",
328                    &plugin->updPrio) != SQLITE_OK) ||
329       (sq_prepare (plugin->dbh,
330                    "INSERT INTO gn080 (size, type, prio, "
331                    "anonLevel, expire, hash, vhash, value) VALUES "
332                    "(?, ?, ?, ?, ?, ?, ?, ?)",
333                    &plugin->insertContent) != SQLITE_OK))
334     {
335       LOG_SQLITE (plugin, NULL,
336                   GNUNET_ERROR_TYPE_ERROR, "precompiling");
337       return GNUNET_SYSERR;
338     }
339   return GNUNET_OK;
340 }
341
342
343 /**
344  * Synchronize our utilization statistics with the 
345  * statistics service.
346  */
347 static void 
348 sync_stats (struct Plugin *plugin)
349 {
350   GNUNET_STATISTICS_set (plugin->statistics,
351                          QUOTA_STAT_NAME,
352                          plugin->payload,
353                          GNUNET_YES);
354   plugin->lastSync = 0;
355 }
356
357
358 /**
359  * Shutdown database connection and associate data
360  * structures.
361  */
362 static void
363 database_shutdown (struct Plugin *plugin)
364 {
365   if (plugin->lastSync > 0)
366     sync_stats (plugin);
367   if (plugin->updPrio != NULL)
368     sqlite3_finalize (plugin->updPrio);
369   if (plugin->insertContent != NULL)
370     sqlite3_finalize (plugin->insertContent);
371   sqlite3_close (plugin->dbh);
372   GNUNET_free_non_null (plugin->fn);
373 }
374
375
376 /**
377  * Get an estimate of how much space the database is
378  * currently using.
379  * @return number of bytes used on disk
380  */
381 static unsigned long long sqlite_plugin_get_size (void *cls)
382 {
383   struct Plugin *plugin = cls;
384   return plugin->payload;
385 }
386
387
388 /**
389  * Delete the database entry with the given
390  * row identifier.
391  */
392 static int
393 delete_by_rowid (struct Plugin* plugin, 
394                  unsigned long long rid)
395 {
396   sqlite3_stmt *stmt;
397
398   if (sq_prepare (plugin->dbh,
399                   "DELETE FROM gn080 WHERE _ROWID_ = ?", &stmt) != SQLITE_OK)
400     {
401       LOG_SQLITE (plugin, NULL,
402                   GNUNET_ERROR_TYPE_ERROR |
403                   GNUNET_ERROR_TYPE_BULK, "sq_prepare");
404       return GNUNET_SYSERR;
405     }
406   sqlite3_bind_int64 (stmt, 1, rid);
407   if (SQLITE_DONE != sqlite3_step (stmt))
408     {
409       LOG_SQLITE (plugin, NULL,
410                   GNUNET_ERROR_TYPE_ERROR |
411                   GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
412       sqlite3_finalize (stmt);
413       return GNUNET_SYSERR;
414     }
415   sqlite3_finalize (stmt);
416   return GNUNET_OK;
417 }
418
419
420 /**
421  * Context for the universal iterator.
422  */
423 struct NextContext;
424
425 /**
426  * Type of a function that will prepare
427  * the next iteration.
428  *
429  * @param cls closure
430  * @param nc the next context; NULL for the last
431  *         call which gives the callback a chance to
432  *         clean up the closure
433  * @return GNUNET_OK on success, GNUNET_NO if there are
434  *         no more values, GNUNET_SYSERR on error
435  */
436 typedef int (*PrepareFunction)(void *cls,
437                                struct NextContext *nc);
438
439
440 /**
441  * Context we keep for the "next request" callback.
442  */
443 struct NextContext
444 {
445   /**
446    * Internal state.
447    */ 
448   struct Plugin *plugin;
449
450   /**
451    * Function to call on the next value.
452    */
453   PluginIterator iter;
454
455   /**
456    * Closure for iter.
457    */
458   void *iter_cls;
459
460   /**
461    * Function to call to prepare the next
462    * iteration.
463    */
464   PrepareFunction prep;
465
466   /**
467    * Closure for prep.
468    */
469   void *prep_cls;
470
471   /**
472    * Statement that the iterator will get the data
473    * from (updated or set by prep).
474    */ 
475   sqlite3_stmt *stmt;
476
477   /**
478    * Row ID of the last result.
479    */
480   unsigned long long last_rowid;
481
482   /**
483    * Key of the last result.
484    */
485   GNUNET_HashCode lastKey;  
486
487   /**
488    * Expiration time of the last value visited.
489    */
490   struct GNUNET_TIME_Absolute lastExpiration;
491
492   /**
493    * Priority of the last value visited.
494    */ 
495   unsigned int lastPriority; 
496
497   /**
498    * Number of results processed so far.
499    */
500   unsigned int count;
501
502   /**
503    * Set to GNUNET_YES if we must stop now.
504    */
505   int end_it;
506 };
507
508
509 /**
510  * Continuation of "sqlite_next_request".
511  *
512  * @param cls the next context
513  */
514 static void 
515 sqlite_next_request_cont (void *cls,
516                           const struct GNUNET_SCHEDULER_TaskContext *tc)
517 {
518   static struct GNUNET_TIME_Absolute zero;
519   struct NextContext * nc= cls;
520   struct Plugin *plugin;
521   unsigned long long rowid;
522   sqlite3_stmt *stmtd;
523   int ret;
524   unsigned int type;
525   unsigned int size;
526   unsigned int priority;
527   unsigned int anonymity;
528   struct GNUNET_TIME_Absolute expiration;
529   const GNUNET_HashCode *key;
530   const void *data;
531
532  
533   plugin = nc->plugin;
534   if ( (GNUNET_YES == nc->end_it) ||
535        (GNUNET_OK != (nc->prep(nc->prep_cls,
536                                nc))) )
537     {
538     END:
539       nc->iter (nc->iter_cls, 
540                 NULL, NULL, 0, NULL, 0, 0, 0, 
541                 zero, 0);
542       nc->prep (nc->prep_cls, NULL);
543       GNUNET_free (nc);
544       return;
545     }
546
547   rowid = sqlite3_column_int64 (nc->stmt, 7);
548   nc->last_rowid = rowid;
549   type = sqlite3_column_int (nc->stmt, 1);
550   size = sqlite3_column_bytes (nc->stmt, 6);
551   if (sqlite3_column_bytes (nc->stmt, 5) != sizeof (GNUNET_HashCode))
552     {
553       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
554                        "sqlite",
555                        _("Invalid data in database.  Trying to fix (by deletion).\n"));
556       if (SQLITE_OK != sqlite3_reset (nc->stmt))
557         LOG_SQLITE (nc->plugin, NULL,
558                     GNUNET_ERROR_TYPE_ERROR |
559                     GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
560       if (sq_prepare
561           (nc->plugin->dbh,
562            "DELETE FROM gn080 WHERE NOT LENGTH(hash) = ?",
563            &stmtd) != SQLITE_OK)
564         {
565           LOG_SQLITE (nc->plugin, NULL,
566                       GNUNET_ERROR_TYPE_ERROR |
567                       GNUNET_ERROR_TYPE_BULK, 
568                       "sq_prepare");
569           goto END;
570         }
571
572       if (SQLITE_OK != sqlite3_bind_int (stmtd, 1, sizeof (GNUNET_HashCode)))
573         LOG_SQLITE (nc->plugin, NULL,
574                     GNUNET_ERROR_TYPE_ERROR |
575                     GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_int");
576       if (SQLITE_DONE != sqlite3_step (stmtd))
577         LOG_SQLITE (nc->plugin, NULL,
578                     GNUNET_ERROR_TYPE_ERROR |
579                     GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
580       if (SQLITE_OK != sqlite3_finalize (stmtd))
581         LOG_SQLITE (nc->plugin, NULL,
582                     GNUNET_ERROR_TYPE_ERROR |
583                     GNUNET_ERROR_TYPE_BULK, "sqlite3_finalize");
584       goto END;
585     }
586
587   priority = sqlite3_column_int (nc->stmt, 2);
588   anonymity = sqlite3_column_int (nc->stmt, 3);
589   expiration.value = sqlite3_column_int64 (nc->stmt, 4);
590   key = sqlite3_column_blob (nc->stmt, 5);
591   nc->lastPriority = priority;
592   nc->lastExpiration = expiration;
593   memcpy (&nc->lastKey, key, sizeof(GNUNET_HashCode));
594   data = sqlite3_column_blob (nc->stmt, 6);
595   nc->count++;
596   ret = nc->iter (nc->iter_cls,
597                   nc,
598                   key,
599                   size,
600                   data, 
601                   type,
602                   priority,
603                   anonymity,
604                   expiration,
605                   rowid);
606   if (ret == GNUNET_SYSERR)
607     {
608       nc->end_it = GNUNET_YES;
609       return;
610     }
611   if ( (ret == GNUNET_NO) &&
612        (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
613     {
614       plugin->payload -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
615       plugin->lastSync++; 
616       if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
617         sync_stats (plugin);
618     }
619 }
620
621
622 /**
623  * Function invoked on behalf of a "PluginIterator"
624  * asking the database plugin to call the iterator
625  * with the next item.
626  *
627  * @param next_cls whatever argument was given
628  *        to the PluginIterator as "next_cls".
629  * @param end_it set to GNUNET_YES if we
630  *        should terminate the iteration early
631  *        (iterator should be still called once more
632  *         to signal the end of the iteration).
633  */
634 static void 
635 sqlite_next_request (void *next_cls,
636                      int end_it)
637 {
638   struct NextContext * nc= next_cls;
639
640   if (GNUNET_YES == end_it)
641     nc->end_it = GNUNET_YES;
642   GNUNET_SCHEDULER_add_continuation (nc->plugin->env->sched,
643                                      GNUNET_NO,                              
644                                      &sqlite_next_request_cont,
645                                      nc,
646                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
647 }
648
649
650
651 /**
652  * Store an item in the datastore.
653  *
654  * @param cls closure
655  * @param key key for the item
656  * @param size number of bytes in data
657  * @param data content stored
658  * @param type type of the content
659  * @param priority priority of the content
660  * @param anonymity anonymity-level for the content
661  * @param expiration expiration time for the content
662  * @param msg set to an error message
663  * @return GNUNET_OK on success
664  */
665 static int
666 sqlite_plugin_put (void *cls,
667                    const GNUNET_HashCode * key,
668                    uint32_t size,
669                    const void *data,
670                    uint32_t type,
671                    uint32_t priority,
672                    uint32_t anonymity,
673                    struct GNUNET_TIME_Absolute expiration,
674                    char ** msg)
675 {
676   struct Plugin *plugin = cls;
677   int n;
678   sqlite3_stmt *stmt;
679   GNUNET_HashCode vhash;
680
681 #if DEBUG_SQLITE
682   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
683                    "sqlite",
684                    "Storing in database block with type %u/key `%s'/priority %u/expiration %llu (%lld).\n",
685                    type, 
686                    GNUNET_h2s(key),
687                    priority,
688                    (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).value,
689                    (long long) expiration.value);
690 #endif
691   GNUNET_CRYPTO_hash (data, size, &vhash);
692   stmt = plugin->insertContent;
693   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, size)) ||
694       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
695       (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
696       (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
697       (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, (sqlite3_int64) expiration.value)) ||
698       (SQLITE_OK !=
699        sqlite3_bind_blob (stmt, 6, key, sizeof (GNUNET_HashCode),
700                           SQLITE_TRANSIENT)) ||
701       (SQLITE_OK !=
702        sqlite3_bind_blob (stmt, 7, &vhash, sizeof (GNUNET_HashCode),
703                           SQLITE_TRANSIENT))
704       || (SQLITE_OK !=
705           sqlite3_bind_blob (stmt, 8, data, size,
706                              SQLITE_TRANSIENT)))
707     {
708       LOG_SQLITE (plugin,
709                   msg,
710                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
711       if (SQLITE_OK != sqlite3_reset (stmt))
712         LOG_SQLITE (plugin, NULL,
713                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
714       return GNUNET_SYSERR;
715     }
716   n = sqlite3_step (stmt);
717   if (n != SQLITE_DONE)
718     {
719       if (n == SQLITE_BUSY)
720         {
721           LOG_SQLITE (plugin, msg,
722                       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
723           sqlite3_reset (stmt);
724           GNUNET_break (0);
725           return GNUNET_NO;
726         }
727       LOG_SQLITE (plugin, msg,
728                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
729       sqlite3_reset (stmt);
730       return GNUNET_SYSERR;
731     }
732   if (SQLITE_OK != sqlite3_reset (stmt))
733     LOG_SQLITE (plugin, NULL,
734                 GNUNET_ERROR_TYPE_ERROR |
735                 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
736   plugin->lastSync++;
737   plugin->payload += size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
738   if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
739     sync_stats (plugin);
740   return GNUNET_OK;
741 }
742
743
744 /**
745  * Update the priority for a particular key in the datastore.  If
746  * the expiration time in value is different than the time found in
747  * the datastore, the higher value should be kept.  For the
748  * anonymity level, the lower value is to be used.  The specified
749  * priority should be added to the existing priority, ignoring the
750  * priority in value.
751  *
752  * Note that it is possible for multiple values to match this put.
753  * In that case, all of the respective values are updated.
754  *
755  * @param uid unique identifier of the datum
756  * @param delta by how much should the priority
757  *     change?  If priority + delta < 0 the
758  *     priority should be set to 0 (never go
759  *     negative).
760  * @param expire new expiration time should be the
761  *     MAX of any existing expiration time and
762  *     this value
763  * @param msg set to an error message
764  * @return GNUNET_OK on success
765  */
766 static int
767 sqlite_plugin_update (void *cls,
768                       uint64_t uid,
769                       int delta, struct GNUNET_TIME_Absolute expire,
770                       char **msg)
771 {
772   struct Plugin *plugin = cls;
773   int n;
774
775   sqlite3_bind_int (plugin->updPrio, 1, delta);
776   sqlite3_bind_int64 (plugin->updPrio, 2, expire.value);
777   sqlite3_bind_int64 (plugin->updPrio, 3, uid);
778   n = sqlite3_step (plugin->updPrio);
779   if (n != SQLITE_OK)
780     LOG_SQLITE (plugin, msg,
781                 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
782                 "sqlite3_step");
783 #if DEBUG_SQLITE
784   else
785     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
786                      "sqlite",
787                      "Block updated\n");
788 #endif
789   sqlite3_reset (plugin->updPrio);
790
791   if (n == SQLITE_BUSY)
792     return GNUNET_NO;
793   return n == SQLITE_OK ? GNUNET_OK : GNUNET_SYSERR;
794 }
795
796
797 struct IterContext
798 {
799   sqlite3_stmt *stmt_1;
800   sqlite3_stmt *stmt_2;
801   int is_asc;
802   int is_prio;
803   int is_migr;
804   int limit_nonanonymous;
805   uint32_t type;
806 };
807
808
809 static int
810 iter_next_prepare (void *cls,
811                    struct NextContext *nc)
812 {
813   struct IterContext *ic = cls;
814   struct Plugin *plugin;
815   int ret;
816
817   if (nc == NULL)
818     {
819 #if DEBUG_SQLITE
820       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
821                   "Asked to clean up iterator state.\n");
822 #endif
823       sqlite3_finalize (ic->stmt_1);
824       sqlite3_finalize (ic->stmt_2);
825       return GNUNET_SYSERR;
826     }
827   sqlite3_reset (ic->stmt_1);
828   sqlite3_reset (ic->stmt_2);
829   plugin = nc->plugin;
830   if (ic->is_prio)
831     {
832 #if DEBUG_SQLITE
833       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
834                   "Restricting to results larger than the last priority %u\n",
835                   nc->lastPriority);
836 #endif
837       sqlite3_bind_int (ic->stmt_1, 1, nc->lastPriority);
838       sqlite3_bind_int (ic->stmt_2, 1, nc->lastPriority);
839     }
840   else
841     {
842 #if DEBUG_SQLITE
843       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
844                   "Restricting to results larger than the last expiration %llu\n",
845                   (unsigned long long) nc->lastExpiration.value);
846 #endif
847       sqlite3_bind_int64 (ic->stmt_1, 1, nc->lastExpiration.value);
848       sqlite3_bind_int64 (ic->stmt_2, 1, nc->lastExpiration.value);
849     }
850 #if DEBUG_SQLITE
851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852               "Restricting to results larger than the last key `%s'\n",
853               GNUNET_h2s(&nc->lastKey));
854 #endif
855   sqlite3_bind_blob (ic->stmt_1, 2, 
856                      &nc->lastKey, 
857                      sizeof (GNUNET_HashCode),
858                      SQLITE_TRANSIENT);
859   if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_1)))
860     {      
861 #if DEBUG_SQLITE
862       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863                   "Result found using iterator 1\n");
864 #endif
865       nc->stmt = ic->stmt_1;
866       return GNUNET_OK;
867     }
868   if (ret != SQLITE_DONE)
869     {
870       LOG_SQLITE (plugin, NULL,
871                   GNUNET_ERROR_TYPE_ERROR |
872                   GNUNET_ERROR_TYPE_BULK,
873                   "sqlite3_step");
874       return GNUNET_SYSERR;
875     }
876   if (SQLITE_OK != sqlite3_reset (ic->stmt_1))
877     LOG_SQLITE (plugin, NULL,
878                 GNUNET_ERROR_TYPE_ERROR | 
879                 GNUNET_ERROR_TYPE_BULK, 
880                 "sqlite3_reset");
881   if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_2))) 
882     {
883 #if DEBUG_SQLITE
884       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885                   "Result found using iterator 2\n");
886 #endif
887       nc->stmt = ic->stmt_2;
888       return GNUNET_OK;
889     }
890   if (ret != SQLITE_DONE)
891     {
892       LOG_SQLITE (plugin, NULL,
893                   GNUNET_ERROR_TYPE_ERROR |
894                   GNUNET_ERROR_TYPE_BULK,
895                   "sqlite3_step");
896       return GNUNET_SYSERR;
897     }
898   if (SQLITE_OK != sqlite3_reset (ic->stmt_2))
899     LOG_SQLITE (plugin, NULL,
900                 GNUNET_ERROR_TYPE_ERROR |
901                 GNUNET_ERROR_TYPE_BULK,
902                 "sqlite3_reset");
903 #if DEBUG_SQLITE
904   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
905               "No result found using either iterator\n");
906 #endif
907   return GNUNET_NO;
908 }
909
910
911 /**
912  * Call a method for each key in the database and
913  * call the callback method on it.
914  *
915  * @param type entries of which type should be considered?
916  * @param iter function to call on each matching value;
917  *        will be called once with a NULL value at the end
918  * @param iter_cls closure for iter
919  * @return the number of results processed,
920  *         GNUNET_SYSERR on error
921  */
922 static void
923 basic_iter (struct Plugin *plugin,
924             uint32_t type,
925             int is_asc,
926             int is_prio,
927             int is_migr,
928             int limit_nonanonymous,
929             const char *stmt_str_1,
930             const char *stmt_str_2,
931             PluginIterator iter,
932             void *iter_cls)
933 {
934   static struct GNUNET_TIME_Absolute zero;
935   struct NextContext *nc;
936   struct IterContext *ic;
937   sqlite3_stmt *stmt_1;
938   sqlite3_stmt *stmt_2;
939
940 #if DEBUG_SQLITE
941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942               "At %llu, using queries `%s' and `%s'\n",
943               (unsigned long long) GNUNET_TIME_absolute_get ().value,
944               stmt_str_1,
945               stmt_str_2);
946 #endif
947   if (sq_prepare (plugin->dbh, stmt_str_1, &stmt_1) != SQLITE_OK)
948     {
949       LOG_SQLITE (plugin, NULL,
950                   GNUNET_ERROR_TYPE_ERROR |
951                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
952       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
953       return;
954     }
955   if (sq_prepare (plugin->dbh, stmt_str_2, &stmt_2) != SQLITE_OK)
956     {
957       LOG_SQLITE (plugin, NULL,
958                   GNUNET_ERROR_TYPE_ERROR |
959                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
960       sqlite3_finalize (stmt_1);
961       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
962       return;
963     }
964   nc = GNUNET_malloc (sizeof(struct NextContext) + 
965                       sizeof(struct IterContext));
966   nc->plugin = plugin;
967   nc->iter = iter;
968   nc->iter_cls = iter_cls;
969   nc->stmt = NULL;
970   ic = (struct IterContext*) &nc[1];
971   ic->stmt_1 = stmt_1;
972   ic->stmt_2 = stmt_2;
973   ic->type = type;
974   ic->is_asc = is_asc;
975   ic->is_prio = is_prio;
976   ic->is_migr = is_migr;
977   ic->limit_nonanonymous = limit_nonanonymous;
978   nc->prep = &iter_next_prepare;
979   nc->prep_cls = ic;
980   if (is_asc)
981     {
982       nc->lastPriority = 0;
983       nc->lastExpiration.value = 0;
984       memset (&nc->lastKey, 0, sizeof (GNUNET_HashCode));
985     }
986   else
987     {
988       nc->lastPriority = 0x7FFFFFFF;
989       nc->lastExpiration.value = 0x7FFFFFFFFFFFFFFFLL;
990       memset (&nc->lastKey, 255, sizeof (GNUNET_HashCode));
991     }
992   sqlite_next_request (nc, GNUNET_NO);
993 }
994
995
996 /**
997  * Select a subset of the items in the datastore and call
998  * the given iterator for each of them.
999  *
1000  * @param type entries of which type should be considered?
1001  *        Use 0 for any type.
1002  * @param iter function to call on each matching value;
1003  *        will be called once with a NULL value at the end
1004  * @param iter_cls closure for iter
1005  */
1006 static void
1007 sqlite_plugin_iter_low_priority (void *cls,
1008                                  uint32_t type,
1009                                  PluginIterator iter,
1010                                  void *iter_cls)
1011 {
1012   basic_iter (cls,
1013               type, 
1014               GNUNET_YES, GNUNET_YES, 
1015               GNUNET_NO, GNUNET_NO,
1016               SELECT_IT_LOW_PRIORITY_1,
1017               SELECT_IT_LOW_PRIORITY_2, 
1018               iter, iter_cls);
1019 }
1020
1021
1022 /**
1023  * Select a subset of the items in the datastore and call
1024  * the given iterator for each of them.
1025  *
1026  * @param type entries of which type should be considered?
1027  *        Use 0 for any type.
1028  * @param iter function to call on each matching value;
1029  *        will be called once with a NULL value at the end
1030  * @param iter_cls closure for iter
1031  */
1032 static void
1033 sqlite_plugin_iter_zero_anonymity (void *cls,
1034                                    uint32_t type,
1035                                    PluginIterator iter,
1036                                    void *iter_cls)
1037 {
1038   struct GNUNET_TIME_Absolute now;
1039   char *q1;
1040   char *q2;
1041
1042   now = GNUNET_TIME_absolute_get ();
1043   GNUNET_asprintf (&q1, SELECT_IT_NON_ANONYMOUS_1,
1044                    (unsigned long long) now.value);
1045   GNUNET_asprintf (&q2, SELECT_IT_NON_ANONYMOUS_2,
1046                    (unsigned long long) now.value);
1047   basic_iter (cls,
1048               type, 
1049               GNUNET_NO, GNUNET_YES, 
1050               GNUNET_NO, GNUNET_YES,
1051               q1,
1052               q2,
1053               iter, iter_cls);
1054   GNUNET_free (q1);
1055   GNUNET_free (q2);
1056 }
1057
1058
1059
1060 /**
1061  * Select a subset of the items in the datastore and call
1062  * the given iterator for each of them.
1063  *
1064  * @param type entries of which type should be considered?
1065  *        Use 0 for any type.
1066  * @param iter function to call on each matching value;
1067  *        will be called once with a NULL value at the end
1068  * @param iter_cls closure for iter
1069  */
1070 static void
1071 sqlite_plugin_iter_ascending_expiration (void *cls,
1072                                          uint32_t type,
1073                                          PluginIterator iter,
1074                                          void *iter_cls)
1075 {
1076   struct GNUNET_TIME_Absolute now;
1077   char *q1;
1078   char *q2;
1079
1080   now = GNUNET_TIME_absolute_get ();
1081   GNUNET_asprintf (&q1, SELECT_IT_EXPIRATION_TIME_1,
1082                    (unsigned long long) 0*now.value);
1083   GNUNET_asprintf (&q2, SELECT_IT_EXPIRATION_TIME_2,
1084                    (unsigned long long) 0*now.value);
1085   basic_iter (cls,
1086               type, 
1087               GNUNET_YES, GNUNET_NO, 
1088               GNUNET_NO, GNUNET_NO,
1089               q1, q2,
1090               iter, iter_cls);
1091   GNUNET_free (q1);
1092   GNUNET_free (q2);
1093 }
1094
1095
1096 /**
1097  * Select a subset of the items in the datastore and call
1098  * the given iterator for each of them.
1099  *
1100  * @param type entries of which type should be considered?
1101  *        Use 0 for any type.
1102  * @param iter function to call on each matching value;
1103  *        will be called once with a NULL value at the end
1104  * @param iter_cls closure for iter
1105  */
1106 static void
1107 sqlite_plugin_iter_migration_order (void *cls,
1108                                     uint32_t type,
1109                                     PluginIterator iter,
1110                                     void *iter_cls)
1111 {
1112   struct GNUNET_TIME_Absolute now;
1113   char *q;
1114
1115   now = GNUNET_TIME_absolute_get ();
1116   GNUNET_asprintf (&q, SELECT_IT_MIGRATION_ORDER_2,
1117                    (unsigned long long) now.value);
1118   basic_iter (cls,
1119               type, 
1120               GNUNET_NO, GNUNET_NO, 
1121               GNUNET_YES, GNUNET_NO,
1122               SELECT_IT_MIGRATION_ORDER_1,
1123               q,
1124               iter, iter_cls);
1125   GNUNET_free (q);
1126 }
1127
1128
1129 static int
1130 all_next_prepare (void *cls,
1131                   struct NextContext *nc)
1132 {
1133   struct Plugin *plugin;
1134   int ret;
1135
1136   if (nc == NULL)
1137     {
1138 #if DEBUG_SQLITE
1139       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1140                   "Asked to clean up iterator state.\n");
1141 #endif
1142       return GNUNET_SYSERR;
1143     }
1144   plugin = nc->plugin;
1145   if (SQLITE_ROW == (ret = sqlite3_step (nc->stmt)))
1146     {      
1147       return GNUNET_OK;
1148     }
1149   if (ret != SQLITE_DONE)
1150     {
1151       LOG_SQLITE (plugin, NULL,
1152                   GNUNET_ERROR_TYPE_ERROR |
1153                   GNUNET_ERROR_TYPE_BULK,
1154                   "sqlite3_step");
1155       return GNUNET_SYSERR;
1156     }
1157   return GNUNET_NO;
1158 }
1159
1160
1161 /**
1162  * Select a subset of the items in the datastore and call
1163  * the given iterator for each of them.
1164  *
1165  * @param type entries of which type should be considered?
1166  *        Use 0 for any type.
1167  * @param iter function to call on each matching value;
1168  *        will be called once with a NULL value at the end
1169  * @param iter_cls closure for iter
1170  */
1171 static void
1172 sqlite_plugin_iter_all_now (void *cls,
1173                             uint32_t type,
1174                             PluginIterator iter,
1175                             void *iter_cls)
1176 {
1177   static struct GNUNET_TIME_Absolute zero;
1178   struct Plugin *plugin = cls;
1179   struct NextContext *nc;
1180   sqlite3_stmt *stmt;
1181
1182   if (sq_prepare (plugin->dbh, 
1183                   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080",
1184                   &stmt) != SQLITE_OK)
1185     {
1186       LOG_SQLITE (plugin, NULL,
1187                   GNUNET_ERROR_TYPE_ERROR |
1188                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
1189       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1190       return;
1191     }
1192   nc = GNUNET_malloc (sizeof(struct NextContext));
1193   nc->plugin = plugin;
1194   nc->iter = iter;
1195   nc->iter_cls = iter_cls;
1196   nc->stmt = stmt;
1197   nc->prep = &all_next_prepare;
1198   nc->prep_cls = NULL;
1199   sqlite_next_request (nc, GNUNET_NO);
1200 }
1201
1202
1203 struct GetNextContext
1204 {
1205   int total;
1206   int off;
1207   int have_vhash;
1208   unsigned int type;
1209   sqlite3_stmt *stmt;
1210   GNUNET_HashCode key;
1211   GNUNET_HashCode vhash;
1212 };
1213
1214
1215 static int
1216 get_next_prepare (void *cls,
1217                   struct NextContext *nc)
1218 {
1219   struct GetNextContext *gnc = cls;
1220   int sqoff;
1221   int ret;
1222   int limit_off;
1223
1224   if (nc == NULL)
1225     {
1226       sqlite3_finalize (gnc->stmt);
1227       return GNUNET_SYSERR;
1228     }
1229   if (nc->count == gnc->total)
1230     return GNUNET_NO;
1231   if (nc->count + gnc->off == gnc->total)
1232     nc->last_rowid = 0;
1233   if (nc->count == 0)
1234     limit_off = gnc->off;
1235   else
1236     limit_off = 0;
1237   sqoff = 1;
1238   sqlite3_reset (nc->stmt);
1239   ret = sqlite3_bind_blob (nc->stmt,
1240                            sqoff++,
1241                            &gnc->key, 
1242                            sizeof (GNUNET_HashCode),
1243                            SQLITE_TRANSIENT);
1244   if ((gnc->have_vhash) && (ret == SQLITE_OK))
1245     ret = sqlite3_bind_blob (nc->stmt,
1246                              sqoff++,
1247                              &gnc->vhash,
1248                              sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1249   if ((gnc->type != 0) && (ret == SQLITE_OK))
1250     ret = sqlite3_bind_int (nc->stmt, sqoff++, gnc->type);
1251   if (ret == SQLITE_OK)
1252     ret = sqlite3_bind_int64 (nc->stmt, sqoff++, nc->last_rowid + 1);
1253   if (ret == SQLITE_OK)
1254     ret = sqlite3_bind_int (nc->stmt, sqoff++, limit_off);
1255   if (ret != SQLITE_OK)
1256     return GNUNET_SYSERR;
1257   if (SQLITE_ROW != sqlite3_step (nc->stmt))
1258     return GNUNET_NO;
1259   return GNUNET_OK;
1260 }
1261
1262
1263 /**
1264  * Iterate over the results for a particular key
1265  * in the datastore.
1266  *
1267  * @param cls closure
1268  * @param key maybe NULL (to match all entries)
1269  * @param vhash hash of the value, maybe NULL (to
1270  *        match all values that have the right key).
1271  *        Note that for DBlocks there is no difference
1272  *        betwen key and vhash, but for other blocks
1273  *        there may be!
1274  * @param type entries of which type are relevant?
1275  *     Use 0 for any type.
1276  * @param iter function to call on each matching value;
1277  *        will be called once with a NULL value at the end
1278  * @param iter_cls closure for iter
1279  */
1280 static void
1281 sqlite_plugin_get (void *cls,
1282                    const GNUNET_HashCode * key,
1283                    const GNUNET_HashCode * vhash,
1284                    uint32_t type,
1285                    PluginIterator iter, void *iter_cls)
1286 {
1287   static struct GNUNET_TIME_Absolute zero;
1288   struct Plugin *plugin = cls;
1289   struct GetNextContext *gpc;
1290   struct NextContext *nc;
1291   int ret;
1292   int total;
1293   sqlite3_stmt *stmt;
1294   char scratch[256];
1295   int sqoff;
1296
1297   GNUNET_assert (iter != NULL);
1298   if (key == NULL)
1299     {
1300       sqlite_plugin_iter_low_priority (cls, type, iter, iter_cls);
1301       return;
1302     }
1303   GNUNET_snprintf (scratch, 256,
1304                    "SELECT count(*) FROM gn080 WHERE hash=:1%s%s",
1305                    vhash == NULL ? "" : " AND vhash=:2",
1306                    type == 0 ? "" : (vhash ==
1307                                      NULL) ? " AND type=:2" : " AND type=:3");
1308   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1309     {
1310       LOG_SQLITE (plugin, NULL,
1311                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1312       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1313       return;
1314     }
1315   sqoff = 1;
1316   ret = sqlite3_bind_blob (stmt,
1317                            sqoff++,
1318                            key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1319   if ((vhash != NULL) && (ret == SQLITE_OK))
1320     ret = sqlite3_bind_blob (stmt,
1321                              sqoff++,
1322                              vhash,
1323                              sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1324   if ((type != 0) && (ret == SQLITE_OK))
1325     ret = sqlite3_bind_int (stmt, sqoff++, type);
1326   if (SQLITE_OK != ret)
1327     {
1328       LOG_SQLITE (plugin, NULL,
1329                   GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
1330       sqlite3_reset (stmt);
1331       sqlite3_finalize (stmt);
1332       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1333       return;
1334     }
1335   ret = sqlite3_step (stmt);
1336   if (ret != SQLITE_ROW)
1337     {
1338       LOG_SQLITE (plugin, NULL,
1339                   GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK, 
1340                   "sqlite_step");
1341       sqlite3_reset (stmt);
1342       sqlite3_finalize (stmt);
1343       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1344       return;
1345     }
1346   total = sqlite3_column_int (stmt, 0);
1347   sqlite3_reset (stmt);
1348   sqlite3_finalize (stmt);
1349   if (0 == total)
1350     {
1351       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1352       return;
1353     }
1354
1355   GNUNET_snprintf (scratch, 256,
1356                    "SELECT size, type, prio, anonLevel, expire, hash, value, _ROWID_ "
1357                    "FROM gn080 WHERE hash=:1%s%s AND _ROWID_ >= :%d "
1358                    "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET :d",
1359                    vhash == NULL ? "" : " AND vhash=:2",
1360                    type == 0 ? "" : (vhash ==
1361                                      NULL) ? " AND type=:2" : " AND type=:3",
1362                    sqoff, sqoff + 1);
1363   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1364     {
1365       LOG_SQLITE (plugin, NULL,
1366                   GNUNET_ERROR_TYPE_ERROR |
1367                   GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1368       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1369       return;
1370     }
1371   nc = GNUNET_malloc (sizeof(struct NextContext) + 
1372                       sizeof(struct GetNextContext));
1373   nc->plugin = plugin;
1374   nc->iter = iter;
1375   nc->iter_cls = iter_cls;
1376   nc->stmt = stmt;
1377   gpc = (struct GetNextContext*) &nc[1];
1378   gpc->total = total;
1379   gpc->type = type;
1380   gpc->key = *key;
1381   gpc->stmt = stmt; /* alias used for freeing at the end! */
1382   if (NULL != vhash)
1383     {
1384       gpc->have_vhash = GNUNET_YES;
1385       gpc->vhash = *vhash;
1386     }
1387   gpc->off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
1388   nc->prep = &get_next_prepare;
1389   nc->prep_cls = gpc;
1390   sqlite_next_request (nc, GNUNET_NO);
1391 }
1392
1393
1394 /**
1395  * Drop database.
1396  */
1397 static void 
1398 sqlite_plugin_drop (void *cls)
1399 {
1400   struct Plugin *plugin = cls;
1401   plugin->drop_on_shutdown = GNUNET_YES;
1402 }
1403
1404
1405 /**
1406  * Callback function to process statistic values.
1407  *
1408  * @param cls closure
1409  * @param subsystem name of subsystem that created the statistic
1410  * @param name the name of the datum
1411  * @param value the current value
1412  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1413  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1414  */
1415 static int
1416 process_stat_in (void *cls,
1417                  const char *subsystem,
1418                  const char *name,
1419                  unsigned long long value,
1420                  int is_persistent)
1421 {
1422   struct Plugin *plugin = cls;
1423   plugin->payload += value;
1424   return GNUNET_OK;
1425 }
1426                                          
1427
1428 /**
1429  * Entry point for the plugin.
1430  */
1431 void *
1432 libgnunet_plugin_datastore_sqlite_init (void *cls)
1433 {
1434   static struct Plugin plugin;
1435   struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1436   struct GNUNET_DATASTORE_PluginFunctions *api;
1437
1438   if (plugin.env != NULL)
1439     return NULL; /* can only initialize once! */
1440   memset (&plugin, 0, sizeof(struct Plugin));
1441   plugin.env = env;
1442   plugin.statistics = GNUNET_STATISTICS_create (env->sched,
1443                                                 "sqlite",
1444                                                 env->cfg);
1445   GNUNET_STATISTICS_get (plugin.statistics,
1446                          "sqlite",
1447                          QUOTA_STAT_NAME,
1448                          GNUNET_TIME_UNIT_MINUTES,
1449                          NULL,
1450                          &process_stat_in,
1451                          &plugin);
1452   if (GNUNET_OK !=
1453       database_setup (env->cfg, &plugin))
1454     {
1455       database_shutdown (&plugin);
1456       return NULL;
1457     }
1458   api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1459   api->cls = &plugin;
1460   api->get_size = &sqlite_plugin_get_size;
1461   api->put = &sqlite_plugin_put;
1462   api->next_request = &sqlite_next_request;
1463   api->get = &sqlite_plugin_get;
1464   api->update = &sqlite_plugin_update;
1465   api->iter_low_priority = &sqlite_plugin_iter_low_priority;
1466   api->iter_zero_anonymity = &sqlite_plugin_iter_zero_anonymity;
1467   api->iter_ascending_expiration = &sqlite_plugin_iter_ascending_expiration;
1468   api->iter_migration_order = &sqlite_plugin_iter_migration_order;
1469   api->iter_all_now = &sqlite_plugin_iter_all_now;
1470   api->drop = &sqlite_plugin_drop;
1471   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1472                    "sqlite", _("Sqlite database running\n"));
1473   return api;
1474 }
1475
1476
1477 /**
1478  * Exit point from the plugin.
1479  */
1480 void *
1481 libgnunet_plugin_datastore_sqlite_done (void *cls)
1482 {
1483   char *fn;
1484   struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1485   struct Plugin *plugin = api->cls;
1486
1487   fn = NULL;
1488   if (plugin->drop_on_shutdown)
1489     fn = GNUNET_strdup (plugin->fn);
1490   database_shutdown (plugin);
1491   plugin->env = NULL; 
1492   plugin->payload = 0;
1493   GNUNET_free (api);
1494   if (fn != NULL)
1495     {
1496       if (0 != UNLINK(fn))
1497         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1498                                   "unlink",
1499                                   fn);
1500       GNUNET_free (fn);
1501     }
1502   return NULL;
1503 }
1504
1505 /* end of plugin_datastore_sqlite.c */