optimizations
[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_internal.h"
30
31
32 /**
33  * Constant for how many bits the initial string regex should have.
34  */
35 #define INITIAL_BITS 8
36
37
38 /**
39  * Set of states.
40  */
41 struct GNUNET_REGEX_StateSet
42 {
43   /**
44    * Array of states.
45    */
46   struct GNUNET_REGEX_State **states;
47
48   /**
49    * Length of the 'states' array.
50    */
51   unsigned int len;
52 };
53
54
55 /**
56  * Compare two strings for equality. If either is NULL they are not equal.
57  *
58  * @param str1 first string for comparison.
59  * @param str2 second string for comparison.
60  *
61  * @return 0 if the strings are the same or both NULL, 1 or -1 if not.
62  */
63 static int
64 nullstrcmp (const char *str1, const char *str2)
65 {
66   if ((NULL == str1) != (NULL == str2))
67     return -1;
68   if ((NULL == str1) && (NULL == str2))
69     return 0;
70
71   return strcmp (str1, str2);
72 }
73
74
75 /**
76  * Adds a transition from one state to another on 'label'. Does not add
77  * duplicate states.
78  *
79  * @param ctx context
80  * @param from_state starting state for the transition
81  * @param label transition label
82  * @param to_state state to where the transition should point to
83  */
84 static void
85 state_add_transition (struct GNUNET_REGEX_Context *ctx,
86                       struct GNUNET_REGEX_State *from_state, const char *label,
87                       struct GNUNET_REGEX_State *to_state)
88 {
89   int is_dup;
90   struct GNUNET_REGEX_Transition *t;
91   struct GNUNET_REGEX_Transition *oth;
92
93   if (NULL == from_state)
94   {
95     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
96     return;
97   }
98
99   // Do not add duplicate state transitions
100   is_dup = GNUNET_NO;
101   for (t = from_state->transitions_head; NULL != t; t = t->next)
102   {
103     if (t->to_state == to_state && 0 == nullstrcmp (t->label, label) &&
104         t->from_state == from_state)
105     {
106       is_dup = GNUNET_YES;
107       break;
108     }
109   }
110
111   if (GNUNET_YES == is_dup)
112     return;
113
114   // sort transitions by label
115   for (oth = from_state->transitions_head; NULL != oth; oth = oth->next)
116   {
117     if (0 < nullstrcmp (oth->label, label))
118       break;
119   }
120
121   t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
122   if (NULL != ctx)
123     t->id = ctx->transition_id++;
124   if (NULL != label)
125     t->label = GNUNET_strdup (label);
126   else
127     t->label = NULL;
128   t->to_state = to_state;
129   t->from_state = from_state;
130
131   // Add outgoing transition to 'from_state'
132   from_state->transition_count++;
133   GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head,
134                                       from_state->transitions_tail, oth, t);
135 }
136
137
138 /**
139  * Remove a 'transition' from 'state'.
140  *
141  * @param state state from which the to-be-removed transition originates.
142  * @param transition transition that should be removed from state 'state'.
143  */
144 static void
145 state_remove_transition (struct GNUNET_REGEX_State *state,
146                          struct GNUNET_REGEX_Transition *transition)
147 {
148   if (NULL == state || NULL == transition)
149     return;
150
151   if (transition->from_state != state)
152     return;
153
154   state->transition_count--;
155   GNUNET_CONTAINER_DLL_remove (state->transitions_head, state->transitions_tail,
156                                transition);
157   GNUNET_free_non_null (transition->label);
158   GNUNET_free (transition);
159 }
160
161
162 /**
163  * Compare two states. Used for sorting.
164  *
165  * @param a first state
166  * @param b second state
167  *
168  * @return an integer less than, equal to, or greater than zero
169  *         if the first argument is considered to be respectively
170  *         less than, equal to, or greater than the second.
171  */
172 static int
173 state_compare (const void *a, const void *b)
174 {
175   struct GNUNET_REGEX_State **s1;
176   struct GNUNET_REGEX_State **s2;
177
178   s1 = (struct GNUNET_REGEX_State **) a;
179   s2 = (struct GNUNET_REGEX_State **) b;
180
181   return (*s1)->id - (*s2)->id;
182 }
183
184
185 /**
186  * Get all edges leaving state 's'.
187  *
188  * @param s state.
189  * @param edges all edges leaving 's', expected to be allocated and have enough
190  *        space for s->transitions_count elements.
191  *
192  * @return number of edges.
193  */
194 static unsigned int
195 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
196 {
197   struct GNUNET_REGEX_Transition *t;
198   unsigned int count;
199
200   if (NULL == s)
201     return 0;
202
203   count = 0;
204
205   for (t = s->transitions_head; NULL != t; t = t->next)
206   {
207     if (NULL != t->to_state)
208     {
209       edges[count].label = t->label;
210       edges[count].destination = t->to_state->hash;
211       count++;
212     }
213   }
214   return count;
215 }
216
217
218 /**
219  * Compare to state sets by comparing the id's of the states that are contained
220  * in each set. Both sets are expected to be sorted by id!
221  *
222  * @param sset1 first state set
223  * @param sset2 second state set
224  *
225  * @return an integer less than, equal to, or greater than zero
226  *         if the first argument is considered to be respectively
227  *         less than, equal to, or greater than the second.
228  */
229 static int
230 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
231                    struct GNUNET_REGEX_StateSet *sset2)
232 {
233   int result;
234   unsigned int i;
235
236   if (NULL == sset1 || NULL == sset2)
237     return 1;
238
239   result = sset1->len - sset2->len;
240
241   for (i = 0; i < sset1->len; i++)
242   {
243     if (0 != result)
244       break;
245
246     result = state_compare (&sset1->states[i], &sset2->states[i]);
247   }
248   return result;
249 }
250
251
252 /**
253  * Clears the given StateSet 'set'
254  *
255  * @param set set to be cleared
256  */
257 static void
258 state_set_clear (struct GNUNET_REGEX_StateSet *set)
259 {
260   if (NULL != set)
261   {
262     GNUNET_free_non_null (set->states);
263     GNUNET_free (set);
264   }
265 }
266
267
268 /**
269  * Clears an automaton fragment. Does not destroy the states inside the
270  * automaton.
271  *
272  * @param a automaton to be cleared
273  */
274 static void
275 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
276 {
277   if (NULL == a)
278     return;
279
280   a->start = NULL;
281   a->end = NULL;
282   a->states_head = NULL;
283   a->states_tail = NULL;
284   a->state_count = 0;
285   GNUNET_free (a);
286 }
287
288
289 /**
290  * Frees the memory used by State 's'
291  *
292  * @param s state that should be destroyed
293  */
294 static void
295 automaton_destroy_state (struct GNUNET_REGEX_State *s)
296 {
297   struct GNUNET_REGEX_Transition *t;
298   struct GNUNET_REGEX_Transition *next_t;
299
300   if (NULL == s)
301     return;
302
303   GNUNET_free_non_null (s->name);
304   GNUNET_free_non_null (s->proof);
305
306   for (t = s->transitions_head; NULL != t; t = next_t)
307   {
308     next_t = t->next;
309     GNUNET_CONTAINER_DLL_remove (s->transitions_head, s->transitions_tail, t);
310     GNUNET_free_non_null (t->label);
311     GNUNET_free (t);
312   }
313
314   state_set_clear (s->nfa_set);
315
316   GNUNET_free (s);
317 }
318
319
320 /**
321  * Remove a state from the given automaton 'a'. Always use this function when
322  * altering the states of an automaton. Will also remove all transitions leading
323  * to this state, before destroying it.
324  *
325  * @param a automaton
326  * @param s state to remove
327  */
328 static void
329 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
330                         struct GNUNET_REGEX_State *s)
331 {
332   struct GNUNET_REGEX_State *ss;
333   struct GNUNET_REGEX_State *s_check;
334   struct GNUNET_REGEX_Transition *t_check;
335
336   if (NULL == a || NULL == s)
337     return;
338
339   // remove state
340   ss = s;
341   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
342   a->state_count--;
343
344   // remove all transitions leading to this state
345   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
346   {
347     for (t_check = s_check->transitions_head; NULL != t_check;
348          t_check = t_check->next)
349     {
350       if (t_check->to_state == ss)
351       {
352         GNUNET_CONTAINER_DLL_remove (s_check->transitions_head,
353                                      s_check->transitions_tail, t_check);
354         s_check->transition_count--;
355       }
356     }
357   }
358
359   automaton_destroy_state (ss);
360 }
361
362
363 /**
364  * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
365  * 's2'.
366  *
367  * @param ctx context
368  * @param a automaton
369  * @param s1 first state
370  * @param s2 second state, will be destroyed
371  */
372 static void
373 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
374                         struct GNUNET_REGEX_Automaton *a,
375                         struct GNUNET_REGEX_State *s1,
376                         struct GNUNET_REGEX_State *s2)
377 {
378   struct GNUNET_REGEX_State *s_check;
379   struct GNUNET_REGEX_Transition *t_check;
380   struct GNUNET_REGEX_Transition *t;
381   struct GNUNET_REGEX_Transition *t_next;
382   char *new_name;
383   int is_dup;
384
385   GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
386
387   if (s1 == s2)
388     return;
389
390   // 1. Make all transitions pointing to s2 point to s1, unless this transition
391   // does not already exists, if it already exists remove transition.
392   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
393   {
394     for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next)
395     {
396       t_next = t_check->next;
397
398       if (s2 == t_check->to_state)
399       {
400         is_dup = GNUNET_NO;
401         for (t = t_check->from_state->transitions_head; NULL != t; t = t->next)
402         {
403           if (t->to_state == s1 && 0 == strcmp (t_check->label, t->label))
404             is_dup = GNUNET_YES;
405         }
406         if (GNUNET_NO == is_dup)
407           t_check->to_state = s1;
408         else
409           state_remove_transition (t_check->from_state, t_check);
410       }
411     }
412   }
413
414   // 2. Add all transitions from s2 to sX to s1
415   for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
416   {
417     if (t_check->to_state != s1)
418       state_add_transition (ctx, s1, t_check->label, t_check->to_state);
419   }
420
421   // 3. Rename s1 to {s1,s2}
422   new_name = s1->name;
423   GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
424   GNUNET_free (new_name);
425
426   // remove state
427   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
428   a->state_count--;
429   automaton_destroy_state (s2);
430 }
431
432
433 /**
434  * Add a state to the automaton 'a', always use this function to alter the
435  * states DLL of the automaton.
436  *
437  * @param a automaton to add the state to
438  * @param s state that should be added
439  */
440 static void
441 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
442                      struct GNUNET_REGEX_State *s)
443 {
444   GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
445   a->state_count++;
446 }
447
448
449 /**
450  * Depth-first traversal (DFS) of all states that are reachable from state
451  * 's'. Performs 'action' on each visited state.
452  *
453  * @param s start state.
454  * @param marks an array of size a->state_count to remember which state was
455  *        already visited.
456  * @param count current count of the state.
457  * @param check function that is checked before advancing on each transition
458  *              in the DFS.
459  * @param check_cls closure for check.
460  * @param action action to be performed on each state.
461  * @param action_cls closure for action.
462  */
463 static void
464 automaton_state_traverse (struct GNUNET_REGEX_State *s, int *marks,
465                           unsigned int *count,
466                           GNUNET_REGEX_traverse_check check, void *check_cls,
467                           GNUNET_REGEX_traverse_action action, void *action_cls)
468 {
469   struct GNUNET_REGEX_Transition *t;
470
471   if (GNUNET_YES == marks[s->traversal_id])
472     return;
473
474   marks[s->traversal_id] = GNUNET_YES;
475
476   if (NULL != action)
477     action (action_cls, *count, s);
478
479   (*count)++;
480
481   for (t = s->transitions_head; NULL != t; t = t->next)
482   {
483     if (NULL == check ||
484         (NULL != check && GNUNET_YES == check (check_cls, s, t)))
485     {
486       automaton_state_traverse (t->to_state, marks, count, check, check_cls,
487                                 action, action_cls);
488     }
489   }
490 }
491
492
493 /**
494  * Traverses the given automaton using depth-first-search (DFS) from it's start
495  * state, visiting all reachable states and calling 'action' on each one of
496  * them.
497  *
498  * @param a automaton to be traversed.
499  * @param start start state, pass a->start or NULL to traverse the whole automaton.
500  * @param check function that is checked before advancing on each transition
501  *              in the DFS.
502  * @param check_cls closure for check.
503  * @param action action to be performed on each state.
504  * @param action_cls closure for action
505  */
506 void
507 GNUNET_REGEX_automaton_traverse (const struct GNUNET_REGEX_Automaton *a,
508                                  struct GNUNET_REGEX_State *start,
509                                  GNUNET_REGEX_traverse_check check,
510                                  void *check_cls,
511                                  GNUNET_REGEX_traverse_action action,
512                                  void *action_cls)
513 {
514   unsigned int count;
515   struct GNUNET_REGEX_State *s;
516
517   if (NULL == a || 0 == a->state_count)
518     return;
519
520   int marks[a->state_count];
521
522   for (count = 0, s = a->states_head; NULL != s && count < a->state_count;
523        s = s->next, count++)
524   {
525     s->traversal_id = count;
526     marks[s->traversal_id] = GNUNET_NO;
527   }
528
529   count = 0;
530
531   if (NULL == start)
532     s = a->start;
533   else
534     s = start;
535
536   automaton_state_traverse (s, marks, &count, check, check_cls, action,
537                             action_cls);
538 }
539
540
541 /**
542  * Context for adding strided transitions to a DFA.
543  */
544 struct GNUNET_REGEX_Strided_Context
545 {
546   /**
547    * Length of the strides.
548    */
549   const unsigned int stride;
550
551   /**
552    * Strided transitions DLL. New strided transitions will be stored in this DLL
553    * and afterwards added to the DFA.
554    */
555   struct GNUNET_REGEX_Transition *transitions_head;
556
557   /**
558    * Strided transitions DLL.
559    */
560   struct GNUNET_REGEX_Transition *transitions_tail;
561 };
562
563
564 /**
565  * Recursive helper function to add strides to a DFA.
566  *
567  * @param cls context, contains stride length and strided transitions DLL.
568  * @param depth current depth of the depth-first traversal of the graph.
569  * @param label current label, string that contains all labels on the path from
570  *        'start' to 's'.
571  * @param start start state for the depth-first traversal of the graph.
572  * @param s current state in the depth-first traversal
573  */
574 void
575 add_multi_strides_to_dfa_helper (void *cls, const unsigned int depth,
576                                  char *label, struct GNUNET_REGEX_State *start,
577                                  struct GNUNET_REGEX_State *s)
578 {
579   struct GNUNET_REGEX_Strided_Context *ctx = cls;
580   struct GNUNET_REGEX_Transition *t;
581   char *new_label;
582
583   if (depth == ctx->stride)
584   {
585     t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
586     t->label = GNUNET_strdup (label);
587     t->to_state = s;
588     t->from_state = start;
589     GNUNET_CONTAINER_DLL_insert (ctx->transitions_head, ctx->transitions_tail,
590                                  t);
591   }
592   else
593   {
594     for (t = s->transitions_head; NULL != t; t = t->next)
595     {
596       /* Do not consider self-loops, because it end's up in too many
597        * transitions */
598       if (t->to_state == t->from_state)
599         continue;
600
601       if (NULL != label)
602       {
603         GNUNET_asprintf (&new_label, "%s%s", label, t->label);
604       }
605       else
606         new_label = GNUNET_strdup (t->label);
607
608       add_multi_strides_to_dfa_helper (cls, (depth + 1), new_label, start,
609                                        t->to_state);
610     }
611   }
612   GNUNET_free_non_null (label);
613 }
614
615
616 /**
617  * Function called for each state in the DFA. Starts a traversal of depth set in
618  * context starting from state 's'.
619  *
620  * @param cls context.
621  * @param count not used.
622  * @param s current state.
623  */
624 void
625 add_multi_strides_to_dfa (void *cls, const unsigned int count,
626                           struct GNUNET_REGEX_State *s)
627 {
628   add_multi_strides_to_dfa_helper (cls, 0, NULL, s, s);
629 }
630
631
632 /**
633  * Adds multi-strided transitions to the given 'dfa'.
634  *
635  * @param regex_ctx regex context needed to add transitions to the automaton.
636  * @param dfa DFA to which the multi strided transitions should be added.
637  * @param stride_len length of the strides.
638  */
639 void
640 GNUNET_REGEX_add_multi_strides_to_dfa (struct GNUNET_REGEX_Context *regex_ctx,
641                                        struct GNUNET_REGEX_Automaton *dfa,
642                                        const unsigned int stride_len)
643 {
644   struct GNUNET_REGEX_Strided_Context ctx = { stride_len, NULL, NULL };
645   struct GNUNET_REGEX_State *s;
646   struct GNUNET_REGEX_State *s_next;
647   struct GNUNET_REGEX_Transition *t;
648   struct GNUNET_REGEX_Transition *t_next;
649
650   if (1 > stride_len || GNUNET_YES == dfa->is_multistrided)
651     return;
652
653   // Unmark all states
654   for (s = dfa->states_head; NULL != s; s = s->next)
655     s->marked = GNUNET_NO;
656
657   // Compute the new transitions of given stride_len
658   GNUNET_REGEX_automaton_traverse (dfa, dfa->start, NULL, NULL,
659                                    &add_multi_strides_to_dfa, &ctx);
660
661   // Add all the new transitions to the automaton.
662   for (t = ctx.transitions_head; NULL != t; t = t_next)
663   {
664     t_next = t->next;
665     state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
666     GNUNET_CONTAINER_DLL_remove (ctx.transitions_head, ctx.transitions_tail, t);
667     GNUNET_free_non_null (t->label);
668     GNUNET_free (t);
669   }
670
671   // Remove marked states (including their incoming and outgoing transitions)
672   for (s = dfa->states_head; NULL != s; s = s_next)
673   {
674     s_next = s->next;
675     if (GNUNET_YES == s->marked)
676       automaton_remove_state (dfa, s);
677   }
678
679   // Mark this automaton as multistrided
680   dfa->is_multistrided = GNUNET_YES;
681 }
682
683
684
685 /**
686  * Check if the given string 'str' needs parentheses around it when
687  * using it to generate a regex.
688  *
689  * @param str string
690  *
691  * @return GNUNET_YES if parentheses are needed, GNUNET_NO otherwise
692  */
693 static int
694 needs_parentheses (const char *str)
695 {
696   size_t slen;
697   const char *op;
698   const char *cl;
699   const char *pos;
700   unsigned int cnt;
701
702   if ((NULL == str) || ((slen = strlen (str)) < 2))
703     return GNUNET_NO;
704
705   if ('(' != str[0])
706     return GNUNET_YES;
707   cnt = 1;
708   pos = &str[1];
709   while (cnt > 0)
710   {
711     cl = strchr (pos, ')');
712     if (NULL == cl)
713     {
714       GNUNET_break (0);
715       return GNUNET_YES;
716     }
717     op = strchr (pos, '(');
718     if ((NULL != op) && (op < cl))
719     {
720       cnt++;
721       pos = op + 1;
722       continue;
723     }
724     /* got ')' first */
725     cnt--;
726     pos = cl + 1;
727   }
728   return (*pos == '\0') ? GNUNET_NO : GNUNET_YES;
729 }
730
731
732 /**
733  * Remove parentheses surrounding string 'str'.
734  * Example: "(a)" becomes "a", "(a|b)|(a|c)" stays the same.
735  * You need to GNUNET_free the returned string.
736  *
737  * @param str string, free'd or re-used by this function, can be NULL
738  *
739  * @return string without surrounding parentheses, string 'str' if no preceding
740  *         epsilon could be found, NULL if 'str' was NULL
741  */
742 static char *
743 remove_parentheses (char *str)
744 {
745   size_t slen;
746   const char *pos;
747
748   if ((NULL == str) || ('(' != str[0]) ||
749       (str[(slen = strlen (str)) - 1] != ')'))
750     return str;
751
752   pos = strchr (&str[1], ')');
753   if (pos == &str[slen - 1])
754   {
755     memmove (str, &str[1], slen - 2);
756     str[slen - 2] = '\0';
757   }
758   return str;
759 }
760
761
762 /**
763  * Check if the string 'str' starts with an epsilon (empty string).
764  * Example: "(|a)" is starting with an epsilon.
765  *
766  * @param str string to test
767  *
768  * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')'
769  */
770 static int
771 has_epsilon (const char *str)
772 {
773   return (NULL != str) && ('(' == str[0]) && ('|' == str[1]) &&
774       (')' == str[strlen (str) - 1]);
775 }
776
777
778 /**
779  * Remove an epsilon from the string str. Where epsilon is an empty string
780  * Example: str = "(|a|b|c)", result: "a|b|c"
781  * The returned string needs to be freed.
782  *
783  * @param str string
784  *
785  * @return string without preceding epsilon, string 'str' if no preceding
786  *         epsilon could be found, NULL if 'str' was NULL
787  */
788 static char *
789 remove_epsilon (const char *str)
790 {
791   size_t len;
792
793   if (NULL == str)
794     return NULL;
795   if (('(' == str[0]) && ('|' == str[1]))
796   {
797     len = strlen (str);
798     if (')' == str[len - 1])
799       return GNUNET_strndup (&str[2], len - 3);
800   }
801   return GNUNET_strdup (str);
802 }
803
804
805 /**
806  * Compare 'str1', starting from position 'k',  with whole 'str2'
807  *
808  * @param str1 first string to compare, starting from position 'k'
809  * @param str2 second string for comparison
810  * @param k starting position in 'str1'
811  *
812  * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
813  */
814 static int
815 strkcmp (const char *str1, const char *str2, size_t k)
816 {
817   if ((NULL == str1) || (NULL == str2) || (strlen (str1) < k))
818     return -1;
819   return strcmp (&str1[k], str2);
820 }
821
822
823 /**
824  * Helper function used as 'action' in 'GNUNET_REGEX_automaton_traverse'
825  * function to create the depth-first numbering of the states.
826  *
827  * @param cls states array.
828  * @param count current state counter.
829  * @param s current state.
830  */
831 void
832 number_states (void *cls, const unsigned int count,
833                struct GNUNET_REGEX_State *s)
834 {
835   struct GNUNET_REGEX_State **states = cls;
836
837   s->dfs_id = count;
838   if (NULL != states)
839     states[count] = s;
840 }
841
842
843 /**
844  * Construct the regular expression given the inductive step,
845  * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^*
846  * R^{(k-1)}_{kj}, and simplify the resulting expression saved in R_cur_ij.
847  *
848  * @param R_last_ij value of  $R^{(k-1)_{ij}.
849  * @param R_last_ik value of  $R^{(k-1)_{ik}.
850  * @param R_last_kk value of  $R^{(k-1)_{kk}.
851  * @param R_last_kj value of  $R^{(k-1)_{kj}.
852  * @param R_cur_ij result for this inductive step is saved in R_cur_ij, R_cur_ij
853  *                 is expected to be NULL when called!
854  */
855 static void
856 automaton_create_proofs_simplify (char *R_last_ij, char *R_last_ik,
857                                   char *R_last_kk, char *R_last_kj,
858                                   char **R_cur_ij)
859 {
860   char *R_cur_l;
861   char *R_cur_r;
862   char *temp_a;
863   char *temp_b;
864   char *R_temp_ij;
865   char *R_temp_ik;
866   char *R_temp_kj;
867   char *R_temp_kk;
868
869   int eps_check;
870   int ij_ik_cmp;
871   int ij_kj_cmp;
872
873   int ik_kk_cmp;
874   int kk_kj_cmp;
875   int clean_ik_kk_cmp;
876   int clean_kk_kj_cmp;
877   unsigned int cnt;
878
879   size_t length;
880   size_t length_l;
881   size_t length_r;
882
883   GNUNET_assert (NULL == *R_cur_ij && NULL != R_cur_ij);
884
885   // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
886   // R_last == R^{(k-1)}, R_cur == R^{(k)}
887   // R_cur_ij = R_cur_l | R_cur_r
888   // R_cur_l == R^{(k-1)}_{ij}
889   // R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
890
891   if ((NULL == R_last_ij) && ((NULL == R_last_ik) || (NULL == R_last_kk) ||     /* technically cannot happen, but looks saner */
892                               (NULL == R_last_kj)))
893   {
894     /* R^{(k)}_{ij} = N | N */
895     *R_cur_ij = NULL;
896     return;
897   }
898
899   if ((NULL == R_last_ik) || (NULL == R_last_kk) ||     /* technically cannot happen, but looks saner */
900       (NULL == R_last_kj))
901   {
902     /*  R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */
903     *R_cur_ij = GNUNET_strdup (R_last_ij);
904     return;
905   }
906
907   // $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
908   // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
909
910   R_cur_r = NULL;
911   R_cur_l = NULL;
912
913   // cache results from strcmp, we might need these many times
914   ij_kj_cmp = nullstrcmp (R_last_ij, R_last_kj);
915   ij_ik_cmp = nullstrcmp (R_last_ij, R_last_ik);
916   ik_kk_cmp = nullstrcmp (R_last_ik, R_last_kk);
917   kk_kj_cmp = nullstrcmp (R_last_kk, R_last_kj);
918
919   // Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
920   // as parentheses, so we can better compare the contents
921   R_temp_ik = remove_parentheses (remove_epsilon (R_last_ik));
922   R_temp_kk = remove_parentheses (remove_epsilon (R_last_kk));
923   R_temp_kj = remove_parentheses (remove_epsilon (R_last_kj));
924
925   clean_ik_kk_cmp = nullstrcmp (R_last_ik, R_temp_kk);
926   clean_kk_kj_cmp = nullstrcmp (R_temp_kk, R_last_kj);
927
928   // construct R_cur_l (and, if necessary R_cur_r)
929   if (NULL != R_last_ij)
930   {
931     // Assign R_temp_ij to R_last_ij and remove epsilon as well
932     // as parentheses, so we can better compare the contents
933     R_temp_ij = remove_parentheses (remove_epsilon (R_last_ij));
934
935     if (0 == strcmp (R_temp_ij, R_temp_ik) && 0 == strcmp (R_temp_ik, R_temp_kk)
936         && 0 == strcmp (R_temp_kk, R_temp_kj))
937     {
938       if (0 == strlen (R_temp_ij))
939       {
940         R_cur_r = GNUNET_strdup ("");
941       }
942       else if ((0 == strncmp (R_last_ij, "(|", 2)) ||
943                (0 == strncmp (R_last_ik, "(|", 2) &&
944                 0 == strncmp (R_last_kj, "(|", 2)))
945       {
946         // a|(e|a)a*(e|a) = a*
947         // a|(e|a)(e|a)*(e|a) = a*
948         // (e|a)|aa*a = a*
949         // (e|a)|aa*(e|a) = a*
950         // (e|a)|(e|a)a*a = a*
951         // (e|a)|(e|a)a*(e|a) = a*
952         // (e|a)|(e|a)(e|a)*(e|a) = a*
953         if (GNUNET_YES == needs_parentheses (R_temp_ij))
954           GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_ij);
955         else
956           GNUNET_asprintf (&R_cur_r, "%s*", R_temp_ij);
957       }
958       else
959       {
960         // a|aa*a = a+
961         // a|(e|a)a*a = a+
962         // a|aa*(e|a) = a+
963         // a|(e|a)(e|a)*a = a+
964         // a|a(e|a)*(e|a) = a+
965         if (GNUNET_YES == needs_parentheses (R_temp_ij))
966           GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_ij);
967         else
968           GNUNET_asprintf (&R_cur_r, "%s+", R_temp_ij);
969       }
970     }
971     else if (0 == ij_ik_cmp && 0 == clean_kk_kj_cmp && 0 != clean_ik_kk_cmp)
972     {
973       // a|ab*b = ab*
974       if (strlen (R_last_kk) < 1)
975         R_cur_r = GNUNET_strdup (R_last_ij);
976       else if (GNUNET_YES == needs_parentheses (R_temp_kk))
977         GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
978       else
979         GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_last_kk);
980
981       R_cur_l = NULL;
982     }
983     else if (0 == ij_kj_cmp && 0 == clean_ik_kk_cmp && 0 != clean_kk_kj_cmp)
984     {
985       // a|bb*a = b*a
986       if (strlen (R_last_kk) < 1)
987         R_cur_r = GNUNET_strdup (R_last_kj);
988       else if (GNUNET_YES == needs_parentheses (R_temp_kk))
989         GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
990       else
991         GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
992
993       R_cur_l = NULL;
994     }
995     else if (0 == ij_ik_cmp && 0 == kk_kj_cmp && !has_epsilon (R_last_ij) &&
996              has_epsilon (R_last_kk))
997     {
998       // a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab*
999       if (needs_parentheses (R_temp_kk))
1000         GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
1001       else
1002         GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_temp_kk);
1003
1004       R_cur_l = NULL;
1005     }
1006     else if (0 == ij_kj_cmp && 0 == ik_kk_cmp && !has_epsilon (R_last_ij) &&
1007              has_epsilon (R_last_kk))
1008     {
1009       // a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|...  = b*a
1010       if (needs_parentheses (R_temp_kk))
1011         GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_ij);
1012       else
1013         GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_ij);
1014
1015       R_cur_l = NULL;
1016     }
1017     else
1018     {
1019       temp_a = (NULL == R_last_ij) ? NULL : GNUNET_strdup (R_last_ij);
1020       temp_a = remove_parentheses (temp_a);
1021       R_cur_l = temp_a;
1022     }
1023
1024     GNUNET_free_non_null (R_temp_ij);
1025   }
1026   else
1027   {
1028     // we have no left side
1029     R_cur_l = NULL;
1030   }
1031
1032   // construct R_cur_r, if not already constructed
1033   if (NULL == R_cur_r)
1034   {
1035     length = strlen (R_temp_kk) - strlen (R_last_ik);
1036
1037     // a(ba)*bx = (ab)+x
1038     if (length > 0 && NULL != R_last_kk && 0 < strlen (R_last_kk) &&
1039         NULL != R_last_kj && 0 < strlen (R_last_kj) && NULL != R_last_ik &&
1040         0 < strlen (R_last_ik) && 0 == strkcmp (R_temp_kk, R_last_ik, length) &&
1041         0 == strncmp (R_temp_kk, R_last_kj, length))
1042     {
1043       temp_a = GNUNET_malloc (length + 1);
1044       temp_b = GNUNET_malloc ((strlen (R_last_kj) - length) + 1);
1045
1046       length_l = 0;
1047       length_r = 0;
1048
1049       for (cnt = 0; cnt < strlen (R_last_kj); cnt++)
1050       {
1051         if (cnt < length)
1052         {
1053           temp_a[length_l] = R_last_kj[cnt];
1054           length_l++;
1055         }
1056         else
1057         {
1058           temp_b[length_r] = R_last_kj[cnt];
1059           length_r++;
1060         }
1061       }
1062       temp_a[length_l] = '\0';
1063       temp_b[length_r] = '\0';
1064
1065       // e|(ab)+ = (ab)*
1066       if (NULL != R_cur_l && 0 == strlen (R_cur_l) && 0 == strlen (temp_b))
1067       {
1068         GNUNET_asprintf (&R_cur_r, "(%s%s)*", R_last_ik, temp_a);
1069         GNUNET_free (R_cur_l);
1070         R_cur_l = NULL;
1071       }
1072       else
1073       {
1074         GNUNET_asprintf (&R_cur_r, "(%s%s)+%s", R_last_ik, temp_a, temp_b);
1075       }
1076       GNUNET_free (temp_a);
1077       GNUNET_free (temp_b);
1078     }
1079     else if (0 == strcmp (R_temp_ik, R_temp_kk) &&
1080              0 == strcmp (R_temp_kk, R_temp_kj))
1081     {
1082       // (e|a)a*(e|a) = a*
1083       // (e|a)(e|a)*(e|a) = a*
1084       if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj))
1085       {
1086         if (needs_parentheses (R_temp_kk))
1087           GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_kk);
1088         else
1089           GNUNET_asprintf (&R_cur_r, "%s*", R_temp_kk);
1090       }
1091       // aa*a = a+a
1092       else if (0 == clean_ik_kk_cmp && 0 == clean_kk_kj_cmp &&
1093                !has_epsilon (R_last_ik))
1094       {
1095         if (needs_parentheses (R_temp_kk))
1096           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1097         else
1098           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1099       }
1100       // (e|a)a*a = a+
1101       // aa*(e|a) = a+
1102       // a(e|a)*(e|a) = a+
1103       // (e|a)a*a = a+
1104       else
1105       {
1106         eps_check =
1107             (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
1108              has_epsilon (R_last_kj));
1109
1110         if (eps_check == 1)
1111         {
1112           if (needs_parentheses (R_temp_kk))
1113             GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_kk);
1114           else
1115             GNUNET_asprintf (&R_cur_r, "%s+", R_temp_kk);
1116         }
1117       }
1118     }
1119     // aa*b = a+b
1120     // (e|a)(e|a)*b = a*b
1121     else if (0 == strcmp (R_temp_ik, R_temp_kk))
1122     {
1123       if (has_epsilon (R_last_ik))
1124       {
1125         if (needs_parentheses (R_temp_kk))
1126           GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
1127         else
1128           GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
1129       }
1130       else
1131       {
1132         if (needs_parentheses (R_temp_kk))
1133           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_last_kj);
1134         else
1135           GNUNET_asprintf (&R_cur_r, "%s+%s", R_temp_kk, R_last_kj);
1136       }
1137     }
1138     // ba*a = ba+
1139     // b(e|a)*(e|a) = ba*
1140     else if (0 == strcmp (R_temp_kk, R_temp_kj))
1141     {
1142       if (has_epsilon (R_last_kj))
1143       {
1144         if (needs_parentheses (R_temp_kk))
1145           GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ik, R_temp_kk);
1146         else
1147           GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ik, R_temp_kk);
1148       }
1149       else
1150       {
1151         if (needs_parentheses (R_temp_kk))
1152           GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_last_ik, R_temp_kk);
1153         else
1154           GNUNET_asprintf (&R_cur_r, "%s+%s", R_last_ik, R_temp_kk);
1155       }
1156     }
1157     else
1158     {
1159       if (strlen (R_temp_kk) > 0)
1160       {
1161         if (needs_parentheses (R_temp_kk))
1162         {
1163           GNUNET_asprintf (&R_cur_r, "%s(%s)*%s", R_last_ik, R_temp_kk,
1164                            R_last_kj);
1165         }
1166         else
1167         {
1168           GNUNET_asprintf (&R_cur_r, "%s%s*%s", R_last_ik, R_temp_kk,
1169                            R_last_kj);
1170         }
1171       }
1172       else
1173       {
1174         GNUNET_asprintf (&R_cur_r, "%s%s", R_last_ik, R_last_kj);
1175       }
1176     }
1177   }
1178
1179   GNUNET_free_non_null (R_temp_ik);
1180   GNUNET_free_non_null (R_temp_kk);
1181   GNUNET_free_non_null (R_temp_kj);
1182
1183   if (NULL == R_cur_l && NULL == R_cur_r)
1184   {
1185     *R_cur_ij = NULL;
1186     return;
1187   }
1188
1189   if (NULL != R_cur_l && NULL == R_cur_r)
1190   {
1191     *R_cur_ij = R_cur_l;
1192     return;
1193   }
1194
1195   if (NULL == R_cur_l && NULL != R_cur_r)
1196   {
1197     *R_cur_ij = R_cur_r;
1198     return;
1199   }
1200
1201   if (0 == nullstrcmp (R_cur_l, R_cur_r))
1202   {
1203     *R_cur_ij = R_cur_l;
1204     GNUNET_free (R_cur_r);
1205     return;
1206   }
1207
1208   GNUNET_asprintf (R_cur_ij, "(%s|%s)", R_cur_l, R_cur_r);
1209
1210   GNUNET_free (R_cur_l);
1211   GNUNET_free (R_cur_r);
1212 }
1213
1214
1215 /**
1216  * create proofs for all states in the given automaton. Implementation of the
1217  * algorithm descriped in chapter 3.2.1 of "Automata Theory, Languages, and
1218  * Computation 3rd Edition" by Hopcroft, Motwani and Ullman.
1219  *
1220  * @param a automaton.
1221  */
1222 static void
1223 automaton_create_proofs (struct GNUNET_REGEX_Automaton *a)
1224 {
1225   if (NULL == a)
1226   {
1227     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1228                 "Could not create proofs, automaton was NULL\n");
1229     return;
1230   }
1231
1232   unsigned int n = a->state_count;
1233   struct GNUNET_REGEX_State *states[n];
1234   char *R_last[n][n];
1235   char *R_cur[n][n];
1236   char *temp;
1237   struct GNUNET_REGEX_Transition *t;
1238   char *complete_regex;
1239   unsigned int i;
1240   unsigned int j;
1241   unsigned int k;
1242
1243   /* create depth-first numbering of the states, initializes 'state' */
1244   GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &number_states,
1245                                    states);
1246
1247   for (i = 0; i < n; i++)
1248     GNUNET_assert (NULL != states[i]);
1249
1250   /* Compute regular expressions of length "1" between each pair of states */
1251   for (i = 0; i < n; i++)
1252   {
1253     for (j = 0; j < n; j++)
1254     {
1255       R_cur[i][j] = NULL;
1256       R_last[i][j] = NULL;
1257     }
1258     for (t = states[i]->transitions_head; NULL != t; t = t->next)
1259     {
1260       j = t->to_state->dfs_id;
1261       if (NULL == R_last[i][j])
1262         GNUNET_asprintf (&R_last[i][j], "%s", t->label);
1263       else
1264       {
1265         temp = R_last[i][j];
1266         GNUNET_asprintf (&R_last[i][j], "%s|%s", R_last[i][j], t->label);
1267         GNUNET_free (temp);
1268       }
1269     }
1270     if (NULL == R_last[i][i])
1271       GNUNET_asprintf (&R_last[i][i], "");
1272     else
1273     {
1274       temp = R_last[i][i];
1275       GNUNET_asprintf (&R_last[i][i], "(|%s)", R_last[i][i]);
1276       GNUNET_free (temp);
1277     }
1278   }
1279   for (i = 0; i < n; i++)
1280     for (j = 0; j < n; j++)
1281       if (needs_parentheses (R_last[i][j]))
1282       {
1283         temp = R_last[i][j];
1284         GNUNET_asprintf (&R_last[i][j], "(%s)", R_last[i][j]);
1285         GNUNET_free (temp);
1286       }
1287
1288   /* Compute regular expressions of length "k" between each pair of states per
1289    * induction */
1290   for (k = 0; k < n; k++)
1291   {
1292     for (i = 0; i < n; i++)
1293     {
1294       for (j = 0; j < n; j++)
1295       {
1296         // Basis for the recursion:
1297         // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1298         // R_last == R^{(k-1)}, R_cur == R^{(k)}
1299
1300         // Create R_cur[i][j] and simplify the expression
1301         automaton_create_proofs_simplify (R_last[i][j], R_last[i][k],
1302                                           R_last[k][k], R_last[k][j],
1303                                           &R_cur[i][j]);
1304       }
1305     }
1306
1307     // set R_last = R_cur
1308     for (i = 0; i < n; i++)
1309     {
1310       for (j = 0; j < n; j++)
1311       {
1312         GNUNET_free_non_null (R_last[i][j]);
1313         R_last[i][j] = R_cur[i][j];
1314         R_cur[i][j] = NULL;
1315       }
1316     }
1317   }
1318
1319   // assign proofs and hashes
1320   for (i = 0; i < n; i++)
1321   {
1322     if (NULL != R_last[a->start->dfs_id][i])
1323     {
1324       states[i]->proof = GNUNET_strdup (R_last[a->start->dfs_id][i]);
1325       GNUNET_CRYPTO_hash (states[i]->proof, strlen (states[i]->proof),
1326                           &states[i]->hash);
1327     }
1328   }
1329
1330   // complete regex for whole DFA: union of all pairs (start state/accepting
1331   // state(s)).
1332   complete_regex = NULL;
1333   for (i = 0; i < n; i++)
1334   {
1335     if (states[i]->accepting)
1336     {
1337       if (NULL == complete_regex && 0 < strlen (R_last[a->start->dfs_id][i]))
1338       {
1339         GNUNET_asprintf (&complete_regex, "%s", R_last[a->start->dfs_id][i]);
1340       }
1341       else if (NULL != R_last[a->start->dfs_id][i] &&
1342                0 < strlen (R_last[a->start->dfs_id][i]))
1343       {
1344         temp = complete_regex;
1345         GNUNET_asprintf (&complete_regex, "%s|%s", complete_regex,
1346                          R_last[a->start->dfs_id][i]);
1347         GNUNET_free (temp);
1348       }
1349     }
1350   }
1351   a->canonical_regex = complete_regex;
1352
1353   // cleanup
1354   for (i = 0; i < n; i++)
1355   {
1356     for (j = 0; j < n; j++)
1357       GNUNET_free_non_null (R_last[i][j]);
1358   }
1359 }
1360
1361
1362 /**
1363  * Creates a new DFA state based on a set of NFA states. Needs to be freed using
1364  * automaton_destroy_state.
1365  *
1366  * @param ctx context
1367  * @param nfa_states set of NFA states on which the DFA should be based on
1368  *
1369  * @return new DFA state
1370  */
1371 static struct GNUNET_REGEX_State *
1372 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
1373                   struct GNUNET_REGEX_StateSet *nfa_states)
1374 {
1375   struct GNUNET_REGEX_State *s;
1376   char *name;
1377   int len = 0;
1378   struct GNUNET_REGEX_State *cstate;
1379   struct GNUNET_REGEX_Transition *ctran;
1380   unsigned int i;
1381
1382   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1383   s->id = ctx->state_id++;
1384   s->accepting = 0;
1385   s->marked = GNUNET_NO;
1386   s->name = NULL;
1387   s->scc_id = 0;
1388   s->index = -1;
1389   s->lowlink = -1;
1390   s->contained = 0;
1391   s->proof = NULL;
1392
1393   if (NULL == nfa_states)
1394   {
1395     GNUNET_asprintf (&s->name, "s%i", s->id);
1396     return s;
1397   }
1398
1399   s->nfa_set = nfa_states;
1400
1401   if (nfa_states->len < 1)
1402     return s;
1403
1404   // Create a name based on 'nfa_states'
1405   s->name = GNUNET_malloc (sizeof (char) * 2);
1406   strcat (s->name, "{");
1407   name = NULL;
1408
1409   for (i = 0; i < nfa_states->len; i++)
1410   {
1411     cstate = nfa_states->states[i];
1412     GNUNET_asprintf (&name, "%i,", cstate->id);
1413
1414     if (NULL != name)
1415     {
1416       len = strlen (s->name) + strlen (name) + 1;
1417       s->name = GNUNET_realloc (s->name, len);
1418       strcat (s->name, name);
1419       GNUNET_free (name);
1420       name = NULL;
1421     }
1422
1423     // Add a transition for each distinct label to NULL state
1424     for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
1425     {
1426       if (NULL != ctran->label)
1427         state_add_transition (ctx, s, ctran->label, NULL);
1428     }
1429
1430     // If the nfa_states contain an accepting state, the new dfa state is also
1431     // accepting
1432     if (cstate->accepting)
1433       s->accepting = 1;
1434   }
1435
1436   s->name[strlen (s->name) - 1] = '}';
1437
1438   return s;
1439 }
1440
1441
1442 /**
1443  * Move from the given state 's' to the next state on transition 'str'. Consumes
1444  * as much of the given 'str' as possible (usefull for strided DFAs). On return
1445  * 's' will point to the next state, and the length of the substring used for
1446  * this transition will be returned. If no transition possible 0 is returned and
1447  * 's' points to NULL.
1448  *
1449  * @param s starting state, will point to the next state or NULL (if no
1450  * transition possible)
1451  * @param str edge label to follow (will match longest common prefix)
1452  *
1453  * @return length of the substring comsumed from 'str'
1454  */
1455 static unsigned int
1456 dfa_move (struct GNUNET_REGEX_State **s, const char *str)
1457 {
1458   struct GNUNET_REGEX_Transition *t;
1459   struct GNUNET_REGEX_State *new_s;
1460   unsigned int len;
1461   unsigned int max_len;
1462
1463   if (NULL == s)
1464     return 0;
1465
1466   new_s = NULL;
1467   max_len = 0;
1468   for (t = (*s)->transitions_head; NULL != t; t = t->next)
1469   {
1470     len = strlen (t->label);
1471
1472     if (0 == strncmp (t->label, str, len))
1473     {
1474       if (len >= max_len)
1475       {
1476         max_len = len;
1477         new_s = t->to_state;
1478       }
1479     }
1480   }
1481
1482   *s = new_s;
1483   return max_len;
1484 }
1485
1486 /**
1487  * Set the given state 'marked' to GNUNET_YES. Used by the
1488  * 'dfa_remove_unreachable_states' function to detect unreachable states in the
1489  * automaton.
1490  *
1491  * @param cls closure, not used.
1492  * @param count count, not used.
1493  * @param s state where the marked attribute will be set to GNUNET_YES.
1494  */
1495 void
1496 mark_states (void *cls, const unsigned int count, struct GNUNET_REGEX_State *s)
1497 {
1498   s->marked = GNUNET_YES;
1499 }
1500
1501 /**
1502  * Remove all unreachable states from DFA 'a'. Unreachable states are those
1503  * states that are not reachable from the starting state.
1504  *
1505  * @param a DFA automaton
1506  */
1507 static void
1508 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
1509 {
1510   struct GNUNET_REGEX_State *s;
1511   struct GNUNET_REGEX_State *s_next;
1512
1513   // 1. unmark all states
1514   for (s = a->states_head; NULL != s; s = s->next)
1515     s->marked = GNUNET_NO;
1516
1517   // 2. traverse dfa from start state and mark all visited states
1518   GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &mark_states, NULL);
1519
1520   // 3. delete all states that were not visited
1521   for (s = a->states_head; NULL != s; s = s_next)
1522   {
1523     s_next = s->next;
1524     if (GNUNET_NO == s->marked)
1525       automaton_remove_state (a, s);
1526   }
1527 }
1528
1529
1530 /**
1531  * Remove all dead states from the DFA 'a'. Dead states are those states that do
1532  * not transition to any other state but themselves.
1533  *
1534  * @param a DFA automaton
1535  */
1536 static void
1537 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
1538 {
1539   struct GNUNET_REGEX_State *s;
1540   struct GNUNET_REGEX_Transition *t;
1541   int dead;
1542
1543   GNUNET_assert (DFA == a->type);
1544
1545   for (s = a->states_head; NULL != s; s = s->next)
1546   {
1547     if (s->accepting)
1548       continue;
1549
1550     dead = 1;
1551     for (t = s->transitions_head; NULL != t; t = t->next)
1552     {
1553       if (NULL != t->to_state && t->to_state != s)
1554       {
1555         dead = 0;
1556         break;
1557       }
1558     }
1559
1560     if (0 == dead)
1561       continue;
1562
1563     // state s is dead, remove it
1564     automaton_remove_state (a, s);
1565   }
1566 }
1567
1568
1569 /**
1570  * Merge all non distinguishable states in the DFA 'a'
1571  *
1572  * @param ctx context
1573  * @param a DFA automaton
1574  */
1575 static void
1576 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
1577                                      struct GNUNET_REGEX_Automaton *a)
1578 {
1579   int table[a->state_count][a->state_count];
1580   struct GNUNET_REGEX_State *s1;
1581   struct GNUNET_REGEX_State *s2;
1582   struct GNUNET_REGEX_Transition *t1;
1583   struct GNUNET_REGEX_Transition *t2;
1584   struct GNUNET_REGEX_State *s1_next;
1585   struct GNUNET_REGEX_State *s2_next;
1586   int change;
1587   unsigned int num_equal_edges;
1588   unsigned int i;
1589
1590   for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
1591        i++, s1 = s1->next)
1592   {
1593     s1->marked = i;
1594   }
1595
1596   // Mark all pairs of accepting/!accepting states
1597   for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1598   {
1599     for (s2 = a->states_head; NULL != s2; s2 = s2->next)
1600     {
1601       table[s1->marked][s2->marked] = 0;
1602
1603       if ((s1->accepting && !s2->accepting) ||
1604           (!s1->accepting && s2->accepting))
1605       {
1606         table[s1->marked][s2->marked] = 1;
1607       }
1608     }
1609   }
1610
1611   // Find all equal states
1612   change = 1;
1613   while (0 != change)
1614   {
1615     change = 0;
1616     for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1617     {
1618       for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
1619       {
1620         if (0 != table[s1->marked][s2->marked])
1621           continue;
1622
1623         num_equal_edges = 0;
1624         for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
1625         {
1626           for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
1627           {
1628             if (0 == strcmp (t1->label, t2->label))
1629             {
1630               num_equal_edges++;
1631               if (0 != table[t1->to_state->marked][t2->to_state->marked] ||
1632                   0 != table[t2->to_state->marked][t1->to_state->marked])
1633               {
1634                 table[s1->marked][s2->marked] = 1;
1635                 change = 1;
1636               }
1637             }
1638           }
1639         }
1640         if (num_equal_edges != s1->transition_count ||
1641             num_equal_edges != s2->transition_count)
1642         {
1643           // Make sure ALL edges of possible equal states are the same
1644           table[s1->marked][s2->marked] = -2;
1645         }
1646       }
1647     }
1648   }
1649
1650   // Merge states that are equal
1651   for (s1 = a->states_head; NULL != s1; s1 = s1_next)
1652   {
1653     s1_next = s1->next;
1654     for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
1655     {
1656       s2_next = s2->next;
1657       if (table[s1->marked][s2->marked] == 0)
1658         automaton_merge_states (ctx, a, s1, s2);
1659     }
1660   }
1661 }
1662
1663
1664 /**
1665  * Minimize the given DFA 'a' by removing all unreachable states, removing all
1666  * dead states and merging all non distinguishable states
1667  *
1668  * @param ctx context
1669  * @param a DFA automaton
1670  */
1671 static void
1672 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
1673               struct GNUNET_REGEX_Automaton *a)
1674 {
1675   if (NULL == a)
1676     return;
1677
1678   GNUNET_assert (DFA == a->type);
1679
1680   // 1. remove unreachable states
1681   dfa_remove_unreachable_states (a);
1682
1683   // 2. remove dead states
1684   dfa_remove_dead_states (a);
1685
1686   // 3. Merge nondistinguishable states
1687   dfa_merge_nondistinguishable_states (ctx, a);
1688 }
1689
1690
1691 /**
1692  * Creates a new NFA fragment. Needs to be cleared using
1693  * automaton_fragment_clear.
1694  *
1695  * @param start starting state
1696  * @param end end state
1697  *
1698  * @return new NFA fragment
1699  */
1700 static struct GNUNET_REGEX_Automaton *
1701 nfa_fragment_create (struct GNUNET_REGEX_State *start,
1702                      struct GNUNET_REGEX_State *end)
1703 {
1704   struct GNUNET_REGEX_Automaton *n;
1705
1706   n = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1707
1708   n->type = NFA;
1709   n->start = NULL;
1710   n->end = NULL;
1711   n->state_count = 0;
1712
1713   if (NULL == start || NULL == end)
1714     return n;
1715
1716   automaton_add_state (n, end);
1717   automaton_add_state (n, start);
1718
1719   n->state_count = 2;
1720
1721   n->start = start;
1722   n->end = end;
1723
1724   return n;
1725 }
1726
1727
1728 /**
1729  * Adds a list of states to the given automaton 'n'.
1730  *
1731  * @param n automaton to which the states should be added
1732  * @param states_head head of the DLL of states
1733  * @param states_tail tail of the DLL of states
1734  */
1735 static void
1736 nfa_add_states (struct GNUNET_REGEX_Automaton *n,
1737                 struct GNUNET_REGEX_State *states_head,
1738                 struct GNUNET_REGEX_State *states_tail)
1739 {
1740   struct GNUNET_REGEX_State *s;
1741
1742   if (NULL == n || NULL == states_head)
1743   {
1744     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n");
1745     return;
1746   }
1747
1748   if (NULL == n->states_head)
1749   {
1750     n->states_head = states_head;
1751     n->states_tail = states_tail;
1752     return;
1753   }
1754
1755   if (NULL != states_head)
1756   {
1757     n->states_tail->next = states_head;
1758     n->states_tail = states_tail;
1759   }
1760
1761   for (s = states_head; NULL != s; s = s->next)
1762     n->state_count++;
1763 }
1764
1765
1766 /**
1767  * Creates a new NFA state. Needs to be freed using automaton_destroy_state.
1768  *
1769  * @param ctx context
1770  * @param accepting is it an accepting state or not
1771  *
1772  * @return new NFA state
1773  */
1774 static struct GNUNET_REGEX_State *
1775 nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
1776 {
1777   struct GNUNET_REGEX_State *s;
1778
1779   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1780   s->id = ctx->state_id++;
1781   s->accepting = accepting;
1782   s->marked = GNUNET_NO;
1783   s->contained = 0;
1784   s->index = -1;
1785   s->lowlink = -1;
1786   s->scc_id = 0;
1787   s->name = NULL;
1788   GNUNET_asprintf (&s->name, "s%i", s->id);
1789
1790   return s;
1791 }
1792
1793
1794 /**
1795  * Calculates the NFA closure set for the given state.
1796  *
1797  * @param nfa the NFA containing 's'
1798  * @param s starting point state
1799  * @param label transitioning label on which to base the closure on,
1800  *                pass NULL for epsilon transition
1801  *
1802  * @return sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
1803  */
1804 static struct GNUNET_REGEX_StateSet *
1805 nfa_closure_create (struct GNUNET_REGEX_Automaton *nfa,
1806                     struct GNUNET_REGEX_State *s, const char *label)
1807 {
1808   struct GNUNET_REGEX_StateSet *cls;
1809   struct GNUNET_REGEX_StateSet *cls_check;
1810   struct GNUNET_REGEX_State *clsstate;
1811   struct GNUNET_REGEX_State *currentstate;
1812   struct GNUNET_REGEX_Transition *ctran;
1813
1814   if (NULL == s)
1815     return NULL;
1816
1817   cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1818   cls_check = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1819
1820   for (clsstate = nfa->states_head; NULL != clsstate; clsstate = clsstate->next)
1821     clsstate->contained = 0;
1822
1823   // Add start state to closure only for epsilon closure
1824   if (NULL == label)
1825     GNUNET_array_append (cls->states, cls->len, s);
1826
1827   GNUNET_array_append (cls_check->states, cls_check->len, s);
1828   while (cls_check->len > 0)
1829   {
1830     currentstate = cls_check->states[cls_check->len - 1];
1831     GNUNET_array_grow (cls_check->states, cls_check->len, cls_check->len - 1);
1832
1833     for (ctran = currentstate->transitions_head; NULL != ctran;
1834          ctran = ctran->next)
1835     {
1836       if (NULL != ctran->to_state && 0 == nullstrcmp (label, ctran->label))
1837       {
1838         clsstate = ctran->to_state;
1839
1840         if (NULL != clsstate && 0 == clsstate->contained)
1841         {
1842           GNUNET_array_append (cls->states, cls->len, clsstate);
1843           GNUNET_array_append (cls_check->states, cls_check->len, clsstate);
1844           clsstate->contained = 1;
1845         }
1846       }
1847     }
1848   }
1849   GNUNET_assert (0 == cls_check->len);
1850   GNUNET_free (cls_check);
1851
1852   // sort the states
1853   if (cls->len > 1)
1854     qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1855            state_compare);
1856
1857   return cls;
1858 }
1859
1860
1861 /**
1862  * Calculates the closure set for the given set of states.
1863  *
1864  * @param nfa the NFA containing 's'
1865  * @param states list of states on which to base the closure on
1866  * @param label transitioning label for which to base the closure on,
1867  *                pass NULL for epsilon transition
1868  *
1869  * @return sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
1870  */
1871 static struct GNUNET_REGEX_StateSet *
1872 nfa_closure_set_create (struct GNUNET_REGEX_Automaton *nfa,
1873                         struct GNUNET_REGEX_StateSet *states, const char *label)
1874 {
1875   struct GNUNET_REGEX_State *s;
1876   struct GNUNET_REGEX_StateSet *sset;
1877   struct GNUNET_REGEX_StateSet *cls;
1878   unsigned int i;
1879   unsigned int j;
1880   unsigned int k;
1881   unsigned int contains;
1882
1883   if (NULL == states)
1884     return NULL;
1885
1886   cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1887
1888   for (i = 0; i < states->len; i++)
1889   {
1890     s = states->states[i];
1891     sset = nfa_closure_create (nfa, s, label);
1892
1893     for (j = 0; j < sset->len; j++)
1894     {
1895       contains = 0;
1896       for (k = 0; k < cls->len; k++)
1897       {
1898         if (sset->states[j]->id == cls->states[k]->id)
1899         {
1900           contains = 1;
1901           break;
1902         }
1903       }
1904       if (!contains)
1905         GNUNET_array_append (cls->states, cls->len, sset->states[j]);
1906     }
1907     state_set_clear (sset);
1908   }
1909
1910   if (cls->len > 1)
1911     qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1912            state_compare);
1913
1914   return cls;
1915 }
1916
1917
1918 /**
1919  * Pops two NFA fragments (a, b) from the stack and concatenates them (ab)
1920  *
1921  * @param ctx context
1922  */
1923 static void
1924 nfa_add_concatenation (struct GNUNET_REGEX_Context *ctx)
1925 {
1926   struct GNUNET_REGEX_Automaton *a;
1927   struct GNUNET_REGEX_Automaton *b;
1928   struct GNUNET_REGEX_Automaton *new_nfa;
1929
1930   b = ctx->stack_tail;
1931   GNUNET_assert (NULL != b);
1932   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
1933   a = ctx->stack_tail;
1934   GNUNET_assert (NULL != a);
1935   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1936
1937   state_add_transition (ctx, a->end, NULL, b->start);
1938   a->end->accepting = 0;
1939   b->end->accepting = 1;
1940
1941   new_nfa = nfa_fragment_create (NULL, NULL);
1942   nfa_add_states (new_nfa, a->states_head, a->states_tail);
1943   nfa_add_states (new_nfa, b->states_head, b->states_tail);
1944   new_nfa->start = a->start;
1945   new_nfa->end = b->end;
1946   new_nfa->state_count += a->state_count + b->state_count;
1947   automaton_fragment_clear (a);
1948   automaton_fragment_clear (b);
1949
1950   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
1951 }
1952
1953
1954 /**
1955  * Pops a NFA fragment from the stack (a) and adds a new fragment (a*)
1956  *
1957  * @param ctx context
1958  */
1959 static void
1960 nfa_add_star_op (struct GNUNET_REGEX_Context *ctx)
1961 {
1962   struct GNUNET_REGEX_Automaton *a;
1963   struct GNUNET_REGEX_Automaton *new_nfa;
1964   struct GNUNET_REGEX_State *start;
1965   struct GNUNET_REGEX_State *end;
1966
1967   a = ctx->stack_tail;
1968
1969   if (NULL == a)
1970   {
1971     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1972                 "nfa_add_star_op failed, because there was no element on the stack");
1973     return;
1974   }
1975
1976   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1977
1978   start = nfa_state_create (ctx, 0);
1979   end = nfa_state_create (ctx, 1);
1980
1981   state_add_transition (ctx, start, NULL, a->start);
1982   state_add_transition (ctx, start, NULL, end);
1983   state_add_transition (ctx, a->end, NULL, a->start);
1984   state_add_transition (ctx, a->end, NULL, end);
1985
1986   a->end->accepting = 0;
1987   end->accepting = 1;
1988
1989   new_nfa = nfa_fragment_create (start, end);
1990   nfa_add_states (new_nfa, a->states_head, a->states_tail);
1991   automaton_fragment_clear (a);
1992
1993   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
1994 }
1995
1996
1997 /**
1998  * Pops an NFA fragment (a) from the stack and adds a new fragment (a+)
1999  *
2000  * @param ctx context
2001  */
2002 static void
2003 nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
2004 {
2005   struct GNUNET_REGEX_Automaton *a;
2006
2007   a = ctx->stack_tail;
2008   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2009
2010   state_add_transition (ctx, a->end, NULL, a->start);
2011
2012   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a);
2013 }
2014
2015
2016 /**
2017  * Pops an NFA fragment (a) from the stack and adds a new fragment (a?)
2018  *
2019  * @param ctx context
2020  */
2021 static void
2022 nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
2023 {
2024   struct GNUNET_REGEX_Automaton *a;
2025   struct GNUNET_REGEX_Automaton *new_nfa;
2026   struct GNUNET_REGEX_State *start;
2027   struct GNUNET_REGEX_State *end;
2028
2029   a = ctx->stack_tail;
2030
2031   if (NULL == a)
2032   {
2033     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2034                 "nfa_add_question_op failed, because there was no element on the stack");
2035     return;
2036   }
2037
2038   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2039
2040   start = nfa_state_create (ctx, 0);
2041   end = nfa_state_create (ctx, 1);
2042
2043   state_add_transition (ctx, start, NULL, a->start);
2044   state_add_transition (ctx, start, NULL, end);
2045   state_add_transition (ctx, a->end, NULL, end);
2046
2047   a->end->accepting = 0;
2048
2049   new_nfa = nfa_fragment_create (start, end);
2050   nfa_add_states (new_nfa, a->states_head, a->states_tail);
2051   automaton_fragment_clear (a);
2052
2053   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2054 }
2055
2056
2057 /**
2058  * Pops two NFA fragments (a, b) from the stack and adds a new NFA fragment that
2059  * alternates between a and b (a|b)
2060  *
2061  * @param ctx context
2062  */
2063 static void
2064 nfa_add_alternation (struct GNUNET_REGEX_Context *ctx)
2065 {
2066   struct GNUNET_REGEX_Automaton *a;
2067   struct GNUNET_REGEX_Automaton *b;
2068   struct GNUNET_REGEX_Automaton *new_nfa;
2069   struct GNUNET_REGEX_State *start;
2070   struct GNUNET_REGEX_State *end;
2071
2072   b = ctx->stack_tail;
2073   GNUNET_assert (NULL != b);
2074   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2075   a = ctx->stack_tail;
2076   GNUNET_assert (NULL != a);
2077   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2078
2079   start = nfa_state_create (ctx, 0);
2080   end = nfa_state_create (ctx, 1);
2081   state_add_transition (ctx, start, NULL, a->start);
2082   state_add_transition (ctx, start, NULL, b->start);
2083
2084   state_add_transition (ctx, a->end, NULL, end);
2085   state_add_transition (ctx, b->end, NULL, end);
2086
2087   a->end->accepting = 0;
2088   b->end->accepting = 0;
2089   end->accepting = 1;
2090
2091   new_nfa = nfa_fragment_create (start, end);
2092   nfa_add_states (new_nfa, a->states_head, a->states_tail);
2093   nfa_add_states (new_nfa, b->states_head, b->states_tail);
2094   automaton_fragment_clear (a);
2095   automaton_fragment_clear (b);
2096
2097   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2098 }
2099
2100
2101 /**
2102  * Adds a new nfa fragment to the stack
2103  *
2104  * @param ctx context
2105  * @param label label for nfa transition
2106  */
2107 static void
2108 nfa_add_label (struct GNUNET_REGEX_Context *ctx, const char *label)
2109 {
2110   struct GNUNET_REGEX_Automaton *n;
2111   struct GNUNET_REGEX_State *start;
2112   struct GNUNET_REGEX_State *end;
2113
2114   GNUNET_assert (NULL != ctx);
2115
2116   start = nfa_state_create (ctx, 0);
2117   end = nfa_state_create (ctx, 1);
2118   state_add_transition (ctx, start, label, end);
2119   n = nfa_fragment_create (start, end);
2120   GNUNET_assert (NULL != n);
2121   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n);
2122 }
2123
2124
2125 /**
2126  * Initialize a new context
2127  *
2128  * @param ctx context
2129  */
2130 static void
2131 GNUNET_REGEX_context_init (struct GNUNET_REGEX_Context *ctx)
2132 {
2133   if (NULL == ctx)
2134   {
2135     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!");
2136     return;
2137   }
2138   ctx->state_id = 0;
2139   ctx->transition_id = 0;
2140   ctx->stack_head = NULL;
2141   ctx->stack_tail = NULL;
2142 }
2143
2144
2145 /**
2146  * Construct an NFA by parsing the regex string of length 'len'.
2147  *
2148  * @param regex regular expression string
2149  * @param len length of the string
2150  *
2151  * @return NFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2152  */
2153 struct GNUNET_REGEX_Automaton *
2154 GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
2155 {
2156   struct GNUNET_REGEX_Context ctx;
2157   struct GNUNET_REGEX_Automaton *nfa;
2158   const char *regexp;
2159   char curlabel[2];
2160   char *error_msg;
2161   unsigned int count;
2162   unsigned int altcount;
2163   unsigned int atomcount;
2164   unsigned int pcount;
2165   struct
2166   {
2167     int altcount;
2168     int atomcount;
2169   }     *p;
2170
2171   if (NULL == regex || 0 == strlen (regex) || 0 == len)
2172   {
2173     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2174                 "Could not parse regex. Empty regex string provided.\n");
2175
2176     return NULL;
2177   }
2178
2179   GNUNET_REGEX_context_init (&ctx);
2180
2181   regexp = regex;
2182   curlabel[1] = '\0';
2183   p = NULL;
2184   error_msg = NULL;
2185   altcount = 0;
2186   atomcount = 0;
2187   pcount = 0;
2188
2189   for (count = 0; count < len && *regexp; count++, regexp++)
2190   {
2191     switch (*regexp)
2192     {
2193     case '(':
2194       if (atomcount > 1)
2195       {
2196         --atomcount;
2197         nfa_add_concatenation (&ctx);
2198       }
2199       GNUNET_array_grow (p, pcount, pcount + 1);
2200       p[pcount - 1].altcount = altcount;
2201       p[pcount - 1].atomcount = atomcount;
2202       altcount = 0;
2203       atomcount = 0;
2204       break;
2205     case '|':
2206       if (0 == atomcount)
2207       {
2208         error_msg = "Cannot append '|' to nothing";
2209         goto error;
2210       }
2211       while (--atomcount > 0)
2212         nfa_add_concatenation (&ctx);
2213       altcount++;
2214       break;
2215     case ')':
2216       if (0 == pcount)
2217       {
2218         error_msg = "Missing opening '('";
2219         goto error;
2220       }
2221       if (0 == atomcount)
2222       {
2223         // Ignore this: "()"
2224         pcount--;
2225         altcount = p[pcount].altcount;
2226         atomcount = p[pcount].atomcount;
2227         break;
2228       }
2229       while (--atomcount > 0)
2230         nfa_add_concatenation (&ctx);
2231       for (; altcount > 0; altcount--)
2232         nfa_add_alternation (&ctx);
2233       pcount--;
2234       altcount = p[pcount].altcount;
2235       atomcount = p[pcount].atomcount;
2236       atomcount++;
2237       break;
2238     case '*':
2239       if (atomcount == 0)
2240       {
2241         error_msg = "Cannot append '*' to nothing";
2242         goto error;
2243       }
2244       nfa_add_star_op (&ctx);
2245       break;
2246     case '+':
2247       if (atomcount == 0)
2248       {
2249         error_msg = "Cannot append '+' to nothing";
2250         goto error;
2251       }
2252       nfa_add_plus_op (&ctx);
2253       break;
2254     case '?':
2255       if (atomcount == 0)
2256       {
2257         error_msg = "Cannot append '?' to nothing";
2258         goto error;
2259       }
2260       nfa_add_question_op (&ctx);
2261       break;
2262     default:
2263       if (atomcount > 1)
2264       {
2265         --atomcount;
2266         nfa_add_concatenation (&ctx);
2267       }
2268       curlabel[0] = *regexp;
2269       nfa_add_label (&ctx, curlabel);
2270       atomcount++;
2271       break;
2272     }
2273   }
2274   if (0 != pcount)
2275   {
2276     error_msg = "Unbalanced parenthesis";
2277     goto error;
2278   }
2279   while (--atomcount > 0)
2280     nfa_add_concatenation (&ctx);
2281   for (; altcount > 0; altcount--)
2282     nfa_add_alternation (&ctx);
2283
2284   GNUNET_free_non_null (p);
2285
2286   nfa = ctx.stack_tail;
2287   GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2288
2289   if (NULL != ctx.stack_head)
2290   {
2291     error_msg = "Creating the NFA failed. NFA stack was not empty!";
2292     goto error;
2293   }
2294
2295   /* Remember the regex that was used to generate this NFA */
2296   nfa->regex = GNUNET_strdup (regex);
2297
2298   /* create depth-first numbering of the states for pretty printing */
2299   GNUNET_REGEX_automaton_traverse (nfa, NULL, NULL, NULL, &number_states, NULL);
2300
2301   /* No multistriding added so far */
2302   nfa->is_multistrided = GNUNET_NO;
2303
2304   return nfa;
2305
2306 error:
2307   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: %s\n", regex);
2308   if (NULL != error_msg)
2309     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
2310
2311   GNUNET_free_non_null (p);
2312
2313   while (NULL != (nfa = ctx.stack_head))
2314   {
2315     GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2316     GNUNET_REGEX_automaton_destroy (nfa);
2317   }
2318
2319   return NULL;
2320 }
2321
2322
2323 /**
2324  * Create DFA states based on given 'nfa' and starting with 'dfa_state'.
2325  *
2326  * @param ctx context.
2327  * @param nfa NFA automaton.
2328  * @param dfa DFA automaton.
2329  * @param dfa_state current dfa state, pass epsilon closure of first nfa state
2330  *                  for starting.
2331  */
2332 static void
2333 construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
2334                       struct GNUNET_REGEX_Automaton *nfa,
2335                       struct GNUNET_REGEX_Automaton *dfa,
2336                       struct GNUNET_REGEX_State *dfa_state)
2337 {
2338   struct GNUNET_REGEX_Transition *ctran;
2339   struct GNUNET_REGEX_State *state_iter;
2340   struct GNUNET_REGEX_State *new_dfa_state;
2341   struct GNUNET_REGEX_State *state_contains;
2342   struct GNUNET_REGEX_StateSet *tmp;
2343   struct GNUNET_REGEX_StateSet *nfa_set;
2344
2345   for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next)
2346   {
2347     if (NULL == ctran->label || NULL != ctran->to_state)
2348       continue;
2349
2350     tmp = nfa_closure_set_create (nfa, dfa_state->nfa_set, ctran->label);
2351     nfa_set = nfa_closure_set_create (nfa, tmp, 0);
2352     state_set_clear (tmp);
2353     new_dfa_state = dfa_state_create (ctx, nfa_set);
2354     state_contains = NULL;
2355     for (state_iter = dfa->states_head; NULL != state_iter;
2356          state_iter = state_iter->next)
2357     {
2358       if (0 == state_set_compare (state_iter->nfa_set, new_dfa_state->nfa_set))
2359         state_contains = state_iter;
2360     }
2361
2362     if (NULL == state_contains)
2363     {
2364       automaton_add_state (dfa, new_dfa_state);
2365       ctran->to_state = new_dfa_state;
2366       construct_dfa_states (ctx, nfa, dfa, new_dfa_state);
2367     }
2368     else
2369     {
2370       ctran->to_state = state_contains;
2371       automaton_destroy_state (new_dfa_state);
2372     }
2373   }
2374 }
2375
2376
2377 /**
2378  * Construct DFA for the given 'regex' of length 'len'
2379  *
2380  * @param regex regular expression string
2381  * @param len length of the regular expression
2382  *
2383  * @return DFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2384  */
2385 struct GNUNET_REGEX_Automaton *
2386 GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
2387 {
2388   struct GNUNET_REGEX_Context ctx;
2389   struct GNUNET_REGEX_Automaton *dfa;
2390   struct GNUNET_REGEX_Automaton *nfa;
2391   struct GNUNET_REGEX_StateSet *nfa_start_eps_cls;
2392
2393   GNUNET_REGEX_context_init (&ctx);
2394
2395   // Create NFA
2396   nfa = GNUNET_REGEX_construct_nfa (regex, len);
2397
2398   if (NULL == nfa)
2399   {
2400     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2401                 "Could not create DFA, because NFA creation failed\n");
2402     return NULL;
2403   }
2404
2405   dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
2406   dfa->type = DFA;
2407   dfa->state_count = 0;
2408   dfa->states_head = NULL;
2409   dfa->states_tail = NULL;
2410   dfa->regex = GNUNET_strdup (regex);
2411   dfa->is_multistrided = GNUNET_NO;
2412
2413   // Create DFA start state from epsilon closure
2414   nfa_start_eps_cls = nfa_closure_create (nfa, nfa->start, 0);
2415   dfa->start = dfa_state_create (&ctx, nfa_start_eps_cls);
2416   automaton_add_state (dfa, dfa->start);
2417
2418   construct_dfa_states (&ctx, nfa, dfa, dfa->start);
2419
2420   GNUNET_REGEX_automaton_destroy (nfa);
2421
2422   // Minimize DFA
2423   dfa_minimize (&ctx, dfa);
2424
2425   // Create proofs for all states
2426   automaton_create_proofs (dfa);
2427
2428   // Add strides to DFA
2429   // GNUNET_REGEX_add_multi_strides_to_dfa (&ctx, dfa, 2);
2430
2431   return dfa;
2432 }
2433
2434
2435 /**
2436  * Free the memory allocated by constructing the GNUNET_REGEX_Automaton data
2437  * structure.
2438  *
2439  * @param a automaton to be destroyed
2440  */
2441 void
2442 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
2443 {
2444   struct GNUNET_REGEX_State *s;
2445   struct GNUNET_REGEX_State *next_state;
2446
2447   if (NULL == a)
2448     return;
2449
2450   GNUNET_free_non_null (a->regex);
2451   GNUNET_free_non_null (a->canonical_regex);
2452
2453   for (s = a->states_head; NULL != s;)
2454   {
2455     next_state = s->next;
2456     automaton_destroy_state (s);
2457     s = next_state;
2458   }
2459
2460   GNUNET_free (a);
2461 }
2462
2463
2464 /**
2465  * Evaluates the given string using the given DFA automaton
2466  *
2467  * @param a automaton, type must be DFA
2468  * @param string string that should be evaluated
2469  *
2470  * @return 0 if string matches, non 0 otherwise
2471  */
2472 static int
2473 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2474 {
2475   const char *strp;
2476   struct GNUNET_REGEX_State *s;
2477   unsigned int step_len;
2478
2479   if (DFA != a->type)
2480   {
2481     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2482                 "Tried to evaluate DFA, but NFA automaton given");
2483     return -1;
2484   }
2485
2486   s = a->start;
2487
2488   // If the string is empty but the starting state is accepting, we accept.
2489   if ((NULL == string || 0 == strlen (string)) && s->accepting)
2490     return 0;
2491
2492   for (strp = string; NULL != strp && *strp; strp += step_len)
2493   {
2494     step_len = dfa_move (&s, strp);
2495
2496     if (NULL == s)
2497       break;
2498   }
2499
2500   if (NULL != s && s->accepting)
2501     return 0;
2502
2503   return 1;
2504 }
2505
2506
2507 /**
2508  * Evaluates the given string using the given NFA automaton
2509  *
2510  * @param a automaton, type must be NFA
2511  * @param string string that should be evaluated
2512  *
2513  * @return 0 if string matches, non 0 otherwise
2514  */
2515 static int
2516 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2517 {
2518   const char *strp;
2519   char str[2];
2520   struct GNUNET_REGEX_State *s;
2521   struct GNUNET_REGEX_StateSet *sset;
2522   struct GNUNET_REGEX_StateSet *new_sset;
2523   unsigned int i;
2524   int result;
2525
2526   if (NFA != a->type)
2527   {
2528     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2529                 "Tried to evaluate NFA, but DFA automaton given");
2530     return -1;
2531   }
2532
2533   // If the string is empty but the starting state is accepting, we accept.
2534   if ((NULL == string || 0 == strlen (string)) && a->start->accepting)
2535     return 0;
2536
2537   result = 1;
2538   sset = nfa_closure_create (a, a->start, 0);
2539
2540   str[1] = '\0';
2541   for (strp = string; NULL != strp && *strp; strp++)
2542   {
2543     str[0] = *strp;
2544     new_sset = nfa_closure_set_create (a, sset, str);
2545     state_set_clear (sset);
2546     sset = nfa_closure_set_create (a, new_sset, 0);
2547     state_set_clear (new_sset);
2548   }
2549
2550   for (i = 0; i < sset->len; i++)
2551   {
2552     s = sset->states[i];
2553     if (NULL != s && s->accepting)
2554     {
2555       result = 0;
2556       break;
2557     }
2558   }
2559
2560   state_set_clear (sset);
2561   return result;
2562 }
2563
2564
2565 /**
2566  * Evaluates the given 'string' against the given compiled regex
2567  *
2568  * @param a automaton
2569  * @param string string to check
2570  *
2571  * @return 0 if string matches, non 0 otherwise
2572  */
2573 int
2574 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
2575 {
2576   int result;
2577
2578   switch (a->type)
2579   {
2580   case DFA:
2581     result = evaluate_dfa (a, string);
2582     break;
2583   case NFA:
2584     result = evaluate_nfa (a, string);
2585     break;
2586   default:
2587     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2588                 "Evaluating regex failed, automaton has no type!\n");
2589     result = GNUNET_SYSERR;
2590     break;
2591   }
2592
2593   return result;
2594 }
2595
2596
2597 /**
2598  * Get the canonical regex of the given automaton.
2599  * When constructing the automaton a proof is computed for each state,
2600  * consisting of the regular expression leading to this state. A complete
2601  * regex for the automaton can be computed by combining these proofs.
2602  * As of now this function is only useful for testing.
2603  *
2604  * @param a automaton for which the canonical regex should be returned.
2605  *
2606  * @return
2607  */
2608 const char *
2609 GNUNET_REGEX_get_canonical_regex (struct GNUNET_REGEX_Automaton *a)
2610 {
2611   if (NULL == a)
2612     return NULL;
2613
2614   return a->canonical_regex;
2615 }
2616
2617
2618 /**
2619  * Get the number of transitions that are contained in the given automaton.
2620  *
2621  * @param a automaton for which the number of transitions should be returned.
2622  *
2623  * @return number of transitions in the given automaton.
2624  */
2625 unsigned int
2626 GNUNET_REGEX_get_transition_count (struct GNUNET_REGEX_Automaton *a)
2627 {
2628   unsigned int t_count;
2629   struct GNUNET_REGEX_State *s;
2630
2631   if (NULL == a)
2632     return 0;
2633
2634   for (t_count = 0, s = a->states_head; NULL != s; s = s->next)
2635   {
2636     t_count += s->transition_count;
2637   }
2638
2639   return t_count;
2640 }
2641
2642
2643 /**
2644  * Get the first key for the given 'input_string'. This hashes the first x bits
2645  * of the 'input_string'.
2646  *
2647  * @param input_string string.
2648  * @param string_len length of the 'input_string'.
2649  * @param key pointer to where to write the hash code.
2650  *
2651  * @return number of bits of 'input_string' that have been consumed
2652  *         to construct the key
2653  */
2654 size_t
2655 GNUNET_REGEX_get_first_key (const char *input_string, size_t string_len,
2656                             struct GNUNET_HashCode * key)
2657 {
2658   unsigned int size;
2659
2660   size = string_len < INITIAL_BITS ? string_len : INITIAL_BITS;
2661
2662   if (NULL == input_string)
2663   {
2664     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
2665     return 0;
2666   }
2667
2668   GNUNET_CRYPTO_hash (input_string, size, key);
2669
2670   return size;
2671 }
2672
2673
2674 /**
2675  * Check if the given 'proof' matches the given 'key'.
2676  *
2677  * @param proof partial regex of a state.
2678  * @param key hash of a state.
2679  *
2680  * @return GNUNET_OK if the proof is valid for the given key.
2681  */
2682 int
2683 GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
2684 {
2685   struct GNUNET_HashCode key_check;
2686
2687   if (NULL == proof || NULL == key)
2688   {
2689     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Proof check failed, was NULL.\n");
2690     return GNUNET_NO;
2691   }
2692
2693   GNUNET_CRYPTO_hash (proof, strlen (proof), &key_check);
2694   return (0 ==
2695           GNUNET_CRYPTO_hash_cmp (key, &key_check)) ? GNUNET_OK : GNUNET_NO;
2696 }
2697
2698
2699 /**
2700  * Recursive helper function for iterate_initial_edges. Will call iterator
2701  * function for each initial state.
2702  *
2703  * @param min_len minimum length of the path in the graph.
2704  * @param max_len maximum length of the path in the graph.
2705  * @param cur_len current length of the path already traversed.
2706  * @param consumed_string string consumed by traversing the graph till this state.
2707  * @param state current state of the automaton.
2708  * @param iterator iterator function called for each edge.
2709  * @param iterator_cls closure for the iterator function.
2710  */
2711 static void
2712 iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
2713                       unsigned int cur_len, char *consumed_string,
2714                       struct GNUNET_REGEX_State *state,
2715                       GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
2716 {
2717   unsigned int i;
2718   char *temp;
2719   struct GNUNET_REGEX_Transition *t;
2720   unsigned int num_edges = state->transition_count;
2721   struct GNUNET_REGEX_Edge edges[num_edges];
2722   struct GNUNET_HashCode hash;
2723
2724   if (cur_len > min_len && NULL != consumed_string && cur_len <= max_len)
2725   {
2726     for (i = 0, t = state->transitions_head; NULL != t; t = t->next, i++)
2727     {
2728       edges[i].label = t->label;
2729       edges[i].destination = t->to_state->hash;
2730     }
2731
2732     GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash);
2733     iterator (iterator_cls, &hash, consumed_string, state->accepting, num_edges,
2734               edges);
2735   }
2736
2737   if (cur_len < max_len)
2738   {
2739     cur_len++;
2740     for (t = state->transitions_head; NULL != t; t = t->next)
2741     {
2742       if (NULL != consumed_string)
2743         GNUNET_asprintf (&temp, "%s%s", consumed_string, t->label);
2744       else
2745         GNUNET_asprintf (&temp, "%s", t->label);
2746
2747       iterate_initial_edge (min_len, max_len, cur_len, temp, t->to_state,
2748                             iterator, iterator_cls);
2749       GNUNET_free (temp);
2750     }
2751   }
2752 }
2753
2754
2755 /**
2756  * Iterate over all initial edges that aren't actually part of the automaton.
2757  * This is needed to find the initial states returned by
2758  * GNUNET_REGEX_get_first_key. Iteration will start at the first state that has
2759  * more than one outgoing edge, i.e. the state that branches the graph.
2760  * For example consider the following graph:
2761  * a -> b -> c -> d -> ...
2762  *            \-> e -> ...
2763  *
2764  * This function will not iterate over the edges leading to "c", because these
2765  * will be covered by the iterate_edges function.
2766  *
2767  * @param a the automaton for which the initial states should be computed.
2768  * @param initial_len length of the initial state string.
2769  * @param iterator iterator function called for each edge.
2770  * @param iterator_cls closure for the iterator function.
2771  */
2772 void
2773 iterate_initial_edges (struct GNUNET_REGEX_Automaton *a,
2774                        const unsigned int initial_len,
2775                        GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
2776 {
2777   char *consumed_string;
2778   char *temp;
2779   struct GNUNET_REGEX_State *s;
2780   unsigned int cur_len;
2781
2782   if (1 > initial_len)
2783     return;
2784
2785   consumed_string = NULL;
2786   s = a->start;
2787   cur_len = 0;
2788
2789   if (1 == s->transition_count)
2790   {
2791     do
2792     {
2793       if (NULL != consumed_string)
2794       {
2795         temp = consumed_string;
2796         GNUNET_asprintf (&consumed_string, "%s%s", consumed_string,
2797                          s->transitions_head->label);
2798         GNUNET_free (temp);
2799       }
2800       else
2801         GNUNET_asprintf (&consumed_string, "%s", s->transitions_head->label);
2802
2803       s = s->transitions_head->to_state;
2804       cur_len += strlen (s->transitions_head->label);
2805     }
2806     while (cur_len < initial_len && 1 == s->transition_count);
2807   }
2808
2809   iterate_initial_edge (cur_len, initial_len, cur_len, consumed_string, s,
2810                         iterator, iterator_cls);
2811
2812   GNUNET_free_non_null (consumed_string);
2813 }
2814
2815
2816 /**
2817  * Iterate over all edges helper function starting from state 's', calling
2818  * iterator function for each edge.
2819  *
2820  * @param s state.
2821  * @param iterator iterator function called for each edge.
2822  * @param iterator_cls closure.
2823  */
2824 static void
2825 iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
2826               void *iterator_cls)
2827 {
2828   struct GNUNET_REGEX_Transition *t;
2829   struct GNUNET_REGEX_Edge edges[s->transition_count];
2830   unsigned int num_edges;
2831
2832   if (GNUNET_YES != s->marked)
2833   {
2834     s->marked = GNUNET_YES;
2835
2836     num_edges = state_get_edges (s, edges);
2837
2838     if ((NULL != s->proof && 0 < strlen (s->proof)) || s->accepting)
2839       iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges,
2840                 edges);
2841
2842     for (t = s->transitions_head; NULL != t; t = t->next)
2843       iterate_edge (t->to_state, iterator, iterator_cls);
2844   }
2845 }
2846
2847
2848 /**
2849  * Iterate over all edges starting from start state of automaton 'a'. Calling
2850  * iterator for each edge.
2851  *
2852  * @param a automaton.
2853  * @param iterator iterator called for each edge.
2854  * @param iterator_cls closure.
2855  */
2856 void
2857 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2858                                 GNUNET_REGEX_KeyIterator iterator,
2859                                 void *iterator_cls)
2860 {
2861   struct GNUNET_REGEX_State *s;
2862
2863   for (s = a->states_head; NULL != s; s = s->next)
2864     s->marked = GNUNET_NO;
2865
2866   iterate_initial_edges (a, INITIAL_BITS, iterator, iterator_cls);
2867   iterate_edge (a->start, iterator, iterator_cls);
2868 }