aboutsummaryrefslogtreecommitdiff
path: root/src/regex/regex_internal_dht.c
blob: 7b93fddca4d7949e62c6707b3a20bb6997e1ca24 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
/*
     This file is part of GNUnet
     Copyright (C) 2012 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/
/**
 * @file src/regex/regex_internal_dht.c
 * @brief library to announce regexes in the network and match strings
 * against published regexes.
 * @author Bartlomiej Polot
 */
#include "platform.h"
#include "regex_internal_lib.h"
#include "regex_block_lib.h"
#include "gnunet_dht_service.h"
#include "gnunet_statistics_service.h"
#include "gnunet_constants.h"
#include "gnunet_signatures.h"


#define LOG(kind,...) GNUNET_log_from (kind,"regex-dht",__VA_ARGS__)

#define DHT_REPLICATION 5
#define DHT_TTL         GNUNET_TIME_UNIT_HOURS
#define DHT_OPT         GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE


/**
 * Handle to store cached data about a regex announce.
 */
struct REGEX_INTERNAL_Announcement
{
  /**
   * DHT handle to use, must be initialized externally.
   */
  struct GNUNET_DHT_Handle *dht;

  /**
   * Regular expression.
   */
  const char *regex;

  /**
   * Automaton representation of the regex (expensive to build).
   */
  struct REGEX_INTERNAL_Automaton* dfa;

  /**
   * Our private key.
   */
  const struct GNUNET_CRYPTO_EddsaPrivateKey *priv;

  /**
   * Optional statistics handle to report usage. Can be NULL.
   */
  struct GNUNET_STATISTICS_Handle *stats;
};


/**
 * Regex callback iterator to store own service description in the DHT.
 *
 * @param cls closure.
 * @param key hash for current state.
 * @param proof proof for current state.
 * @param accepting GNUNET_YES if this is an accepting state, GNUNET_NO if not.
 * @param num_edges number of edges leaving current state.
 * @param edges edges leaving current state.
 */
static void
regex_iterator (void *cls,
                const struct GNUNET_HashCode *key,
                const char *proof,
                int accepting,
                unsigned int num_edges,
                const struct REGEX_BLOCK_Edge *edges)
{
  struct REGEX_INTERNAL_Announcement *h = cls;
  struct RegexBlock *block;
  size_t size;
  unsigned int i;

  LOG (GNUNET_ERROR_TYPE_INFO,
       "DHT PUT for state %s with proof `%s' and %u edges\n",
       GNUNET_h2s (key),
       proof,
       num_edges);
  for (i = 0; i < num_edges; i++)
  {
    LOG (GNUNET_ERROR_TYPE_INFO,
         "  edge %s towards %s (%s)\n",
         edges[i].label,
         GNUNET_h2s (&edges[i].destination),
         proof);
  }
  if (GNUNET_YES == accepting)
  {
    struct RegexAcceptBlock ab;

    LOG (GNUNET_ERROR_TYPE_INFO,
         "State %s is accepting, putting own id\n",
         GNUNET_h2s (key));
    size = sizeof (struct RegexAcceptBlock);
    ab.purpose.size = ntohl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
                             sizeof (struct GNUNET_TIME_AbsoluteNBO) +
                             sizeof (struct GNUNET_HashCode));
    ab.purpose.purpose = ntohl (GNUNET_SIGNATURE_PURPOSE_REGEX_ACCEPT);
    ab.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_DHT_MAX_EXPIRATION));
    ab.key = *key;
    GNUNET_CRYPTO_eddsa_key_get_public (h->priv,
						    &ab.peer.public_key);
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CRYPTO_eddsa_sign (h->priv,
                                           &ab.purpose,
                                           &ab.signature));

    GNUNET_STATISTICS_update (h->stats, "# regex accepting blocks stored",
                              1, GNUNET_NO);
    GNUNET_STATISTICS_update (h->stats, "# regex accepting block bytes stored",
                              sizeof (struct RegexAcceptBlock), GNUNET_NO);
    (void)
    GNUNET_DHT_put (h->dht, key,
                    DHT_REPLICATION,
                    DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE,
                    GNUNET_BLOCK_TYPE_REGEX_ACCEPT,
                    size,
                    &ab,
                    GNUNET_TIME_relative_to_absolute (DHT_TTL),
                    DHT_TTL,
                    NULL, NULL);
  }
  block = REGEX_BLOCK_create (proof,
                              num_edges, edges,
                              accepting,
                              &size);
  (void)
  GNUNET_DHT_put (h->dht, key,
                  DHT_REPLICATION,
                  DHT_OPT,
                  GNUNET_BLOCK_TYPE_REGEX,
                  size, block,
                  GNUNET_TIME_relative_to_absolute (DHT_TTL),
                  DHT_TTL,
                  NULL, NULL);
  GNUNET_STATISTICS_update (h->stats, "# regex blocks stored",
                            1, GNUNET_NO);
  GNUNET_STATISTICS_update (h->stats, "# regex block bytes stored",
                            size, GNUNET_NO);
  GNUNET_free (block);
}


