2 This file is part of GNUnet
3 Copyright (C) 2012, 2015 GNUnet e.V.
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.
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.
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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file src/regex/regex_internal_dht.c
22 * @brief library to announce regexes in the network and match strings
23 * against published regexes.
24 * @author Bartlomiej Polot
27 #include "regex_internal_lib.h"
28 #include "regex_block_lib.h"
29 #include "gnunet_dht_service.h"
30 #include "gnunet_statistics_service.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_signatures.h"
35 #define LOG(kind,...) GNUNET_log_from (kind,"regex-dht",__VA_ARGS__)
38 * DHT replication level to use.
40 #define DHT_REPLICATION 5
43 * DHT record lifetime to use.
45 #define DHT_TTL GNUNET_TIME_UNIT_HOURS
50 #define DHT_OPT GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
54 * Handle to store cached data about a regex announce.
56 struct REGEX_INTERNAL_Announcement
59 * DHT handle to use, must be initialized externally.
61 struct GNUNET_DHT_Handle *dht;
69 * Automaton representation of the regex (expensive to build).
71 struct REGEX_INTERNAL_Automaton *dfa;
76 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
79 * Optional statistics handle to report usage. Can be NULL.
81 struct GNUNET_STATISTICS_Handle *stats;
86 * Regex callback iterator to store own service description in the DHT.
89 * @param key hash for current state.
90 * @param proof proof for current state.
91 * @param accepting #GNUNET_YES if this is an accepting state, #GNUNET_NO if not.
92 * @param num_edges number of edges leaving current state.
93 * @param edges edges leaving current state.
96 regex_iterator (void *cls,
97 const struct GNUNET_HashCode *key,
100 unsigned int num_edges,
101 const struct REGEX_BLOCK_Edge *edges)
103 struct REGEX_INTERNAL_Announcement *h = cls;
104 struct RegexBlock *block;
108 LOG (GNUNET_ERROR_TYPE_INFO,
109 "DHT PUT for state %s with proof `%s' and %u edges:\n",
113 for (i = 0; i < num_edges; i++)
115 LOG (GNUNET_ERROR_TYPE_INFO,
116 "Edge %u `%s' towards %s\n",
119 GNUNET_h2s (&edges[i].destination));
121 if (GNUNET_YES == accepting)
123 struct RegexAcceptBlock ab;
125 LOG (GNUNET_ERROR_TYPE_INFO,
126 "State %s is accepting, putting own id\n",
128 size = sizeof (struct RegexAcceptBlock);
129 ab.purpose.size = ntohl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
130 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
131 sizeof (struct GNUNET_HashCode));
132 ab.purpose.purpose = ntohl (GNUNET_SIGNATURE_PURPOSE_REGEX_ACCEPT);
133 ab.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_DHT_MAX_EXPIRATION));
135 GNUNET_CRYPTO_eddsa_key_get_public (h->priv,
136 &ab.peer.public_key);
137 GNUNET_assert (GNUNET_OK ==
138 GNUNET_CRYPTO_eddsa_sign (h->priv,
142 GNUNET_STATISTICS_update (h->stats, "# regex accepting blocks stored",
144 GNUNET_STATISTICS_update (h->stats, "# regex accepting block bytes stored",
145 sizeof (struct RegexAcceptBlock), GNUNET_NO);
147 GNUNET_DHT_put (h->dht, key,
149 DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE,
150 GNUNET_BLOCK_TYPE_REGEX_ACCEPT,
153 GNUNET_TIME_relative_to_absolute (DHT_TTL),
157 block = REGEX_BLOCK_create (proof,
162 GNUNET_DHT_put (h->dht, key,
165 GNUNET_BLOCK_TYPE_REGEX,
167 GNUNET_TIME_relative_to_absolute (DHT_TTL),
170 GNUNET_STATISTICS_update (h->stats,
171 "# regex blocks stored",
173 GNUNET_STATISTICS_update (h->stats,
174 "# regex block bytes stored",
181 * Announce a regular expression: put all states of the automaton in the DHT.
182 * Does not free resources, must call #REGEX_INTERNAL_announce_cancel() for that.
184 * @param dht An existing and valid DHT service handle. CANNOT be NULL.
185 * @param priv our private key, must remain valid until the announcement is cancelled
186 * @param regex Regular expression to announce.
187 * @param compression How many characters per edge can we squeeze?
188 * @param stats Optional statistics handle to report usage. Can be NULL.
189 * @return Handle to reuse o free cached resources.
190 * Must be freed by calling #REGEX_INTERNAL_announce_cancel().
192 struct REGEX_INTERNAL_Announcement *
193 REGEX_INTERNAL_announce (struct GNUNET_DHT_Handle *dht,
194 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
196 uint16_t compression,
197 struct GNUNET_STATISTICS_Handle *stats)
199 struct REGEX_INTERNAL_Announcement *h;
201 GNUNET_assert (NULL != dht);
202 h = GNUNET_new (struct REGEX_INTERNAL_Announcement);
207 h->dfa = REGEX_INTERNAL_construct_dfa (regex, strlen (regex), compression);
208 REGEX_INTERNAL_reannounce (h);
214 * Announce again a regular expression previously announced.
215 * Does use caching to speed up process.
217 * @param h Handle returned by a previous #REGEX_INTERNAL_announce call().
220 REGEX_INTERNAL_reannounce (struct REGEX_INTERNAL_Announcement *h)
222 GNUNET_assert (NULL != h->dfa); /* make sure to call announce first */
223 LOG (GNUNET_ERROR_TYPE_INFO,
224 "REGEX_INTERNAL_reannounce: %s\n",
226 REGEX_INTERNAL_iterate_reachable_edges (h->dfa,
233 * Clear all cached data used by a regex announce.
234 * Does not close DHT connection.
236 * @param h Handle returned by a previous #REGEX_INTERNAL_announce() call.
239 REGEX_INTERNAL_announce_cancel (struct REGEX_INTERNAL_Announcement *h)
241 REGEX_INTERNAL_automaton_destroy (h->dfa);
246 /******************************************************************************/
250 * Struct to keep state of running searches that have consumed a part of
253 struct RegexSearchContext
256 * Part of the description already consumed by
257 * this particular search branch.
262 * Information about the search.
264 struct REGEX_INTERNAL_Search *info;
267 * We just want to look for one edge, the longer the better.
270 unsigned int longest_match;
273 * Destination hash of the longest match.
275 struct GNUNET_HashCode hash;
280 * Type of values in `dht_get_results`.
285 * Number of bytes in data.
290 * The raw result data.
297 * Struct to keep information of searches of services described by a regex
298 * using a user-provided string service description.
300 struct REGEX_INTERNAL_Search
303 * DHT handle to use, must be initialized externally.
305 struct GNUNET_DHT_Handle *dht;
308 * Optional statistics handle to report usage. Can be NULL.
310 struct GNUNET_STATISTICS_Handle *stats;
313 * User provided description of the searched service.
320 struct GNUNET_CONTAINER_MultiHashMap *dht_get_handles;
323 * Results from running DHT GETs, values are of type
326 struct GNUNET_CONTAINER_MultiHashMap *dht_get_results;
329 * Contexts, for each running DHT GET. Free all on end of search.
331 struct RegexSearchContext **contexts;
334 * Number of contexts (branches/steps in search).
336 unsigned int n_contexts;
339 * @param callback Callback for found peers.
341 REGEX_INTERNAL_Found callback;
344 * @param callback_cls Closure for @c callback.
351 * Jump to the next edge, with the longest matching token.
353 * @param block Block found in the DHT.
354 * @param size Size of the block.
355 * @param ctx Context of the search.
358 regex_next_edge (const struct RegexBlock *block,
360 struct RegexSearchContext *ctx);
364 * Function to process DHT string to regex matching.
365 * Called on each result obtained for the DHT search.
367 * @param cls Closure (search context).
368 * @param exp When will this value expire.
369 * @param key Key of the result.
370 * @param get_path Path of the get request.
371 * @param get_path_length Lenght of get_path.
372 * @param put_path Path of the put request.
373 * @param put_path_length Length of the put_path.
374 * @param type Type of the result.
375 * @param size Number of bytes in data.
376 * @param data Pointer to the result data.
379 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
380 const struct GNUNET_HashCode *key,
381 const struct GNUNET_PeerIdentity *get_path,
382 unsigned int get_path_length,
383 const struct GNUNET_PeerIdentity *put_path,
384 unsigned int put_path_length,
385 enum GNUNET_BLOCK_Type type,
386 size_t size, const void *data)
388 const struct RegexAcceptBlock *block = data;
389 struct RegexSearchContext *ctx = cls;
390 struct REGEX_INTERNAL_Search *info = ctx->info;
392 LOG (GNUNET_ERROR_TYPE_DEBUG,
393 "Regex result accept for %s (key %s)\n",
394 info->description, GNUNET_h2s(key));
396 GNUNET_STATISTICS_update (info->stats,
397 "# regex accepting blocks found",
399 GNUNET_STATISTICS_update (info->stats,
400 "# regex accepting block bytes found",
402 info->callback (info->callback_cls,
404 get_path, get_path_length,
405 put_path, put_path_length);
410 * Find a path to a peer that offers a regex service compatible
411 * with a given string.
413 * @param key The key of the accepting state.
414 * @param ctx Context containing info about the string, tunnel, etc.
417 regex_find_path (const struct GNUNET_HashCode *key,
418 struct RegexSearchContext *ctx)
420 struct GNUNET_DHT_GetHandle *get_h;
422 LOG (GNUNET_ERROR_TYPE_DEBUG,
423 "Accept state found, now searching for paths to %s\n",
425 (unsigned int) ctx->position);
426 get_h = GNUNET_DHT_get_start (ctx->info->dht, /* handle */
427 GNUNET_BLOCK_TYPE_REGEX_ACCEPT, /* type */
428 key, /* key to search */
429 DHT_REPLICATION, /* replication level */
430 DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE,
431 NULL, /* xquery */ // FIXME BLOOMFILTER
432 0, /* xquery bits */ // FIXME BLOOMFILTER SIZE
433 &dht_get_string_accept_handler, ctx);
434 GNUNET_break (GNUNET_OK ==
435 GNUNET_CONTAINER_multihashmap_put(ctx->info->dht_get_handles,
438 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
443 * Function to process DHT string to regex matching.
444 * Called on each result obtained for the DHT search.
446 * @param cls closure (search context)
447 * @param exp when will this value expire
448 * @param key key of the result
449 * @param get_path path of the get request (not used)
450 * @param get_path_length length of @a get_path (not used)
451 * @param put_path path of the put request (not used)
452 * @param put_path_length length of the @a put_path (not used)
453 * @param type type of the result
454 * @param size number of bytes in data
455 * @param data pointer to the result data
457 * TODO: re-issue the request after certain time? cancel after X results?
460 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
461 const struct GNUNET_HashCode *key,
462 const struct GNUNET_PeerIdentity *get_path,
463 unsigned int get_path_length,
464 const struct GNUNET_PeerIdentity *put_path,
465 unsigned int put_path_length,
466 enum GNUNET_BLOCK_Type type,
467 size_t size, const void *data)
469 const struct RegexBlock *block = data;
470 struct RegexSearchContext *ctx = cls;
471 struct REGEX_INTERNAL_Search *info = ctx->info;
475 LOG (GNUNET_ERROR_TYPE_INFO,
476 "DHT GET result for %s (%s)\n",
477 GNUNET_h2s (key), ctx->info->description);
478 copy = GNUNET_malloc (sizeof (struct Result) + size);
480 copy->data = ©[1];
481 memcpy (©[1], block, size);
482 GNUNET_break (GNUNET_OK ==
483 GNUNET_CONTAINER_multihashmap_put (info->dht_get_results,
485 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
486 len = strlen (info->description);
487 if (len == ctx->position) // String processed
489 if (GNUNET_YES == GNUNET_BLOCK_is_accepting (block, size))
491 regex_find_path (key, ctx);
495 LOG (GNUNET_ERROR_TYPE_INFO, "block not accepting!\n");
496 /* FIXME REGEX this block not successful, wait for more? start timeout? */
500 regex_next_edge (block, size, ctx);
505 * Iterator over found existing cadet regex blocks that match an ongoing search.
507 * @param cls Closure (current context)-
508 * @param key Current key code (key for cached block).
509 * @param value Value in the hash map (cached RegexBlock).
510 * @return #GNUNET_YES: we should always continue to iterate.
513 regex_result_iterator (void *cls,
514 const struct GNUNET_HashCode * key,
517 struct Result *result = value;
518 const struct RegexBlock *block = result->data;
519 struct RegexSearchContext *ctx = cls;
522 GNUNET_BLOCK_is_accepting (block, result->size)) &&
523 (ctx->position == strlen (ctx->info->description)) )
525 LOG (GNUNET_ERROR_TYPE_INFO,
526 "Found accepting known block\n");
527 regex_find_path (key, ctx);
528 return GNUNET_YES; // We found an accept state!
530 LOG (GNUNET_ERROR_TYPE_DEBUG,
533 strlen (ctx->info->description),
534 GNUNET_BLOCK_is_accepting (block, result->size));
535 regex_next_edge (block, result->size, ctx);
537 GNUNET_STATISTICS_update (ctx->info->stats, "# regex cadet blocks iterated",
545 * Iterator over edges in a regex block retrieved from the DHT.
547 * @param cls Closure (context of the search).
548 * @param token Token that follows to next state.
549 * @param len Lenght of token.
550 * @param key Hash of next state.
551 * @return #GNUNET_YES if should keep iterating, #GNUNET_NO otherwise.
554 regex_edge_iterator (void *cls,
557 const struct GNUNET_HashCode *key)
559 struct RegexSearchContext *ctx = cls;
560 struct REGEX_INTERNAL_Search *info = ctx->info;
564 GNUNET_STATISTICS_update (info->stats, "# regex edges iterated",
566 current = &info->description[ctx->position];
567 current_len = strlen (info->description) - ctx->position;
568 if (len > current_len)
570 LOG (GNUNET_ERROR_TYPE_DEBUG, "Token too long, END\n");
573 if (0 != strncmp (current, token, len))
575 LOG (GNUNET_ERROR_TYPE_DEBUG, "Token doesn't match, END\n");
579 if (len > ctx->longest_match)
581 LOG (GNUNET_ERROR_TYPE_DEBUG, "Token is longer, KEEP\n");
582 ctx->longest_match = len;
587 LOG (GNUNET_ERROR_TYPE_DEBUG, "Token is not longer, IGNORE\n");
590 LOG (GNUNET_ERROR_TYPE_DEBUG, "* End of regex edge iterator\n");
596 * Jump to the next edge, with the longest matching token.
598 * @param block Block found in the DHT.
599 * @param size Size of the block.
600 * @param ctx Context of the search.
603 regex_next_edge (const struct RegexBlock *block,
605 struct RegexSearchContext *ctx)
607 struct RegexSearchContext *new_ctx;
608 struct REGEX_INTERNAL_Search *info = ctx->info;
609 struct GNUNET_DHT_GetHandle *get_h;
610 struct GNUNET_HashCode *hash;
614 LOG (GNUNET_ERROR_TYPE_DEBUG, "Next edge\n");
615 /* Find the longest match for the current string position,
616 * among tokens in the given block */
617 ctx->longest_match = 0;
618 result = REGEX_BLOCK_iterate (block, size,
619 ®ex_edge_iterator, ctx);
620 GNUNET_break (GNUNET_OK == result);
622 /* Did anything match? */
623 if (0 == ctx->longest_match)
625 LOG (GNUNET_ERROR_TYPE_DEBUG,
626 "no match in block\n");
631 new_ctx = GNUNET_new (struct RegexSearchContext);
632 new_ctx->info = info;
633 new_ctx->position = ctx->position + ctx->longest_match;
634 GNUNET_array_append (info->contexts, info->n_contexts, new_ctx);
636 /* Check whether we already have a DHT GET running for it */
638 GNUNET_CONTAINER_multihashmap_contains (info->dht_get_handles, hash))
640 LOG (GNUNET_ERROR_TYPE_DEBUG,
641 "GET for %s running, END\n",
643 GNUNET_CONTAINER_multihashmap_get_multiple (info->dht_get_results,
645 ®ex_result_iterator,
647 return; /* We are already looking for it */
650 GNUNET_STATISTICS_update (info->stats, "# regex nodes traversed",
653 LOG (GNUNET_ERROR_TYPE_DEBUG,
654 "Following edges at %s for offset %u in `%s'\n",
656 (unsigned int) ctx->position,
658 rest = &new_ctx->info->description[new_ctx->position];
660 GNUNET_DHT_get_start (info->dht, /* handle */
661 GNUNET_BLOCK_TYPE_REGEX, /* type */
662 hash, /* key to search */
663 DHT_REPLICATION, /* replication level */
666 strlen (rest) + 1, /* xquery bits */
667 &dht_get_string_handler, new_ctx);
669 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
672 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
681 * Search for a peer offering a regex matching certain string in the DHT.
682 * The search runs until #REGEX_INTERNAL_search_cancel() is called, even if results
685 * @param dht An existing and valid DHT service handle.
686 * @param string String to match against the regexes in the DHT.
687 * @param callback Callback for found peers.
688 * @param callback_cls Closure for @c callback.
689 * @param stats Optional statistics handle to report usage. Can be NULL.
690 * @return Handle to stop search and free resources.
691 * Must be freed by calling #REGEX_INTERNAL_search_cancel().
693 struct REGEX_INTERNAL_Search *
694 REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht,
696 REGEX_INTERNAL_Found callback,
698 struct GNUNET_STATISTICS_Handle *stats)
700 struct REGEX_INTERNAL_Search *h;
701 struct GNUNET_DHT_GetHandle *get_h;
702 struct RegexSearchContext *ctx;
703 struct GNUNET_HashCode key;
707 /* Initialize handle */
708 GNUNET_assert (NULL != dht);
709 GNUNET_assert (NULL != callback);
710 h = GNUNET_new (struct REGEX_INTERNAL_Search);
712 h->description = GNUNET_strdup (string);
713 h->callback = callback;
714 h->callback_cls = callback_cls;
716 h->dht_get_handles = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
717 h->dht_get_results = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
719 /* Initialize context */
720 len = strlen (string);
721 size = REGEX_INTERNAL_get_first_key (string, len, &key);
722 LOG (GNUNET_ERROR_TYPE_INFO,
723 "Initial key for `%s' is %s (based on `%.*s')\n",
728 ctx = GNUNET_new (struct RegexSearchContext);
729 ctx->position = size;
731 GNUNET_array_append (h->contexts,
734 /* Start search in DHT */
735 get_h = GNUNET_DHT_get_start (h->dht, /* handle */
736 GNUNET_BLOCK_TYPE_REGEX, /* type */
737 &key, /* key to search */
738 DHT_REPLICATION, /* replication level */
740 &h->description[size], /* xquery */
741 // FIXME add BLOOMFILTER to exclude filtered peers
742 len + 1 - size, /* xquery bits */
743 // FIXME add BLOOMFILTER SIZE
744 &dht_get_string_handler, ctx);
747 GNUNET_CONTAINER_multihashmap_put (h->dht_get_handles,
750 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)
758 * Iterator over hash map entries to cancel DHT GET requests after a
759 * successful connect_by_string.
761 * @param cls Closure (unused).
762 * @param key Current key code (unused).
763 * @param value Value in the hash map (get handle).
764 * @return #GNUNET_YES if we should continue to iterate,
768 regex_cancel_dht_get (void *cls,
769 const struct GNUNET_HashCode * key,
772 struct GNUNET_DHT_GetHandle *h = value;
774 GNUNET_DHT_get_stop (h);
780 * Iterator over hash map entries to free CadetRegexBlocks stored during the
781 * search for connect_by_string.
783 * @param cls Closure (unused).
784 * @param key Current key code (unused).
785 * @param value CadetRegexBlock in the hash map.
786 * @return #GNUNET_YES if we should continue to iterate,
790 regex_free_result (void *cls,
791 const struct GNUNET_HashCode * key,
800 * Cancel an ongoing regex search in the DHT and free all resources.
802 * @param h the search context.
805 REGEX_INTERNAL_search_cancel (struct REGEX_INTERNAL_Search *h)
809 GNUNET_free (h->description);
810 GNUNET_CONTAINER_multihashmap_iterate (h->dht_get_handles,
811 ®ex_cancel_dht_get, NULL);
812 GNUNET_CONTAINER_multihashmap_iterate (h->dht_get_results,
813 ®ex_free_result, NULL);
814 GNUNET_CONTAINER_multihashmap_destroy (h->dht_get_results);
815 GNUNET_CONTAINER_multihashmap_destroy (h->dht_get_handles);
816 if (0 < h->n_contexts)
818 for (i = 0; i < h->n_contexts; i++)
819 GNUNET_free (h->contexts[i]);
820 GNUNET_free (h->contexts);
826 /* end of regex_internal_dht.c */