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