/**
 * Announce a regular expression: put all states of the automaton in the DHT.
 * Does not free resources, must call REGEX_INTERNAL_announce_cancel for that.
 *
 * @param dht An existing and valid DHT service handle. CANNOT be NULL.
 * @param priv our private key, must remain valid until the announcement is cancelled
 * @param regex Regular expression to announce.
 * @param compression How many characters per edge can we squeeze?
 * @param stats Optional statistics handle to report usage. Can be NULL.
 *
 * @return Handle to reuse o free cached resources.
 *         Must be freed by calling REGEX_INTERNAL_announce_cancel.
 */
struct REGEX_INTERNAL_Announcement *
REGEX_INTERNAL_announce (struct GNUNET_DHT_Handle *dht,
			 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
			 const char *regex,
			 uint16_t compression,
			 struct GNUNET_STATISTICS_Handle *stats)
{
  struct REGEX_INTERNAL_Announcement *h;

  GNUNET_assert (NULL != dht);
  h = GNUNET_new (struct REGEX_INTERNAL_Announcement);
  h->regex = regex;
  h->dht = dht;
  h->stats = stats;
  h->priv = priv;
  h->dfa = REGEX_INTERNAL_construct_dfa (regex, strlen (regex), compression);
  REGEX_INTERNAL_reannounce (h);
  return h;
}


/**
 * Announce again a regular expression previously announced.
 * Does use caching to speed up process.
 *
 * @param h Handle returned by a previous REGEX_INTERNAL_announce call.
 */
void
REGEX_INTERNAL_reannounce (struct REGEX_INTERNAL_Announcement *h)
{
  GNUNET_assert (NULL != h->dfa); /* make sure to call announce first */
  LOG (GNUNET_ERROR_TYPE_INFO,
       "REGEX_INTERNAL_reannounce: %s\n",
       h->regex);
  REGEX_INTERNAL_iterate_reachable_edges (h->dfa, &regex_iterator, h);
}


/**
 * Clear all cached data used by a regex announce.
 * Does not close DHT connection.
 *
 * @param h Handle returned by a previous REGEX_INTERNAL_announce call.
 */
void
REGEX_INTERNAL_announce_cancel (struct REGEX_INTERNAL_Announcement *h)
{
  REGEX_INTERNAL_automaton_destroy (h->dfa);
  GNUNET_free (h);
}


/******************************************************************************/


/**
 * Struct to keep state of running searches that have consumed a part of
 * the inital string.
 */
struct RegexSearchContext
{
  /**
   * Part of the description already consumed by
   * this particular search branch.
   */
  size_t position;

  /**
   * Information about the search.
   */
  struct REGEX_INTERNAL_Search *info;

  /**
   * We just want to look for one edge, the longer the better.
   * Keep its length.
   */
  unsigned int longest_match;

  /**
   * Destination hash of the longest match.
   */
  struct GNUNET_HashCode hash;
};


/**
 * Type of values in 'dht_get_results'.
 */
struct Result
{
  /**
   * Number of bytes in data.
   */
  size_t size;

