-more logging
[oweals/gnunet.git] / src / namestore / plugin_namestore_sqlite.c
1  /*
2   * This file is part of GNUnet
3   * (C) 2009-2013 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 namestore/plugin_namestore_sqlite.c
23  * @brief sqlite-based namestore backend
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_namestore_plugin.h"
29 #include "gnunet_namestore_service.h"
30 #include "namestore.h"
31 #include <sqlite3.h>
32
33 /**
34  * After how many ms "busy" should a DB operation fail for good?  A
35  * low value makes sure that we are more responsive to requests
36  * (especially PUTs).  A high value guarantees a higher success rate
37  * (SELECTs in iterate can take several seconds despite LIMIT=1).
38  *
39  * The default value of 1s should ensure that users do not experience
40  * huge latencies while at the same time allowing operations to
41  * succeed with reasonable probability.
42  */
43 #define BUSY_TIMEOUT_MS 1000
44
45
46 /**
47  * Log an error message at log-level 'level' that indicates
48  * a failure of the command 'cmd' on file 'filename'
49  * with the message given by strerror(errno).
50  */
51 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "namestore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
52
53 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-sqlite", __VA_ARGS__)
54
55
56 /**
57  * Context for all functions in this plugin.
58  */
59 struct Plugin
60 {
61
62   const struct GNUNET_CONFIGURATION_Handle *cfg;
63
64   /**
65    * Database filename.
66    */
67   char *fn;
68
69   /**
70    * Native SQLite database handle.
71    */
72   sqlite3 *dbh;
73
74   /**
75    * Precompiled SQL for caching a block
76    */
77   sqlite3_stmt *cache_block;
78
79   /**
80    * Precompiled SQL for looking up a block
81    */
82   sqlite3_stmt *lookup_block;
83
84   /**
85    * Precompiled SQL for removing expired blocks
86    */
87   sqlite3_stmt *expire_blocks;
88
89   /**
90    * Precompiled SQL to store records.
91    */
92   sqlite3_stmt *store_records;
93
94   /**
95    * Precompiled SQL to deltete existing records.
96    */
97   sqlite3_stmt *delete_records;
98
99   /**
100    * Precompiled SQL for iterate records within a zone.
101    */
102   sqlite3_stmt *iterate_zone;
103
104   /**
105    * Precompiled SQL for iterate all records within all zones.
106    */
107   sqlite3_stmt *iterate_all_zones;
108
109   /**
110    * Precompiled SQL to for reverse lookup based on PKEY.
111    */
112   sqlite3_stmt *zone_to_name;
113
114 };
115
116
117 /**
118  * @brief Prepare a SQL statement
119  *
120  * @param dbh handle to the database
121  * @param zSql SQL statement, UTF-8 encoded
122  * @param ppStmt set to the prepared statement
123  * @return 0 on success
124  */
125 static int
126 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
127 {
128   char *dummy;
129   int result;
130
131   result =
132       sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
133                           (const char **) &dummy);
134   LOG (GNUNET_ERROR_TYPE_DEBUG, 
135        "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
136   return result;
137 }
138
139
140 /**
141  * Create our database indices.
142  *
143  * @param dbh handle to the database
144  */
145 static void
146 create_indices (sqlite3 * dbh)
147 {
148   /* create indices */
149   if ( (SQLITE_OK !=
150         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_query_hash ON ns096blocks (query,expiration_time)",
151                       NULL, NULL, NULL)) ||
152        (SQLITE_OK !=
153         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_block_expiration ON ns096blocks (expiration_time)",
154                       NULL, NULL, NULL)) ||
155        (SQLITE_OK !=
156         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_pkey_reverse ON ns096records (zone_private_key,pkey_hash)",
157                       NULL, NULL, NULL)) ||
158        (SQLITE_OK !=
159         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS ir_pkey_iter ON ns096records (zone_private_key,rvalue)",
160                       NULL, NULL, NULL)) ||
161        (SQLITE_OK !=
162         sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS it_iter ON ns096records (rvalue)",
163                       NULL, NULL, NULL)) )
164     LOG (GNUNET_ERROR_TYPE_ERROR, 
165          "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
166 }
167
168
169 #if 0
170 #define CHECK(a) GNUNET_break(a)
171 #define ENULL NULL
172 #else
173 #define ENULL &e
174 #define ENULL_DEFINED 1
175 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
176 #endif
177
178
179 /**
180  * Initialize the database connections and associated
181  * data structures (create tables and indices
182  * as needed as well).
183  *
184  * @param plugin the plugin context (state for this module)
185  * @return #GNUNET_OK on success
186  */
187 static int
188 database_setup (struct Plugin *plugin)
189 {
190   sqlite3_stmt *stmt;
191   char *afsdir;
192 #if ENULL_DEFINED
193   char *e;
194 #endif
195
196   if (GNUNET_OK !=
197       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "namestore-sqlite",
198                                                "FILENAME", &afsdir))
199   {
200     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
201                                "namestore-sqlite", "FILENAME");
202     return GNUNET_SYSERR;
203   }
204   if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
205   {
206     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
207     {
208       GNUNET_break (0);
209       GNUNET_free (afsdir);
210       return GNUNET_SYSERR;
211     }
212   }
213   /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
214   plugin->fn = afsdir;
215
216   /* Open database and precompile statements */
217   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
218   {
219     LOG (GNUNET_ERROR_TYPE_ERROR,
220          _("Unable to initialize SQLite: %s.\n"),
221          sqlite3_errmsg (plugin->dbh));
222     return GNUNET_SYSERR;
223   }
224   CHECK (SQLITE_OK ==
225          sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
226                        ENULL));
227   CHECK (SQLITE_OK ==
228          sqlite3_exec (plugin->dbh, "PRAGMA synchronous=NORMAL", NULL, NULL,
229                        ENULL));
230   CHECK (SQLITE_OK ==
231          sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
232                        ENULL));
233   CHECK (SQLITE_OK ==
234          sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
235                        NULL, ENULL));
236   CHECK (SQLITE_OK ==
237          sqlite3_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"", NULL,
238                        NULL, ENULL));
239   CHECK (SQLITE_OK ==
240          sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
241                        ENULL));
242   CHECK (SQLITE_OK ==
243          sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
244                        ENULL));
245   CHECK (SQLITE_OK ==
246          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
247                        ENULL));
248
249   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
250
251
252   /* Create tables */
253   CHECK (SQLITE_OK ==
254          sq_prepare (plugin->dbh,
255                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096blocks'",
256                      &stmt));
257   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
258       (sqlite3_exec
259        (plugin->dbh,
260         "CREATE TABLE ns096blocks (" 
261         " query BLOB NOT NULL DEFAULT ''," 
262         " block BLOB NOT NULL DEFAULT ''," 
263         " expiration_time INT8 NOT NULL DEFAULT 0" 
264         ")", 
265         NULL, NULL, NULL) != SQLITE_OK))
266   {
267     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
268     sqlite3_finalize (stmt);
269     return GNUNET_SYSERR;
270   }
271   sqlite3_finalize (stmt);
272
273   CHECK (SQLITE_OK ==
274          sq_prepare (plugin->dbh,
275                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'ns096records'",
276                      &stmt));
277   if ((sqlite3_step (stmt) == SQLITE_DONE) &&
278       (sqlite3_exec
279        (plugin->dbh,
280         "CREATE TABLE ns096records (" 
281         " zone_private_key BLOB NOT NULL DEFAULT ''," 
282         " pkey_hash BLOB," 
283         " rvalue INT8 NOT NULL DEFAULT '',"
284         " record_count INT NOT NULL DEFAULT 0,"
285         " record_data BLOB NOT NULL DEFAULT '',"
286         " label TEXT NOT NULL DEFAULT ''" 
287         ")", 
288         NULL, NULL, NULL) != SQLITE_OK))
289   {
290     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
291     sqlite3_finalize (stmt);
292     return GNUNET_SYSERR;
293   }
294   sqlite3_finalize (stmt);
295
296   create_indices (plugin->dbh);
297
298   if ((sq_prepare
299        (plugin->dbh,
300         "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
301         &plugin->cache_block) != SQLITE_OK) ||
302       (sq_prepare
303        (plugin->dbh,
304         "DELETE FROM ns096blocks WHERE expiration_time<?",
305         &plugin->expire_blocks) != SQLITE_OK) ||
306       (sq_prepare
307        (plugin->dbh,
308         "SELECT block FROM ns096blocks WHERE query=? ORDER BY expiration_time DESC LIMIT 1",
309         &plugin->lookup_block) != SQLITE_OK) ||
310       (sq_prepare
311        (plugin->dbh,
312         "INSERT INTO ns096records (zone_private_key, pkey_hash, rvalue, record_count, record_data, label)"
313         " VALUES (?, ?, ?, ?, ?, ?)",
314         &plugin->store_records) != SQLITE_OK) ||
315       (sq_prepare
316        (plugin->dbh,
317         "DELETE FROM ns096records WHERE zone_private_key=? AND label=?",
318         &plugin->delete_records) != SQLITE_OK) ||
319       (sq_prepare
320        (plugin->dbh,
321         "SELECT record_count,record_data,label"
322         " FROM ns096records WHERE zone_private_key=? AND pkey_hash=?",
323         &plugin->zone_to_name) != SQLITE_OK) ||
324       (sq_prepare
325        (plugin->dbh,
326         "SELECT record_count,record_data,label" 
327         " FROM ns096records WHERE zone_private_key=? ORDER BY rvalue LIMIT 1 OFFSET ?",
328         &plugin->iterate_zone) != SQLITE_OK) ||
329       (sq_prepare
330        (plugin->dbh,
331         "SELECT record_count,record_data,label,zone_private_key" 
332         " FROM ns096records ORDER BY rvalue LIMIT 1 OFFSET ?",
333         &plugin->iterate_all_zones) != SQLITE_OK) 
334       )
335   {
336     LOG_SQLITE (plugin,GNUNET_ERROR_TYPE_ERROR, "precompiling");
337     return GNUNET_SYSERR;
338   }
339   return GNUNET_OK;
340 }
341
342
343 /**
344  * Shutdown database connection and associate data
345  * structures.
346  * @param plugin the plugin context (state for this module)
347  */
348 static void
349 database_shutdown (struct Plugin *plugin)
350 {
351   int result;
352   sqlite3_stmt *stmt;
353
354   if (NULL != plugin->cache_block)
355     sqlite3_finalize (plugin->cache_block);
356   if (NULL != plugin->lookup_block)
357     sqlite3_finalize (plugin->lookup_block);
358   if (NULL != plugin->expire_blocks)
359     sqlite3_finalize (plugin->expire_blocks);
360   if (NULL != plugin->store_records)
361     sqlite3_finalize (plugin->store_records);
362   if (NULL != plugin->delete_records)
363     sqlite3_finalize (plugin->delete_records);
364   if (NULL != plugin->iterate_zone)
365     sqlite3_finalize (plugin->iterate_zone);
366   if (NULL != plugin->iterate_all_zones)
367     sqlite3_finalize (plugin->iterate_all_zones);
368   if (NULL != plugin->zone_to_name)
369     sqlite3_finalize (plugin->zone_to_name);
370   result = sqlite3_close (plugin->dbh);
371   if (result == SQLITE_BUSY)
372   {
373     LOG (GNUNET_ERROR_TYPE_WARNING,
374          _("Tried to close sqlite without finalizing all prepared statements.\n"));
375     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
376     while (stmt != NULL)
377     {
378       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
379                        "Closing statement %p\n", stmt);
380       result = sqlite3_finalize (stmt);
381       if (result != SQLITE_OK)
382         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
383                          "Failed to close statement %p: %d\n", stmt, result);
384       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
385     }
386     result = sqlite3_close (plugin->dbh);
387   }
388   if (SQLITE_OK != result)
389     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
390
391   GNUNET_free_non_null (plugin->fn);
392 }
393
394
395 /**
396  * Removes any expired block.
397  *
398  * @param plugin the plugin
399  */
400 static void
401 namestore_sqlite_expire_blocks (struct Plugin *plugin)
402 {
403   struct GNUNET_TIME_Absolute now;
404   int n;
405
406   now = GNUNET_TIME_absolute_get ();
407   if (SQLITE_OK != sqlite3_bind_int64 (plugin->expire_blocks, 
408                                        1, now.abs_value_us))
409   {
410     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
411                 "sqlite3_bind_XXXX");
412     if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
413       LOG_SQLITE (plugin,
414                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415                   "sqlite3_reset");
416     return;
417   }
418   n = sqlite3_step (plugin->expire_blocks);
419   if (SQLITE_OK != sqlite3_reset (plugin->expire_blocks))
420     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
421                 "sqlite3_reset");
422   switch (n)
423   {
424   case SQLITE_DONE:
425     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Records expired\n");
426     return;
427   case SQLITE_BUSY:
428     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
429                 "sqlite3_step");
430     return;
431   default:
432     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
433                 "sqlite3_step");
434     return;
435   }
436 }
437
438
439 /**
440  * Cache a block in the datastore.
441  *
442  * @param cls closure (internal context for the plugin)
443  * @param block block to cache
444  * @return GNUNET_OK on success, else GNUNET_SYSERR
445  */
446 static int 
447 namestore_sqlite_cache_block (void *cls, 
448                               const struct GNUNET_NAMESTORE_Block *block)
449 {
450   struct Plugin *plugin = cls;
451   struct GNUNET_HashCode query;
452   struct GNUNET_TIME_Absolute expiration;
453   size_t block_size;
454   int n;
455
456   namestore_sqlite_expire_blocks (plugin);
457   GNUNET_CRYPTO_hash (&block->derived_key, 
458                       sizeof (struct GNUNET_CRYPTO_EccPublicSignKey), 
459                       &query);
460   expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time);
461   block_size = ntohl (block->purpose.size) + 
462     sizeof (struct GNUNET_CRYPTO_EccPublicSignKey) + 
463     sizeof (struct GNUNET_CRYPTO_EccSignature); 
464   if (block_size > 64 * 65536)
465   {
466     GNUNET_break (0);
467     return GNUNET_SYSERR;
468   }
469   if ((SQLITE_OK != sqlite3_bind_blob (plugin->cache_block, 1, &query, sizeof (struct GNUNET_HashCode), SQLITE_STATIC)) ||
470       (SQLITE_OK != sqlite3_bind_blob (plugin->cache_block, 2, block, block_size, SQLITE_STATIC)) ||
471       (SQLITE_OK != sqlite3_bind_int64 (plugin->cache_block, 3, expiration.abs_value_us)))
472   {
473     LOG_SQLITE (plugin, 
474                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
475                 "sqlite3_bind_XXXX");
476     if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
477       LOG_SQLITE (plugin, 
478                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
479                   "sqlite3_reset");
480     return GNUNET_SYSERR;
481     
482   }
483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
484               "Caching block under derived key `%s'\n", 
485               GNUNET_h2s (&query));
486   n = sqlite3_step (plugin->cache_block);
487   if (SQLITE_OK != sqlite3_reset (plugin->cache_block))
488     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
489                 "sqlite3_reset");
490   switch (n)
491   {
492   case SQLITE_DONE:
493     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
494     return GNUNET_OK;
495   case SQLITE_BUSY:
496     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
497                 "sqlite3_step");
498     return GNUNET_NO;
499   default:
500     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
501                 "sqlite3_step");
502     return GNUNET_SYSERR;  
503   }
504 }
505
506
507 /**
508  * Get the block for a particular zone and label in the
509  * datastore.  Will return at most one result to the iterator.
510  *
511  * @param cls closure (internal context for the plugin)
512  * @param query hash of public key derived from the zone and the label
513  * @param iter function to call with the result
514  * @param iter_cls closure for iter
515  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
516  */
517 static int
518 namestore_sqlite_lookup_block (void *cls, 
519                                const struct GNUNET_HashCode *query,
520                                GNUNET_NAMESTORE_BlockCallback iter, void *iter_cls)
521 {
522   struct Plugin *plugin = cls;
523   int ret;
524   int sret;
525   size_t block_size;
526   const struct GNUNET_NAMESTORE_Block *block;
527
528   if (SQLITE_OK != sqlite3_bind_blob (plugin->lookup_block, 1,
529                                       query, sizeof (struct GNUNET_HashCode),
530                                       SQLITE_STATIC))
531   {
532     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
533                 "sqlite3_bind_XXXX");
534     if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
535       LOG_SQLITE (plugin,
536                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
537                   "sqlite3_reset");
538     return GNUNET_SYSERR;
539   }      
540   ret = GNUNET_NO;
541   if (SQLITE_ROW == (sret = sqlite3_step (plugin->lookup_block)))
542   {     
543     block = sqlite3_column_blob (plugin->lookup_block, 0);
544     block_size = sqlite3_column_bytes (plugin->lookup_block, 0);
545     if ( (block_size < sizeof (struct GNUNET_NAMESTORE_Block)) ||
546          (ntohl (block->purpose.size) + 
547           sizeof (struct GNUNET_CRYPTO_EccPublicSignKey) + 
548           sizeof (struct GNUNET_CRYPTO_EccSignature) != block_size) )
549     {
550       GNUNET_break (0);
551       ret = GNUNET_SYSERR;     
552     }
553     else
554     {
555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
556                   "Found block under derived key `%s'\n", 
557                   GNUNET_h2s (query));
558       iter (iter_cls, block);    
559       ret = GNUNET_YES;
560     }
561   }
562   else
563   {
564     if (SQLITE_DONE != sret)
565     {
566       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");    
567       ret = GNUNET_SYSERR;
568     }
569     else
570     {
571       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
572                   "No block found under derived key `%s'\n", 
573                   GNUNET_h2s (query));
574     }
575   }
576   if (SQLITE_OK != sqlite3_reset (plugin->lookup_block))
577     LOG_SQLITE (plugin,
578                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
579                 "sqlite3_reset");
580   return ret;
581 }
582
583
584 /**
585  * Store a record in the datastore.  Removes any existing record in the
586  * same zone with the same name.
587  *
588  * @param cls closure (internal context for the plugin)
589  * @param zone_key private key of the zone
590  * @param label name that is being mapped (at most 255 characters long)
591  * @param rd_count number of entries in 'rd' array
592  * @param rd array of records with data to store
593  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
594  */
595 static int 
596 namestore_sqlite_store_records (void *cls, 
597                                 const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
598                                 const char *label,
599                                 unsigned int rd_count,
600                                 const struct GNUNET_NAMESTORE_RecordData *rd)
601 {
602   struct Plugin *plugin = cls;
603   int n;
604   struct GNUNET_HashCode pkey_hash;
605   uint64_t rvalue;
606   size_t data_size;
607   unsigned int i;
608
609   memset (&pkey_hash, 0, sizeof (pkey_hash));
610   for (i=0;i<rd_count;i++)
611     if (GNUNET_NAMESTORE_TYPE_PKEY == rd[i].record_type)
612     {
613       GNUNET_break (sizeof (struct GNUNET_CRYPTO_EccPublicSignKey) == rd[i].data_size);
614       GNUNET_CRYPTO_hash (rd[i].data,
615                           rd[i].data_size,
616                           &pkey_hash);
617       break;
618     }
619   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
620   data_size = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
621   if (data_size > 64 * 65536)
622   {
623     GNUNET_break (0);
624     return GNUNET_SYSERR;
625   }
626   {
627     char data[data_size];
628
629     if (data_size != GNUNET_NAMESTORE_records_serialize (rd_count, rd,
630                                                          data_size, data))
631     {
632       GNUNET_break (0);
633       return GNUNET_SYSERR;
634     }
635
636     /* First delete 'old' records */
637     if ((SQLITE_OK != sqlite3_bind_blob (plugin->delete_records, 1, 
638                                          zone_key, sizeof (struct GNUNET_CRYPTO_EccPrivateKey), SQLITE_STATIC)) ||
639         (SQLITE_OK != sqlite3_bind_text (plugin->delete_records, 2, label, -1, SQLITE_STATIC)))
640     {
641       LOG_SQLITE (plugin, 
642                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
643                   "sqlite3_bind_XXXX");
644       if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
645         LOG_SQLITE (plugin, 
646                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
647                     "sqlite3_reset");
648       return GNUNET_SYSERR;
649       
650     }
651     n = sqlite3_step (plugin->delete_records);
652     if (SQLITE_OK != sqlite3_reset (plugin->delete_records))
653       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
654                   "sqlite3_reset");
655
656     if (0 != rd_count)
657     {
658       if ((SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 1, 
659                                            zone_key, sizeof (struct GNUNET_CRYPTO_EccPrivateKey), SQLITE_STATIC)) ||
660           (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 2,
661                                            &pkey_hash, sizeof (struct GNUNET_HashCode), SQLITE_STATIC)) ||
662           (SQLITE_OK != sqlite3_bind_int64 (plugin->store_records, 3, rvalue)) ||
663           (SQLITE_OK != sqlite3_bind_int (plugin->store_records, 4, rd_count)) ||
664           (SQLITE_OK != sqlite3_bind_blob (plugin->store_records, 5, data, data_size, SQLITE_STATIC)) ||
665           (SQLITE_OK != sqlite3_bind_text (plugin->store_records, 6, label, -1, SQLITE_STATIC)))
666       {
667         LOG_SQLITE (plugin, 
668                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
669                     "sqlite3_bind_XXXX");
670         if (SQLITE_OK != sqlite3_reset (plugin->store_records))
671           LOG_SQLITE (plugin, 
672                       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
673                       "sqlite3_reset");
674         return GNUNET_SYSERR;   
675       }
676       n = sqlite3_step (plugin->store_records);
677       if (SQLITE_OK != sqlite3_reset (plugin->store_records))
678         LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
679                     "sqlite3_reset");
680     }
681   }
682   switch (n)
683   {
684   case SQLITE_DONE:
685     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Record stored\n");
686     return GNUNET_OK;
687   case SQLITE_BUSY:
688     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
689                 "sqlite3_step");
690     return GNUNET_NO;
691   default:
692     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
693                 "sqlite3_step");
694     return GNUNET_SYSERR;  
695   }
696 }
697
698
699 /**
700  * The given 'sqlite' statement has been prepared to be run.
701  * It will return a record which should be given to the iterator.
702  * Runs the statement and parses the returned record.
703  *
704  * @param plugin plugin context
705  * @param stmt to run (and then clean up)
706  * @param zone_key private key of the zone
707  * @param iter iterator to call with the result
708  * @param iter_cls closure for @a iter
709  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
710  */
711 static int
712 get_record_and_call_iterator (struct Plugin *plugin,
713                               sqlite3_stmt *stmt,                             
714                               const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
715                               GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
716 {
717   unsigned int record_count;
718   size_t data_size;
719   const char *data;
720   const char *label;
721   int ret;
722   int sret;
723
724   ret = GNUNET_NO;
725   if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
726   {     
727     record_count = sqlite3_column_int (stmt, 0);
728     data_size = sqlite3_column_bytes (stmt, 1);
729     data = sqlite3_column_blob (stmt, 1);
730     label = (const char*) sqlite3_column_text (stmt, 2);
731     if (NULL == zone_key)
732     {
733       /* must be "iterate_all_zones", got one extra return value */
734       if (sizeof (struct GNUNET_CRYPTO_EccPrivateKey) !=
735           sqlite3_column_bytes (stmt, 3))
736       {
737         GNUNET_break (0);
738         ret = GNUNET_SYSERR;
739       }
740       else
741       {
742         zone_key = sqlite3_column_blob (stmt, 3);
743       }
744     }
745     if (record_count > 64 * 1024)
746     {
747       /* sanity check, don't stack allocate far too much just
748          because database might contain a large value here */
749       GNUNET_break (0);
750       ret = GNUNET_SYSERR;
751     } 
752     else
753     {
754       struct GNUNET_NAMESTORE_RecordData rd[record_count];
755
756       if (GNUNET_OK !=
757           GNUNET_NAMESTORE_records_deserialize (data_size, data,
758                                                 record_count, rd))
759       {
760         GNUNET_break (0);
761         ret = GNUNET_SYSERR;
762       }
763       else if (NULL != zone_key)
764       {
765         if (NULL != iter)
766                 iter (iter_cls, zone_key, label, record_count, rd);
767         ret = GNUNET_YES;
768       }
769     }
770   }
771   else
772   {
773     if (SQLITE_DONE != sret)
774       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
775   }
776   if (SQLITE_OK != sqlite3_reset (stmt))
777     LOG_SQLITE (plugin,
778                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
779                 "sqlite3_reset");
780   return ret;
781 }
782
783
784 /**
785  * Iterate over the results for a particular key and zone in the
786  * datastore.  Will return at most one result to the iterator.
787  *
788  * @param cls closure (internal context for the plugin)
789  * @param zone hash of public key of the zone, NULL to iterate over all zones
790  * @param offset offset in the list of all matching records
791  * @param iter function to call with the result
792  * @param iter_cls closure for @a iter
793  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
794  */
795 static int 
796 namestore_sqlite_iterate_records (void *cls, 
797                                   const struct GNUNET_CRYPTO_EccPrivateKey *zone,
798                                   uint64_t offset,
799                                   GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
800 {
801   struct Plugin *plugin = cls;
802   sqlite3_stmt *stmt;
803   int err;
804
805   if (NULL == zone)
806   {
807     stmt = plugin->iterate_all_zones;
808     err = (SQLITE_OK != sqlite3_bind_int64 (stmt, 1,
809                                             offset));
810   }
811   else
812   {
813     stmt = plugin->iterate_zone;
814     err = ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1, 
815                                              zone, sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
816                                              SQLITE_STATIC)) ||
817             (SQLITE_OK != sqlite3_bind_int64 (stmt, 2,
818                                               offset)) );
819   }
820   if (err)
821   {
822     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
823                 "sqlite3_bind_XXXX");
824     if (SQLITE_OK != sqlite3_reset (stmt))
825       LOG_SQLITE (plugin,
826                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
827                   "sqlite3_reset");
828     return GNUNET_SYSERR;
829   }      
830   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
831 }
832
833
834 /**
835  * Look for an existing PKEY delegation record for a given public key.
836  * Returns at most one result to the iterator.
837  *
838  * @param cls closure (internal context for the plugin)
839  * @param zone private key of the zone to look up in, never NULL
840  * @param value_zone public key of the target zone (value), never NULL
841  * @param iter function to call with the result
842  * @param iter_cls closure for @a iter
843  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
844  */
845 static int
846 namestore_sqlite_zone_to_name (void *cls, 
847                                const struct GNUNET_CRYPTO_EccPrivateKey *zone,
848                                const struct GNUNET_CRYPTO_EccPublicSignKey *value_zone,
849                                GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
850 {
851   struct Plugin *plugin = cls;
852   sqlite3_stmt *stmt;
853
854   stmt = plugin->zone_to_name;
855   if ( (SQLITE_OK != sqlite3_bind_blob (stmt, 1, 
856                                         zone, sizeof (struct GNUNET_CRYPTO_EccPrivateKey),
857                                         SQLITE_STATIC)) ||
858        (SQLITE_OK != sqlite3_bind_blob (stmt, 2, 
859                                         value_zone, sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
860                                         SQLITE_STATIC)) )
861   {
862     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
863                 "sqlite3_bind_XXXX");
864     if (SQLITE_OK != sqlite3_reset (stmt))
865       LOG_SQLITE (plugin,
866                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
867                   "sqlite3_reset");
868     return GNUNET_SYSERR;
869   }      
870   return get_record_and_call_iterator (plugin, stmt, zone, iter, iter_cls);
871 }
872
873
874 /**
875  * Entry point for the plugin.
876  *
877  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
878  * @return NULL on error, otherwise the plugin context
879  */
880 void *
881 libgnunet_plugin_namestore_sqlite_init (void *cls)
882 {
883   static struct Plugin plugin;
884   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
885   struct GNUNET_NAMESTORE_PluginFunctions *api;
886
887   if (NULL != plugin.cfg)
888     return NULL;                /* can only initialize once! */
889   memset (&plugin, 0, sizeof (struct Plugin));
890   plugin.cfg = cfg;  
891   if (GNUNET_OK != database_setup (&plugin))
892   {
893     database_shutdown (&plugin);
894     return NULL;
895   }
896   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
897   api->cls = &plugin;
898   api->cache_block = &namestore_sqlite_cache_block;
899   api->lookup_block = &namestore_sqlite_lookup_block;
900   api->store_records = &namestore_sqlite_store_records;
901   api->iterate_records = &namestore_sqlite_iterate_records;
902   api->zone_to_name = &namestore_sqlite_zone_to_name;
903   LOG (GNUNET_ERROR_TYPE_INFO, 
904        _("Sqlite database running\n"));
905   return api;
906 }
907
908
909 /**
910  * Exit point from the plugin.
911  *
912  * @param cls the plugin context (as returned by "init")
913  * @return always NULL
914  */
915 void *
916 libgnunet_plugin_namestore_sqlite_done (void *cls)
917 {
918   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
919   struct Plugin *plugin = api->cls;
920
921   database_shutdown (plugin);
922   plugin->cfg = NULL;
923   GNUNET_free (api);
924   LOG (GNUNET_ERROR_TYPE_DEBUG, 
925        "sqlite plugin is finished\n");
926   return NULL;
927 }
928
929 /* end of plugin_namestore_sqlite.c */