d200becc96c89109a8378caf50e778b97ba3bc7a
[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 /*
278  * Debug helper functions
279  */
280 void
281 debug_print_transitions (struct GNUNET_REGEX_State *);
282
283 void
284 debug_print_state (struct GNUNET_REGEX_State *s)
285 {
286   char *proof;
287
288   if (NULL == s->proof)
289     proof = "NULL";
290   else
291     proof = s->proof;
292
293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
294               "State %i: %s marked: %i accepting: %i scc_id: %i transitions: %i proof: %s\n",
295               s->id, s->name, s->marked, s->accepting, s->scc_id,
296               s->transition_count, proof);
297
298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transitions:\n");
299   debug_print_transitions (s);
300 }
301
302 void
303 debug_print_states (struct GNUNET_REGEX_Automaton *a)
304 {
305   struct GNUNET_REGEX_State *s;
306
307   for (s = a->states_head; NULL != s; s = s->next)
308     debug_print_state (s);
309 }
310
311 void
312 debug_print_transition (struct Transition *t)
313 {
314   char *to_state;
315   char *from_state;
316   char label;
317
318   if (NULL == t)
319     return;
320
321   if (0 == t->label)
322     label = '0';
323   else
324     label = t->label;
325
326   if (NULL == t->to_state)
327     to_state = "NULL";
328   else
329     to_state = t->to_state->name;
330
331   if (NULL == t->from_state)
332     from_state = "NULL";
333   else
334     from_state = t->from_state->name;
335
336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transition %i: From %s on %c to %s\n",
337               t->id, from_state, label, to_state);
338 }
339
340 void
341 debug_print_transitions (struct GNUNET_REGEX_State *s)
342 {
343   struct Transition *t;
344
345   for (t = s->transitions_head; NULL != t; t = t->next)
346     debug_print_transition (t);
347 }
348
349 /**
350  * Recursive function doing DFS with 'v' as a start, detecting all SCCs inside
351  * the subgraph reachable from 'v'. Used with scc_tarjan function to detect all
352  * SCCs inside an automaton.
353  *
354  * @param ctx context
355  * @param v start vertex
356  * @param index current index
357  * @param stack stack for saving all SCCs
358  * @param stack_size current size of the stack
359  */
360 static void
361 scc_tarjan_strongconnect (struct GNUNET_REGEX_Context *ctx,
362                           struct GNUNET_REGEX_State *v, int *index,
363                           struct GNUNET_REGEX_State **stack,
364                           unsigned int *stack_size)
365 {
366   struct GNUNET_REGEX_State *w;
367   struct Transition *t;
368
369   v->index = *index;
370   v->lowlink = *index;
371   (*index)++;
372   stack[(*stack_size)++] = v;
373   v->contained = 1;
374
375   for (t = v->transitions_head; NULL != t; t = t->next)
376   {
377     w = t->to_state;
378     if (NULL != w && w->index < 0)
379     {
380       scc_tarjan_strongconnect (ctx, w, index, stack, stack_size);
381       v->lowlink = (v->lowlink > w->lowlink) ? w->lowlink : v->lowlink;
382     }
383     else if (0 != w->contained)
384       v->lowlink = (v->lowlink > w->index) ? w->index : v->lowlink;
385   }
386
387   if (v->lowlink == v->index)
388   {
389     w = stack[--(*stack_size)];
390     w->contained = 0;
391
392     if (v != w)
393     {
394       ctx->scc_id++;
395       while (v != w)
396       {
397         w->scc_id = ctx->scc_id;
398         w = stack[--(*stack_size)];
399         w->contained = 0;
400       }
401       w->scc_id = ctx->scc_id;
402     }
403   }
404 }
405
406 /**
407  * Detect all SCCs (Strongly Connected Components) inside the given automaton.
408  * SCCs will be marked using the scc_id on each state.
409  *
410  * @param ctx context
411  * @param a automaton
412  */
413 static void
414 scc_tarjan (struct GNUNET_REGEX_Context *ctx, struct GNUNET_REGEX_Automaton *a)
415 {
416   int index;
417   struct GNUNET_REGEX_State *v;
418   struct GNUNET_REGEX_State *stack[a->state_count];
419   unsigned int stack_size;
420
421   for (v = a->states_head; NULL != v; v = v->next)
422   {
423     v->contained = 0;
424     v->index = -1;
425     v->lowlink = -1;
426   }
427
428   stack_size = 0;
429   index = 0;
430
431   for (v = a->states_head; NULL != v; v = v->next)
432   {
433     if (v->index < 0)
434       scc_tarjan_strongconnect (ctx, v, &index, stack, &stack_size);
435   }
436 }
437
438 /**
439  * Adds a transition from one state to another on 'label'. Does not add
440  * duplicate states.
441  *
442  * @param ctx context
443  * @param from_state starting state for the transition
444  * @param label transition label
445  * @param to_state state to where the transition should point to
446  */
447 static void
448 state_add_transition (struct GNUNET_REGEX_Context *ctx,
449                       struct GNUNET_REGEX_State *from_state, const char label,
450                       struct GNUNET_REGEX_State *to_state)
451 {
452   int is_dup;
453   struct Transition *t;
454
455   if (NULL == from_state)
456   {
457     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
458     return;
459   }
460
461   // Do not add duplicate state transitions
462   is_dup = GNUNET_NO;
463   for (t = from_state->transitions_head; NULL != t; t = t->next)
464   {
465     if (t->to_state == to_state && t->label == label &&
466         t->from_state == from_state)
467     {
468       is_dup = GNUNET_YES;
469       break;
470     }
471   }
472
473   if (is_dup)
474     return;
475
476   t = GNUNET_malloc (sizeof (struct Transition));
477   t->id = ctx->transition_id++;
478   t->label = label;
479   t->to_state = to_state;
480   t->from_state = from_state;
481
482   // Add outgoing transition to 'from_state'
483   from_state->transition_count++;
484   GNUNET_CONTAINER_DLL_insert (from_state->transitions_head,
485                                from_state->transitions_tail, t);
486 }
487
488 /**
489  * Compare two states. Used for sorting.
490  *
491  * @param a first state
492  * @param b second state
493  *
494  * @return an integer less than, equal to, or greater than zero
495  *         if the first argument is considered to be respectively
496  *         less than, equal to, or greater than the second.
497  */
498 static int
499 state_compare (const void *a, const void *b)
500 {
501   struct GNUNET_REGEX_State **s1;
502   struct GNUNET_REGEX_State **s2;
503
504   s1 = (struct GNUNET_REGEX_State **) a;
505   s2 = (struct GNUNET_REGEX_State **) b;
506
507   return (*s1)->id - (*s2)->id;
508 }
509
510 /**
511  * Create a proof for the given state. Intended to be used as a parameter for
512  * automaton_traverse() function.
513  *
514  * @param cls closure
515  * @param s state
516  */
517 void
518 state_create_proof (void *cls, struct GNUNET_REGEX_State *s)
519 {
520   struct Transition *inc_t;
521   int i;
522   char *proof = NULL;
523   char *stars = NULL;
524   char *tmp = NULL;
525
526   for (i = 0; i < s->incoming_transition_count; i++)
527   {
528     inc_t = s->incoming_transitions[i];
529
530     if (NULL == inc_t)
531       continue;
532
533     GNUNET_assert (inc_t->label != 0 && inc_t->from_state != NULL);
534
535     if (inc_t->from_state == inc_t->to_state)
536       GNUNET_asprintf (&stars, "%c*", inc_t->label);
537     else
538     {
539       if (NULL != inc_t->from_state->proof)
540         GNUNET_asprintf (&tmp, "%s%c", inc_t->from_state->proof, inc_t->label);
541       else
542         GNUNET_asprintf (&tmp, "%c", inc_t->label);
543     }
544
545     if (i > 0 && NULL != tmp && NULL != proof)
546       GNUNET_asprintf (&proof, "%s|%s", proof, tmp);
547     else if (NULL != tmp)
548       proof = GNUNET_strdup (tmp);
549
550     if (NULL != tmp)
551     {
552       GNUNET_free (tmp);
553       tmp = NULL;
554     }
555   }
556
557   if (NULL != s->proof)
558     GNUNET_free (s->proof);
559
560   if (s->incoming_transition_count > 1)
561   {
562     if (NULL != stars)
563     {
564       GNUNET_asprintf (&s->proof, "(%s)%s", proof, stars);
565       GNUNET_free (stars);
566     }
567     else if (NULL != proof)
568       GNUNET_asprintf (&s->proof, "(%s)", proof);
569
570     if (NULL != proof)
571       GNUNET_free (proof);
572   }
573   else
574     s->proof = proof;
575 }
576
577 /**
578  * Get all edges leaving state 's'.
579  *
580  * @param s state.
581  * @param edges all edges leaving 's'.
582  *
583  * @return number of edges.
584  */
585 static unsigned int
586 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
587 {
588   struct Transition *t;
589   unsigned int count;
590
591   if (NULL == s)
592     return 0;
593
594   count = 0;
595
596   for (t = s->transitions_head; NULL != t; t = t->next)
597   {
598     if (NULL != t->to_state)
599     {
600       edges[count].label = &t->label;
601       edges[count].destination = t->to_state->hash;
602       count++;
603     }
604   }
605   return count;
606 }
607
608 /**
609  * Compare to state sets by comparing the id's of the states that are contained
610  * in each set. Both sets are expected to be sorted by id!
611  *
612  * @param sset1 first state set
613  * @param sset2 second state set
614  *
615  * @return an integer less than, equal to, or greater than zero
616  *         if the first argument is considered to be respectively
617  *         less than, equal to, or greater than the second.
618  */
619 static int
620 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
621                    struct GNUNET_REGEX_StateSet *sset2)
622 {
623   int result;
624   int i;
625
626   if (NULL == sset1 || NULL == sset2)
627     return 1;
628
629   result = sset1->len - sset2->len;
630
631   for (i = 0; i < sset1->len; i++)
632   {
633     if (0 != result)
634       break;
635
636     result = state_compare (&sset1->states[i], &sset2->states[i]);
637   }
638   return result;
639 }
640
641 /**
642  * Clears the given StateSet 'set'
643  *
644  * @param set set to be cleared
645  */
646 static void
647 state_set_clear (struct GNUNET_REGEX_StateSet *set)
648 {
649   if (NULL != set)
650   {
651     if (NULL != set->states)
652       GNUNET_free (set->states);
653     GNUNET_free (set);
654   }
655 }
656
657 /**
658  * Clears an automaton fragment. Does not destroy the states inside the
659  * automaton.
660  *
661  * @param a automaton to be cleared
662  */
663 static void
664 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
665 {
666   if (NULL == a)
667     return;
668
669   a->start = NULL;
670   a->end = NULL;
671   a->states_head = NULL;
672   a->states_tail = NULL;
673   a->state_count = 0;
674   GNUNET_free (a);
675 }
676
677 /**
678  * Frees the memory used by State 's'
679  *
680  * @param s state that should be destroyed
681  */
682 static void
683 automaton_destroy_state (struct GNUNET_REGEX_State *s)
684 {
685   struct Transition *t;
686   struct Transition *next_t;
687
688   if (NULL == s)
689     return;
690
691   if (NULL != s->name)
692     GNUNET_free (s->name);
693
694   for (t = s->transitions_head; NULL != t; t = next_t)
695   {
696     next_t = t->next;
697     GNUNET_CONTAINER_DLL_remove (s->transitions_head, s->transitions_tail, t);
698     GNUNET_free (t);
699   }
700
701   if (s->incoming_transition_count > 0 && NULL != s->incoming_transitions)
702   {
703     GNUNET_free (s->incoming_transitions);
704   }
705
706   state_set_clear (s->nfa_set);
707
708   GNUNET_free (s);
709 }
710
711 /**
712  * Remove a state from the given automaton 'a'. Always use this function when
713  * altering the states of an automaton. Will also remove all transitions leading
714  * to this state, before destroying it.
715  *
716  * @param a automaton
717  * @param s state to remove
718  */
719 static void
720 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
721                         struct GNUNET_REGEX_State *s)
722 {
723   struct GNUNET_REGEX_State *ss;
724   struct GNUNET_REGEX_State *s_check;
725   struct Transition *t_check;
726
727   if (NULL == a || NULL == s)
728     return;
729
730   // remove state
731   ss = s;
732   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
733   a->state_count--;
734
735   // remove all transitions leading to this state
736   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
737   {
738     for (t_check = s_check->transitions_head; NULL != t_check;
739          t_check = t_check->next)
740     {
741       if (t_check->to_state == ss)
742       {
743         GNUNET_CONTAINER_DLL_remove (s_check->transitions_head,
744                                      s_check->transitions_tail, t_check);
745         s_check->transition_count--;
746       }
747     }
748   }
749
750   automaton_destroy_state (ss);
751 }
752
753 /**
754  * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
755  * 's2'.
756  *
757  * @param ctx context
758  * @param a automaton
759  * @param s1 first state
760  * @param s2 second state, will be destroyed
761  */
762 static void
763 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
764                         struct GNUNET_REGEX_Automaton *a,
765                         struct GNUNET_REGEX_State *s1,
766                         struct GNUNET_REGEX_State *s2)
767 {
768   struct GNUNET_REGEX_State *s_check;
769   struct Transition *t_check;
770   char *new_name;
771   int i;
772   struct Transition *inc_t;
773
774   GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
775
776   if (s1 == s2)
777     return;
778
779   // 1. Make all transitions pointing to s2 point to s1
780   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
781   {
782     for (t_check = s_check->transitions_head; NULL != t_check;
783          t_check = t_check->next)
784     {
785       if (s2 == t_check->to_state)
786         t_check->to_state = s1;
787     }
788   }
789
790   // 2. Remove all transitions coming from s2
791   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
792   {
793     for (i = 0; i < s_check->incoming_transition_count; i++)
794     {
795       inc_t = s_check->incoming_transitions[i];
796
797       if (inc_t != 0 && inc_t->from_state == s2)
798       {
799         s_check->incoming_transitions[i] = NULL;
800       }
801     }
802   }
803
804   // 3. Add all transitions from s2 to sX to s1
805   for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
806   {
807     if (t_check->to_state != s1)
808       state_add_transition (ctx, s1, t_check->label, t_check->to_state);
809   }
810
811   // 4. Rename s1 to {s1,s2}
812   new_name = GNUNET_strdup (s1->name);
813   if (NULL != s1->name)
814   {
815     GNUNET_free (s1->name);
816     s1->name = NULL;
817   }
818   GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
819   GNUNET_free (new_name);
820
821   // remove state
822   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
823   a->state_count--;
824   automaton_destroy_state (s2);
825 }
826
827 /**
828  * Add a state to the automaton 'a', always use this function to alter the
829  * states DLL of the automaton.
830  *
831  * @param a automaton to add the state to
832  * @param s state that should be added
833  */
834 static void
835 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
836                      struct GNUNET_REGEX_State *s)
837 {
838   GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
839   a->state_count++;
840 }
841
842 /**
843  * Function that is called with each state, when traversing an automaton.
844  *
845  * @param cls closure
846  * @param s state
847  */
848 typedef void (*GNUNET_REGEX_traverse_action) (void *cls,
849                                               struct GNUNET_REGEX_State * s);
850
851 /**
852  * Traverses all states that are reachable from state 's'. Expects the states to
853  * be unmarked (s->marked == GNUNET_NO). Performs 'action' on each visited
854  * state.
855  *
856  * @param cls closure.
857  * @param s start state.
858  * @param action action to be performed on each state.
859  */
860 static void
861 automaton_state_traverse (void *cls, struct GNUNET_REGEX_State *s,
862                           GNUNET_REGEX_traverse_action action)
863 {
864   struct Transition *t;
865   int i;
866
867   if (GNUNET_NO == s->marked)
868   {
869     s->marked = GNUNET_YES;
870
871     // First make sure all incoming states have been traversed
872     for (i = 0; i < s->incoming_transition_count; i++)
873     {
874       if (NULL != s->incoming_transitions[i])
875         automaton_state_traverse (cls, s->incoming_transitions[i]->from_state,
876                                   action);
877     }
878
879     if (action > 0)
880       action (cls, s);
881
882     for (t = s->transitions_head; NULL != t; t = t->next)
883       automaton_state_traverse (cls, t->to_state, action);
884   }
885 }
886
887 /**
888  * Traverses the given automaton from it's start state, visiting all reachable
889  * states and calling 'action' on each one of them.
890  *
891  * @param cls closure.
892  * @param a automaton.
893  * @param action action to be performed on each state.
894  */
895 static void
896 automaton_traverse (void *cls, struct GNUNET_REGEX_Automaton *a,
897                     GNUNET_REGEX_traverse_action action)
898 {
899   struct GNUNET_REGEX_State *s;
900
901   for (s = a->states_head; NULL != s; s = s->next)
902     s->marked = GNUNET_NO;
903
904   automaton_state_traverse (cls, a->start, action);
905 }
906
907 /**
908  * Creates a new DFA state based on a set of NFA states. Needs to be freed using
909  * automaton_destroy_state.
910  *
911  * @param ctx context
912  * @param nfa_states set of NFA states on which the DFA should be based on
913  *
914  * @return new DFA state
915  */
916 static struct GNUNET_REGEX_State *
917 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
918                   struct GNUNET_REGEX_StateSet *nfa_states)
919 {
920   struct GNUNET_REGEX_State *s;
921   char *name;
922   int len = 0;
923   struct GNUNET_REGEX_State *cstate;
924   struct Transition *ctran;
925   int insert = 1;
926   struct Transition *t;
927   int i;
928
929   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
930   s->id = ctx->state_id++;
931   s->accepting = 0;
932   s->marked = 0;
933   s->name = NULL;
934   s->scc_id = 0;
935   s->index = -1;
936   s->lowlink = -1;
937   s->contained = 0;
938   s->proof = NULL;
939
940   if (NULL == nfa_states)
941   {
942     GNUNET_asprintf (&s->name, "s%i", s->id);
943     return s;
944   }
945
946   s->nfa_set = nfa_states;
947
948   if (nfa_states->len < 1)
949     return s;
950
951   // Create a name based on 'sset'
952   s->name = GNUNET_malloc (sizeof (char) * 2);
953   strcat (s->name, "{");
954   name = NULL;
955
956   for (i = 0; i < nfa_states->len; i++)
957   {
958     cstate = nfa_states->states[i];
959     GNUNET_asprintf (&name, "%i,", cstate->id);
960
961     if (NULL != name)
962     {
963       len = strlen (s->name) + strlen (name) + 1;
964       s->name = GNUNET_realloc (s->name, len);
965       strcat (s->name, name);
966       GNUNET_free (name);
967       name = NULL;
968     }
969
970     // Add a transition for each distinct label to NULL state
971     for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
972     {
973       if (0 != ctran->label)
974       {
975         insert = 1;
976
977         for (t = s->transitions_head; NULL != t; t = t->next)
978         {
979           if (t->label == ctran->label)
980           {
981             insert = 0;
982             break;
983           }
984         }
985
986         if (insert)
987           state_add_transition (ctx, s, ctran->label, NULL);
988       }
989     }
990
991     // If the nfa_states contain an accepting state, the new dfa state is also
992     // accepting
993     if (cstate->accepting)
994       s->accepting = 1;
995   }
996
997   s->name[strlen (s->name) - 1] = '}';
998
999   return s;
1000 }
1001
1002 /**
1003  * Move from the given state 's' to the next state on transition 'label'
1004  *
1005  * @param s starting state
1006  * @param label edge label to follow
1007  *
1008  * @return new state or NULL, if transition on label not possible
1009  */
1010 static struct GNUNET_REGEX_State *
1011 dfa_move (struct GNUNET_REGEX_State *s, const char label)
1012 {
1013   struct Transition *t;
1014   struct GNUNET_REGEX_State *new_s;
1015
1016   if (NULL == s)
1017     return NULL;
1018
1019   new_s = NULL;
1020
1021   for (t = s->transitions_head; NULL != t; t = t->next)
1022   {
1023     if (label == t->label)
1024     {
1025       new_s = t->to_state;
1026       break;
1027     }
1028   }
1029
1030   return new_s;
1031 }
1032
1033 /**
1034  * Remove all unreachable states from DFA 'a'. Unreachable states are those
1035  * states that are not reachable from the starting state.
1036  *
1037  * @param a DFA automaton
1038  */
1039 static void
1040 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
1041 {
1042   struct GNUNET_REGEX_State *s;
1043   struct GNUNET_REGEX_State *s_next;
1044
1045   // 1. unmark all states
1046   for (s = a->states_head; NULL != s; s = s->next)
1047     s->marked = GNUNET_NO;
1048
1049   // 2. traverse dfa from start state and mark all visited states
1050   automaton_traverse (NULL, a, NULL);
1051
1052   // 3. delete all states that were not visited
1053   for (s = a->states_head; NULL != s; s = s_next)
1054   {
1055     s_next = s->next;
1056     if (GNUNET_NO == s->marked)
1057       automaton_remove_state (a, s);
1058   }
1059 }
1060
1061 /**
1062  * Remove all dead states from the DFA 'a'. Dead states are those states that do
1063  * not transition to any other state but themselfes.
1064  *
1065  * @param a DFA automaton
1066  */
1067 static void
1068 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
1069 {
1070   struct GNUNET_REGEX_State *s;
1071   struct Transition *t;
1072   int dead;
1073
1074   GNUNET_assert (DFA == a->type);
1075
1076   for (s = a->states_head; NULL != s; s = s->next)
1077   {
1078     if (s->accepting)
1079       continue;
1080
1081     dead = 1;
1082     for (t = s->transitions_head; NULL != t; t = t->next)
1083     {
1084       if (NULL != t->to_state && t->to_state != s)
1085       {
1086         dead = 0;
1087         break;
1088       }
1089     }
1090
1091     if (0 == dead)
1092       continue;
1093
1094     // state s is dead, remove it
1095     automaton_remove_state (a, s);
1096   }
1097 }
1098
1099 /**
1100  * Merge all non distinguishable states in the DFA 'a'
1101  *
1102  * @param ctx context
1103  * @param a DFA automaton
1104  */
1105 static void
1106 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
1107                                      struct GNUNET_REGEX_Automaton *a)
1108 {
1109   int i;
1110   int table[a->state_count][a->state_count];
1111   struct GNUNET_REGEX_State *s1;
1112   struct GNUNET_REGEX_State *s2;
1113   struct Transition *t1;
1114   struct Transition *t2;
1115   struct GNUNET_REGEX_State *s1_next;
1116   struct GNUNET_REGEX_State *s2_next;
1117   int change;
1118   int num_equal_edges;
1119
1120   for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
1121        i++, s1 = s1->next)
1122   {
1123     s1->marked = i;
1124   }
1125
1126   // Mark all pairs of accepting/!accepting states
1127   for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1128   {
1129     for (s2 = a->states_head; NULL != s2; s2 = s2->next)
1130     {
1131       table[s1->marked][s2->marked] = 0;
1132
1133       if ((s1->accepting && !s2->accepting) ||
1134           (!s1->accepting && s2->accepting))
1135       {
1136         table[s1->marked][s2->marked] = 1;
1137       }
1138     }
1139   }
1140
1141   // Find all equal states
1142   change = 1;
1143   while (0 != change)
1144   {
1145     change = 0;
1146     for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1147     {
1148       for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
1149       {
1150         if (0 != table[s1->marked][s2->marked])
1151           continue;
1152
1153         num_equal_edges = 0;
1154         for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
1155         {
1156           for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
1157           {
1158             if (t1->label == t2->label)
1159             {
1160               num_equal_edges++;
1161               if (0 != table[t1->to_state->marked][t2->to_state->marked] ||
1162                   0 != table[t2->to_state->marked][t1->to_state->marked])
1163               {
1164                 table[s1->marked][s2->marked] = t1->label != 0 ? t1->label : 1;
1165                 change = 1;
1166               }
1167             }
1168           }
1169         }
1170         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   return dfa;
1917 }
1918
1919 /**
1920  * Free the memory allocated by constructing the GNUNET_REGEX_Automaton data
1921  * structure.
1922  *
1923  * @param a automaton to be destroyed
1924  */
1925 void
1926 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
1927 {
1928   struct GNUNET_REGEX_State *s;
1929   struct GNUNET_REGEX_State *next_state;
1930
1931   if (NULL == a)
1932     return;
1933
1934   for (s = a->states_head; NULL != s;)
1935   {
1936     next_state = s->next;
1937     automaton_destroy_state (s);
1938     s = next_state;
1939   }
1940
1941   GNUNET_free (a);
1942 }
1943
1944 /**
1945  * Save the given automaton as a GraphViz dot file
1946  *
1947  * @param a the automaton to be saved
1948  * @param filename where to save the file
1949  */
1950 void
1951 GNUNET_REGEX_automaton_save_graph (struct GNUNET_REGEX_Automaton *a,
1952                                    const char *filename)
1953 {
1954   struct GNUNET_REGEX_State *s;
1955   struct Transition *ctran;
1956   char *s_acc = NULL;
1957   char *s_tran = NULL;
1958   char *start;
1959   char *end;
1960   FILE *p;
1961
1962   if (NULL == a)
1963   {
1964     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print NFA, was NULL!");
1965     return;
1966   }
1967
1968   if (NULL == filename || strlen (filename) < 1)
1969   {
1970     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No Filename given!");
1971     return;
1972   }
1973
1974   p = fopen (filename, "w");
1975
1976   if (NULL == p)
1977   {
1978     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not open file for writing: %s",
1979                 filename);
1980     return;
1981   }
1982
1983   start = "digraph G {\nrankdir=LR\n";
1984   fwrite (start, strlen (start), 1, p);
1985
1986   for (s = a->states_head; NULL != s; s = s->next)
1987   {
1988     if (s->accepting)
1989     {
1990       GNUNET_asprintf (&s_acc,
1991                        "\"%s\" [shape=doublecircle, color=\"0.%i 0.8 0.95\"];\n",
1992                        s->name, s->scc_id);
1993     }
1994     else
1995     {
1996       GNUNET_asprintf (&s_acc, "\"%s\" [color=\"0.%i 0.8 0.95\"];\n", s->name,
1997                        s->scc_id);
1998     }
1999
2000     if (NULL == s_acc)
2001     {
2002       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print state %s\n",
2003                   s->name);
2004       return;
2005     }
2006     fwrite (s_acc, strlen (s_acc), 1, p);
2007     GNUNET_free (s_acc);
2008     s_acc = NULL;
2009
2010     for (ctran = s->transitions_head; NULL != ctran; ctran = ctran->next)
2011     {
2012       if (NULL == ctran->to_state)
2013       {
2014         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2015                     "Transition from State %i has has no state for transitioning\n",
2016                     s->id);
2017         continue;
2018       }
2019
2020       if (ctran->label == 0)
2021       {
2022         GNUNET_asprintf (&s_tran,
2023                          "\"%s\" -> \"%s\" [label = \"epsilon\", color=\"0.%i 0.8 0.95\"];\n",
2024                          s->name, ctran->to_state->name, s->scc_id);
2025       }
2026       else
2027       {
2028         GNUNET_asprintf (&s_tran,
2029                          "\"%s\" -> \"%s\" [label = \"%c\", color=\"0.%i 0.8 0.95\"];\n",
2030                          s->name, ctran->to_state->name, ctran->label,
2031                          s->scc_id);
2032       }
2033
2034       if (NULL == s_tran)
2035       {
2036         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print state %s\n",
2037                     s->name);
2038         return;
2039       }
2040
2041       fwrite (s_tran, strlen (s_tran), 1, p);
2042       GNUNET_free (s_tran);
2043       s_tran = NULL;
2044     }
2045   }
2046
2047   end = "\n}\n";
2048   fwrite (end, strlen (end), 1, p);
2049   fclose (p);
2050 }
2051
2052 /**
2053  * Evaluates the given string using the given DFA automaton
2054  *
2055  * @param a automaton, type must be DFA
2056  * @param string string that should be evaluated
2057  *
2058  * @return 0 if string matches, non 0 otherwise
2059  */
2060 static int
2061 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2062 {
2063   const char *strp;
2064   struct GNUNET_REGEX_State *s;
2065
2066   if (DFA != a->type)
2067   {
2068     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2069                 "Tried to evaluate DFA, but NFA automaton given");
2070     return -1;
2071   }
2072
2073   s = a->start;
2074
2075   for (strp = string; NULL != strp && *strp; strp++)
2076   {
2077     s = dfa_move (s, *strp);
2078     if (NULL == s)
2079       break;
2080   }
2081
2082   if (NULL != s && s->accepting)
2083     return 0;
2084
2085   return 1;
2086 }
2087
2088 /**
2089  * Evaluates the given string using the given NFA automaton
2090  *
2091  * @param a automaton, type must be NFA
2092  * @param string string that should be evaluated
2093  *
2094  * @return 0 if string matches, non 0 otherwise
2095  */
2096 static int
2097 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2098 {
2099   const char *strp;
2100   struct GNUNET_REGEX_State *s;
2101   struct GNUNET_REGEX_StateSet *sset;
2102   struct GNUNET_REGEX_StateSet *new_sset;
2103   int i;
2104   int result;
2105
2106   if (NFA != a->type)
2107   {
2108     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2109                 "Tried to evaluate NFA, but DFA automaton given");
2110     return -1;
2111   }
2112
2113   result = 1;
2114   strp = string;
2115   sset = nfa_closure_create (a, a->start, 0);
2116
2117   for (strp = string; NULL != strp && *strp; strp++)
2118   {
2119     new_sset = nfa_closure_set_create (a, sset, *strp);
2120     state_set_clear (sset);
2121     sset = nfa_closure_set_create (a, new_sset, 0);
2122     state_set_clear (new_sset);
2123   }
2124
2125   for (i = 0; i < sset->len; i++)
2126   {
2127     s = sset->states[i];
2128     if (NULL != s && s->accepting)
2129     {
2130       result = 0;
2131       break;
2132     }
2133   }
2134
2135   state_set_clear (sset);
2136   return result;
2137 }
2138
2139 /**
2140  * Evaluates the given 'string' against the given compiled regex
2141  *
2142  * @param a automaton
2143  * @param string string to check
2144  *
2145  * @return 0 if string matches, non 0 otherwise
2146  */
2147 int
2148 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
2149 {
2150   int result;
2151
2152   switch (a->type)
2153   {
2154   case DFA:
2155     result = evaluate_dfa (a, string);
2156     break;
2157   case NFA:
2158     result = evaluate_nfa (a, string);
2159     break;
2160   default:
2161     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2162                 "Evaluating regex failed, automaton has no type!\n");
2163     result = GNUNET_SYSERR;
2164     break;
2165   }
2166
2167   return result;
2168 }
2169
2170 /**
2171  * Get the first key for the given 'input_string'. This hashes the first x bits
2172  * of the 'input_strings'.
2173  *
2174  * @param input_string string.
2175  * @param string_len length of the 'input_string'.
2176  * @param key pointer to where to write the hash code.
2177  *
2178  * @return number of bits of 'input_string' that have been consumed
2179  *         to construct the key
2180  */
2181 unsigned int
2182 GNUNET_REGEX_get_first_key (const char *input_string, unsigned int string_len,
2183                             GNUNET_HashCode * key)
2184 {
2185   unsigned int size;
2186
2187   size = string_len < initial_bits ? string_len : initial_bits;
2188
2189   if (NULL == input_string)
2190   {
2191     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
2192     return 0;
2193   }
2194
2195   GNUNET_CRYPTO_hash (input_string, size, key);
2196
2197   return size;
2198 }
2199
2200 /**
2201  * Check if the given 'proof' matches the given 'key'.
2202  *
2203  * @param proof partial regex
2204  * @param key hash
2205  *
2206  * @return GNUNET_OK if the proof is valid for the given key
2207  */
2208 int
2209 GNUNET_REGEX_check_proof (const char *proof, const GNUNET_HashCode * key)
2210 {
2211   return GNUNET_OK;
2212 }
2213
2214 /**
2215  * Iterate over all edges helper function starting from state 's', calling
2216  * iterator on for each edge.
2217  *
2218  * @param s state.
2219  * @param iterator iterator function called for each edge.
2220  * @param iterator_cls closure.
2221  */
2222 static void
2223 iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
2224               void *iterator_cls)
2225 {
2226   struct Transition *t;
2227   struct GNUNET_REGEX_Edge edges[s->transition_count];
2228   unsigned int num_edges;
2229
2230   if (GNUNET_YES != s->marked)
2231   {
2232     s->marked = GNUNET_YES;
2233
2234     num_edges = state_get_edges (s, edges);
2235
2236     iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges, edges);
2237
2238     for (t = s->transitions_head; NULL != t; t = t->next)
2239       iterate_edge (t->to_state, iterator, iterator_cls);
2240   }
2241 }
2242
2243 /**
2244  * Iterate over all edges starting from start state of automaton 'a'. Calling
2245  * iterator for each edge.
2246  *
2247  * @param a automaton.
2248  * @param iterator iterator called for each edge.
2249  * @param iterator_cls closure.
2250  */
2251 void
2252 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2253                                 GNUNET_REGEX_KeyIterator iterator,
2254                                 void *iterator_cls)
2255 {
2256   struct GNUNET_REGEX_State *s;
2257
2258   for (s = a->states_head; NULL != s; s = s->next)
2259     s->marked = GNUNET_NO;
2260
2261   iterate_edge (a->start, iterator, iterator_cls);
2262 }