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