aboutsummaryrefslogtreecommitdiff
path: root/src/plugin/namecache/plugin_namecache_sqlite.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/plugin/namecache/plugin_namecache_sqlite.c')
-rw-r--r--src/plugin/namecache/plugin_namecache_sqlite.c589
1 files changed, 589 insertions, 0 deletions
diff --git a/src/plugin/namecache/plugin_namecache_sqlite.c b/src/plugin/namecache/plugin_namecache_sqlite.c
new file mode 100644
index 000000000..d8b485381
--- /dev/null
+++ b/src/plugin/namecache/plugin_namecache_sqlite.c
@@ -0,0 +1,589 @@
1/*
2 * This file is part of GNUnet
3 * Copyright (C) 2009-2013 GNUnet e.V.
4 *
5 * GNUnet is free software: you can redistribute it and/or modify it
6 * under the terms of the GNU Affero General Public License as published
7 * by the Free Software Foundation, either version 3 of the License,
8 * or (at your 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 * Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21/**
22 * @file namecache/plugin_namecache_sqlite.c
23 * @brief sqlite-based namecache backend
24 * @author Christian Grothoff
25 */
26#include "platform.h"
27#include "gnunet_sq_lib.h"
28#include "gnunet_namecache_plugin.h"
29#include "gnunet_namecache_service.h"
30#include "gnunet_gnsrecord_lib.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, \
52 "namecache-sqlite", _ ( \
53 "`%s' failed at %s:%d with error: %s\n"), \
54 cmd, \
55 __FILE__, __LINE__, \
56 sqlite3_errmsg ( \
57 db->dbh)); \
58} while (0)
59
60#define LOG(kind, ...) GNUNET_log_from (kind, "namecache-sqlite", __VA_ARGS__)
61
62
63/**
64 * Context for all functions in this plugin.
65 */
66struct Plugin
67{
68 const struct GNUNET_CONFIGURATION_Handle *cfg;
69
70 /**
71 * Database filename.
72 */
73 char *fn;
74
75 /**
76 * Native SQLite database handle.
77 */
78 sqlite3 *dbh;
79
80 /**
81 * Precompiled SQL for caching a block
82 */
83 sqlite3_stmt *cache_block;
84
85 /**
86 * Precompiled SQL for deleting an older block
87 */
88 sqlite3_stmt *delete_block;
89
90 /**
91 * Precompiled SQL for looking up a block
92 */
93 sqlite3_stmt *lookup_block;
94
95 /**
96 * Precompiled SQL for removing expired blocks
97 */
98 sqlite3_stmt *expire_blocks;
99};
100
101
102/**
103 * Initialize the database connections and associated
104 * data structures (create tables and indices
105 * as needed as well).
106 *
107 * @param plugin the plugin context (state for this module)
108 * @return #GNUNET_OK on success
109 */
110static int
111database_setup (struct Plugin *plugin)
112{
113 struct GNUNET_SQ_ExecuteStatement es[] = {
114 GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"),
115 GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"),
116 GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"),
117 GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"),
118 GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""),
119 GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"),
120 GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"),
121 GNUNET_SQ_make_try_execute ("PRAGMA journal_mode=WAL"),
122 GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns096blocks ("
123 " query BLOB NOT NULL,"
124 " block BLOB NOT NULL,"
125 " expiration_time INT8 NOT NULL"
126 ")"),
127 GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_query_hash "
128 "ON ns096blocks (query,expiration_time)"),
129 GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_block_expiration "
130 "ON ns096blocks (expiration_time)"),
131 GNUNET_SQ_EXECUTE_STATEMENT_END
132 };
133 struct GNUNET_SQ_PrepareStatement ps[] = {
134 GNUNET_SQ_make_prepare (
135 "INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)",
136 &plugin->cache_block),
137 GNUNET_SQ_make_prepare ("DELETE FROM ns096blocks WHERE expiration_time<?",
138 &plugin->expire_blocks),
139 GNUNET_SQ_make_prepare (
140 "DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?",
141 &plugin->delete_block),
142 GNUNET_SQ_make_prepare ("SELECT block FROM ns096blocks WHERE query=? "
143 "ORDER BY expiration_time DESC LIMIT 1",
144 &plugin->lookup_block),
145 GNUNET_SQ_PREPARE_END
146 };
147 char *afsdir;
148
149 if (GNUNET_OK !=
150 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
151 "namecache-sqlite",
152 "FILENAME",
153 &afsdir))
154 {
155 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
156 "namecache-sqlite",
157 "FILENAME");
158 return GNUNET_SYSERR;
159 }
160 if (GNUNET_OK !=
161 GNUNET_DISK_file_test (afsdir))
162 {
163 if (GNUNET_OK !=
164 GNUNET_DISK_directory_create_for_file (afsdir))
165 {
166 GNUNET_break (0);
167 GNUNET_free (afsdir);
168 return GNUNET_SYSERR;
169 }
170 }
171 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
172 plugin->fn = afsdir;
173
174 /* Open database and precompile statements */
175 if (SQLITE_OK !=
176 sqlite3_open (plugin->fn, &plugin->dbh))
177 {
178 LOG (GNUNET_ERROR_TYPE_ERROR,
179 _ ("Unable to initialize SQLite: %s.\n"),
180 sqlite3_errmsg (plugin->dbh));
181 return GNUNET_SYSERR;
182 }
183 if (GNUNET_OK !=
184 GNUNET_SQ_exec_statements (plugin->dbh,
185 es))
186 {
187 GNUNET_break (0);
188 LOG (GNUNET_ERROR_TYPE_ERROR,
189 _ ("Failed to setup database at `%s'\n"),
190 plugin->fn);
191 return GNUNET_SYSERR;
192 }
193 GNUNET_break (SQLITE_OK ==
194 sqlite3_busy_timeout (plugin->dbh,
195 BUSY_TIMEOUT_MS));
196
197 if (GNUNET_OK !=
198 GNUNET_SQ_prepare (plugin->dbh,
199 ps))
200 {
201 GNUNET_break (0);
202 LOG (GNUNET_ERROR_TYPE_ERROR,
203 _ ("Failed to setup database at `%s'\n"),
204 plugin->fn);
205 return GNUNET_SYSERR;
206 }
207
208 return GNUNET_OK;
209}
210
211
212/**
213 * Shutdown database connection and associate data
214 * structures.
215 * @param plugin the plugin context (state for this module)
216 */
217static void
218database_shutdown (struct Plugin *plugin)
219{
220 int result;
221 sqlite3_stmt *stmt;
222
223 if (NULL != plugin->cache_block)
224 sqlite3_finalize (plugin->cache_block);
225 if (NULL != plugin->lookup_block)
226 sqlite3_finalize (plugin->lookup_block);
227 if (NULL != plugin->expire_blocks)
228 sqlite3_finalize (plugin->expire_blocks);
229 if (NULL != plugin->delete_block)
230 sqlite3_finalize (plugin->delete_block);
231 result = sqlite3_close (plugin->dbh);
232 if (result == SQLITE_BUSY)
233 {
234 LOG (GNUNET_ERROR_TYPE_WARNING,
235 _ (
236 "Tried to close sqlite without finalizing all prepared statements.\n"));
237 stmt = sqlite3_next_stmt (plugin->dbh,
238 NULL);
239 while (stmt != NULL)
240 {
241 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
242 "sqlite",
243 "Closing statement %p\n",
244 stmt);
245 result = sqlite3_finalize (stmt);
246 if (result != SQLITE_OK)
247 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
248 "sqlite",
249 "Failed to close statement %p: %d\n",
250 stmt,
251 result);
252 stmt = sqlite3_next_stmt (plugin->dbh,
253 NULL);
254 }
255 result = sqlite3_close (plugin->dbh);
256 }
257 if (SQLITE_OK != result)
258 LOG_SQLITE (plugin,
259 GNUNET_ERROR_TYPE_ERROR,
260 "sqlite3_close");
261
262 GNUNET_free (plugin->fn);
263}
264
265
266/**
267 * Removes any expired block.
268 *
269 * @param plugin the plugin
270 */
271static void
272namecache_sqlite_expire_blocks (struct Plugin *plugin)
273{
274 struct GNUNET_TIME_Absolute now;
275 now = GNUNET_TIME_absolute_get ();
276 struct GNUNET_SQ_QueryParam params[] = {
277 GNUNET_SQ_query_param_absolute_time (&now),
278 GNUNET_SQ_query_param_end
279 };
280 int n;
281
282 if (GNUNET_OK !=
283 GNUNET_SQ_bind (plugin->expire_blocks,
284 params))
285 {
286 LOG_SQLITE (plugin,
287 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
288 "sqlite3_bind_XXXX");
289 GNUNET_SQ_reset (plugin->dbh,
290 plugin->expire_blocks);
291 return;
292 }
293 n = sqlite3_step (plugin->expire_blocks);
294 GNUNET_SQ_reset (plugin->dbh,
295 plugin->expire_blocks);
296 switch (n)
297 {
298 case SQLITE_DONE:
299 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
300 "sqlite",
301 "Records expired\n");
302 return;
303
304 case SQLITE_BUSY:
305 LOG_SQLITE (plugin,
306 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
307 "sqlite3_step");
308 return;
309
310 default:
311 LOG_SQLITE (plugin,
312 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
313 "sqlite3_step");
314 return;
315 }
316}
317
318
319/**
320 * Cache a block in the datastore.
321 *
322 * @param cls closure (internal context for the plugin)
323 * @param block block to cache
324 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
325 */
326static int
327namecache_sqlite_cache_block (void *cls,
328 const struct GNUNET_GNSRECORD_Block *block)
329{
330 static struct GNUNET_TIME_Absolute last_expire;
331 struct Plugin *plugin = cls;
332 struct GNUNET_HashCode query;
333 struct GNUNET_TIME_Absolute expiration;
334 size_t block_size = GNUNET_GNSRECORD_block_get_size (block);
335 struct GNUNET_SQ_QueryParam del_params[] = {
336 GNUNET_SQ_query_param_auto_from_type (&query),
337 GNUNET_SQ_query_param_absolute_time (&expiration),
338 GNUNET_SQ_query_param_end
339 };
340 struct GNUNET_SQ_QueryParam ins_params[] = {
341 GNUNET_SQ_query_param_auto_from_type (&query),
342 GNUNET_SQ_query_param_fixed_size (block,
343 block_size),
344 GNUNET_SQ_query_param_absolute_time (&expiration),
345 GNUNET_SQ_query_param_end
346 };
347 int n;
348
349 /* run expiration of old cache entries once per hour */
350 if (GNUNET_TIME_absolute_get_duration (last_expire).rel_value_us >
351 GNUNET_TIME_UNIT_HOURS.rel_value_us)
352 {
353 last_expire = GNUNET_TIME_absolute_get ();
354 namecache_sqlite_expire_blocks (plugin);
355 }
356 GNUNET_assert (GNUNET_OK ==
357 GNUNET_GNSRECORD_query_from_block (block, &query));
358 expiration = GNUNET_GNSRECORD_block_get_expiration (block);
359 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
360 "Caching new version of block %s (expires %s)\n",
361 GNUNET_h2s (&query),
362 GNUNET_STRINGS_absolute_time_to_string (expiration));
363 if (block_size > 64 * 65536)
364 {
365 GNUNET_break (0);
366 return GNUNET_SYSERR;
367 }
368
369 /* delete old version of the block */
370 if (GNUNET_OK !=
371 GNUNET_SQ_bind (plugin->delete_block,
372 del_params))
373 {
374 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
375 "sqlite3_bind_XXXX");
376 GNUNET_SQ_reset (plugin->dbh,
377 plugin->delete_block);
378 return GNUNET_SYSERR;
379 }
380 n = sqlite3_step (plugin->delete_block);
381 switch (n)
382 {
383 case SQLITE_DONE:
384 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
385 "sqlite",
386 "Old block deleted\n");
387 break;
388
389 case SQLITE_BUSY:
390 LOG_SQLITE (plugin,
391 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
392 "sqlite3_step");
393 break;
394
395 default:
396 LOG_SQLITE (plugin,
397 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
398 "sqlite3_step");
399 break;
400 }
401 GNUNET_SQ_reset (plugin->dbh,
402 plugin->delete_block);
403
404 /* insert new version of the block */
405 if (GNUNET_OK !=
406 GNUNET_SQ_bind (plugin->cache_block,
407 ins_params))
408 {
409 LOG_SQLITE (plugin,
410 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
411 "sqlite3_bind_XXXX");
412 GNUNET_SQ_reset (plugin->dbh,
413 plugin->cache_block);
414 return GNUNET_SYSERR;
415 }
416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
417 "Caching block under derived key `%s'\n",
418 GNUNET_h2s_full (&query));
419 n = sqlite3_step (plugin->cache_block);
420 GNUNET_SQ_reset (plugin->dbh,
421 plugin->cache_block);
422 switch (n)
423 {
424 case SQLITE_DONE:
425 LOG (GNUNET_ERROR_TYPE_DEBUG,
426 "Record stored\n");
427 return GNUNET_OK;
428
429 case SQLITE_BUSY:
430 LOG_SQLITE (plugin,
431 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
432 "sqlite3_step");
433 return GNUNET_NO;
434
435 default:
436 LOG_SQLITE (plugin,
437 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438 "sqlite3_step");
439 return GNUNET_SYSERR;
440 }
441}
442
443
444/**
445 * Get the block for a particular zone and label in the
446 * datastore. Will return at most one result to the iterator.
447 *
448 * @param cls closure (internal context for the plugin)
449 * @param query hash of public key derived from the zone and the label
450 * @param iter function to call with the result
451 * @param iter_cls closure for @a iter
452 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
453 */
454static int
455namecache_sqlite_lookup_block (void *cls,
456 const struct GNUNET_HashCode *query,
457 GNUNET_NAMECACHE_BlockCallback iter,
458 void *iter_cls)
459{
460 struct Plugin *plugin = cls;
461 int ret;
462 int sret;
463 size_t block_size;
464 const struct GNUNET_GNSRECORD_Block *block;
465 struct GNUNET_SQ_QueryParam params[] = {
466 GNUNET_SQ_query_param_auto_from_type (query),
467 GNUNET_SQ_query_param_end
468 };
469 struct GNUNET_SQ_ResultSpec rs[] = {
470 GNUNET_SQ_result_spec_variable_size ((void **) &block,
471 &block_size),
472 GNUNET_SQ_result_spec_end
473 };
474
475 if (GNUNET_OK !=
476 GNUNET_SQ_bind (plugin->lookup_block,
477 params))
478 {
479 LOG_SQLITE (plugin,
480 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
481 "sqlite3_bind_XXXX");
482 GNUNET_SQ_reset (plugin->dbh,
483 plugin->lookup_block);
484 return GNUNET_SYSERR;
485 }
486 ret = GNUNET_NO;
487 if (SQLITE_ROW ==
488 (sret = sqlite3_step (plugin->lookup_block)))
489 {
490 if (GNUNET_OK !=
491 GNUNET_SQ_extract_result (plugin->lookup_block,
492 rs))
493 {
494 GNUNET_break (0);
495 ret = GNUNET_SYSERR;
496 }
497 else if ((block_size < sizeof(struct GNUNET_GNSRECORD_Block)))
498 {
499 GNUNET_break (0);
500 GNUNET_SQ_cleanup_result (rs);
501 ret = GNUNET_SYSERR;
502 }
503 else
504 {
505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
506 "Found block under derived key `%s'\n",
507 GNUNET_h2s_full (query));
508 iter (iter_cls,
509 block);
510 GNUNET_SQ_cleanup_result (rs);
511 ret = GNUNET_YES;
512 }
513 }
514 else
515 {
516 if (SQLITE_DONE != sret)
517 {
518 LOG_SQLITE (plugin,
519 GNUNET_ERROR_TYPE_ERROR,
520 "sqlite_step");
521 ret = GNUNET_SYSERR;
522 }
523 else
524 {
525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
526 "No block found under derived key `%s'\n",
527 GNUNET_h2s_full (query));
528 }
529 }
530 GNUNET_SQ_reset (plugin->dbh,
531 plugin->lookup_block);
532 return ret;
533}
534
535
536/**
537 * Entry point for the plugin.
538 *
539 * @param cls the "struct GNUNET_NAMECACHE_PluginEnvironment*"
540 * @return NULL on error, otherwise the plugin context
541 */
542void *
543libgnunet_plugin_namecache_sqlite_init (void *cls)
544{
545 static struct Plugin plugin;
546 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
547 struct GNUNET_NAMECACHE_PluginFunctions *api;
548
549 if (NULL != plugin.cfg)
550 return NULL; /* can only initialize once! */
551 memset (&plugin, 0, sizeof(struct Plugin));
552 plugin.cfg = cfg;
553 if (GNUNET_OK != database_setup (&plugin))
554 {
555 database_shutdown (&plugin);
556 return NULL;
557 }
558 api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions);
559 api->cls = &plugin;
560 api->cache_block = &namecache_sqlite_cache_block;
561 api->lookup_block = &namecache_sqlite_lookup_block;
562 LOG (GNUNET_ERROR_TYPE_INFO,
563 _ ("Sqlite database running\n"));
564 return api;
565}
566
567
568/**
569 * Exit point from the plugin.
570 *
571 * @param cls the plugin context (as returned by "init")
572 * @return always NULL
573 */
574void *
575libgnunet_plugin_namecache_sqlite_done (void *cls)
576{
577 struct GNUNET_NAMECACHE_PluginFunctions *api = cls;
578 struct Plugin *plugin = api->cls;
579
580 database_shutdown (plugin);
581 plugin->cfg = NULL;
582 GNUNET_free (api);
583 LOG (GNUNET_ERROR_TYPE_DEBUG,
584 "sqlite plugin is finished\n");
585 return NULL;
586}
587
588
589/* end of plugin_namecache_sqlite.c */