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