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