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