  /**
   * The raw result data.
   */
  const void *data;
};


/**
 * Struct to keep information of searches of services described by a regex
 * using a user-provided string service description.
 */
struct REGEX_INTERNAL_Search
{
  /**
   * DHT handle to use, must be initialized externally.
   */
  struct GNUNET_DHT_Handle *dht;

  /**
   * Optional statistics handle to report usage. Can be NULL.
   */
  struct GNUNET_STATISTICS_Handle *stats;

  /**
   * User provided description of the searched service.
   */
  char *description;

  /**
   * Running DHT GETs.
   */
  struct GNUNET_CONTAINER_MultiHashMap *dht_get_handles;

  /**
   * Results from running DHT GETs, values are of type
   * 'struct Result'.
   */
  struct GNUNET_CONTAINER_MultiHashMap *dht_get_results;

  /**
   * Contexts, for each running DHT GET. Free all on end of search.
   */
  struct RegexSearchContext **contexts;

  /**
   * Number of contexts (branches/steps in search).
   */
  unsigned int n_contexts;

  /**
   * @param callback Callback for found peers.
   */
  REGEX_INTERNAL_Found callback;

  /**
   * @param callback_cls Closure for @c callback.
   */
  void *callback_cls;
};


/**
 * Jump to the next edge, with the longest matching token.
 *
 * @param block Block found in the DHT.
 * @param size Size of the block.
 * @param ctx Context of the search.
 */
static void
regex_next_edge (const struct RegexBlock *block,
                 size_t size,
                 struct RegexSearchContext *ctx);


/**
 * Function to process DHT string to regex matching.
 * Called on each result obtained for the DHT search.
 *
 * @param cls Closure (search context).
 * @param exp When will this value expire.
 * @param key Key of the result.
 * @param get_path Path of the get request.
 * @param get_path_length Lenght of get_path.
 * @param put_path Path of the put request.
 * @param put_path_length Length of the put_path.
 * @param type Type of the result.
 * @param size Number of bytes in data.
 * @param data Pointer to the result data.
 */
static void
dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
                               const struct GNUNET_HashCode *key,
                               const struct GNUNET_PeerIdentity *get_path,
                               unsigned int get_path_length,
                               const struct GNUNET_PeerIdentity *put_path,
                               unsigned int put_path_length,
                               enum GNUNET_BLOCK_Type type,
                               size_t size, const void *data)
{
  const struct RegexAcceptBlock *block = data;
  struct RegexSearchContext *ctx = cls;
  struct REGEX_INTERNAL_Search *info = ctx->info;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Regex result accept for %s (key %s)\n",
       info->description, GNUNET_h2s(key));

  GNUNET_STATISTICS_update (info->stats,
			    "# regex accepting blocks found",
                            1, GNUNET_NO);
  GNUNET_STATISTICS_update (info->stats,
			    "# regex accepting block bytes found",
                            size, GNUNET_NO);
  info->callback (info->callback_cls,
                  &block->peer,
                  get_path, get_path_length,
                  put_path, put_path_length);
}


/**
 * Find a path to a peer that offers a regex servcie compatible
 * with a given string.
 *
 * @param key The key of the accepting state.
 * @param ctx Context containing info about the string, tunnel, etc.
 */
