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