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