static void
regex_find_path (const struct GNUNET_HashCode *key,
                 struct RegexSearchContext *ctx)
{
  struct GNUNET_DHT_GetHandle *get_h;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "regex finds path for %s\n",
       GNUNET_h2s (key));
  get_h = GNUNET_DHT_get_start (ctx->info->dht,    /* handle */
                                GNUNET_BLOCK_TYPE_REGEX_ACCEPT, /* type */
                                key,     /* key to search */
                                DHT_REPLICATION, /* replication level */
                                DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE,
                                NULL,       /* xquery */ // FIXME BLOOMFILTER
                                0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
                                &dht_get_string_accept_handler, ctx);
  GNUNET_break (GNUNET_OK ==
                GNUNET_CONTAINER_multihashmap_put(ctx->info->dht_get_handles,
                                                  key,
                                                  get_h,
                                                  GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
}


/**
 * Function to process DHT string to regex matching.
 * Called on each result obtained for the DHT search.
 *
 * @param cls closure (search context)
 * @param exp when will this value expire
 * @param key key of the result
 * @param get_path path of the get request (not used)
 * @param get_path_length lenght of get_path (not used)
 * @param put_path path of the put request (not used)
 * @param put_path_length length of the put_path (not used)
 * @param type type of the result
 * @param size number of bytes in data
 * @param data pointer to the result data
 *
 * TODO: re-issue the request after certain time? cancel after X results?
 */
static void
dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
                        const struct GNUNET_HashCode *key,
                        const struct GNUNET_PeerIdentity *get_path,
                        unsigned int get_path_length,
                        const struct GNUNET_PeerIdentity *put_path,
                        unsigned int put_path_length,
                        enum GNUNET_BLOCK_Type type,
                        size_t size, const void *data)
{
  const struct RegexBlock *block = data;
  struct RegexSearchContext *ctx = cls;
  struct REGEX_INTERNAL_Search *info = ctx->info;
  size_t len;
  struct Result *copy;

  LOG (GNUNET_ERROR_TYPE_INFO,
       "DHT GET result for %s (%s)\n",
       GNUNET_h2s (key), ctx->info->description);
  copy = GNUNET_malloc (sizeof (struct Result) + size);
  copy->size = size;
  copy->data = &copy[1];
  memcpy (&copy[1], block, size);
  GNUNET_break (GNUNET_OK ==
		GNUNET_CONTAINER_multihashmap_put (info->dht_get_results,
						   key, copy,
						   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
  len = strlen (info->description);
  if (len == ctx->position) // String processed
  {
    if (GNUNET_YES == GNUNET_BLOCK_is_accepting (block, size))
    {
      regex_find_path (key, ctx);
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_INFO, "block not accepting!\n");
      /* FIXME REGEX this block not successful, wait for more? start timeout? */
    }
    return;
  }
  regex_next_edge (block, size, ctx);
}


/**
 * Iterator over found existing cadet regex blocks that match an ongoing search.
 *
 * @param cls Closure (current context)-
 * @param key Current key code (key for cached block).
 * @param value Value in the hash map (cached RegexBlock).
 * @return GNUNET_YES: we should always continue to iterate.
 */
static int
regex_result_iterator (void *cls,
                       const struct GNUNET_HashCode * key,
                       void *value)
{
  struct Result *result = value;
  const struct RegexBlock *block = result->data;
  struct RegexSearchContext *ctx = cls;

  if ( (GNUNET_YES ==
	GNUNET_BLOCK_is_accepting (block, result->size)) &&
       (ctx->position == strlen (ctx->info->description)) )
  {
    LOG (GNUNET_ERROR_TYPE_INFO,
	 "Found accepting known block\n");
    regex_find_path (key, ctx);
    return GNUNET_YES; // We found an accept state!
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "* %u, %u, [%u]\n",
       ctx->position,
       strlen (ctx->info->description),
       GNUNET_BLOCK_is_accepting (block, result->size));
  regex_next_edge (block, result->size, ctx);

  GNUNET_STATISTICS_update (ctx->info->stats, "# regex cadet blocks iterated",
                            1, GNUNET_NO);

  return GNUNET_YES;
}


/**
 * Iterator over edges in a regex block retrieved from the DHT.
 *
 * @param cls Closure (context of the search).
 * @param token Token that follows to next state.
 * @param len Lenght of token.
 * @param key Hash of next state.
 *
 * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
 */
static int
regex_edge_iterator (void *cls,
                     const char *token,
                     size_t len,
                     const struct GNUNET_HashCode *key)
{
  struct RegexSearchContext *ctx = cls;
  struct REGEX_INTERNAL_Search *info = ctx->info;
  const char *current;
  size_t current_len;

  GNUNET_STATISTICS_update (info->stats, "# regex edges iterated",
                            1, GNUNET_NO);
  current = &info->description[ctx->position];
  current_len = strlen (info->description) - ctx->position;
  if (len > current_len)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Token too long, END\n");
    return GNUNET_YES;
  }
  if (0 != strncmp (current, token, len))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Token doesn't match, END\n");
    return GNUNET_YES;
  }

  if (len > ctx->longest_match)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Token is longer, KEEP\n");
    ctx->longest_match = len;
    ctx->hash = *key;
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Token is not longer, IGNORE\n");
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG, "*    End of regex edge iterator\n");
  return GNUNET_YES;
}


