51ceab26a2112f41211ddb25082a11c2e06e080a
[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
35  * as well as a 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
91    * used for constructing an NFA, where each NFA
92    * itself consists of one or more NFAs linked
93    * together.
94    */
95   struct GNUNET_REGEX_State *start;
96
97   /**
98    * End state of the automaton.
99    */
100   struct GNUNET_REGEX_State *end;
101
102   /**
103    * Number of states in the automaton.
104    */
105   unsigned int state_count;
106
107   /**
108    * DLL of states.
109    */
110   struct GNUNET_REGEX_State *states_head;
111
112   /**
113    * DLL of states
114    */
115   struct GNUNET_REGEX_State *states_tail;
116
117   /**
118    * Type of the automaton.
119    */
120   enum GNUNET_REGEX_automaton_type type;
121 };
122
123 /**
124  * A state. Can be used in DFA and NFA automatons.
125  */
126 struct GNUNET_REGEX_State
127 {
128   /**
129    * This is a linked list.
130    */
131   struct GNUNET_REGEX_State *prev;
132
133   /**
134    * This is a linked list.
135    */
136   struct GNUNET_REGEX_State *next;
137
138   /**
139    * Unique state id.
140    */
141   unsigned int id;
142
143   /**
144    * If this is an accepting state or not.
145    */
146   int accepting;
147
148   /**
149    * Marking of the state. This is used for marking all visited
150    * states when traversing all states of an automaton and for
151    * cases where the state id cannot be used (dfa minimization).
152    */
153   int marked;
154
155   /**
156    * Marking the state as contained. This is used for checking,
157    * if the state is contained in a set in constant time
158    */
159   int contained;
160
161   /**
162    * Marking the state as part of an SCC (Strongly Connected Component).
163    * All states with the same scc_id are part of the same SCC.
164    */
165   unsigned int scc_id;
166
167   /**
168    * Used for SCC detection.
169    */
170   int index;
171
172   /**
173    * Used for SCC detection.
174    */
175   int lowlink;
176
177   /**
178    * Human readable name of the automaton. Used for debugging
179    * and graph creation.
180    */
181   char *name;
182
183   GNUNET_HashCode hash;
184
185   /**
186    * Number of transitions from this state to other states.
187    */
188   unsigned int transition_count;
189
190   /**
191    * DLL of transitions.
192    */
193   struct Transition *transitions_head;
194
195   /**
196    * DLL of transitions.
197    */
198   struct Transition *transitions_tail;
199
200   /**
201    * Set of states on which this state is based on. Used when
202    * creating a DFA out of several NFA states.
203    */
204   struct GNUNET_REGEX_StateSet *nfa_set;
205 };
206
207 /**
208  * Transition between two states. Each state can have 0-n transitions.
209  * If label is 0, this is considered to be an epsilon transition.
210  */
211 struct Transition
212 {
213   /**
214    * This is a linked list.
215    */
216   struct Transition *prev;
217
218   /**
219    * This is a linked list.
220    */
221   struct Transition *next;
222
223   /**
224    * Unique id of this transition.
225    */
226   unsigned int id;
227
228   /**
229    * label for this transition. This is basically the edge label for
230    * the graph.
231    */
232   char label;
233
234   /**
235    * State to which this transition leads.
236    */
237   struct GNUNET_REGEX_State *to_state;
238
239   /**
240    * State from which this transition origins.
241    */
242   struct GNUNET_REGEX_State *from_state;
243 };
244
245 /**
246  * Set of states.
247  */
248 struct GNUNET_REGEX_StateSet
249 {
250   /**
251    * Array of states.
252    */
253   struct GNUNET_REGEX_State **states;
254
255   /**
256    * Length of the 'states' array.
257    */
258   unsigned int len;
259 };
260
261 static void
262 debug_print_state (struct GNUNET_REGEX_State *s)
263 {
264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
265               "State %i: %s marked: %i accepting: %i scc_id: %i\n", s->id,
266               s->name, s->marked, s->accepting, s->scc_id);
267 }
268
269 static void
270 debug_print_states (struct GNUNET_REGEX_StateSet *sset)
271 {
272   struct GNUNET_REGEX_State *s;
273   int i;
274
275   for (i = 0; i < sset->len; i++)
276   {
277     s = sset->states[i];
278     debug_print_state (s);
279   }
280 }
281
282 static void
283 debug_print_transitions (struct GNUNET_REGEX_State *s)
284 {
285   struct Transition *t;
286   char *state;
287   char label;
288
289   for (t = s->transitions_head; NULL != t; t = t->next)
290   {
291     if (0 == t->label)
292       label = '0';
293     else
294       label = t->label;
295
296     if (NULL == t->to_state)
297       state = "NULL";
298     else
299       state = t->to_state->name;
300
301     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transition %i: On %c to %s\n", t->id,
302                 label, state);
303   }
304 }
305
306 /**
307  * Recursive function doing DFS with 'v' as a start, detecting all SCCs
308  * inside the subgraph reachable from 'v'. Used with scc_tarjan function
309  * to detect all SCCs inside an automaton.
310  *
311  * @param ctx context
312  * @param v start vertex
313  * @param index current index
314  * @param stack stack for saving all SCCs
315  * @param stack_size current size of the stack
316  */
317 static void
318 scc_tarjan_strongconnect (struct GNUNET_REGEX_Context *ctx,
319                           struct GNUNET_REGEX_State *v, int *index,
320                           struct GNUNET_REGEX_State **stack,
321                           unsigned int *stack_size)
322 {
323   struct GNUNET_REGEX_State *w;
324   struct Transition *t;
325
326   v->index = *index;
327   v->lowlink = *index;
328   (*index)++;
329   stack[(*stack_size)++] = v;
330   v->contained = 1;
331
332   for (t = v->transitions_head; NULL != t; t = t->next)
333   {
334     w = t->to_state;
335     if (NULL != w && w->index < 0)
336     {
337       scc_tarjan_strongconnect (ctx, w, index, stack, stack_size);
338       v->lowlink = (v->lowlink > w->lowlink) ? w->lowlink : v->lowlink;
339     }
340     else if (0 != w->contained)
341       v->lowlink = (v->lowlink > w->index) ? w->index : v->lowlink;
342   }
343
344   if (v->lowlink == v->index)
345   {
346     w = stack[--(*stack_size)];
347     w->contained = 0;
348
349     if (v != w)
350     {
351       ctx->scc_id++;
352       while (v != w)
353       {
354         w->scc_id = ctx->scc_id;
355         w = stack[--(*stack_size)];
356         w->contained = 0;
357       }
358       w->scc_id = ctx->scc_id;
359     }
360   }
361 }
362
363 /**
364  * Detect all SCCs (Strongly Connected Components) inside the given automaton.
365  * SCCs will be marked using the scc_id on each state.
366  *
367  * @param ctx context
368  * @param a automaton
369  */
370 static void
371 scc_tarjan (struct GNUNET_REGEX_Context *ctx, struct GNUNET_REGEX_Automaton *a)
372 {
373   unsigned int i;
374   int index;
375   struct GNUNET_REGEX_State *v;
376   struct GNUNET_REGEX_State *stack[a->state_count];
377   unsigned int stack_size;
378
379   for (v = a->states_head; NULL != v; v = v->next)
380   {
381     v->contained = 0;
382     v->index = -1;
383     v->lowlink = -1;
384   }
385
386   stack_size = 0;
387   index = 0;
388
389   for (i = 0, v = a->states_head; NULL != v; v = v->next)
390   {
391     if (v->index < 0)
392       scc_tarjan_strongconnect (ctx, v, &index, stack, &stack_size);
393   }
394 }
395
396 /**
397  * Compare two states. Used for sorting.
398  *
399  * @param a first state
400  * @param b second state
401  *
402  * @return an integer less than, equal to, or greater than zero
403  *         if the first argument is considered to be respectively
404  *         less than, equal to, or greater than the second.
405  */
406 static int
407 state_compare (const void *a, const void *b)
408 {
409   struct GNUNET_REGEX_State **s1;
410   struct GNUNET_REGEX_State **s2;
411
412   s1 = (struct GNUNET_REGEX_State **) a;
413   s2 = (struct GNUNET_REGEX_State **) b;
414
415   return (*s1)->id - (*s2)->id;
416 }
417
418 /**
419  * Compare to state sets by comparing the id's of the states that are
420  * contained in each set. Both sets are expected to be sorted by id!
421  *
422  * @param sset1 first state set
423  * @param sset2 second state set
424  *
425  * @return an integer less than, equal to, or greater than zero
426  *         if the first argument is considered to be respectively
427  *         less than, equal to, or greater than the second.
428  */
429 static int
430 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
431                    struct GNUNET_REGEX_StateSet *sset2)
432 {
433   int result;
434   int i;
435
436   if (NULL == sset1 || NULL == sset2)
437     return 1;
438
439   result = sset1->len - sset2->len;
440
441   for (i = 0; i < sset1->len; i++)
442   {
443     if (0 != result)
444       break;
445
446     result = state_compare (&sset1->states[i], &sset2->states[i]);
447   }
448   return result;
449 }
450
451 /**
452  * Clears the given StateSet 'set'
453  *
454  * @param set set to be cleared
455  */
456 static void
457 state_set_clear (struct GNUNET_REGEX_StateSet *set)
458 {
459   if (NULL != set)
460   {
461     if (NULL != set->states)
462       GNUNET_free (set->states);
463     GNUNET_free (set);
464   }
465 }
466
467 /**
468  * Adds a transition from one state to another on 'label'
469  *
470  * @param ctx context
471  * @param from_state starting state for the transition
472  * @param label transition label
473  * @param to_state state to where the transition should point to
474  */
475 static void
476 state_add_transition (struct GNUNET_REGEX_Context *ctx,
477                       struct GNUNET_REGEX_State *from_state, const char label,
478                       struct GNUNET_REGEX_State *to_state)
479 {
480   struct Transition *t;
481
482   if (NULL == from_state)
483   {
484     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
485     return;
486   }
487
488   t = GNUNET_malloc (sizeof (struct Transition));
489
490   t->id = ctx->transition_id++;
491   t->label = label;
492   t->to_state = to_state;
493   t->from_state = from_state;
494
495   GNUNET_CONTAINER_DLL_insert (from_state->transitions_head,
496                                from_state->transitions_tail, t);
497 }
498
499 /**
500  * Clears an automaton fragment. Does not destroy the states inside
501  * the automaton.
502  *
503  * @param a automaton to be cleared
504  */
505 static void
506 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
507 {
508   if (NULL == a)
509     return;
510
511   a->start = NULL;
512   a->end = NULL;
513   a->states_head = NULL;
514   a->states_tail = NULL;
515   a->state_count = 0;
516   GNUNET_free (a);
517 }
518
519 /**
520  * Frees the memory used by State 's'
521  *
522  * @param s state that should be destroyed
523  */
524 static void
525 automaton_destroy_state (struct GNUNET_REGEX_State *s)
526 {
527   struct Transition *t;
528   struct Transition *next_t;
529
530   if (NULL == s)
531     return;
532
533   if (NULL != s->name)
534     GNUNET_free (s->name);
535
536   for (t = s->transitions_head; NULL != t;)
537   {
538     next_t = t->next;
539     GNUNET_CONTAINER_DLL_remove (s->transitions_head, s->transitions_tail, t);
540     GNUNET_free (t);
541     t = next_t;
542   }
543
544   state_set_clear (s->nfa_set);
545
546   GNUNET_free (s);
547 }
548
549 /**
550  * Remove a state from the given automaton 'a'. Always use this function
551  * when altering the states of an automaton. Will also remove all transitions
552  * leading to this state, before destroying it.
553  *
554  * @param a automaton
555  * @param s state to remove
556  */
557 static void
558 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
559                         struct GNUNET_REGEX_State *s)
560 {
561   struct GNUNET_REGEX_State *ss;
562   struct GNUNET_REGEX_State *s_check;
563   struct Transition *t_check;
564
565   if (NULL == a || NULL == s)
566     return;
567
568   // remove state
569   ss = s;
570   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
571   a->state_count--;
572
573   // remove all transitions leading to this state
574   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
575   {
576     for (t_check = s_check->transitions_head; NULL != t_check;
577          t_check = t_check->next)
578     {
579       if (t_check->to_state == ss)
580       {
581         GNUNET_CONTAINER_DLL_remove (s_check->transitions_head,
582                                      s_check->transitions_tail, t_check);
583         s_check->transition_count--;
584       }
585     }
586   }
587
588   automaton_destroy_state (ss);
589 }
590
591 /**
592  * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy 's2'.
593  *
594  * @param ctx context
595  * @param a automaton
596  * @param s1 first state
597  * @param s2 second state, will be destroyed
598  */
599 static void
600 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
601                         struct GNUNET_REGEX_Automaton *a,
602                         struct GNUNET_REGEX_State *s1,
603                         struct GNUNET_REGEX_State *s2)
604 {
605   struct GNUNET_REGEX_State *s_check;
606   struct Transition *t_check;
607   struct Transition *t;
608   char *new_name;
609
610   GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
611
612   // 1. Make all transitions pointing to s2 point to s1
613   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
614   {
615     for (t_check = s_check->transitions_head; NULL != t_check;
616          t_check = t_check->next)
617     {
618       if (s_check != s1 && s2 == t_check->to_state)
619         t_check->to_state = s1;
620     }
621   }
622
623   // 2. Add all transitions from s2 to sX to s1
624   for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
625   {
626     for (t = s1->transitions_head; NULL != t; t = t->next)
627     {
628       if (t_check->label != t->label && NULL != t_check->to_state &&
629           t_check->to_state != t->to_state && t_check->to_state != s2)
630       {
631         state_add_transition (ctx, s1, t_check->label, t_check->to_state);
632       }
633     }
634   }
635
636   // 3. Rename s1 to {s1,s2}
637   new_name = GNUNET_malloc (strlen (s1->name) + strlen (s2->name) + 1);
638   strncat (new_name, s1->name, strlen (s1->name));
639   strncat (new_name, s2->name, strlen (s2->name));
640   if (NULL != s1->name)
641     GNUNET_free (s1->name);
642   s1->name = new_name;
643
644   // remove state
645   s_check = s2;
646   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s_check);
647   a->state_count--;
648   automaton_destroy_state (s_check);
649 }
650
651 /**
652  * Add a state to the automaton 'a', always use this function to
653  * alter the states DLL of the automaton.
654  *
655  * @param a automaton to add the state to
656  * @param s state that should be added
657  */
658 static void
659 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
660                      struct GNUNET_REGEX_State *s)
661 {
662   GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
663   a->state_count++;
664 }
665
666 typedef void (*GNUNET_REGEX_traverse_action) (void *cls,
667                                               struct GNUNET_REGEX_State * s);
668
669 /**
670  * Traverses all states that are reachable from state 's'. Expects
671  * the states to be unmarked (s->marked == GNUNET_NO). Performs
672  * 'action' on each visited state.
673  *
674  * @param cls closure.
675  * @param s start state.
676  * @param action action to be performed on each state.
677  */
678 static void
679 automaton_state_traverse (void *cls, struct GNUNET_REGEX_State *s,
680                           GNUNET_REGEX_traverse_action action)
681 {
682   struct Transition *t;
683
684   if (GNUNET_NO == s->marked)
685   {
686     s->marked = GNUNET_YES;
687
688     if (NULL != action)
689       action (cls, s);
690
691     for (t = s->transitions_head; NULL != t; t = t->next)
692       automaton_state_traverse (cls, t->to_state, action);
693   }
694 }
695
696 /**
697  * Traverses the given automaton from it's start state, visiting all
698  * reachable states and calling 'action' on each one of them.
699  *
700  * @param cls closure.
701  * @param a automaton.
702  * @param action action to be performed on each state.
703  */
704 static void
705 automaton_traverse (void *cls, struct GNUNET_REGEX_Automaton *a,
706                     GNUNET_REGEX_traverse_action action)
707 {
708   struct GNUNET_REGEX_State *s;
709
710   for (s = a->start; NULL != s; s = s->next)
711     s->marked = GNUNET_NO;
712
713   automaton_state_traverse (cls, a->start, action);
714 }
715
716 /**
717  * Creates a new DFA state based on a set of NFA states. Needs to be freed
718  * using automaton_destroy_state.
719  *
720  * @param ctx context
721  * @param nfa_states set of NFA states on which the DFA should be based on
722  *
723  * @return new DFA state
724  */
725 static struct GNUNET_REGEX_State *
726 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
727                   struct GNUNET_REGEX_StateSet *nfa_states)
728 {
729   struct GNUNET_REGEX_State *s;
730   char *name;
731   int len = 0;
732   struct GNUNET_REGEX_State *cstate;
733   struct Transition *ctran;
734   int insert = 1;
735   struct Transition *t;
736   int i;
737
738   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
739   s->id = ctx->state_id++;
740   s->accepting = 0;
741   s->marked = 0;
742   s->name = NULL;
743   s->scc_id = 0;
744   s->index = -1;
745   s->lowlink = -1;
746   s->contained = 0;
747
748   if (NULL == nfa_states)
749   {
750     GNUNET_asprintf (&s->name, "s%i", s->id);
751     return s;
752   }
753
754   s->nfa_set = nfa_states;
755
756   if (nfa_states->len < 1)
757     return s;
758
759   // Create a name based on 'sset'
760   s->name = GNUNET_malloc (sizeof (char) * 2);
761   strcat (s->name, "{");
762   name = NULL;
763
764   for (i = 0; i < nfa_states->len; i++)
765   {
766     cstate = nfa_states->states[i];
767     GNUNET_asprintf (&name, "%i,", cstate->id);
768
769     if (NULL != name)
770     {
771       len = strlen (s->name) + strlen (name) + 1;
772       s->name = GNUNET_realloc (s->name, len);
773       strcat (s->name, name);
774       GNUNET_free (name);
775       name = NULL;
776     }
777
778     // Add a transition for each distinct label to NULL state
779     for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
780     {
781       if (0 != ctran->label)
782       {
783         insert = 1;
784
785         for (t = s->transitions_head; NULL != t; t = t->next)
786         {
787           if (t->label == ctran->label)
788           {
789             insert = 0;
790             break;
791           }
792         }
793
794         if (insert)
795           state_add_transition (ctx, s, ctran->label, NULL);
796       }
797     }
798
799     // If the nfa_states contain an accepting state, the new dfa state is also accepting
800     if (cstate->accepting)
801       s->accepting = 1;
802   }
803
804   s->name[strlen (s->name) - 1] = '}';
805
806   return s;
807 }
808
809 /**
810  * Move from the given state 's' to the next state on
811  * transition 'label'
812  *
813  * @param s starting state
814  * @param label edge label to follow
815  *
816  * @return new state or NULL, if transition on label not possible
817  */
818 static struct GNUNET_REGEX_State *
819 dfa_move (struct GNUNET_REGEX_State *s, const char label)
820 {
821   struct Transition *t;
822   struct GNUNET_REGEX_State *new_s;
823
824   if (NULL == s)
825     return NULL;
826
827   new_s = NULL;
828
829   for (t = s->transitions_head; NULL != t; t = t->next)
830   {
831     if (label == t->label)
832     {
833       new_s = t->to_state;
834       break;
835     }
836   }
837
838   return new_s;
839 }
840
841
842 /**
843  * Remove all unreachable states from DFA 'a'. Unreachable states
844  * are those states that are not reachable from the starting state.
845  *
846  * @param a DFA automaton
847  */
848 static void
849 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
850 {
851   struct GNUNET_REGEX_State *s;
852   struct GNUNET_REGEX_State *s_next;
853
854   // 1. unmark all states
855   for (s = a->states_head; NULL != s; s = s->next)
856     s->marked = GNUNET_NO;
857
858   // 2. traverse dfa from start state and mark all visited states
859   automaton_traverse (NULL, a, NULL);
860
861   // 3. delete all states that were not visited
862   for (s = a->states_head; NULL != s; s = s_next)
863   {
864     s_next = s->next;
865     if (GNUNET_NO == s->marked)
866     {
867       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Removed state %s\n", s->name);
868       automaton_remove_state (a, s);
869     }
870   }
871 }
872
873 /**
874  * Remove all dead states from the DFA 'a'. Dead states are those
875  * states that do not transition to any other state but themselfes.
876  *
877  * @param a DFA automaton
878  */
879 static void
880 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
881 {
882   struct GNUNET_REGEX_State *s;
883   struct Transition *t;
884   int dead;
885
886   GNUNET_assert (DFA == a->type);
887
888   for (s = a->states_head; NULL != s; s = s->next)
889   {
890     if (s->accepting)
891       continue;
892
893     dead = 1;
894     for (t = s->transitions_head; NULL != t; t = t->next)
895     {
896       if (NULL != t->to_state && t->to_state != s)
897       {
898         dead = 0;
899         break;
900       }
901     }
902
903     if (0 == dead)
904       continue;
905
906     // state s is dead, remove it
907     automaton_remove_state (a, s);
908   }
909 }
910
911 /**
912  * Merge all non distinguishable states in the DFA 'a'
913  *
914  * @param ctx context
915  * @param a DFA automaton
916  */
917 static void
918 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
919                                      struct GNUNET_REGEX_Automaton *a)
920 {
921   int i;
922   int table[a->state_count][a->state_count];
923   struct GNUNET_REGEX_State *s1;
924   struct GNUNET_REGEX_State *s2;
925   struct Transition *t1;
926   struct Transition *t2;
927   int change;
928
929   change = 1;
930   for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
931        i++, s1 = s1->next)
932     s1->marked = i;
933
934   // Mark all pairs of accepting/!accepting states
935   for (s1 = a->states_head; NULL != s1; s1 = s1->next)
936   {
937     for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
938     {
939       if ((s1->accepting && !s2->accepting) ||
940           (!s1->accepting && s2->accepting))
941       {
942         table[s1->marked][s2->marked] = 1;
943       }
944       else
945         table[s1->marked][s2->marked] = 0;
946     }
947   }
948
949   while (0 != change)
950   {
951     change = 0;
952     for (s1 = a->states_head; NULL != s1; s1 = s1->next)
953     {
954       for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
955       {
956         if (0 != table[s1->marked][s2->marked])
957           continue;
958
959         for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
960         {
961           for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
962           {
963             if (t1->label == t2->label && t1->to_state == t2->to_state &&
964                 (0 != table[t1->to_state->marked][t2->to_state->marked] ||
965                  0 != table[t2->to_state->marked][t1->to_state->marked]))
966             {
967               table[s1->marked][s2->marked] = t1->label;
968               change = 1;
969             }
970             else if (t1->label != t2->label && t1->to_state != t2->to_state)
971             {
972               table[s1->marked][s2->marked] = -1;
973               change = 1;
974             }
975           }
976         }
977       }
978     }
979   }
980
981   struct GNUNET_REGEX_State *s2_next;
982
983   for (i = 0, s1 = a->states_head; NULL != s1; s1 = s1->next)
984   {
985     for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
986     {
987       s2_next = s2->next;
988       if (s1 != s2 && table[s1->marked][s2->marked] == 0)
989         automaton_merge_states (ctx, a, s1, s2);
990     }
991   }
992 }
993
994 /**
995  * Minimize the given DFA 'a' by removing all unreachable states,
996  * removing all dead states and merging all non distinguishable states
997  *
998  * @param ctx context
999  * @param a DFA automaton
1000  */
1001 static void
1002 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
1003               struct GNUNET_REGEX_Automaton *a)
1004 {
1005   if (NULL == a)
1006     return;
1007
1008   GNUNET_assert (DFA == a->type);
1009
1010   // 1. remove unreachable states
1011   dfa_remove_unreachable_states (a);
1012
1013   // 2. remove dead states
1014   dfa_remove_dead_states (a);
1015
1016   // 3. Merge nondistinguishable states
1017   dfa_merge_nondistinguishable_states (ctx, a);
1018 }
1019
1020 /**
1021  * Creates a new NFA fragment. Needs to be cleared using automaton_fragment_clear.
1022  *
1023  * @param start starting state
1024  * @param end end state
1025  *
1026  * @return new NFA fragment
1027  */
1028 static struct GNUNET_REGEX_Automaton *
1029 nfa_fragment_create (struct GNUNET_REGEX_State *start,
1030                      struct GNUNET_REGEX_State *end)
1031 {
1032   struct GNUNET_REGEX_Automaton *n;
1033
1034   n = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1035
1036   n->type = NFA;
1037   n->start = NULL;
1038   n->end = NULL;
1039
1040   if (NULL == start && NULL == end)
1041     return n;
1042
1043   automaton_add_state (n, end);
1044   automaton_add_state (n, start);
1045
1046   n->start = start;
1047   n->end = end;
1048
1049   return n;
1050 }
1051
1052 /**
1053  * Adds a list of states to the given automaton 'n'.
1054  *
1055  * @param n automaton to which the states should be added
1056  * @param states_head head of the DLL of states
1057  * @param states_tail tail of the DLL of states
1058  */
1059 static void
1060 nfa_add_states (struct GNUNET_REGEX_Automaton *n,
1061                 struct GNUNET_REGEX_State *states_head,
1062                 struct GNUNET_REGEX_State *states_tail)
1063 {
1064   struct GNUNET_REGEX_State *s;
1065
1066   if (NULL == n || NULL == states_head)
1067   {
1068     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n");
1069     return;
1070   }
1071
1072   if (NULL == n->states_head)
1073   {
1074     n->states_head = states_head;
1075     n->states_tail = states_tail;
1076     return;
1077   }
1078
1079   if (NULL != states_head)
1080   {
1081     n->states_tail->next = states_head;
1082     n->states_tail = states_tail;
1083   }
1084
1085   for (s = states_head; NULL != s; s = s->next)
1086     n->state_count++;
1087 }
1088
1089 /**
1090  * Creates a new NFA state. Needs to be freed using automaton_destroy_state.
1091  *
1092  * @param ctx context
1093  * @param accepting is it an accepting state or not
1094  *
1095  * @return new NFA state
1096  */
1097 static struct GNUNET_REGEX_State *
1098 nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
1099 {
1100   struct GNUNET_REGEX_State *s;
1101
1102   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1103   s->id = ctx->state_id++;
1104   s->accepting = accepting;
1105   s->marked = 0;
1106   s->contained = 0;
1107   s->index = -1;
1108   s->lowlink = -1;
1109   s->scc_id = 0;
1110   s->name = NULL;
1111   GNUNET_asprintf (&s->name, "s%i", s->id);
1112
1113   return s;
1114 }
1115
1116 /**
1117  * Calculates the NFA closure set for the given state.
1118  *
1119  * @param nfa the NFA containing 's'
1120  * @param s starting point state
1121  * @param label transitioning label on which to base the closure on,
1122  *                pass 0 for epsilon transition
1123  *
1124  * @return sorted nfa closure on 'label' (epsilon closure if 'label' is 0)
1125  */
1126 static struct GNUNET_REGEX_StateSet *
1127 nfa_closure_create (struct GNUNET_REGEX_Automaton *nfa,
1128                     struct GNUNET_REGEX_State *s, const char label)
1129 {
1130   struct GNUNET_REGEX_StateSet *cls;
1131   struct GNUNET_REGEX_StateSet *cls_check;
1132   struct GNUNET_REGEX_State *clsstate;
1133   struct GNUNET_REGEX_State *currentstate;
1134   struct Transition *ctran;
1135
1136   if (NULL == s)
1137     return NULL;
1138
1139   cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1140   cls_check = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1141
1142   for (clsstate = nfa->states_head; NULL != clsstate; clsstate = clsstate->next)
1143     clsstate->contained = 0;
1144
1145   // Add start state to closure only for epsilon closure
1146   if (0 == label)
1147     GNUNET_array_append (cls->states, cls->len, s);
1148
1149   GNUNET_array_append (cls_check->states, cls_check->len, s);
1150   while (cls_check->len > 0)
1151   {
1152     currentstate = cls_check->states[cls_check->len - 1];
1153     GNUNET_array_grow (cls_check->states, cls_check->len, cls_check->len - 1);
1154
1155     for (ctran = currentstate->transitions_head; NULL != ctran;
1156          ctran = ctran->next)
1157     {
1158       if (NULL != ctran->to_state && label == ctran->label)
1159       {
1160         clsstate = ctran->to_state;
1161
1162         if (NULL != clsstate && 0 == clsstate->contained)
1163         {
1164           GNUNET_array_append (cls->states, cls->len, clsstate);
1165           GNUNET_array_append (cls_check->states, cls_check->len, clsstate);
1166           clsstate->contained = 1;
1167         }
1168       }
1169     }
1170   }
1171   GNUNET_assert (0 == cls_check->len);
1172   GNUNET_free (cls_check);
1173
1174   if (cls->len > 1)
1175     qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1176            state_compare);
1177
1178   return cls;
1179 }
1180
1181 /**
1182  * Calculates the closure set for the given set of states.
1183  *
1184  * @param nfa the NFA containing 's'
1185  * @param states list of states on which to base the closure on
1186  * @param label transitioning label for which to base the closure on,
1187  *                pass 0 for epsilon transition
1188  *
1189  * @return sorted nfa closure on 'label' (epsilon closure if 'label' is 0)
1190  */
1191 static struct GNUNET_REGEX_StateSet *
1192 nfa_closure_set_create (struct GNUNET_REGEX_Automaton *nfa,
1193                         struct GNUNET_REGEX_StateSet *states, const char label)
1194 {
1195   struct GNUNET_REGEX_State *s;
1196   struct GNUNET_REGEX_StateSet *sset;
1197   struct GNUNET_REGEX_StateSet *cls;
1198   int i;
1199   int j;
1200   int k;
1201   int contains;
1202
1203   if (NULL == states)
1204     return NULL;
1205
1206   cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1207
1208   for (i = 0; i < states->len; i++)
1209   {
1210     s = states->states[i];
1211     sset = nfa_closure_create (nfa, s, label);
1212
1213     for (j = 0; j < sset->len; j++)
1214     {
1215       contains = 0;
1216       for (k = 0; k < cls->len; k++)
1217       {
1218         if (sset->states[j]->id == cls->states[k]->id)
1219         {
1220           contains = 1;
1221           break;
1222         }
1223       }
1224       if (!contains)
1225         GNUNET_array_append (cls->states, cls->len, sset->states[j]);
1226     }
1227     state_set_clear (sset);
1228   }
1229
1230   if (cls->len > 1)
1231     qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1232            state_compare);
1233
1234   return cls;
1235 }
1236
1237 /**
1238  * Pops two NFA fragments (a, b) from the stack and concatenates them (ab)
1239  *
1240  * @param ctx context
1241  */
1242 static void
1243 nfa_add_concatenation (struct GNUNET_REGEX_Context *ctx)
1244 {
1245   struct GNUNET_REGEX_Automaton *a;
1246   struct GNUNET_REGEX_Automaton *b;
1247   struct GNUNET_REGEX_Automaton *new;
1248
1249   b = ctx->stack_tail;
1250   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
1251   a = ctx->stack_tail;
1252   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1253
1254   state_add_transition (ctx, a->end, 0, b->start);
1255   a->end->accepting = 0;
1256   b->end->accepting = 1;
1257
1258   new = nfa_fragment_create (NULL, NULL);
1259   nfa_add_states (new, a->states_head, a->states_tail);
1260   nfa_add_states (new, b->states_head, b->states_tail);
1261   new->start = a->start;
1262   new->end = b->end;
1263   automaton_fragment_clear (a);
1264   automaton_fragment_clear (b);
1265
1266   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1267 }
1268
1269 /**
1270  * Pops a NFA fragment from the stack (a) and adds a new fragment (a*)
1271  *
1272  * @param ctx context
1273  */
1274 static void
1275 nfa_add_star_op (struct GNUNET_REGEX_Context *ctx)
1276 {
1277   struct GNUNET_REGEX_Automaton *a;
1278   struct GNUNET_REGEX_Automaton *new;
1279   struct GNUNET_REGEX_State *start;
1280   struct GNUNET_REGEX_State *end;
1281
1282   a = ctx->stack_tail;
1283   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1284
1285   if (NULL == a)
1286   {
1287     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1288                 "nfa_add_star_op failed, because there was no element on the stack");
1289     return;
1290   }
1291
1292   start = nfa_state_create (ctx, 0);
1293   end = nfa_state_create (ctx, 1);
1294
1295   state_add_transition (ctx, start, 0, a->start);
1296   state_add_transition (ctx, start, 0, end);
1297   state_add_transition (ctx, a->end, 0, a->start);
1298   state_add_transition (ctx, a->end, 0, end);
1299
1300   a->end->accepting = 0;
1301   end->accepting = 1;
1302
1303   new = nfa_fragment_create (start, end);
1304   nfa_add_states (new, a->states_head, a->states_tail);
1305   automaton_fragment_clear (a);
1306
1307   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1308 }
1309
1310 /**
1311  * Pops an NFA fragment (a) from the stack and adds a new fragment (a+)
1312  *
1313  * @param ctx context
1314  */
1315 static void
1316 nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
1317 {
1318   struct GNUNET_REGEX_Automaton *a;
1319
1320   a = ctx->stack_tail;
1321   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1322
1323   state_add_transition (ctx, a->end, 0, a->start);
1324
1325   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a);
1326 }
1327
1328 /**
1329  * Pops an NFA fragment (a) from the stack and adds a new fragment (a?)
1330  *
1331  * @param ctx context
1332  */
1333 static void
1334 nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
1335 {
1336   struct GNUNET_REGEX_Automaton *a;
1337   struct GNUNET_REGEX_Automaton *new;
1338   struct GNUNET_REGEX_State *start;
1339   struct GNUNET_REGEX_State *end;
1340
1341   a = ctx->stack_tail;
1342   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1343
1344   if (NULL == a)
1345   {
1346     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1347                 "nfa_add_question_op failed, because there was no element on the stack");
1348     return;
1349   }
1350
1351   start = nfa_state_create (ctx, 0);
1352   end = nfa_state_create (ctx, 1);
1353
1354   state_add_transition (ctx, start, 0, a->start);
1355   state_add_transition (ctx, start, 0, end);
1356   state_add_transition (ctx, a->end, 0, end);
1357
1358   a->end->accepting = 0;
1359
1360   new = nfa_fragment_create (start, end);
1361   nfa_add_states (new, a->states_head, a->states_tail);
1362   automaton_fragment_clear (a);
1363
1364   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1365 }
1366
1367 /**
1368  * Pops two NFA fragments (a, b) from the stack and adds a new NFA fragment
1369  * that alternates between a and b (a|b)
1370  *
1371  * @param ctx context
1372  */
1373 static void
1374 nfa_add_alternation (struct GNUNET_REGEX_Context *ctx)
1375 {
1376   struct GNUNET_REGEX_Automaton *a;
1377   struct GNUNET_REGEX_Automaton *b;
1378   struct GNUNET_REGEX_Automaton *new;
1379   struct GNUNET_REGEX_State *start;
1380   struct GNUNET_REGEX_State *end;
1381
1382   b = ctx->stack_tail;
1383   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
1384   a = ctx->stack_tail;
1385   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1386
1387   start = nfa_state_create (ctx, 0);
1388   end = nfa_state_create (ctx, 1);
1389   state_add_transition (ctx, start, 0, a->start);
1390   state_add_transition (ctx, start, 0, b->start);
1391
1392   state_add_transition (ctx, a->end, 0, end);
1393   state_add_transition (ctx, b->end, 0, end);
1394
1395   a->end->accepting = 0;
1396   b->end->accepting = 0;
1397   end->accepting = 1;
1398
1399   new = nfa_fragment_create (start, end);
1400   nfa_add_states (new, a->states_head, a->states_tail);
1401   nfa_add_states (new, b->states_head, b->states_tail);
1402   automaton_fragment_clear (a);
1403   automaton_fragment_clear (b);
1404
1405   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1406 }
1407
1408 /**
1409  * Adds a new nfa fragment to the stack
1410  *
1411  * @param ctx context
1412  * @param lit label for nfa transition
1413  */
1414 static void
1415 nfa_add_label (struct GNUNET_REGEX_Context *ctx, const char lit)
1416 {
1417   struct GNUNET_REGEX_Automaton *n;
1418   struct GNUNET_REGEX_State *start;
1419   struct GNUNET_REGEX_State *end;
1420
1421   GNUNET_assert (NULL != ctx);
1422
1423   start = nfa_state_create (ctx, 0);
1424   end = nfa_state_create (ctx, 1);
1425   state_add_transition (ctx, start, lit, end);
1426   n = nfa_fragment_create (start, end);
1427   GNUNET_assert (NULL != n);
1428   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n);
1429 }
1430
1431 /**
1432  * Initialize a new context
1433  *
1434  * @param ctx context
1435  */
1436 static void
1437 GNUNET_REGEX_context_init (struct GNUNET_REGEX_Context *ctx)
1438 {
1439   if (NULL == ctx)
1440   {
1441     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!");
1442     return;
1443   }
1444   ctx->state_id = 0;
1445   ctx->transition_id = 0;
1446   ctx->scc_id = 0;
1447   ctx->stack_head = NULL;
1448   ctx->stack_tail = NULL;
1449 }
1450
1451 /**
1452  * Construct an NFA by parsing the regex string of length 'len'.
1453  *
1454  * @param regex regular expression string
1455  * @param len length of the string
1456  *
1457  * @return NFA, needs to be freed using GNUNET_REGEX_destroy_automaton
1458  */
1459 struct GNUNET_REGEX_Automaton *
1460 GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
1461 {
1462   struct GNUNET_REGEX_Context ctx;
1463   struct GNUNET_REGEX_Automaton *nfa;
1464   const char *regexp;
1465   char *error_msg;
1466   unsigned int count;
1467   unsigned int altcount;
1468   unsigned int atomcount;
1469   unsigned int pcount;
1470   struct
1471   {
1472     int altcount;
1473     int atomcount;
1474   }     *p;
1475
1476   GNUNET_REGEX_context_init (&ctx);
1477
1478   regexp = regex;
1479   p = NULL;
1480   error_msg = NULL;
1481   altcount = 0;
1482   atomcount = 0;
1483   pcount = 0;
1484
1485   for (count = 0; count < len && *regexp; count++, regexp++)
1486   {
1487     switch (*regexp)
1488     {
1489     case '(':
1490       if (atomcount > 1)
1491       {
1492         --atomcount;
1493         nfa_add_concatenation (&ctx);
1494       }
1495       GNUNET_array_grow (p, pcount, pcount + 1);
1496       p[pcount - 1].altcount = altcount;
1497       p[pcount - 1].atomcount = atomcount;
1498       altcount = 0;
1499       atomcount = 0;
1500       break;
1501     case '|':
1502       if (0 == atomcount)
1503       {
1504         error_msg = "Cannot append '|' to nothing";
1505         goto error;
1506       }
1507       while (--atomcount > 0)
1508         nfa_add_concatenation (&ctx);
1509       altcount++;
1510       break;
1511     case ')':
1512       if (0 == pcount)
1513       {
1514         error_msg = "Missing opening '('";
1515         goto error;
1516       }
1517       if (0 == atomcount)
1518       {
1519         // Ignore this: "()"
1520         pcount--;
1521         altcount = p[pcount].altcount;
1522         atomcount = p[pcount].atomcount;
1523         break;
1524       }
1525       while (--atomcount > 0)
1526         nfa_add_concatenation (&ctx);
1527       for (; altcount > 0; altcount--)
1528         nfa_add_alternation (&ctx);
1529       pcount--;
1530       altcount = p[pcount].altcount;
1531       atomcount = p[pcount].atomcount;
1532       atomcount++;
1533       break;
1534     case '*':
1535       if (atomcount == 0)
1536       {
1537         error_msg = "Cannot append '+' to nothing";
1538         goto error;
1539       }
1540       nfa_add_star_op (&ctx);
1541       break;
1542     case '+':
1543       if (atomcount == 0)
1544       {
1545         error_msg = "Cannot append '+' to nothing";
1546         goto error;
1547       }
1548       nfa_add_plus_op (&ctx);
1549       break;
1550     case '?':
1551       if (atomcount == 0)
1552       {
1553         error_msg = "Cannot append '?' to nothing";
1554         goto error;
1555       }
1556       nfa_add_question_op (&ctx);
1557       break;
1558     case 92:                   /* escape: \ */
1559       regexp++;
1560       count++;
1561     default:
1562       if (atomcount > 1)
1563       {
1564         --atomcount;
1565         nfa_add_concatenation (&ctx);
1566       }
1567       nfa_add_label (&ctx, *regexp);
1568       atomcount++;
1569       break;
1570     }
1571   }
1572   if (0 != pcount)
1573   {
1574     error_msg = "Unbalanced parenthesis";
1575     goto error;
1576   }
1577   while (--atomcount > 0)
1578     nfa_add_concatenation (&ctx);
1579   for (; altcount > 0; altcount--)
1580     nfa_add_alternation (&ctx);
1581
1582   if (NULL != p)
1583     GNUNET_free (p);
1584
1585   nfa = ctx.stack_tail;
1586   GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
1587
1588
1589   if (NULL != ctx.stack_head)
1590   {
1591     error_msg = "Creating the NFA failed. NFA stack was not empty!";
1592     goto error;
1593   }
1594
1595   return nfa;
1596
1597 error:
1598   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex\n");
1599   if (NULL != error_msg)
1600     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
1601   if (NULL != p)
1602     GNUNET_free (p);
1603   while (NULL != ctx.stack_tail)
1604   {
1605     GNUNET_REGEX_automaton_destroy (ctx.stack_tail);
1606     GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail,
1607                                  ctx.stack_tail);
1608   }
1609   return NULL;
1610 }
1611
1612 /**
1613  * Construct DFA for the given 'regex' of length 'len'
1614  *
1615  * @param regex regular expression string
1616  * @param len length of the regular expression
1617  *
1618  * @return DFA, needs to be freed using GNUNET_REGEX_destroy_automaton
1619  */
1620 struct GNUNET_REGEX_Automaton *
1621 GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
1622 {
1623   struct GNUNET_REGEX_Context ctx;
1624   struct GNUNET_REGEX_Automaton *dfa;
1625   struct GNUNET_REGEX_Automaton *nfa;
1626   struct GNUNET_REGEX_StateSet *tmp;
1627   struct GNUNET_REGEX_StateSet *nfa_set;
1628   struct GNUNET_REGEX_StateSet *dfa_stack;
1629   struct Transition *ctran;
1630   struct GNUNET_REGEX_State *dfa_state;
1631   struct GNUNET_REGEX_State *new_dfa_state;
1632   struct GNUNET_REGEX_State *state_contains;
1633   struct GNUNET_REGEX_State *state_iter;
1634
1635   GNUNET_REGEX_context_init (&ctx);
1636
1637   // Create NFA
1638   nfa = GNUNET_REGEX_construct_nfa (regex, len);
1639
1640   if (NULL == nfa)
1641   {
1642     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1643                 "Could not create DFA, because NFA creation failed\n");
1644     return NULL;
1645   }
1646
1647   dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1648   dfa->type = DFA;
1649
1650   // Create DFA start state from epsilon closure
1651   dfa_stack = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1652   nfa_set = nfa_closure_create (nfa, nfa->start, 0);
1653   dfa->start = dfa_state_create (&ctx, nfa_set);
1654   automaton_add_state (dfa, dfa->start);
1655   GNUNET_array_append (dfa_stack->states, dfa_stack->len, dfa->start);
1656
1657   // Create dfa states by combining nfa states
1658   while (dfa_stack->len > 0)
1659   {
1660     dfa_state = dfa_stack->states[dfa_stack->len - 1];
1661     GNUNET_array_grow (dfa_stack->states, dfa_stack->len, dfa_stack->len - 1);
1662
1663     for (ctran = dfa_state->transitions_head; NULL != ctran;
1664          ctran = ctran->next)
1665     {
1666       if (0 != ctran->label && NULL == ctran->to_state)
1667       {
1668         tmp = nfa_closure_set_create (nfa, dfa_state->nfa_set, ctran->label);
1669         nfa_set = nfa_closure_set_create (nfa, tmp, 0);
1670         state_set_clear (tmp);
1671         new_dfa_state = dfa_state_create (&ctx, nfa_set);
1672         state_contains = NULL;
1673         for (state_iter = dfa->states_head; NULL != state_iter;
1674              state_iter = state_iter->next)
1675         {
1676           if (0 ==
1677               state_set_compare (state_iter->nfa_set, new_dfa_state->nfa_set))
1678             state_contains = state_iter;
1679         }
1680
1681         if (NULL == state_contains)
1682         {
1683           automaton_add_state (dfa, new_dfa_state);
1684           GNUNET_array_append (dfa_stack->states, dfa_stack->len,
1685                                new_dfa_state);
1686           ctran->to_state = new_dfa_state;
1687         }
1688         else
1689         {
1690           ctran->to_state = state_contains;
1691           automaton_destroy_state (new_dfa_state);
1692         }
1693       }
1694     }
1695   }
1696
1697   GNUNET_free (dfa_stack);
1698   GNUNET_REGEX_automaton_destroy (nfa);
1699
1700   dfa_minimize (&ctx, dfa);
1701   scc_tarjan (&ctx, dfa);
1702
1703   return dfa;
1704 }
1705
1706 /**
1707  * Free the memory allocated by constructing the GNUNET_REGEX_Automaton
1708  * data structure.
1709  *
1710  * @param a automaton to be destroyed
1711  */
1712 void
1713 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
1714 {
1715   struct GNUNET_REGEX_State *s;
1716   struct GNUNET_REGEX_State *next_state;
1717
1718   if (NULL == a)
1719     return;
1720
1721   for (s = a->states_head; NULL != s;)
1722   {
1723     next_state = s->next;
1724     automaton_destroy_state (s);
1725     s = next_state;
1726   }
1727
1728   GNUNET_free (a);
1729 }
1730
1731 /**
1732  * Save the given automaton as a GraphViz dot file
1733  *
1734  * @param a the automaton to be saved
1735  * @param filename where to save the file
1736  */
1737 void
1738 GNUNET_REGEX_automaton_save_graph (struct GNUNET_REGEX_Automaton *a,
1739                                    const char *filename)
1740 {
1741   struct GNUNET_REGEX_State *s;
1742   struct Transition *ctran;
1743   char *s_acc = NULL;
1744   char *s_tran = NULL;
1745   char *start;
1746   char *end;
1747   FILE *p;
1748
1749   if (NULL == a)
1750   {
1751     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print NFA, was NULL!");
1752     return;
1753   }
1754
1755   if (NULL == filename || strlen (filename) < 1)
1756   {
1757     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No Filename given!");
1758     return;
1759   }
1760
1761   p = fopen (filename, "w");
1762
1763   if (p == NULL)
1764   {
1765     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not open file for writing: %s",
1766                 filename);
1767     return;
1768   }
1769
1770   start = "digraph G {\nrankdir=LR\n";
1771   fwrite (start, strlen (start), 1, p);
1772
1773   for (s = a->states_head; NULL != s; s = s->next)
1774   {
1775     if (s->accepting)
1776     {
1777       GNUNET_asprintf (&s_acc,
1778                        "\"%s\" [shape=doublecircle, color=\"0.%i 0.8 0.95\"];\n",
1779                        s->name, s->scc_id);
1780       fwrite (s_acc, strlen (s_acc), 1, p);
1781       GNUNET_free (s_acc);
1782     }
1783     else
1784     {
1785       GNUNET_asprintf (&s_acc, "\"%s\" [color=\"0.%i 0.8 0.95\"];\n", s->name,
1786                        s->scc_id);
1787       fwrite (s_acc, strlen (s_acc), 1, p);
1788       GNUNET_free (s_acc);
1789     }
1790
1791     s->marked = 1;
1792
1793     for (ctran = s->transitions_head; NULL != ctran; ctran = ctran->next)
1794     {
1795       if (NULL == ctran->to_state)
1796       {
1797         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1798                     "Transition from State %i has has no state for transitioning\n",
1799                     s->id);
1800         continue;
1801       }
1802
1803       if (ctran->label == 0)
1804       {
1805         GNUNET_asprintf (&s_tran,
1806                          "\"%s\" -> \"%s\" [label = \"epsilon\", color=\"0.%i 0.8 0.95\"];\n",
1807                          s->name, ctran->to_state->name, s->scc_id);
1808       }
1809       else
1810       {
1811         GNUNET_asprintf (&s_tran,
1812                          "\"%s\" -> \"%s\" [label = \"%c\", color=\"0.%i 0.8 0.95\"];\n",
1813                          s->name, ctran->to_state->name, ctran->label,
1814                          s->scc_id);
1815       }
1816
1817       fwrite (s_tran, strlen (s_tran), 1, p);
1818       GNUNET_free (s_tran);
1819     }
1820   }
1821
1822   end = "\n}\n";
1823   fwrite (end, strlen (end), 1, p);
1824   fclose (p);
1825 }
1826
1827 /**
1828  * Evaluates the given string using the given DFA automaton
1829  *
1830  * @param a automaton, type must be DFA
1831  * @param string string that should be evaluated
1832  *
1833  * @return 0 if string matches, non 0 otherwise
1834  */
1835 static int
1836 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
1837 {
1838   const char *strp;
1839   struct GNUNET_REGEX_State *s;
1840
1841   if (DFA != a->type)
1842   {
1843     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1844                 "Tried to evaluate DFA, but NFA automaton given");
1845     return -1;
1846   }
1847
1848   s = a->start;
1849
1850   for (strp = string; NULL != strp && *strp; strp++)
1851   {
1852     s = dfa_move (s, *strp);
1853     if (NULL == s)
1854       break;
1855   }
1856
1857   if (NULL != s && s->accepting)
1858     return 0;
1859
1860   return 1;
1861 }
1862
1863 /**
1864  * Evaluates the given string using the given NFA automaton
1865  *
1866  * @param a automaton, type must be NFA
1867  * @param string string that should be evaluated
1868  *
1869  * @return 0 if string matches, non 0 otherwise
1870  */
1871 static int
1872 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
1873 {
1874   const char *strp;
1875   struct GNUNET_REGEX_State *s;
1876   struct GNUNET_REGEX_StateSet *sset;
1877   struct GNUNET_REGEX_StateSet *new_sset;
1878   int i;
1879   int result;
1880
1881   if (NFA != a->type)
1882   {
1883     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1884                 "Tried to evaluate NFA, but DFA automaton given");
1885     return -1;
1886   }
1887
1888   result = 1;
1889   strp = string;
1890   sset = nfa_closure_create (a, a->start, 0);
1891
1892   for (strp = string; NULL != strp && *strp; strp++)
1893   {
1894     new_sset = nfa_closure_set_create (a, sset, *strp);
1895     state_set_clear (sset);
1896     sset = nfa_closure_set_create (a, new_sset, 0);
1897     state_set_clear (new_sset);
1898   }
1899
1900   for (i = 0; i < sset->len; i++)
1901   {
1902     s = sset->states[i];
1903     if (NULL != s && s->accepting)
1904     {
1905       result = 0;
1906       break;
1907     }
1908   }
1909
1910   state_set_clear (sset);
1911   return result;
1912 }
1913
1914 /**
1915  * Evaluates the given 'string' against the given compiled regex
1916  *
1917  * @param a automaton
1918  * @param string string to check
1919  *
1920  * @return 0 if string matches, non 0 otherwise
1921  */
1922 int
1923 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
1924 {
1925   int result;
1926
1927   switch (a->type)
1928   {
1929   case DFA:
1930     result = evaluate_dfa (a, string);
1931     break;
1932   case NFA:
1933     result = evaluate_nfa (a, string);
1934     break;
1935   default:
1936     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1937                 "Evaluating regex failed, automaton has no type!\n");
1938     result = GNUNET_SYSERR;
1939     break;
1940   }
1941
1942   return result;
1943 }
1944
1945 /**
1946  * Get the first key for the given 'input_string'. This hashes
1947  * the first x bits of the 'input_strings'.
1948  *
1949  * @param input_string string.
1950  * @param string_len length of the 'input_string'.
1951  * @param key pointer to where to write the hash code.
1952  *
1953  * @return number of bits of 'input_string' that have been consumed
1954  *         to construct the key
1955  */
1956 unsigned int
1957 GNUNET_REGEX_get_first_key (const char *input_string, unsigned int string_len,
1958                             GNUNET_HashCode * key)
1959 {
1960   unsigned int size;
1961
1962   size = string_len < initial_bits ? string_len : initial_bits;
1963
1964   if (NULL == input_string)
1965   {
1966     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
1967     return 0;
1968   }
1969
1970   GNUNET_CRYPTO_hash (input_string, size, key);
1971
1972   return size;
1973 }
1974
1975 /**
1976  * Check if the given 'proof' matches the given 'key'.
1977  *
1978  * @param proof partial regex
1979  * @param key hash
1980  *
1981  * @return GNUNET_OK if the proof is valid for the given key
1982  */
1983 int
1984 GNUNET_REGEX_check_proof (const char *proof, const GNUNET_HashCode * key)
1985 {
1986   return GNUNET_OK;
1987 }
1988
1989 /**
1990  * Get all edges leaving state 's'.
1991  *
1992  * @param s state.
1993  * @param edges all edges leaving 's'.
1994  *
1995  * @return number of edges.
1996  */
1997 static unsigned int
1998 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
1999 {
2000   struct Transition *t;
2001   unsigned int count;
2002
2003   if (NULL == s)
2004     return 0;
2005
2006   count = 0;
2007
2008   for (t = s->transitions_head; NULL != t; t = t->next)
2009   {
2010     if (NULL != t->to_state)
2011     {
2012       edges[count].label = &t->label;
2013       edges[count].destination = t->to_state->hash;
2014       count++;
2015     }
2016   }
2017   return count;
2018 }
2019
2020 /**
2021  * Iterate over all edges helper function starting from state 's', calling
2022  * iterator on for each edge.
2023  *
2024  * @param s state.
2025  * @param iterator iterator function called for each edge.
2026  * @param iterator_cls closure.
2027  */
2028 static void
2029 iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
2030               void *iterator_cls)
2031 {
2032   struct Transition *t;
2033   struct GNUNET_REGEX_Edge edges[s->transition_count];
2034   unsigned int num_edges;
2035
2036   if (GNUNET_NO == s->marked)
2037   {
2038     s->marked = GNUNET_YES;
2039
2040     num_edges = state_get_edges (s, edges);
2041
2042     iterator (iterator_cls, &s->hash, NULL, s->accepting, num_edges, edges);
2043
2044
2045     for (t = s->transitions_head; NULL != t; t = t->next)
2046       iterate_edge (t->to_state, iterator, iterator_cls);
2047   }
2048 }
2049
2050 /**
2051  * Iterate over all edges starting from start state of automaton 'a'. Calling
2052  * iterator for each edge.
2053  *
2054  * @param a automaton.
2055  * @param iterator iterator called for each edge.
2056  * @param iterator_cls closure.
2057  */
2058 void
2059 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2060                                 GNUNET_REGEX_KeyIterator iterator,
2061                                 void *iterator_cls)
2062 {
2063   iterate_edge (a->start, iterator, iterator_cls);
2064 }