-enable peer API to return pointer to interned peer hash code
[oweals/gnunet.git] / src / regex / regex.c
1 /*
2      This file is part of GNUnet
3      (C) 2012 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  * @file src/regex/regex.c
22  * @brief library to create automatons from regular expressions
23  * @author Maximilian Szengel
24  */
25 #include "platform.h"
26 #include "gnunet_container_lib.h"
27 #include "gnunet_crypto_lib.h"
28 #include "gnunet_regex_lib.h"
29 #include "regex_internal.h"
30
31
32 /**
33  * Constant for how many bits the initial string regex should have.
34  */
35 #define INITIAL_BITS 8
36
37
38 /**
39  * Set of states.
40  */
41 struct GNUNET_REGEX_StateSet
42 {
43   /**
44    * Array of states.
45    */
46   struct GNUNET_REGEX_State **states;
47
48   /**
49    * Length of the 'states' array.
50    */
51   unsigned int len;
52 };
53
54
55 /**
56  * Compare two strings for equality. If either is NULL they are not equal.
57  *
58  * @param str1 first string for comparison.
59  * @param str2 second string for comparison.
60  *
61  * @return 0 if the strings are the same or both NULL, 1 or -1 if not.
62  */
63 static int
64 nullstrcmp (const char *str1, const char *str2)
65 {
66   if ((NULL == str1) != (NULL == str2))
67     return -1;
68   if ((NULL == str1) && (NULL == str2))
69     return 0;
70
71   return strcmp (str1, str2);
72 }
73
74
75 /**
76  * Adds a transition from one state to another on 'label'. Does not add
77  * duplicate states.
78  *
79  * @param ctx context
80  * @param from_state starting state for the transition
81  * @param label transition label
82  * @param to_state state to where the transition should point to
83  */
84 static void
85 state_add_transition (struct GNUNET_REGEX_Context *ctx,
86                       struct GNUNET_REGEX_State *from_state, const char *label,
87                       struct GNUNET_REGEX_State *to_state)
88 {
89   struct GNUNET_REGEX_Transition *t;
90   struct GNUNET_REGEX_Transition *oth;
91
92   if (NULL == from_state)
93   {
94     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
95     return;
96   }
97
98   // Do not add duplicate state transitions
99   for (t = from_state->transitions_head; NULL != t; t = t->next)
100   {
101     if (t->to_state == to_state && 0 == nullstrcmp (t->label, label) &&
102         t->from_state == from_state)
103       return;
104   }
105
106   // sort transitions by label
107   for (oth = from_state->transitions_head; NULL != oth; oth = oth->next)
108   {
109     if (0 < nullstrcmp (oth->label, label))
110       break;
111   }
112
113   t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
114   if (NULL != ctx)
115     t->id = ctx->transition_id++;
116   if (NULL != label)
117     t->label = GNUNET_strdup (label);
118   else
119     t->label = NULL;
120   t->to_state = to_state;
121   t->from_state = from_state;
122
123   // Add outgoing transition to 'from_state'
124   from_state->transition_count++;
125   GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head,
126                                       from_state->transitions_tail, oth, t);
127 }
128
129
130 /**
131  * Remove a 'transition' from 'state'.
132  *
133  * @param state state from which the to-be-removed transition originates.
134  * @param transition transition that should be removed from state 'state'.
135  */
136 static void
137 state_remove_transition (struct GNUNET_REGEX_State *state,
138                          struct GNUNET_REGEX_Transition *transition)
139 {
140   if (NULL == state || NULL == transition)
141     return;
142
143   if (transition->from_state != state)
144     return;
145
146   GNUNET_free_non_null (transition->label);
147
148   state->transition_count--;
149   GNUNET_CONTAINER_DLL_remove (state->transitions_head, state->transitions_tail,
150                                transition);
151   GNUNET_free (transition);
152 }
153
154
155 /**
156  * Compare two states. Used for sorting.
157  *
158  * @param a first state
159  * @param b second state
160  *
161  * @return an integer less than, equal to, or greater than zero
162  *         if the first argument is considered to be respectively
163  *         less than, equal to, or greater than the second.
164  */
165 static int
166 state_compare (const void *a, const void *b)
167 {
168   struct GNUNET_REGEX_State **s1;
169   struct GNUNET_REGEX_State **s2;
170
171   s1 = (struct GNUNET_REGEX_State **) a;
172   s2 = (struct GNUNET_REGEX_State **) b;
173
174   return (*s1)->id - (*s2)->id;
175 }
176
177
178 /**
179  * Get all edges leaving state 's'.
180  *
181  * @param s state.
182  * @param edges all edges leaving 's', expected to be allocated and have enough
183  *        space for s->transitions_count elements.
184  *
185  * @return number of edges.
186  */
187 static unsigned int
188 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
189 {
190   struct GNUNET_REGEX_Transition *t;
191   unsigned int count;
192
193   if (NULL == s)
194     return 0;
195
196   count = 0;
197
198   for (t = s->transitions_head; NULL != t; t = t->next)
199   {
200     if (NULL != t->to_state)
201     {
202       edges[count].label = t->label;
203       edges[count].destination = t->to_state->hash;
204       count++;
205     }
206   }
207   return count;
208 }
209
210
211 /**
212  * Compare to state sets by comparing the id's of the states that are contained
213  * in each set. Both sets are expected to be sorted by id!
214  *
215  * @param sset1 first state set
216  * @param sset2 second state set
217  *
218  * @return an integer less than, equal to, or greater than zero
219  *         if the first argument is considered to be respectively
220  *         less than, equal to, or greater than the second.
221  */
222 static int
223 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
224                    struct GNUNET_REGEX_StateSet *sset2)
225 {
226   int result;
227   unsigned int i;
228
229   if (NULL == sset1 || NULL == sset2)
230     return 1;
231
232   result = sset1->len - sset2->len;
233
234   for (i = 0; i < sset1->len; i++)
235   {
236     if (0 != result)
237       break;
238
239     result = state_compare (&sset1->states[i], &sset2->states[i]);
240   }
241   return result;
242 }
243
244
245 /**
246  * Clears the given StateSet 'set'
247  *
248  * @param set set to be cleared
249  */
250 static void
251 state_set_clear (struct GNUNET_REGEX_StateSet *set)
252 {
253   if (NULL == set)
254     return;
255
256   if (set->len > 0)
257     GNUNET_array_grow (set->states, set->len, 0);
258   GNUNET_free (set);
259 }
260
261
262 /**
263  * Clears an automaton fragment. Does not destroy the states inside the
264  * automaton.
265  *
266  * @param a automaton to be cleared
267  */
268 static void
269 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
270 {
271   if (NULL == a)
272     return;
273
274   a->start = NULL;
275   a->end = NULL;
276   a->states_head = NULL;
277   a->states_tail = NULL;
278   a->state_count = 0;
279   GNUNET_free (a);
280 }
281
282
283 /**
284  * Frees the memory used by State 's'
285  *
286  * @param s state that should be destroyed
287  */
288 static void
289 automaton_destroy_state (struct GNUNET_REGEX_State *s)
290 {
291   struct GNUNET_REGEX_Transition *t;
292   struct GNUNET_REGEX_Transition *next_t;
293
294   if (NULL == s)
295     return;
296
297   GNUNET_free_non_null (s->name);
298   GNUNET_free_non_null (s->proof);
299   state_set_clear (s->nfa_set);
300
301   for (t = s->transitions_head; NULL != t; t = next_t)
302   {
303     next_t = t->next;
304     state_remove_transition (s, t);
305   }
306
307   GNUNET_free (s);
308 }
309
310
311 /**
312  * Remove a state from the given automaton 'a'. Always use this function when
313  * altering the states of an automaton. Will also remove all transitions leading
314  * to this state, before destroying it.
315  *
316  * @param a automaton
317  * @param s state to remove
318  */
319 static void
320 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
321                         struct GNUNET_REGEX_State *s)
322 {
323   struct GNUNET_REGEX_State *s_check;
324   struct GNUNET_REGEX_Transition *t_check;
325   struct GNUNET_REGEX_Transition *t_check_next;
326
327   if (NULL == a || NULL == s)
328     return;
329
330   // remove all transitions leading to this state
331   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
332   {
333     for (t_check = s_check->transitions_head; NULL != t_check;
334          t_check = t_check_next)
335     {
336       t_check_next = t_check->next;
337       if (t_check->to_state == s)
338         state_remove_transition (s_check, t_check);
339     }
340   }
341
342   // remove state
343   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
344   a->state_count--;
345
346   automaton_destroy_state (s);
347 }
348
349
350 /**
351  * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
352  * 's2'.
353  *
354  * @param ctx context
355  * @param a automaton
356  * @param s1 first state
357  * @param s2 second state, will be destroyed
358  */
359 static void
360 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
361                         struct GNUNET_REGEX_Automaton *a,
362                         struct GNUNET_REGEX_State *s1,
363                         struct GNUNET_REGEX_State *s2)
364 {
365   struct GNUNET_REGEX_State *s_check;
366   struct GNUNET_REGEX_Transition *t_check;
367   struct GNUNET_REGEX_Transition *t;
368   struct GNUNET_REGEX_Transition *t_next;
369   char *new_name;
370   int is_dup;
371
372   GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
373
374   if (s1 == s2)
375     return;
376
377   // 1. Make all transitions pointing to s2 point to s1, unless this transition
378   // does not already exists, if it already exists remove transition.
379   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
380   {
381     for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next)
382     {
383       t_next = t_check->next;
384
385       if (s2 == t_check->to_state)
386       {
387         is_dup = GNUNET_NO;
388         for (t = t_check->from_state->transitions_head; NULL != t; t = t->next)
389         {
390           if (t->to_state == s1 && 0 == strcmp (t_check->label, t->label))
391             is_dup = GNUNET_YES;
392         }
393         if (GNUNET_NO == is_dup)
394           t_check->to_state = s1;
395         else
396           state_remove_transition (t_check->from_state, t_check);
397       }
398     }
399   }
400
401   // 2. Add all transitions from s2 to sX to s1
402   for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
403   {
404     if (t_check->to_state != s1)
405       state_add_transition (ctx, s1, t_check->label, t_check->to_state);
406   }
407
408   // 3. Rename s1 to {s1,s2}
409   new_name = s1->name;
410   GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
411   GNUNET_free (new_name);
412
413   // remove state
414   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
415   a->state_count--;
416   automaton_destroy_state (s2);
417 }
418
419
420 /**
421  * Add a state to the automaton 'a', always use this function to alter the
422  * states DLL of the automaton.
423  *
424  * @param a automaton to add the state to
425  * @param s state that should be added
426  */
427 static void
428 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
429                      struct GNUNET_REGEX_State *s)
430 {
431   GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
432   a->state_count++;
433 }
434
435
436 /**
437  * Depth-first traversal (DFS) of all states that are reachable from state
438  * 's'. Performs 'action' on each visited state.
439  *
440  * @param s start state.
441  * @param marks an array of size a->state_count to remember which state was
442  *        already visited.
443  * @param count current count of the state.
444  * @param check function that is checked before advancing on each transition
445  *              in the DFS.
446  * @param check_cls closure for check.
447  * @param action action to be performed on each state.
448  * @param action_cls closure for action.
449  */
450 static void
451 automaton_state_traverse (struct GNUNET_REGEX_State *s, int *marks,
452                           unsigned int *count,
453                           GNUNET_REGEX_traverse_check check, void *check_cls,
454                           GNUNET_REGEX_traverse_action action, void *action_cls)
455 {
456   struct GNUNET_REGEX_Transition *t;
457
458   if (GNUNET_YES == marks[s->traversal_id])
459     return;
460
461   marks[s->traversal_id] = GNUNET_YES;
462
463   if (NULL != action)
464     action (action_cls, *count, s);
465
466   (*count)++;
467
468   for (t = s->transitions_head; NULL != t; t = t->next)
469   {
470     if (NULL == check ||
471         (NULL != check && GNUNET_YES == check (check_cls, s, t)))
472     {
473       automaton_state_traverse (t->to_state, marks, count, check, check_cls,
474                                 action, action_cls);
475     }
476   }
477 }
478
479
480 /**
481  * Traverses the given automaton using depth-first-search (DFS) from it's start
482  * state, visiting all reachable states and calling 'action' on each one of
483  * them.
484  *
485  * @param a automaton to be traversed.
486  * @param start start state, pass a->start or NULL to traverse the whole automaton.
487  * @param check function that is checked before advancing on each transition
488  *              in the DFS.
489  * @param check_cls closure for check.
490  * @param action action to be performed on each state.
491  * @param action_cls closure for action
492  */
493 void
494 GNUNET_REGEX_automaton_traverse (const struct GNUNET_REGEX_Automaton *a,
495                                  struct GNUNET_REGEX_State *start,
496                                  GNUNET_REGEX_traverse_check check,
497                                  void *check_cls,
498                                  GNUNET_REGEX_traverse_action action,
499                                  void *action_cls)
500 {
501   unsigned int count;
502   struct GNUNET_REGEX_State *s;
503
504   if (NULL == a || 0 == a->state_count)
505     return;
506
507   int marks[a->state_count];
508
509   for (count = 0, s = a->states_head; NULL != s && count < a->state_count;
510        s = s->next, count++)
511   {
512     s->traversal_id = count;
513     marks[s->traversal_id] = GNUNET_NO;
514   }
515
516   count = 0;
517
518   if (NULL == start)
519     s = a->start;
520   else
521     s = start;
522
523   automaton_state_traverse (s, marks, &count, check, check_cls, action,
524                             action_cls);
525 }
526
527
528 /**
529  * Context for adding strided transitions to a DFA.
530  */
531 struct GNUNET_REGEX_Strided_Context
532 {
533   /**
534    * Length of the strides.
535    */
536   const unsigned int stride;
537
538   /**
539    * Strided transitions DLL. New strided transitions will be stored in this DLL
540    * and afterwards added to the DFA.
541    */
542   struct GNUNET_REGEX_Transition *transitions_head;
543
544   /**
545    * Strided transitions DLL.
546    */
547   struct GNUNET_REGEX_Transition *transitions_tail;
548 };
549
550
551 /**
552  * Check if the given string 'str' needs parentheses around it when
553  * using it to generate a regex.
554  *
555  * @param str string
556  *
557  * @return GNUNET_YES if parentheses are needed, GNUNET_NO otherwise
558  */
559 static int
560 needs_parentheses (const char *str)
561 {
562   size_t slen;
563   const char *op;
564   const char *cl;
565   const char *pos;
566   unsigned int cnt;
567
568   if ((NULL == str) || ((slen = strlen (str)) < 2))
569     return GNUNET_NO;
570
571   if ('(' != str[0])
572     return GNUNET_YES;
573   cnt = 1;
574   pos = &str[1];
575   while (cnt > 0)
576   {
577     cl = strchr (pos, ')');
578     if (NULL == cl)
579     {
580       GNUNET_break (0);
581       return GNUNET_YES;
582     }
583     op = strchr (pos, '(');
584     if ((NULL != op) && (op < cl))
585     {
586       cnt++;
587       pos = op + 1;
588       continue;
589     }
590     /* got ')' first */
591     cnt--;
592     pos = cl + 1;
593   }
594   return (*pos == '\0') ? GNUNET_NO : GNUNET_YES;
595 }
596
597
598 /**
599  * Remove parentheses surrounding string 'str'.
600  * Example: "(a)" becomes "a", "(a|b)|(a|c)" stays the same.
601  * You need to GNUNET_free the returned string.
602  *
603  * @param str string, free'd or re-used by this function, can be NULL
604  *
605  * @return string without surrounding parentheses, string 'str' if no preceding
606  *         epsilon could be found, NULL if 'str' was NULL
607  */
608 static char *
609 remove_parentheses (char *str)
610 {
611   size_t slen;
612   const char *pos;
613
614   if ((NULL == str) || ('(' != str[0]) ||
615       (str[(slen = strlen (str)) - 1] != ')'))
616     return str;
617
618   pos = strchr (&str[1], ')');
619   if (pos == &str[slen - 1])
620   {
621     memmove (str, &str[1], slen - 2);
622     str[slen - 2] = '\0';
623   }
624   return str;
625 }
626
627
628 /**
629  * Check if the string 'str' starts with an epsilon (empty string).
630  * Example: "(|a)" is starting with an epsilon.
631  *
632  * @param str string to test
633  *
634  * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')'
635  */
636 static int
637 has_epsilon (const char *str)
638 {
639   return (NULL != str) && ('(' == str[0]) && ('|' == str[1]) &&
640       (')' == str[strlen (str) - 1]);
641 }
642
643
644 /**
645  * Remove an epsilon from the string str. Where epsilon is an empty string
646  * Example: str = "(|a|b|c)", result: "a|b|c"
647  * The returned string needs to be freed.
648  *
649  * @param str string
650  *
651  * @return string without preceding epsilon, string 'str' if no preceding
652  *         epsilon could be found, NULL if 'str' was NULL
653  */
654 static char *
655 remove_epsilon (const char *str)
656 {
657   size_t len;
658
659   if (NULL == str)
660     return NULL;
661   if (('(' == str[0]) && ('|' == str[1]))
662   {
663     len = strlen (str);
664     if (')' == str[len - 1])
665       return GNUNET_strndup (&str[2], len - 3);
666   }
667   return GNUNET_strdup (str);
668 }
669
670
671 /**
672  * Compare 'str1', starting from position 'k',  with whole 'str2'
673  *
674  * @param str1 first string to compare, starting from position 'k'
675  * @param str2 second string for comparison
676  * @param k starting position in 'str1'
677  *
678  * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
679  */
680 static int
681 strkcmp (const char *str1, const char *str2, size_t k)
682 {
683   if ((NULL == str1) || (NULL == str2) || (strlen (str1) < k))
684     return -1;
685   return strcmp (&str1[k], str2);
686 }
687
688
689 /**
690  * Helper function used as 'action' in 'GNUNET_REGEX_automaton_traverse'
691  * function to create the depth-first numbering of the states.
692  *
693  * @param cls states array.
694  * @param count current state counter.
695  * @param s current state.
696  */
697 void
698 number_states (void *cls, const unsigned int count,
699                struct GNUNET_REGEX_State *s)
700 {
701   struct GNUNET_REGEX_State **states = cls;
702
703   s->dfs_id = count;
704   if (NULL != states)
705     states[count] = s;
706 }
707
708
709 /**
710  * Construct the regular expression given the inductive step,
711  * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^*
712  * R^{(k-1)}_{kj}, and simplify the resulting expression saved in R_cur_ij.
713  *
714  * @param R_last_ij value of  $R^{(k-1)_{ij}.
715  * @param R_last_ik value of  $R^{(k-1)_{ik}.
716  * @param R_last_kk value of  $R^{(k-1)_{kk}.
717  * @param R_last_kj value of  $R^{(k-1)_{kj}.
718  * @param R_cur_ij result for this inductive step is saved in R_cur_ij, R_cur_ij
719  *                 is expected to be NULL when called!
720  */
721 static void
722 automaton_create_proofs_simplify (char *R_last_ij, char *R_last_ik,
723                                   char *R_last_kk, char *R_last_kj,
724                                   char **R_cur_ij)
725 {
726   char *R_cur_l;
727   char *R_cur_r;
728   char *temp_a;
729   char *temp_b;
730   char *R_temp_ij;
731   char *R_temp_ik;
732   char *R_temp_kj;
733   char *R_temp_kk;
734
735   int eps_check;
736   int ij_ik_cmp;
737   int ij_kj_cmp;
738
739   int ik_kk_cmp;
740   int kk_kj_cmp;
741   int clean_ik_kk_cmp;
742   int clean_kk_kj_cmp;
743   unsigned int cnt;
744
745   size_t length;
746   size_t length_l;
747   size_t length_r;
748
749   GNUNET_assert (NULL == *R_cur_ij && NULL != R_cur_ij);
750
751   // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
752   // R_last == R^{(k-1)}, R_cur == R^{(k)}
753   // R_cur_ij = R_cur_l | R_cur_r
754   // R_cur_l == R^{(k-1)}_{ij}
755   // R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
756
757   if ((NULL == R_last_ij) && ((NULL == R_last_ik) || (NULL == R_last_kk) ||     /* technically cannot happen, but looks saner */
758                               (NULL == R_last_kj)))
759   {
760     /* R^{(k)}_{ij} = N | N */
761     *R_cur_ij = NULL;
762     return;
763   }
764
765   if ((NULL == R_last_ik) || (NULL == R_last_kk) ||     /* technically cannot happen, but looks saner */
766       (NULL == R_last_kj))
767   {
768     /*  R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */
769     *R_cur_ij = GNUNET_strdup (R_last_ij);
770     return;
771   }
772
773   // $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
774   // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
775
776   R_cur_r = NULL;
777   R_cur_l = NULL;
778
779   // cache results from strcmp, we might need these many times
780   ij_kj_cmp = nullstrcmp (R_last_ij, R_last_kj);
781   ij_ik_cmp = nullstrcmp (R_last_ij, R_last_ik);
782   ik_kk_cmp = nullstrcmp (R_last_ik, R_last_kk);
783   kk_kj_cmp = nullstrcmp (R_last_kk, R_last_kj);
784
785   // Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
786   // as parentheses, so we can better compare the contents
787   R_temp_ik = remove_parentheses (remove_epsilon (R_last_ik));
788   R_temp_kk = remove_parentheses (remove_epsilon (R_last_kk));
789   R_temp_kj = remove_parentheses (remove_epsilon (R_last_kj));
790
791   clean_ik_kk_cmp = nullstrcmp (R_last_ik, R_temp_kk);
792   clean_kk_kj_cmp = nullstrcmp (R_temp_kk, R_last_kj);
793
794   // construct R_cur_l (and, if necessary R_cur_r)
795   if (NULL != R_last_ij)
796   {
797     // Assign R_temp_ij to R_last_ij and remove epsilon as well
798     // as parentheses, so we can better compare the contents
799     R_temp_ij = remove_parentheses (remove_epsilon (R_last_ij));
800
801     if (0 == strcmp (R_temp_ij, R_temp_ik) && 0 == strcmp (R_temp_ik, R_temp_kk)
802         && 0 == strcmp (R_temp_kk, R_temp_kj))
803     {
804       if (0 == strlen (R_temp_ij))
805       {
806         R_cur_r = GNUNET_strdup ("");
807       }
808       else if ((0 == strncmp (R_last_ij, "(|", 2)) ||
809                (0 == strncmp (R_last_ik, "(|", 2) &&
810                 0 == strncmp (R_last_kj, "(|", 2)))
811       {
812         // a|(e|a)a*(e|a) = a*
813         // a|(e|a)(e|a)*(e|a) = a*
814         // (e|a)|aa*a = a*
815         // (e|a)|aa*(e|a) = a*
816         // (e|a)|(e|a)a*a = a*
817         // (e|a)|(e|a)a*(e|a) = a*
818         // (e|a)|(e|a)(e|a)*(e|a) = a*
819         if (GNUNET_YES == needs_parentheses (R_temp_ij))
820           GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_ij);
821         else
822           GNUNET_asprintf (&R_cur_r, "%s*", R_temp_ij);
823       }
824       else
825       {
826         // a|aa*a = a+
827         // a|(e|a)a*a = a+
828         // a|aa*(e|a) = a+
829         // a|(e|a)(e|a)*a = a+
830         // a|a(e|a)*(e|a) = a+
831         if (GNUNET_YES == needs_parentheses (R_temp_ij))
832           GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_ij);
833         else
834           GNUNET_asprintf (&R_cur_r, "%s+", R_temp_ij);
835       }
836     }
837     else if (0 == ij_ik_cmp && 0 == clean_kk_kj_cmp && 0 != clean_ik_kk_cmp)
838     {
839       // a|ab*b = ab*
840       if (strlen (R_last_kk) < 1)
841         R_cur_r = GNUNET_strdup (R_last_ij);
842       else if (GNUNET_YES == needs_parentheses (R_temp_kk))
843         GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
844       else
845         GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_last_kk);
846
847       R_cur_l = NULL;
848     }
849     else if (0 == ij_kj_cmp && 0 == clean_ik_kk_cmp && 0 != clean_kk_kj_cmp)
850     {
851       // a|bb*a = b*a
852       if (strlen (R_last_kk) < 1)
853         R_cur_r = GNUNET_strdup (R_last_kj);
854       else if (GNUNET_YES == needs_parentheses (R_temp_kk))
855         GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
856       else
857         GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
858
859       R_cur_l = NULL;
860     }
861     else if (0 == ij_ik_cmp && 0 == kk_kj_cmp && !has_epsilon (R_last_ij) &&
862              has_epsilon (R_last_kk))
863     {
864       // a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab*
865       if (needs_parentheses (R_temp_kk))
866         GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
867       else
868         GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_temp_kk);
869
870       R_cur_l = NULL;
871     }
872     else if (0 == ij_kj_cmp && 0 == ik_kk_cmp && !has_epsilon (R_last_ij) &&
873              has_epsilon (R_last_kk))
874     {
875       // a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|...  = b*a
876       if (needs_parentheses (R_temp_kk))
877         GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_ij);
878       else
879         GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_ij);
880
881       R_cur_l = NULL;
882     }
883     else
884     {
885       temp_a = (NULL == R_last_ij) ? NULL : GNUNET_strdup (R_last_ij);
886       temp_a = remove_parentheses (temp_a);
887       R_cur_l = temp_a;
888     }
889
890     GNUNET_free_non_null (R_temp_ij);
891   }
892   else
893   {
894     // we have no left side
895     R_cur_l = NULL;
896   }
897
898   // construct R_cur_r, if not already constructed
899   if (NULL == R_cur_r)
900   {
901     length = strlen (R_temp_kk) - strlen (R_last_ik);
902
903     // a(ba)*bx = (ab)+x
904     if (length > 0 && NULL != R_last_kk && 0 < strlen (R_last_kk) &&
905         NULL != R_last_kj && 0 < strlen (R_last_kj) && NULL != R_last_ik &&
906         0 < strlen (R_last_ik) && 0 == strkcmp (R_temp_kk, R_last_ik, length) &&
907         0 == strncmp (R_temp_kk, R_last_kj, length))
908     {
909       temp_a = GNUNET_malloc (length + 1);
910       temp_b = GNUNET_malloc ((strlen (R_last_kj) - length) + 1);
911
912       length_l = 0;
913       length_r = 0;
914
915       for (cnt = 0; cnt < strlen (R_last_kj); cnt++)
916       {
917         if (cnt < length)
918         {
919           temp_a[length_l] = R_last_kj[cnt];
920           length_l++;
921         }
922         else
923         {
924           temp_b[length_r] = R_last_kj[cnt];
925           length_r++;
926         }
927       }
928       temp_a[length_l] = '\0';
929       temp_b[length_r] = '\0';
930
931       // e|(ab)+ = (ab)*
932       if (NULL != R_cur_l && 0 == strlen (R_cur_l) && 0 == strlen (temp_b))
933       {
934         GNUNET_asprintf (&R_cur_r, "(%s%s)*", R_last_ik, temp_a);
935         GNUNET_free (R_cur_l);
936         R_cur_l = NULL;
937       }
938       else
939       {
940         GNUNET_asprintf (&R_cur_r, "(%s%s)+%s", R_last_ik, temp_a, temp_b);
941       }
942       GNUNET_free (temp_a);
943       GNUNET_free (temp_b);
944     }
945     else if (0 == strcmp (R_temp_ik, R_temp_kk) &&
946              0 == strcmp (R_temp_kk, R_temp_kj))
947     {
948       // (e|a)a*(e|a) = a*
949       // (e|a)(e|a)*(e|a) = a*
950       if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj))
951       {
952         if (needs_parentheses (R_temp_kk))
953           GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_kk);
954         else
955           GNUNET_asprintf (&R_cur_r, "%s*", R_temp_kk);
956       }
957       // aa*a = a+a
958       else if (0 == clean_ik_kk_cmp && 0 == clean_kk_kj_cmp &&
959                !has_epsilon (R_last_ik))
960       {
961         if (needs_parentheses (R_temp_kk))
962           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
963         else
964           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
965       }
966       // (e|a)a*a = a+
967       // aa*(e|a) = a+
968       // a(e|a)*(e|a) = a+
969       // (e|a)a*a = a+
970       else
971       {
972         eps_check =
973             (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
974              has_epsilon (R_last_kj));
975
976         if (eps_check == 1)
977         {
978           if (needs_parentheses (R_temp_kk))
979             GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_kk);
980           else
981             GNUNET_asprintf (&R_cur_r, "%s+", R_temp_kk);
982         }
983       }
984     }
985     // aa*b = a+b
986     // (e|a)(e|a)*b = a*b
987     else if (0 == strcmp (R_temp_ik, R_temp_kk))
988     {
989       if (has_epsilon (R_last_ik))
990       {
991         if (needs_parentheses (R_temp_kk))
992           GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
993         else
994           GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
995       }
996       else
997       {
998         if (needs_parentheses (R_temp_kk))
999           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_last_kj);
1000         else
1001           GNUNET_asprintf (&R_cur_r, "%s+%s", R_temp_kk, R_last_kj);
1002       }
1003     }
1004     // ba*a = ba+
1005     // b(e|a)*(e|a) = ba*
1006     else if (0 == strcmp (R_temp_kk, R_temp_kj))
1007     {
1008       if (has_epsilon (R_last_kj))
1009       {
1010         if (needs_parentheses (R_temp_kk))
1011           GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ik, R_temp_kk);
1012         else
1013           GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ik, R_temp_kk);
1014       }
1015       else
1016       {
1017         if (needs_parentheses (R_temp_kk))
1018           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_last_ik, R_temp_kk);
1019         else
1020           GNUNET_asprintf (&R_cur_r, "%s+%s", R_last_ik, R_temp_kk);
1021       }
1022     }
1023     else
1024     {
1025       if (strlen (R_temp_kk) > 0)
1026       {
1027         if (needs_parentheses (R_temp_kk))
1028         {
1029           GNUNET_asprintf (&R_cur_r, "%s(%s)*%s", R_last_ik, R_temp_kk,
1030                            R_last_kj);
1031         }
1032         else
1033         {
1034           GNUNET_asprintf (&R_cur_r, "%s%s*%s", R_last_ik, R_temp_kk,
1035                            R_last_kj);
1036         }
1037       }
1038       else
1039       {
1040         GNUNET_asprintf (&R_cur_r, "%s%s", R_last_ik, R_last_kj);
1041       }
1042     }
1043   }
1044
1045   GNUNET_free_non_null (R_temp_ik);
1046   GNUNET_free_non_null (R_temp_kk);
1047   GNUNET_free_non_null (R_temp_kj);
1048
1049   if (NULL == R_cur_l && NULL == R_cur_r)
1050   {
1051     *R_cur_ij = NULL;
1052     return;
1053   }
1054
1055   if (NULL != R_cur_l && NULL == R_cur_r)
1056   {
1057     *R_cur_ij = R_cur_l;
1058     return;
1059   }
1060
1061   if (NULL == R_cur_l && NULL != R_cur_r)
1062   {
1063     *R_cur_ij = R_cur_r;
1064     return;
1065   }
1066
1067   if (0 == nullstrcmp (R_cur_l, R_cur_r))
1068   {
1069     *R_cur_ij = R_cur_l;
1070     GNUNET_free (R_cur_r);
1071     return;
1072   }
1073
1074   GNUNET_asprintf (R_cur_ij, "(%s|%s)", R_cur_l, R_cur_r);
1075
1076   GNUNET_free (R_cur_l);
1077   GNUNET_free (R_cur_r);
1078 }
1079
1080
1081 /**
1082  * create proofs for all states in the given automaton. Implementation of the
1083  * algorithm descriped in chapter 3.2.1 of "Automata Theory, Languages, and
1084  * Computation 3rd Edition" by Hopcroft, Motwani and Ullman.
1085  *
1086  * @param a automaton.
1087  */
1088 static void
1089 automaton_create_proofs (struct GNUNET_REGEX_Automaton *a)
1090 {
1091   if (NULL == a)
1092   {
1093     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1094                 "Could not create proofs, automaton was NULL\n");
1095     return;
1096   }
1097
1098   unsigned int n = a->state_count;
1099   struct GNUNET_REGEX_State *states[n];
1100   char *R_last[n][n];
1101   char *R_cur[n][n];
1102   char *temp;
1103   struct GNUNET_REGEX_Transition *t;
1104   char *complete_regex;
1105   unsigned int i;
1106   unsigned int j;
1107   unsigned int k;
1108
1109   /* create depth-first numbering of the states, initializes 'state' */
1110   GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &number_states,
1111                                    states);
1112
1113   for (i = 0; i < n; i++)
1114     GNUNET_assert (NULL != states[i]);
1115
1116   /* Compute regular expressions of length "1" between each pair of states */
1117   for (i = 0; i < n; i++)
1118   {
1119     for (j = 0; j < n; j++)
1120     {
1121       R_cur[i][j] = NULL;
1122       R_last[i][j] = NULL;
1123     }
1124     for (t = states[i]->transitions_head; NULL != t; t = t->next)
1125     {
1126       j = t->to_state->dfs_id;
1127       if (NULL == R_last[i][j])
1128         GNUNET_asprintf (&R_last[i][j], "%s", t->label);
1129       else
1130       {
1131         temp = R_last[i][j];
1132         GNUNET_asprintf (&R_last[i][j], "%s|%s", R_last[i][j], t->label);
1133         GNUNET_free (temp);
1134       }
1135     }
1136     if (NULL == R_last[i][i])
1137       GNUNET_asprintf (&R_last[i][i], "");
1138     else
1139     {
1140       temp = R_last[i][i];
1141       GNUNET_asprintf (&R_last[i][i], "(|%s)", R_last[i][i]);
1142       GNUNET_free (temp);
1143     }
1144   }
1145   for (i = 0; i < n; i++)
1146     for (j = 0; j < n; j++)
1147       if (needs_parentheses (R_last[i][j]))
1148       {
1149         temp = R_last[i][j];
1150         GNUNET_asprintf (&R_last[i][j], "(%s)", R_last[i][j]);
1151         GNUNET_free (temp);
1152       }
1153
1154   /* Compute regular expressions of length "k" between each pair of states per
1155    * induction */
1156   for (k = 0; k < n; k++)
1157   {
1158     for (i = 0; i < n; i++)
1159     {
1160       for (j = 0; j < n; j++)
1161       {
1162         // Basis for the recursion:
1163         // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1164         // R_last == R^{(k-1)}, R_cur == R^{(k)}
1165
1166         // Create R_cur[i][j] and simplify the expression
1167         automaton_create_proofs_simplify (R_last[i][j], R_last[i][k],
1168                                           R_last[k][k], R_last[k][j],
1169                                           &R_cur[i][j]);
1170       }
1171     }
1172
1173     // set R_last = R_cur
1174     for (i = 0; i < n; i++)
1175     {
1176       for (j = 0; j < n; j++)
1177       {
1178         GNUNET_free_non_null (R_last[i][j]);
1179         R_last[i][j] = R_cur[i][j];
1180         R_cur[i][j] = NULL;
1181       }
1182     }
1183   }
1184
1185   // assign proofs and hashes
1186   for (i = 0; i < n; i++)
1187   {
1188     if (NULL != R_last[a->start->dfs_id][i])
1189     {
1190       states[i]->proof = GNUNET_strdup (R_last[a->start->dfs_id][i]);
1191       GNUNET_CRYPTO_hash (states[i]->proof, strlen (states[i]->proof),
1192                           &states[i]->hash);
1193     }
1194   }
1195
1196   // complete regex for whole DFA: union of all pairs (start state/accepting
1197   // state(s)).
1198   complete_regex = NULL;
1199   for (i = 0; i < n; i++)
1200   {
1201     if (states[i]->accepting)
1202     {
1203       if (NULL == complete_regex && 0 < strlen (R_last[a->start->dfs_id][i]))
1204       {
1205         GNUNET_asprintf (&complete_regex, "%s", R_last[a->start->dfs_id][i]);
1206       }
1207       else if (NULL != R_last[a->start->dfs_id][i] &&
1208                0 < strlen (R_last[a->start->dfs_id][i]))
1209       {
1210         temp = complete_regex;
1211         GNUNET_asprintf (&complete_regex, "%s|%s", complete_regex,
1212                          R_last[a->start->dfs_id][i]);
1213         GNUNET_free (temp);
1214       }
1215     }
1216   }
1217   a->canonical_regex = complete_regex;
1218
1219   // cleanup
1220   for (i = 0; i < n; i++)
1221   {
1222     for (j = 0; j < n; j++)
1223       GNUNET_free_non_null (R_last[i][j]);
1224   }
1225 }
1226
1227
1228 /**
1229  * Creates a new DFA state based on a set of NFA states. Needs to be freed using
1230  * automaton_destroy_state.
1231  *
1232  * @param ctx context
1233  * @param nfa_states set of NFA states on which the DFA should be based on
1234  *
1235  * @return new DFA state
1236  */
1237 static struct GNUNET_REGEX_State *
1238 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
1239                   struct GNUNET_REGEX_StateSet *nfa_states)
1240 {
1241   struct GNUNET_REGEX_State *s;
1242   char *name;
1243   int len = 0;
1244   struct GNUNET_REGEX_State *cstate;
1245   struct GNUNET_REGEX_Transition *ctran;
1246   unsigned int i;
1247
1248   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1249   s->id = ctx->state_id++;
1250   s->accepting = 0;
1251   s->marked = GNUNET_NO;
1252   s->name = NULL;
1253   s->scc_id = 0;
1254   s->index = -1;
1255   s->lowlink = -1;
1256   s->contained = 0;
1257   s->proof = NULL;
1258
1259   if (NULL == nfa_states)
1260   {
1261     GNUNET_asprintf (&s->name, "s%i", s->id);
1262     return s;
1263   }
1264
1265   s->nfa_set = nfa_states;
1266
1267   if (nfa_states->len < 1)
1268     return s;
1269
1270   // Create a name based on 'nfa_states'
1271   s->name = GNUNET_malloc (sizeof (char) * 2);
1272   strcat (s->name, "{");
1273   name = NULL;
1274
1275   for (i = 0; i < nfa_states->len; i++)
1276   {
1277     cstate = nfa_states->states[i];
1278     GNUNET_asprintf (&name, "%i,", cstate->id);
1279
1280     if (NULL != name)
1281     {
1282       len = strlen (s->name) + strlen (name) + 1;
1283       s->name = GNUNET_realloc (s->name, len);
1284       strcat (s->name, name);
1285       GNUNET_free (name);
1286       name = NULL;
1287     }
1288
1289     // Add a transition for each distinct label to NULL state
1290     for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
1291     {
1292       if (NULL != ctran->label)
1293         state_add_transition (ctx, s, ctran->label, NULL);
1294     }
1295
1296     // If the nfa_states contain an accepting state, the new dfa state is also
1297     // accepting
1298     if (cstate->accepting)
1299       s->accepting = 1;
1300   }
1301
1302   s->name[strlen (s->name) - 1] = '}';
1303
1304   return s;
1305 }
1306
1307
1308 /**
1309  * Move from the given state 's' to the next state on transition 'str'. Consumes
1310  * as much of the given 'str' as possible (usefull for strided DFAs). On return
1311  * 's' will point to the next state, and the length of the substring used for
1312  * this transition will be returned. If no transition possible 0 is returned and
1313  * 's' points to NULL.
1314  *
1315  * @param s starting state, will point to the next state or NULL (if no
1316  * transition possible)
1317  * @param str edge label to follow (will match longest common prefix)
1318  *
1319  * @return length of the substring comsumed from 'str'
1320  */
1321 static unsigned int
1322 dfa_move (struct GNUNET_REGEX_State **s, const char *str)
1323 {
1324   struct GNUNET_REGEX_Transition *t;
1325   struct GNUNET_REGEX_State *new_s;
1326   unsigned int len;
1327   unsigned int max_len;
1328
1329   if (NULL == s)
1330     return 0;
1331
1332   new_s = NULL;
1333   max_len = 0;
1334   for (t = (*s)->transitions_head; NULL != t; t = t->next)
1335   {
1336     len = strlen (t->label);
1337
1338     if (0 == strncmp (t->label, str, len))
1339     {
1340       if (len >= max_len)
1341       {
1342         max_len = len;
1343         new_s = t->to_state;
1344       }
1345     }
1346   }
1347
1348   *s = new_s;
1349   return max_len;
1350 }
1351
1352 /**
1353  * Set the given state 'marked' to GNUNET_YES. Used by the
1354  * 'dfa_remove_unreachable_states' function to detect unreachable states in the
1355  * automaton.
1356  *
1357  * @param cls closure, not used.
1358  * @param count count, not used.
1359  * @param s state where the marked attribute will be set to GNUNET_YES.
1360  */
1361 void
1362 mark_states (void *cls, const unsigned int count, struct GNUNET_REGEX_State *s)
1363 {
1364   s->marked = GNUNET_YES;
1365 }
1366
1367 /**
1368  * Remove all unreachable states from DFA 'a'. Unreachable states are those
1369  * states that are not reachable from the starting state.
1370  *
1371  * @param a DFA automaton
1372  */
1373 static void
1374 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
1375 {
1376   struct GNUNET_REGEX_State *s;
1377   struct GNUNET_REGEX_State *s_next;
1378
1379   // 1. unmark all states
1380   for (s = a->states_head; NULL != s; s = s->next)
1381     s->marked = GNUNET_NO;
1382
1383   // 2. traverse dfa from start state and mark all visited states
1384   GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &mark_states, NULL);
1385
1386   // 3. delete all states that were not visited
1387   for (s = a->states_head; NULL != s; s = s_next)
1388   {
1389     s_next = s->next;
1390     if (GNUNET_NO == s->marked)
1391       automaton_remove_state (a, s);
1392   }
1393 }
1394
1395
1396 /**
1397  * Remove all dead states from the DFA 'a'. Dead states are those states that do
1398  * not transition to any other state but themselves.
1399  *
1400  * @param a DFA automaton
1401  */
1402 static void
1403 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
1404 {
1405   struct GNUNET_REGEX_State *s;
1406   struct GNUNET_REGEX_Transition *t;
1407   int dead;
1408
1409   GNUNET_assert (DFA == a->type);
1410
1411   for (s = a->states_head; NULL != s; s = s->next)
1412   {
1413     if (s->accepting)
1414       continue;
1415
1416     dead = 1;
1417     for (t = s->transitions_head; NULL != t; t = t->next)
1418     {
1419       if (NULL != t->to_state && t->to_state != s)
1420       {
1421         dead = 0;
1422         break;
1423       }
1424     }
1425
1426     if (0 == dead)
1427       continue;
1428
1429     // state s is dead, remove it
1430     automaton_remove_state (a, s);
1431   }
1432 }
1433
1434
1435 /**
1436  * Merge all non distinguishable states in the DFA 'a'
1437  *
1438  * @param ctx context
1439  * @param a DFA automaton
1440  */
1441 static void
1442 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
1443                                      struct GNUNET_REGEX_Automaton *a)
1444 {
1445   int table[a->state_count][a->state_count];
1446   struct GNUNET_REGEX_State *s1;
1447   struct GNUNET_REGEX_State *s2;
1448   struct GNUNET_REGEX_Transition *t1;
1449   struct GNUNET_REGEX_Transition *t2;
1450   struct GNUNET_REGEX_State *s1_next;
1451   struct GNUNET_REGEX_State *s2_next;
1452   int change;
1453   unsigned int num_equal_edges;
1454   unsigned int i;
1455
1456   for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
1457        i++, s1 = s1->next)
1458   {
1459     s1->marked = i;
1460   }
1461
1462   // Mark all pairs of accepting/!accepting states
1463   for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1464   {
1465     for (s2 = a->states_head; NULL != s2; s2 = s2->next)
1466     {
1467       table[s1->marked][s2->marked] = 0;
1468
1469       if ((s1->accepting && !s2->accepting) ||
1470           (!s1->accepting && s2->accepting))
1471       {
1472         table[s1->marked][s2->marked] = 1;
1473       }
1474     }
1475   }
1476
1477   // Find all equal states
1478   change = 1;
1479   while (0 != change)
1480   {
1481     change = 0;
1482     for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1483     {
1484       for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
1485       {
1486         if (0 != table[s1->marked][s2->marked])
1487           continue;
1488
1489         num_equal_edges = 0;
1490         for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
1491         {
1492           for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
1493           {
1494             if (0 == strcmp (t1->label, t2->label))
1495             {
1496               num_equal_edges++;
1497               if (0 != table[t1->to_state->marked][t2->to_state->marked] ||
1498                   0 != table[t2->to_state->marked][t1->to_state->marked])
1499               {
1500                 table[s1->marked][s2->marked] = 1;
1501                 change = 1;
1502               }
1503             }
1504           }
1505         }
1506         if (num_equal_edges != s1->transition_count ||
1507             num_equal_edges != s2->transition_count)
1508         {
1509           // Make sure ALL edges of possible equal states are the same
1510           table[s1->marked][s2->marked] = -2;
1511         }
1512       }
1513     }
1514   }
1515
1516   // Merge states that are equal
1517   for (s1 = a->states_head; NULL != s1; s1 = s1_next)
1518   {
1519     s1_next = s1->next;
1520     for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
1521     {
1522       s2_next = s2->next;
1523       if (table[s1->marked][s2->marked] == 0)
1524         automaton_merge_states (ctx, a, s1, s2);
1525     }
1526   }
1527 }
1528
1529
1530 /**
1531  * Minimize the given DFA 'a' by removing all unreachable states, removing all
1532  * dead states and merging all non distinguishable states
1533  *
1534  * @param ctx context
1535  * @param a DFA automaton
1536  */
1537 static void
1538 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
1539               struct GNUNET_REGEX_Automaton *a)
1540 {
1541   if (NULL == a)
1542     return;
1543
1544   GNUNET_assert (DFA == a->type);
1545
1546   // 1. remove unreachable states
1547   dfa_remove_unreachable_states (a);
1548
1549   // 2. remove dead states
1550   dfa_remove_dead_states (a);
1551
1552   // 3. Merge nondistinguishable states
1553   dfa_merge_nondistinguishable_states (ctx, a);
1554 }
1555
1556
1557 /**
1558  * Recursive helper function to add strides to a DFA.
1559  *
1560  * @param cls context, contains stride length and strided transitions DLL.
1561  * @param depth current depth of the depth-first traversal of the graph.
1562  * @param label current label, string that contains all labels on the path from
1563  *        'start' to 's'.
1564  * @param start start state for the depth-first traversal of the graph.
1565  * @param s current state in the depth-first traversal
1566  */
1567 void
1568 dfa_add_multi_strides_helper (void *cls, const unsigned int depth, char *label,
1569                               struct GNUNET_REGEX_State *start,
1570                               struct GNUNET_REGEX_State *s)
1571 {
1572   struct GNUNET_REGEX_Strided_Context *ctx = cls;
1573   struct GNUNET_REGEX_Transition *t;
1574   char *new_label;
1575
1576   if (depth == ctx->stride)
1577   {
1578     t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
1579     t->label = GNUNET_strdup (label);
1580     t->to_state = s;
1581     t->from_state = start;
1582     GNUNET_CONTAINER_DLL_insert (ctx->transitions_head, ctx->transitions_tail,
1583                                  t);
1584   }
1585   else
1586   {
1587     for (t = s->transitions_head; NULL != t; t = t->next)
1588     {
1589       /* Do not consider self-loops, because it end's up in too many
1590        * transitions */
1591       if (t->to_state == t->from_state)
1592         continue;
1593
1594       if (NULL != label)
1595       {
1596         GNUNET_asprintf (&new_label, "%s%s", label, t->label);
1597       }
1598       else
1599         new_label = GNUNET_strdup (t->label);
1600
1601       dfa_add_multi_strides_helper (cls, (depth + 1), new_label, start,
1602                                     t->to_state);
1603     }
1604   }
1605   GNUNET_free_non_null (label);
1606 }
1607
1608
1609 /**
1610  * Function called for each state in the DFA. Starts a traversal of depth set in
1611  * context starting from state 's'.
1612  *
1613  * @param cls context.
1614  * @param count not used.
1615  * @param s current state.
1616  */
1617 void
1618 dfa_add_multi_strides (void *cls, const unsigned int count,
1619                        struct GNUNET_REGEX_State *s)
1620 {
1621   dfa_add_multi_strides_helper (cls, 0, NULL, s, s);
1622 }
1623
1624
1625 /**
1626  * Adds multi-strided transitions to the given 'dfa'.
1627  *
1628  * @param regex_ctx regex context needed to add transitions to the automaton.
1629  * @param dfa DFA to which the multi strided transitions should be added.
1630  * @param stride_len length of the strides.
1631  */
1632 void
1633 GNUNET_REGEX_dfa_add_multi_strides (struct GNUNET_REGEX_Context *regex_ctx,
1634                                     struct GNUNET_REGEX_Automaton *dfa,
1635                                     const unsigned int stride_len)
1636 {
1637   struct GNUNET_REGEX_Strided_Context ctx = { stride_len, NULL, NULL };
1638   struct GNUNET_REGEX_Transition *t;
1639   struct GNUNET_REGEX_Transition *t_next;
1640
1641   if (1 > stride_len || GNUNET_YES == dfa->is_multistrided)
1642     return;
1643
1644   // Compute the new transitions of given stride_len
1645   GNUNET_REGEX_automaton_traverse (dfa, dfa->start, NULL, NULL,
1646                                    &dfa_add_multi_strides, &ctx);
1647
1648   // Add all the new transitions to the automaton.
1649   for (t = ctx.transitions_head; NULL != t; t = t_next)
1650   {
1651     t_next = t->next;
1652     state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
1653     GNUNET_CONTAINER_DLL_remove (ctx.transitions_head, ctx.transitions_tail, t);
1654     GNUNET_free_non_null (t->label);
1655     GNUNET_free (t);
1656   }
1657
1658   // Mark this automaton as multistrided
1659   dfa->is_multistrided = GNUNET_YES;
1660 }
1661
1662 /**
1663  * Recursive Helper function for DFA path compression. Does DFS on the DFA graph
1664  * and adds new transitions to the given transitions DLL and marks states that
1665  * should be removed by setting state->contained to GNUNET_YES.
1666  *
1667  * @param start starting state for linear path search.
1668  * @param cur current state in the recursive DFS.
1669  * @param label current label (string of traversed labels).
1670  * @param transitions_head transitions DLL.
1671  * @param transitions_tail transitions DLL.
1672  */
1673 void
1674 dfa_compress_paths_helper (struct GNUNET_REGEX_State *start,
1675                            struct GNUNET_REGEX_State *cur, char *label,
1676                            struct GNUNET_REGEX_Transition **transitions_head,
1677                            struct GNUNET_REGEX_Transition **transitions_tail)
1678 {
1679   struct GNUNET_REGEX_Transition *t;
1680   char *new_label;
1681
1682
1683   if (NULL != label &&
1684       (cur->incoming_transition_count > 1 || GNUNET_YES == cur->accepting ||
1685        cur->transition_count > 1 || GNUNET_YES == cur->marked))
1686   {
1687     t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
1688     t->label = GNUNET_strdup (label);
1689     t->to_state = cur;
1690     t->from_state = start;
1691     GNUNET_CONTAINER_DLL_insert (*transitions_head, *transitions_tail, t);
1692
1693     if (GNUNET_NO == cur->marked)
1694     {
1695       dfa_compress_paths_helper (cur, cur, NULL, transitions_head,
1696                                  transitions_tail);
1697     }
1698     return;
1699   }
1700   else if (cur != start)
1701     cur->contained = GNUNET_YES;
1702
1703   if (GNUNET_YES == cur->marked && cur != start)
1704     return;
1705
1706   cur->marked = GNUNET_YES;
1707
1708
1709   for (t = cur->transitions_head; NULL != t; t = t->next)
1710   {
1711     if (NULL != label)
1712       GNUNET_asprintf (&new_label, "%s%s", label, t->label);
1713     else
1714       new_label = GNUNET_strdup (t->label);
1715
1716     if (t->to_state != cur)
1717     {
1718       dfa_compress_paths_helper (start, t->to_state, new_label,
1719                                  transitions_head, transitions_tail);
1720     }
1721     GNUNET_free (new_label);
1722   }
1723 }
1724
1725 /**
1726  * Compress paths in the given 'dfa'. Linear paths like 0->1->2->3 will be
1727  * compressed to 0->3 by combining transitions.
1728  *
1729  * @param regex_ctx context for adding new transitions.
1730  * @param dfa DFA representation, will directly modify the given DFA.
1731  */
1732 static void
1733 dfa_compress_paths (struct GNUNET_REGEX_Context *regex_ctx,
1734                     struct GNUNET_REGEX_Automaton *dfa)
1735 {
1736   struct GNUNET_REGEX_State *s;
1737   struct GNUNET_REGEX_State *s_next;
1738   struct GNUNET_REGEX_Transition *t;
1739   struct GNUNET_REGEX_Transition *t_next;
1740   struct GNUNET_REGEX_Transition *transitions_head = NULL;
1741   struct GNUNET_REGEX_Transition *transitions_tail = NULL;
1742
1743   if (NULL == dfa)
1744     return;
1745
1746   // Count the incoming transitions on each state.
1747   for (s = dfa->states_head; NULL != s; s = s->next)
1748   {
1749     for (t = s->transitions_head; NULL != t; t = t->next)
1750     {
1751       if (NULL != t->to_state)
1752         t->to_state->incoming_transition_count++;
1753     }
1754   }
1755
1756   // Unmark all states.
1757   for (s = dfa->states_head; NULL != s; s = s->next)
1758   {
1759     s->marked = GNUNET_NO;
1760     s->contained = GNUNET_NO;
1761   }
1762
1763   // Add strides and mark states that can be deleted.
1764   dfa_compress_paths_helper (dfa->start, dfa->start, NULL, &transitions_head,
1765                              &transitions_tail);
1766
1767   // Add all the new transitions to the automaton.
1768   for (t = transitions_head; NULL != t; t = t_next)
1769   {
1770     t_next = t->next;
1771     state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
1772     GNUNET_CONTAINER_DLL_remove (transitions_head, transitions_tail, t);
1773     GNUNET_free_non_null (t->label);
1774     GNUNET_free (t);
1775   }
1776
1777   // Remove marked states (including their incoming and outgoing transitions).
1778   for (s = dfa->states_head; NULL != s; s = s_next)
1779   {
1780     s_next = s->next;
1781     if (GNUNET_YES == s->contained)
1782       automaton_remove_state (dfa, s);
1783   }
1784 }
1785
1786
1787 /**
1788  * Creates a new NFA fragment. Needs to be cleared using
1789  * automaton_fragment_clear.
1790  *
1791  * @param start starting state
1792  * @param end end state
1793  *
1794  * @return new NFA fragment
1795  */
1796 static struct GNUNET_REGEX_Automaton *
1797 nfa_fragment_create (struct GNUNET_REGEX_State *start,
1798                      struct GNUNET_REGEX_State *end)
1799 {
1800   struct GNUNET_REGEX_Automaton *n;
1801
1802   n = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1803
1804   n->type = NFA;
1805   n->start = NULL;
1806   n->end = NULL;
1807   n->state_count = 0;
1808
1809   if (NULL == start || NULL == end)
1810     return n;
1811
1812   automaton_add_state (n, end);
1813   automaton_add_state (n, start);
1814
1815   n->state_count = 2;
1816
1817   n->start = start;
1818   n->end = end;
1819
1820   return n;
1821 }
1822
1823
1824 /**
1825  * Adds a list of states to the given automaton 'n'.
1826  *
1827  * @param n automaton to which the states should be added
1828  * @param states_head head of the DLL of states
1829  * @param states_tail tail of the DLL of states
1830  */
1831 static void
1832 nfa_add_states (struct GNUNET_REGEX_Automaton *n,
1833                 struct GNUNET_REGEX_State *states_head,
1834                 struct GNUNET_REGEX_State *states_tail)
1835 {
1836   struct GNUNET_REGEX_State *s;
1837
1838   if (NULL == n || NULL == states_head)
1839   {
1840     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n");
1841     return;
1842   }
1843
1844   if (NULL == n->states_head)
1845   {
1846     n->states_head = states_head;
1847     n->states_tail = states_tail;
1848     return;
1849   }
1850
1851   if (NULL != states_head)
1852   {
1853     n->states_tail->next = states_head;
1854     n->states_tail = states_tail;
1855   }
1856
1857   for (s = states_head; NULL != s; s = s->next)
1858     n->state_count++;
1859 }
1860
1861
1862 /**
1863  * Creates a new NFA state. Needs to be freed using automaton_destroy_state.
1864  *
1865  * @param ctx context
1866  * @param accepting is it an accepting state or not
1867  *
1868  * @return new NFA state
1869  */
1870 static struct GNUNET_REGEX_State *
1871 nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
1872 {
1873   struct GNUNET_REGEX_State *s;
1874
1875   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1876   s->id = ctx->state_id++;
1877   s->accepting = accepting;
1878   s->marked = GNUNET_NO;
1879   s->contained = 0;
1880   s->index = -1;
1881   s->lowlink = -1;
1882   s->scc_id = 0;
1883   s->name = NULL;
1884   GNUNET_asprintf (&s->name, "s%i", s->id);
1885
1886   return s;
1887 }
1888
1889
1890 /**
1891  * Calculates the NFA closure set for the given state.
1892  *
1893  * @param nfa the NFA containing 's'
1894  * @param s starting point state
1895  * @param label transitioning label on which to base the closure on,
1896  *                pass NULL for epsilon transition
1897  *
1898  * @return sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
1899  */
1900 static struct GNUNET_REGEX_StateSet *
1901 nfa_closure_create (struct GNUNET_REGEX_Automaton *nfa,
1902                     struct GNUNET_REGEX_State *s, const char *label)
1903 {
1904   struct GNUNET_REGEX_StateSet *cls;
1905   struct GNUNET_REGEX_StateSet *cls_check;
1906   struct GNUNET_REGEX_State *clsstate;
1907   struct GNUNET_REGEX_State *currentstate;
1908   struct GNUNET_REGEX_Transition *ctran;
1909
1910   if (NULL == s)
1911     return NULL;
1912
1913   cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1914   cls_check = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1915
1916   for (clsstate = nfa->states_head; NULL != clsstate; clsstate = clsstate->next)
1917     clsstate->contained = 0;
1918
1919   // Add start state to closure only for epsilon closure
1920   if (NULL == label)
1921     GNUNET_array_append (cls->states, cls->len, s);
1922
1923   GNUNET_array_append (cls_check->states, cls_check->len, s);
1924   while (cls_check->len > 0)
1925   {
1926     currentstate = cls_check->states[cls_check->len - 1];
1927     GNUNET_array_grow (cls_check->states, cls_check->len, cls_check->len - 1);
1928
1929     for (ctran = currentstate->transitions_head; NULL != ctran;
1930          ctran = ctran->next)
1931     {
1932       if (NULL != ctran->to_state && 0 == nullstrcmp (label, ctran->label))
1933       {
1934         clsstate = ctran->to_state;
1935
1936         if (NULL != clsstate && 0 == clsstate->contained)
1937         {
1938           GNUNET_array_append (cls->states, cls->len, clsstate);
1939           GNUNET_array_append (cls_check->states, cls_check->len, clsstate);
1940           clsstate->contained = 1;
1941         }
1942       }
1943     }
1944   }
1945   GNUNET_assert (0 == cls_check->len);
1946   GNUNET_free (cls_check);
1947
1948   // sort the states
1949   if (cls->len > 1)
1950     qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1951            state_compare);
1952
1953   return cls;
1954 }
1955
1956
1957 /**
1958  * Calculates the closure set for the given set of states.
1959  *
1960  * @param nfa the NFA containing 's'
1961  * @param states list of states on which to base the closure on
1962  * @param label transitioning label for which to base the closure on,
1963  *                pass NULL for epsilon transition
1964  *
1965  * @return sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
1966  */
1967 static struct GNUNET_REGEX_StateSet *
1968 nfa_closure_set_create (struct GNUNET_REGEX_Automaton *nfa,
1969                         struct GNUNET_REGEX_StateSet *states, const char *label)
1970 {
1971   struct GNUNET_REGEX_State *s;
1972   struct GNUNET_REGEX_StateSet *sset;
1973   struct GNUNET_REGEX_StateSet *cls;
1974   unsigned int i;
1975   unsigned int j;
1976   unsigned int k;
1977   unsigned int contains;
1978
1979   if (NULL == states)
1980     return NULL;
1981
1982   cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1983
1984   for (i = 0; i < states->len; i++)
1985   {
1986     s = states->states[i];
1987     sset = nfa_closure_create (nfa, s, label);
1988
1989     for (j = 0; j < sset->len; j++)
1990     {
1991       contains = 0;
1992       for (k = 0; k < cls->len; k++)
1993       {
1994         if (sset->states[j]->id == cls->states[k]->id)
1995         {
1996           contains = 1;
1997           break;
1998         }
1999       }
2000       if (!contains)
2001         GNUNET_array_append (cls->states, cls->len, sset->states[j]);
2002     }
2003     state_set_clear (sset);
2004   }
2005
2006   if (cls->len > 1)
2007     qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
2008            state_compare);
2009
2010   return cls;
2011 }
2012
2013
2014 /**
2015  * Pops two NFA fragments (a, b) from the stack and concatenates them (ab)
2016  *
2017  * @param ctx context
2018  */
2019 static void
2020 nfa_add_concatenation (struct GNUNET_REGEX_Context *ctx)
2021 {
2022   struct GNUNET_REGEX_Automaton *a;
2023   struct GNUNET_REGEX_Automaton *b;
2024   struct GNUNET_REGEX_Automaton *new_nfa;
2025
2026   b = ctx->stack_tail;
2027   GNUNET_assert (NULL != b);
2028   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2029   a = ctx->stack_tail;
2030   GNUNET_assert (NULL != a);
2031   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2032
2033   state_add_transition (ctx, a->end, NULL, b->start);
2034   a->end->accepting = 0;
2035   b->end->accepting = 1;
2036
2037   new_nfa = nfa_fragment_create (NULL, NULL);
2038   nfa_add_states (new_nfa, a->states_head, a->states_tail);
2039   nfa_add_states (new_nfa, b->states_head, b->states_tail);
2040   new_nfa->start = a->start;
2041   new_nfa->end = b->end;
2042   new_nfa->state_count += a->state_count + b->state_count;
2043   automaton_fragment_clear (a);
2044   automaton_fragment_clear (b);
2045
2046   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2047 }
2048
2049
2050 /**
2051  * Pops a NFA fragment from the stack (a) and adds a new fragment (a*)
2052  *
2053  * @param ctx context
2054  */
2055 static void
2056 nfa_add_star_op (struct GNUNET_REGEX_Context *ctx)
2057 {
2058   struct GNUNET_REGEX_Automaton *a;
2059   struct GNUNET_REGEX_Automaton *new_nfa;
2060   struct GNUNET_REGEX_State *start;
2061   struct GNUNET_REGEX_State *end;
2062
2063   a = ctx->stack_tail;
2064
2065   if (NULL == a)
2066   {
2067     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2068                 "nfa_add_star_op failed, because there was no element on the stack");
2069     return;
2070   }
2071
2072   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2073
2074   start = nfa_state_create (ctx, 0);
2075   end = nfa_state_create (ctx, 1);
2076
2077   state_add_transition (ctx, start, NULL, a->start);
2078   state_add_transition (ctx, start, NULL, end);
2079   state_add_transition (ctx, a->end, NULL, a->start);
2080   state_add_transition (ctx, a->end, NULL, end);
2081
2082   a->end->accepting = 0;
2083   end->accepting = 1;
2084
2085   new_nfa = nfa_fragment_create (start, end);
2086   nfa_add_states (new_nfa, a->states_head, a->states_tail);
2087   automaton_fragment_clear (a);
2088
2089   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2090 }
2091
2092
2093 /**
2094  * Pops an NFA fragment (a) from the stack and adds a new fragment (a+)
2095  *
2096  * @param ctx context
2097  */
2098 static void
2099 nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
2100 {
2101   struct GNUNET_REGEX_Automaton *a;
2102
2103   a = ctx->stack_tail;
2104   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2105
2106   state_add_transition (ctx, a->end, NULL, a->start);
2107
2108   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a);
2109 }
2110
2111
2112 /**
2113  * Pops an NFA fragment (a) from the stack and adds a new fragment (a?)
2114  *
2115  * @param ctx context
2116  */
2117 static void
2118 nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
2119 {
2120   struct GNUNET_REGEX_Automaton *a;
2121   struct GNUNET_REGEX_Automaton *new_nfa;
2122   struct GNUNET_REGEX_State *start;
2123   struct GNUNET_REGEX_State *end;
2124
2125   a = ctx->stack_tail;
2126
2127   if (NULL == a)
2128   {
2129     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2130                 "nfa_add_question_op failed, because there was no element on the stack");
2131     return;
2132   }
2133
2134   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2135
2136   start = nfa_state_create (ctx, 0);
2137   end = nfa_state_create (ctx, 1);
2138
2139   state_add_transition (ctx, start, NULL, a->start);
2140   state_add_transition (ctx, start, NULL, end);
2141   state_add_transition (ctx, a->end, NULL, end);
2142
2143   a->end->accepting = 0;
2144
2145   new_nfa = nfa_fragment_create (start, end);
2146   nfa_add_states (new_nfa, a->states_head, a->states_tail);
2147   automaton_fragment_clear (a);
2148
2149   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2150 }
2151
2152
2153 /**
2154  * Pops two NFA fragments (a, b) from the stack and adds a new NFA fragment that
2155  * alternates between a and b (a|b)
2156  *
2157  * @param ctx context
2158  */
2159 static void
2160 nfa_add_alternation (struct GNUNET_REGEX_Context *ctx)
2161 {
2162   struct GNUNET_REGEX_Automaton *a;
2163   struct GNUNET_REGEX_Automaton *b;
2164   struct GNUNET_REGEX_Automaton *new_nfa;
2165   struct GNUNET_REGEX_State *start;
2166   struct GNUNET_REGEX_State *end;
2167
2168   b = ctx->stack_tail;
2169   GNUNET_assert (NULL != b);
2170   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2171   a = ctx->stack_tail;
2172   GNUNET_assert (NULL != a);
2173   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2174
2175   start = nfa_state_create (ctx, 0);
2176   end = nfa_state_create (ctx, 1);
2177   state_add_transition (ctx, start, NULL, a->start);
2178   state_add_transition (ctx, start, NULL, b->start);
2179
2180   state_add_transition (ctx, a->end, NULL, end);
2181   state_add_transition (ctx, b->end, NULL, end);
2182
2183   a->end->accepting = 0;
2184   b->end->accepting = 0;
2185   end->accepting = 1;
2186
2187   new_nfa = nfa_fragment_create (start, end);
2188   nfa_add_states (new_nfa, a->states_head, a->states_tail);
2189   nfa_add_states (new_nfa, b->states_head, b->states_tail);
2190   automaton_fragment_clear (a);
2191   automaton_fragment_clear (b);
2192
2193   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2194 }
2195
2196
2197 /**
2198  * Adds a new nfa fragment to the stack
2199  *
2200  * @param ctx context
2201  * @param label label for nfa transition
2202  */
2203 static void
2204 nfa_add_label (struct GNUNET_REGEX_Context *ctx, const char *label)
2205 {
2206   struct GNUNET_REGEX_Automaton *n;
2207   struct GNUNET_REGEX_State *start;
2208   struct GNUNET_REGEX_State *end;
2209
2210   GNUNET_assert (NULL != ctx);
2211
2212   start = nfa_state_create (ctx, 0);
2213   end = nfa_state_create (ctx, 1);
2214   state_add_transition (ctx, start, label, end);
2215   n = nfa_fragment_create (start, end);
2216   GNUNET_assert (NULL != n);
2217   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n);
2218 }
2219
2220
2221 /**
2222  * Initialize a new context
2223  *
2224  * @param ctx context
2225  */
2226 static void
2227 GNUNET_REGEX_context_init (struct GNUNET_REGEX_Context *ctx)
2228 {
2229   if (NULL == ctx)
2230   {
2231     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!");
2232     return;
2233   }
2234   ctx->state_id = 0;
2235   ctx->transition_id = 0;
2236   ctx->stack_head = NULL;
2237   ctx->stack_tail = NULL;
2238 }
2239
2240
2241 /**
2242  * Construct an NFA by parsing the regex string of length 'len'.
2243  *
2244  * @param regex regular expression string
2245  * @param len length of the string
2246  *
2247  * @return NFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2248  */
2249 struct GNUNET_REGEX_Automaton *
2250 GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
2251 {
2252   struct GNUNET_REGEX_Context ctx;
2253   struct GNUNET_REGEX_Automaton *nfa;
2254   const char *regexp;
2255   char curlabel[2];
2256   char *error_msg;
2257   unsigned int count;
2258   unsigned int altcount;
2259   unsigned int atomcount;
2260   unsigned int pcount;
2261   struct
2262   {
2263     int altcount;
2264     int atomcount;
2265   }     *p;
2266
2267   if (NULL == regex || 0 == strlen (regex) || 0 == len)
2268   {
2269     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2270                 "Could not parse regex. Empty regex string provided.\n");
2271
2272     return NULL;
2273   }
2274
2275   GNUNET_REGEX_context_init (&ctx);
2276
2277   regexp = regex;
2278   curlabel[1] = '\0';
2279   p = NULL;
2280   error_msg = NULL;
2281   altcount = 0;
2282   atomcount = 0;
2283   pcount = 0;
2284
2285   for (count = 0; count < len && *regexp; count++, regexp++)
2286   {
2287     switch (*regexp)
2288     {
2289     case '(':
2290       if (atomcount > 1)
2291       {
2292         --atomcount;
2293         nfa_add_concatenation (&ctx);
2294       }
2295       GNUNET_array_grow (p, pcount, pcount + 1);
2296       p[pcount - 1].altcount = altcount;
2297       p[pcount - 1].atomcount = atomcount;
2298       altcount = 0;
2299       atomcount = 0;
2300       break;
2301     case '|':
2302       if (0 == atomcount)
2303       {
2304         error_msg = "Cannot append '|' to nothing";
2305         goto error;
2306       }
2307       while (--atomcount > 0)
2308         nfa_add_concatenation (&ctx);
2309       altcount++;
2310       break;
2311     case ')':
2312       if (0 == pcount)
2313       {
2314         error_msg = "Missing opening '('";
2315         goto error;
2316       }
2317       if (0 == atomcount)
2318       {
2319         // Ignore this: "()"
2320         pcount--;
2321         altcount = p[pcount].altcount;
2322         atomcount = p[pcount].atomcount;
2323         break;
2324       }
2325       while (--atomcount > 0)
2326         nfa_add_concatenation (&ctx);
2327       for (; altcount > 0; altcount--)
2328         nfa_add_alternation (&ctx);
2329       pcount--;
2330       altcount = p[pcount].altcount;
2331       atomcount = p[pcount].atomcount;
2332       atomcount++;
2333       break;
2334     case '*':
2335       if (atomcount == 0)
2336       {
2337         error_msg = "Cannot append '*' to nothing";
2338         goto error;
2339       }
2340       nfa_add_star_op (&ctx);
2341       break;
2342     case '+':
2343       if (atomcount == 0)
2344       {
2345         error_msg = "Cannot append '+' to nothing";
2346         goto error;
2347       }
2348       nfa_add_plus_op (&ctx);
2349       break;
2350     case '?':
2351       if (atomcount == 0)
2352       {
2353         error_msg = "Cannot append '?' to nothing";
2354         goto error;
2355       }
2356       nfa_add_question_op (&ctx);
2357       break;
2358     default:
2359       if (atomcount > 1)
2360       {
2361         --atomcount;
2362         nfa_add_concatenation (&ctx);
2363       }
2364       curlabel[0] = *regexp;
2365       nfa_add_label (&ctx, curlabel);
2366       atomcount++;
2367       break;
2368     }
2369   }
2370   if (0 != pcount)
2371   {
2372     error_msg = "Unbalanced parenthesis";
2373     goto error;
2374   }
2375   while (--atomcount > 0)
2376     nfa_add_concatenation (&ctx);
2377   for (; altcount > 0; altcount--)
2378     nfa_add_alternation (&ctx);
2379
2380   GNUNET_free_non_null (p);
2381
2382   nfa = ctx.stack_tail;
2383   GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2384
2385   if (NULL != ctx.stack_head)
2386   {
2387     error_msg = "Creating the NFA failed. NFA stack was not empty!";
2388     goto error;
2389   }
2390
2391   /* Remember the regex that was used to generate this NFA */
2392   nfa->regex = GNUNET_strdup (regex);
2393
2394   /* create depth-first numbering of the states for pretty printing */
2395   GNUNET_REGEX_automaton_traverse (nfa, NULL, NULL, NULL, &number_states, NULL);
2396
2397   /* No multistriding added so far */
2398   nfa->is_multistrided = GNUNET_NO;
2399
2400   return nfa;
2401
2402 error:
2403   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: %s\n", regex);
2404   if (NULL != error_msg)
2405     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
2406
2407   GNUNET_free_non_null (p);
2408
2409   while (NULL != (nfa = ctx.stack_head))
2410   {
2411     GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2412     GNUNET_REGEX_automaton_destroy (nfa);
2413   }
2414
2415   return NULL;
2416 }
2417
2418
2419 /**
2420  * Create DFA states based on given 'nfa' and starting with 'dfa_state'.
2421  *
2422  * @param ctx context.
2423  * @param nfa NFA automaton.
2424  * @param dfa DFA automaton.
2425  * @param dfa_state current dfa state, pass epsilon closure of first nfa state
2426  *                  for starting.
2427  */
2428 static void
2429 construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
2430                       struct GNUNET_REGEX_Automaton *nfa,
2431                       struct GNUNET_REGEX_Automaton *dfa,
2432                       struct GNUNET_REGEX_State *dfa_state)
2433 {
2434   struct GNUNET_REGEX_Transition *ctran;
2435   struct GNUNET_REGEX_State *state_iter;
2436   struct GNUNET_REGEX_State *new_dfa_state;
2437   struct GNUNET_REGEX_State *state_contains;
2438   struct GNUNET_REGEX_StateSet *tmp;
2439   struct GNUNET_REGEX_StateSet *nfa_set;
2440
2441   for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next)
2442   {
2443     if (NULL == ctran->label || NULL != ctran->to_state)
2444       continue;
2445
2446     tmp = nfa_closure_set_create (nfa, dfa_state->nfa_set, ctran->label);
2447     nfa_set = nfa_closure_set_create (nfa, tmp, 0);
2448     state_set_clear (tmp);
2449     new_dfa_state = dfa_state_create (ctx, nfa_set);
2450     state_contains = NULL;
2451     for (state_iter = dfa->states_head; NULL != state_iter;
2452          state_iter = state_iter->next)
2453     {
2454       if (0 == state_set_compare (state_iter->nfa_set, new_dfa_state->nfa_set))
2455         state_contains = state_iter;
2456     }
2457
2458     if (NULL == state_contains)
2459     {
2460       automaton_add_state (dfa, new_dfa_state);
2461       ctran->to_state = new_dfa_state;
2462       construct_dfa_states (ctx, nfa, dfa, new_dfa_state);
2463     }
2464     else
2465     {
2466       ctran->to_state = state_contains;
2467       automaton_destroy_state (new_dfa_state);
2468     }
2469   }
2470 }
2471
2472
2473 /**
2474  * Construct DFA for the given 'regex' of length 'len'
2475  *
2476  * @param regex regular expression string
2477  * @param len length of the regular expression
2478  *
2479  * @return DFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2480  */
2481 struct GNUNET_REGEX_Automaton *
2482 GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
2483 {
2484   struct GNUNET_REGEX_Context ctx;
2485   struct GNUNET_REGEX_Automaton *dfa;
2486   struct GNUNET_REGEX_Automaton *nfa;
2487   struct GNUNET_REGEX_StateSet *nfa_start_eps_cls;
2488
2489   GNUNET_REGEX_context_init (&ctx);
2490
2491   // Create NFA
2492   nfa = GNUNET_REGEX_construct_nfa (regex, len);
2493
2494   if (NULL == nfa)
2495   {
2496     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2497                 "Could not create DFA, because NFA creation failed\n");
2498     return NULL;
2499   }
2500
2501   dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
2502   dfa->type = DFA;
2503   dfa->state_count = 0;
2504   dfa->states_head = NULL;
2505   dfa->states_tail = NULL;
2506   dfa->regex = GNUNET_strdup (regex);
2507   dfa->is_multistrided = GNUNET_NO;
2508
2509   // Create DFA start state from epsilon closure
2510   nfa_start_eps_cls = nfa_closure_create (nfa, nfa->start, 0);
2511   dfa->start = dfa_state_create (&ctx, nfa_start_eps_cls);
2512   automaton_add_state (dfa, dfa->start);
2513
2514   construct_dfa_states (&ctx, nfa, dfa, dfa->start);
2515
2516   GNUNET_REGEX_automaton_destroy (nfa);
2517
2518   // Minimize DFA
2519   dfa_minimize (&ctx, dfa);
2520
2521   // Compress DFA paths
2522   dfa_compress_paths (&ctx, dfa);
2523
2524   // Create proofs for all states
2525   automaton_create_proofs (dfa);
2526
2527   // Add strides to DFA
2528   //GNUNET_REGEX_dfa_add_multi_strides (&ctx, dfa, 2);
2529
2530   return dfa;
2531 }
2532
2533
2534 /**
2535  * Free the memory allocated by constructing the GNUNET_REGEX_Automaton data
2536  * structure.
2537  *
2538  * @param a automaton to be destroyed
2539  */
2540 void
2541 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
2542 {
2543   struct GNUNET_REGEX_State *s;
2544   struct GNUNET_REGEX_State *next_state;
2545
2546   if (NULL == a)
2547     return;
2548
2549   GNUNET_free_non_null (a->regex);
2550   GNUNET_free_non_null (a->canonical_regex);
2551
2552   for (s = a->states_head; NULL != s; s = next_state)
2553   {
2554     next_state = s->next;
2555     GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
2556     automaton_destroy_state (s);
2557   }
2558
2559   GNUNET_free (a);
2560 }
2561
2562
2563 /**
2564  * Evaluates the given string using the given DFA automaton
2565  *
2566  * @param a automaton, type must be DFA
2567  * @param string string that should be evaluated
2568  *
2569  * @return 0 if string matches, non 0 otherwise
2570  */
2571 static int
2572 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2573 {
2574   const char *strp;
2575   struct GNUNET_REGEX_State *s;
2576   unsigned int step_len;
2577
2578   if (DFA != a->type)
2579   {
2580     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2581                 "Tried to evaluate DFA, but NFA automaton given");
2582     return -1;
2583   }
2584
2585   s = a->start;
2586
2587   // If the string is empty but the starting state is accepting, we accept.
2588   if ((NULL == string || 0 == strlen (string)) && s->accepting)
2589     return 0;
2590
2591   for (strp = string; NULL != strp && *strp; strp += step_len)
2592   {
2593     step_len = dfa_move (&s, strp);
2594
2595     if (NULL == s)
2596       break;
2597   }
2598
2599   if (NULL != s && s->accepting)
2600     return 0;
2601
2602   return 1;
2603 }
2604
2605
2606 /**
2607  * Evaluates the given string using the given NFA automaton
2608  *
2609  * @param a automaton, type must be NFA
2610  * @param string string that should be evaluated
2611  *
2612  * @return 0 if string matches, non 0 otherwise
2613  */
2614 static int
2615 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2616 {
2617   const char *strp;
2618   char str[2];
2619   struct GNUNET_REGEX_State *s;
2620   struct GNUNET_REGEX_StateSet *sset;
2621   struct GNUNET_REGEX_StateSet *new_sset;
2622   unsigned int i;
2623   int result;
2624
2625   if (NFA != a->type)
2626   {
2627     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2628                 "Tried to evaluate NFA, but DFA automaton given");
2629     return -1;
2630   }
2631
2632   // If the string is empty but the starting state is accepting, we accept.
2633   if ((NULL == string || 0 == strlen (string)) && a->start->accepting)
2634     return 0;
2635
2636   result = 1;
2637   sset = nfa_closure_create (a, a->start, 0);
2638
2639   str[1] = '\0';
2640   for (strp = string; NULL != strp && *strp; strp++)
2641   {
2642     str[0] = *strp;
2643     new_sset = nfa_closure_set_create (a, sset, str);
2644     state_set_clear (sset);
2645     sset = nfa_closure_set_create (a, new_sset, 0);
2646     state_set_clear (new_sset);
2647   }
2648
2649   for (i = 0; i < sset->len; i++)
2650   {
2651     s = sset->states[i];
2652     if (NULL != s && s->accepting)
2653     {
2654       result = 0;
2655       break;
2656     }
2657   }
2658
2659   state_set_clear (sset);
2660   return result;
2661 }
2662
2663
2664 /**
2665  * Evaluates the given 'string' against the given compiled regex
2666  *
2667  * @param a automaton
2668  * @param string string to check
2669  *
2670  * @return 0 if string matches, non 0 otherwise
2671  */
2672 int
2673 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
2674 {
2675   int result;
2676
2677   switch (a->type)
2678   {
2679   case DFA:
2680     result = evaluate_dfa (a, string);
2681     break;
2682   case NFA:
2683     result = evaluate_nfa (a, string);
2684     break;
2685   default:
2686     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2687                 "Evaluating regex failed, automaton has no type!\n");
2688     result = GNUNET_SYSERR;
2689     break;
2690   }
2691
2692   return result;
2693 }
2694
2695
2696 /**
2697  * Get the canonical regex of the given automaton.
2698  * When constructing the automaton a proof is computed for each state,
2699  * consisting of the regular expression leading to this state. A complete
2700  * regex for the automaton can be computed by combining these proofs.
2701  * As of now this function is only useful for testing.
2702  *
2703  * @param a automaton for which the canonical regex should be returned.
2704  *
2705  * @return
2706  */
2707 const char *
2708 GNUNET_REGEX_get_canonical_regex (struct GNUNET_REGEX_Automaton *a)
2709 {
2710   if (NULL == a)
2711     return NULL;
2712
2713   return a->canonical_regex;
2714 }
2715
2716
2717 /**
2718  * Get the number of transitions that are contained in the given automaton.
2719  *
2720  * @param a automaton for which the number of transitions should be returned.
2721  *
2722  * @return number of transitions in the given automaton.
2723  */
2724 unsigned int
2725 GNUNET_REGEX_get_transition_count (struct GNUNET_REGEX_Automaton *a)
2726 {
2727   unsigned int t_count;
2728   struct GNUNET_REGEX_State *s;
2729
2730   if (NULL == a)
2731     return 0;
2732
2733   for (t_count = 0, s = a->states_head; NULL != s; s = s->next)
2734   {
2735     t_count += s->transition_count;
2736   }
2737
2738   return t_count;
2739 }
2740
2741
2742 /**
2743  * Get the first key for the given 'input_string'. This hashes the first x bits
2744  * of the 'input_string'.
2745  *
2746  * @param input_string string.
2747  * @param string_len length of the 'input_string'.
2748  * @param key pointer to where to write the hash code.
2749  *
2750  * @return number of bits of 'input_string' that have been consumed
2751  *         to construct the key
2752  */
2753 size_t
2754 GNUNET_REGEX_get_first_key (const char *input_string, size_t string_len,
2755                             struct GNUNET_HashCode * key)
2756 {
2757   unsigned int size;
2758
2759   size = string_len < INITIAL_BITS ? string_len : INITIAL_BITS;
2760
2761   if (NULL == input_string)
2762   {
2763     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
2764     return 0;
2765   }
2766
2767   GNUNET_CRYPTO_hash (input_string, size, key);
2768
2769   return size;
2770 }
2771
2772
2773 /**
2774  * Check if the given 'proof' matches the given 'key'.
2775  *
2776  * @param proof partial regex of a state.
2777  * @param key hash of a state.
2778  *
2779  * @return GNUNET_OK if the proof is valid for the given key.
2780  */
2781 int
2782 GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
2783 {
2784   struct GNUNET_HashCode key_check;
2785
2786   if (NULL == proof || NULL == key)
2787   {
2788     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Proof check failed, was NULL.\n");
2789     return GNUNET_NO;
2790   }
2791
2792   GNUNET_CRYPTO_hash (proof, strlen (proof), &key_check);
2793   return (0 ==
2794           GNUNET_CRYPTO_hash_cmp (key, &key_check)) ? GNUNET_OK : GNUNET_NO;
2795 }
2796
2797
2798 /**
2799  * Recursive helper function for iterate_initial_edges. Will call iterator
2800  * function for each initial state.
2801  *
2802  * @param min_len minimum length of the path in the graph.
2803  * @param max_len maximum length of the path in the graph.
2804  * @param consumed_string string consumed by traversing the graph till this state.
2805  * @param state current state of the automaton.
2806  * @param iterator iterator function called for each edge.
2807  * @param iterator_cls closure for the iterator function.
2808  */
2809 static void
2810 iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
2811                       char *consumed_string, struct GNUNET_REGEX_State *state,
2812                       GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
2813 {
2814   unsigned int i;
2815   char *temp;
2816   struct GNUNET_REGEX_Transition *t;
2817   unsigned int num_edges = state->transition_count;
2818   struct GNUNET_REGEX_Edge edges[num_edges];
2819   struct GNUNET_REGEX_Edge edge[1];
2820   struct GNUNET_HashCode hash;
2821   struct GNUNET_HashCode hash_new;
2822
2823   unsigned int cur_len;
2824
2825   if (NULL != consumed_string)
2826     cur_len = strlen (consumed_string);
2827   else
2828     cur_len = 0;
2829
2830   if (cur_len >= min_len && cur_len > 0 && NULL != consumed_string)
2831   {
2832     if (cur_len <= max_len)
2833     {
2834       for (i = 0, t = state->transitions_head; NULL != t && i < num_edges;
2835            t = t->next, i++)
2836       {
2837         edges[i].label = t->label;
2838         edges[i].destination = t->to_state->hash;
2839       }
2840
2841       GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash);
2842       iterator (iterator_cls, &hash, consumed_string, state->accepting,
2843                 num_edges, edges);
2844
2845       // Special case for regex consisting of just a string that is shorter than
2846       // max_len
2847       if (GNUNET_YES == state->accepting && cur_len > 1 &&
2848           state->transition_count < 1 && cur_len < max_len)
2849       {
2850         edge[0].label = &consumed_string[cur_len - 1];
2851         edge[0].destination = state->hash;
2852         temp = GNUNET_strdup (consumed_string);
2853         temp[cur_len - 1] = '\0';
2854         GNUNET_CRYPTO_hash (temp, cur_len - 1, &hash_new);
2855         iterator (iterator_cls, &hash_new, temp, GNUNET_NO, 1, edge);
2856         GNUNET_free (temp);
2857       }
2858     }
2859     else if (max_len < cur_len)
2860     {
2861       edge[0].label = &consumed_string[max_len];
2862       edge[0].destination = state->hash;
2863       temp = GNUNET_strdup (consumed_string);
2864       temp[max_len] = '\0';
2865       GNUNET_CRYPTO_hash (temp, max_len, &hash);
2866       iterator (iterator_cls, &hash, temp, GNUNET_NO, 1, edge);
2867       GNUNET_free (temp);
2868     }
2869   }
2870
2871   if (cur_len < max_len)
2872   {
2873     for (t = state->transitions_head; NULL != t; t = t->next)
2874     {
2875       if (NULL != consumed_string)
2876         GNUNET_asprintf (&temp, "%s%s", consumed_string, t->label);
2877       else
2878         GNUNET_asprintf (&temp, "%s", t->label);
2879
2880       iterate_initial_edge (min_len, max_len, temp, t->to_state, iterator,
2881                             iterator_cls);
2882       GNUNET_free (temp);
2883     }
2884   }
2885 }
2886
2887
2888 /**
2889  * Iterate over all edges helper function starting from state 's', calling
2890  * iterator function for each edge if the automaton.
2891  *
2892  * @param s state.
2893  * @param iterator iterator function called for each edge.
2894  * @param iterator_cls closure.
2895  */
2896 static void
2897 iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
2898               void *iterator_cls)
2899 {
2900   struct GNUNET_REGEX_Transition *t;
2901   struct GNUNET_REGEX_Edge edges[s->transition_count];
2902   unsigned int num_edges;
2903
2904   if (GNUNET_YES != s->marked)
2905   {
2906     s->marked = GNUNET_YES;
2907
2908     num_edges = state_get_edges (s, edges);
2909
2910     if ((NULL != s->proof && 0 < strlen (s->proof)) || s->accepting)
2911       iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges,
2912                 edges);
2913
2914     for (t = s->transitions_head; NULL != t; t = t->next)
2915       iterate_edge (t->to_state, iterator, iterator_cls);
2916   }
2917 }
2918
2919
2920 /**
2921  * Iterate over all edges starting from start state of automaton 'a'. Calling
2922  * iterator for each edge.
2923  *
2924  * @param a automaton.
2925  * @param iterator iterator called for each edge.
2926  * @param iterator_cls closure.
2927  */
2928 void
2929 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2930                                 GNUNET_REGEX_KeyIterator iterator,
2931                                 void *iterator_cls)
2932 {
2933   struct GNUNET_REGEX_State *s;
2934
2935   for (s = a->states_head; NULL != s; s = s->next)
2936     s->marked = GNUNET_NO;
2937
2938   iterate_initial_edge (0, INITIAL_BITS, NULL, a->start, iterator,
2939                         iterator_cls);
2940   iterate_edge (a->start, iterator, iterator_cls);
2941 }
2942
2943
2944 /**
2945  * Create a string with binary IP notation for the given 'addr' in 'str'.
2946  *
2947  * @param af address family of the given 'addr'.
2948  * @param addr address that should be converted to a string.
2949  *             struct in_addr * for IPv4 and struct in6_addr * for IPv6.
2950  * @param str string that will contain binary notation of 'addr'. Expected
2951  *            to be at least 33 bytes long for IPv4 and 129 bytes long for IPv6.
2952  */
2953 static void
2954 iptobinstr (const int af, const void *addr, char *str)
2955 {
2956   int i;
2957
2958   switch (af)
2959   {
2960   case AF_INET:
2961   {
2962     uint32_t b = htonl (((struct in_addr *) addr)->s_addr);
2963
2964     str[32] = '\0';
2965     str += 31;
2966     for (i = 31; i >= 0; i--)
2967     {
2968       *str = (b & 1) + '0';
2969       str--;
2970       b >>= 1;
2971     }
2972     break;
2973   }
2974   case AF_INET6:
2975   {
2976     struct in6_addr b = *(const struct in6_addr *) addr;
2977
2978     str[128] = '\0';
2979     str += 127;
2980     for (i = 127; i >= 0; i--)
2981     {
2982       *str = (b.s6_addr[i / 8] & 1) + '0';
2983       str--;
2984       b.s6_addr[i / 8] >>= 1;
2985     }
2986     break;
2987   }
2988   }
2989 }
2990
2991
2992 /**
2993  * Get the ipv4 network prefix from the given 'netmask'.
2994  *
2995  * @param netmask netmask for which to get the prefix len.
2996  *
2997  * @return length of ipv4 prefix for 'netmask'.
2998  */
2999 static unsigned int
3000 ipv4netmasktoprefixlen (const char *netmask)
3001 {
3002   struct in_addr a;
3003   unsigned int len;
3004   uint32_t t;
3005
3006   if (1 != inet_pton (AF_INET, netmask, &a))
3007     return 0;
3008   len = 32;
3009   for (t = htonl (~a.s_addr); 0 != t; t >>= 1)
3010     len--;
3011   return len;
3012 }
3013
3014
3015 /**
3016  * Create a regex in 'rxstr' from the given 'ip' and 'netmask'.
3017  *
3018  * @param ip IPv4 representation.
3019  * @param netmask netmask for the ip.
3020  * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV4_REGEXLEN
3021  *              bytes long.
3022  */
3023 void
3024 GNUNET_REGEX_ipv4toregex (const struct in_addr *ip, const char *netmask,
3025                           char *rxstr)
3026 {
3027   unsigned int pfxlen;
3028
3029   pfxlen = ipv4netmasktoprefixlen (netmask);
3030   iptobinstr (AF_INET, ip, rxstr);
3031   rxstr[pfxlen] = '\0';
3032   if (pfxlen < 32)
3033     strcat (rxstr, "(0|1)+");
3034 }
3035
3036
3037 /**
3038  * Create a regex in 'rxstr' from the given 'ipv6' and 'prefixlen'.
3039  *
3040  * @param ipv6 IPv6 representation.
3041  * @param prefixlen length of the ipv6 prefix.
3042  * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV6_REGEXLEN
3043  *              bytes long.
3044  */
3045 void
3046 GNUNET_REGEX_ipv6toregex (const struct in6_addr *ipv6, unsigned int prefixlen,
3047                           char *rxstr)
3048 {
3049   iptobinstr (AF_INET6, ipv6, rxstr);
3050   rxstr[prefixlen] = '\0';
3051   if (prefixlen < 128)
3052     strcat (rxstr, "(0|1)+");
3053 }