/**
 * Jump to the next edge, with the longest matching token.
 *
 * @param block Block found in the DHT.
 * @param size Size of the block.
 * @param ctx Context of the search.
 */
static void
regex_next_edge (const struct RegexBlock *block,
                 size_t size,
                 struct RegexSearchContext *ctx)
{
  struct RegexSearchContext *new_ctx;
  struct REGEX_INTERNAL_Search *info = ctx->info;
  struct GNUNET_DHT_GetHandle *get_h;
  struct GNUNET_HashCode *hash;
  const char *rest;
  int result;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "Next edge\n");
  /* Find the longest match for the current string position,
   * among tokens in the given block */
  ctx->longest_match = 0;
  result = REGEX_BLOCK_iterate (block, size,
                                &regex_edge_iterator, ctx);
  GNUNET_break (GNUNET_OK == result);

  /* Did anything match? */
  if (0 == ctx->longest_match)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "no match in block\n");
    return;
  }

  hash = &ctx->hash;
  new_ctx = GNUNET_new (struct RegexSearchContext);
  new_ctx->info = info;
  new_ctx->position = ctx->position + ctx->longest_match;
  GNUNET_array_append (info->contexts, info->n_contexts, new_ctx);

  /* Check whether we already have a DHT GET running for it */
  if (GNUNET_YES ==
      GNUNET_CONTAINER_multihashmap_contains (info->dht_get_handles, hash))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "GET for %s running, END\n",
         GNUNET_h2s (hash));
    GNUNET_CONTAINER_multihashmap_get_multiple (info->dht_get_results,
                                                hash,
                                                &regex_result_iterator,
                                                new_ctx);
    return; /* We are already looking for it */
  }

  GNUNET_STATISTICS_update (info->stats, "# regex nodes traversed",
                            1, GNUNET_NO);

  LOG (GNUNET_ERROR_TYPE_INFO,
       "looking for %s\n",
       GNUNET_h2s (hash));
  rest = &new_ctx->info->description[new_ctx->position];
  get_h =
      GNUNET_DHT_get_start (info->dht,    /* handle */
                            GNUNET_BLOCK_TYPE_REGEX, /* type */
                            hash,     /* key to search */
                            DHT_REPLICATION, /* replication level */
                            DHT_OPT,
                            rest, /* xquery */
                            strlen (rest) + 1,     /* xquery bits */
                            &dht_get_string_handler, new_ctx);
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
                                        hash,
                                        get_h,
                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
  {
    GNUNET_break (0);
    return;
  }
}


/**
 * Search for a peer offering a regex matching certain string in the DHT.
 * The search runs until REGEX_INTERNAL_search_cancel is called, even if results
 * are returned.
 *
 * @param dht An existing and valid DHT service handle.
 * @param string String to match against the regexes in the DHT.
 * @param callback Callback for found peers.
 * @param callback_cls Closure for @c callback.
 * @param stats Optional statistics handle to report usage. Can be NULL.
 *
 * @return Handle to stop search and free resources.
 *         Must be freed by calling REGEX_INTERNAL_search_cancel.
 */
struct REGEX_INTERNAL_Search *
REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht,
                     const char *string,
                     REGEX_INTERNAL_Found callback,
                     void *callback_cls,
                     struct GNUNET_STATISTICS_Handle *stats)
{
  struct REGEX_INTERNAL_Search *h;
  struct GNUNET_DHT_GetHandle *get_h;
  struct RegexSearchContext *ctx;
  struct GNUNET_HashCode key;
  size_t size;
  size_t len;

