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