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