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