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