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