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