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