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