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