  /* Initialize handle */
  LOG (GNUNET_ERROR_TYPE_INFO, "REGEX_INTERNAL_search: %s\n", string);
  GNUNET_assert (NULL != dht);
  GNUNET_assert (NULL != callback);
  h = GNUNET_new (struct REGEX_INTERNAL_Search);
  h->dht = dht;
  h->description = GNUNET_strdup (string);
  h->callback = callback;
  h->callback_cls = callback_cls;
  h->stats = stats;
  h->dht_get_handles = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
  h->dht_get_results = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);

  /* Initialize context */
  len = strlen (string);
  size = REGEX_INTERNAL_get_first_key (string, len, &key);
  LOG (GNUNET_ERROR_TYPE_INFO,
       "  initial key for %s: %s (%.*s)\n",
       string, GNUNET_h2s (&key), size, string);
  ctx = GNUNET_new (struct RegexSearchContext);
  ctx->position = size;
  ctx->info = h;
  GNUNET_array_append (h->contexts, h->n_contexts, ctx);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "consumed %u bits out of %u, now looking for %s\n",
       size, len,
       GNUNET_h2s (&key));

  /* Start search in DHT */
  get_h = GNUNET_DHT_get_start (h->dht,    /* handle */
                                GNUNET_BLOCK_TYPE_REGEX, /* type */
                                &key,     /* key to search */
                                DHT_REPLICATION, /* replication level */
                                DHT_OPT,
                                &h->description[size],           /* xquery */
                                // FIXME add BLOOMFILTER to exclude filtered peers
                                len + 1 - size,                /* xquery bits */
                                // FIXME add BLOOMFILTER SIZE
                                &dht_get_string_handler, ctx);
  GNUNET_break (
    GNUNET_OK ==
    GNUNET_CONTAINER_multihashmap_put (h->dht_get_handles,
                                       &key,
                                       get_h,
                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)
               );

  return h;
}


/**
 * Iterator over hash map entries to cancel DHT GET requests after a
 * successful connect_by_string.
 *
 * @param cls Closure (unused).
 * @param key Current key code (unused).
 * @param value Value in the hash map (get handle).
 * @return GNUNET_YES if we should continue to iterate,
 *         GNUNET_NO if not.
 */
static int
regex_cancel_dht_get (void *cls,
                      const struct GNUNET_HashCode * key,
                      void *value)
{
  struct GNUNET_DHT_GetHandle *h = value;

  GNUNET_DHT_get_stop (h);
  return GNUNET_YES;
}


/**
 * Iterator over hash map entries to free CadetRegexBlocks stored during the
 * search for connect_by_string.
 *
 * @param cls Closure (unused).
 * @param key Current key code (unused).
 * @param value CadetRegexBlock in the hash map.
 * @return GNUNET_YES if we should continue to iterate,
 *         GNUNET_NO if not.
 */
static int
regex_free_result (void *cls,
                   const struct GNUNET_HashCode * key,
                   void *value)
{
  GNUNET_free (value);
  return GNUNET_YES;
}


/**
 * Cancel an ongoing regex search in the DHT and free all resources.
 *
 * @param h the search context.
 */
void
REGEX_INTERNAL_search_cancel (struct REGEX_INTERNAL_Search *h)
{
  unsigned int i;

  GNUNET_free (h->description);
  GNUNET_CONTAINER_multihashmap_iterate (h->dht_get_handles,
                                         &regex_cancel_dht_get, NULL);
  GNUNET_CONTAINER_multihashmap_iterate (h->dht_get_results,
                                         &regex_free_result, NULL);
  GNUNET_CONTAINER_multihashmap_destroy (h->dht_get_results);
  GNUNET_CONTAINER_multihashmap_destroy (h->dht_get_handles);
  if (0 < h->n_contexts)
  {
    for (i = 0; i < h->n_contexts; i++)
      GNUNET_free (h->contexts[i]);
    GNUNET_free (h->contexts);
  }
  GNUNET_free (h);
}


/* end of regex_internal_dht.c */