2 This file is part of GNUnet
3 (C) 2012 Christian Grothoff (and other contributing authors)
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.
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.
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.
21 * @file src/regex/regex.c
22 * @brief library to create automatons from regular expressions
23 * @author Maximilian Szengel
26 #include "gnunet_container_lib.h"
27 #include "gnunet_crypto_lib.h"
28 #include "gnunet_regex_lib.h"
29 #include "regex_internal.h"
33 * Constant for how many bits the initial string regex should have.
35 #define INITIAL_BITS 8
39 * Context that contains an id counter for states and transitions as well as a
40 * DLL of automatons used as a stack for NFA construction.
42 struct GNUNET_REGEX_Context
47 unsigned int state_id;
50 * Unique transition id.
52 unsigned int transition_id;
55 * DLL of GNUNET_REGEX_Automaton's used as a stack.
57 struct GNUNET_REGEX_Automaton *stack_head;
60 * DLL of GNUNET_REGEX_Automaton's used as a stack.
62 struct GNUNET_REGEX_Automaton *stack_tail;
69 struct GNUNET_REGEX_StateSet
74 struct GNUNET_REGEX_State **states;
77 * Length of the 'states' array.
84 * Debug helper functions
88 * Print all the transitions of state 's'.
90 * @param s state for which to print it's transitions.
93 debug_print_transitions (struct GNUNET_REGEX_State *s);
97 * Print information of the given state 's'.
99 * @param s state for which debug information should be printed.
102 debug_print_state (struct GNUNET_REGEX_State *s)
106 if (NULL == s->proof)
111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
112 "State %i: %s marked: %i accepting: %i scc_id: %i transitions: %i proof: %s\n",
113 s->id, s->name, s->marked, s->accepting, s->scc_id,
114 s->transition_count, proof);
116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transitions:\n");
117 debug_print_transitions (s);
122 * Print debug information for all states contained in the automaton 'a'.
124 * @param a automaton for which debug information of it's states should be printed.
127 debug_print_states (struct GNUNET_REGEX_Automaton *a)
129 struct GNUNET_REGEX_State *s;
131 for (s = a->states_head; NULL != s; s = s->next)
132 debug_print_state (s);
137 * Print debug information for given transition 't'.
139 * @param t transition for which to print debug info.
142 debug_print_transition (struct GNUNET_REGEX_Transition *t)
156 if (NULL == t->to_state)
159 to_state = t->to_state->name;
161 if (NULL == t->from_state)
164 from_state = t->from_state->name;
166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transition %i: From %s on %c to %s\n",
167 t->id, from_state, label, to_state);
172 debug_print_transitions (struct GNUNET_REGEX_State *s)
174 struct GNUNET_REGEX_Transition *t;
176 for (t = s->transitions_head; NULL != t; t = t->next)
177 debug_print_transition (t);
182 * Adds a transition from one state to another on 'label'. Does not add
186 * @param from_state starting state for the transition
187 * @param label transition label
188 * @param to_state state to where the transition should point to
191 state_add_transition (struct GNUNET_REGEX_Context *ctx,
192 struct GNUNET_REGEX_State *from_state, const char label,
193 struct GNUNET_REGEX_State *to_state)
196 struct GNUNET_REGEX_Transition *t;
197 struct GNUNET_REGEX_Transition *oth;
199 if (NULL == from_state)
201 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
205 // Do not add duplicate state transitions
207 for (t = from_state->transitions_head; NULL != t; t = t->next)
209 if (t->to_state == to_state && t->label == label &&
210 t->from_state == from_state)
217 if (GNUNET_YES == is_dup)
220 // sort transitions by label
221 for (oth = from_state->transitions_head; NULL != oth; oth = oth->next)
223 if (oth->label > label)
227 t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
228 t->id = ctx->transition_id++;
230 t->to_state = to_state;
231 t->from_state = from_state;
233 // Add outgoing transition to 'from_state'
234 from_state->transition_count++;
235 GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head,
236 from_state->transitions_tail, oth, t);
241 * Remove a 'transition' from 'state'.
243 * @param state state from which the to-be-removed transition originates.
244 * @param transition transition that should be removed from state 'state'.
247 state_remove_transition (struct GNUNET_REGEX_State *state,
248 struct GNUNET_REGEX_Transition *transition)
250 if (NULL == state || NULL == transition)
253 if (transition->from_state != state)
256 state->transition_count--;
257 GNUNET_CONTAINER_DLL_remove (state->transitions_head, state->transitions_tail,
259 GNUNET_free (transition);
264 * Compare two states. Used for sorting.
266 * @param a first state
267 * @param b second state
269 * @return an integer less than, equal to, or greater than zero
270 * if the first argument is considered to be respectively
271 * less than, equal to, or greater than the second.
274 state_compare (const void *a, const void *b)
276 struct GNUNET_REGEX_State **s1;
277 struct GNUNET_REGEX_State **s2;
279 s1 = (struct GNUNET_REGEX_State **) a;
280 s2 = (struct GNUNET_REGEX_State **) b;
282 return (*s1)->id - (*s2)->id;
287 * Get all edges leaving state 's'.
290 * @param edges all edges leaving 's', expected to be allocated and have enough
291 * space for s->transitions_count elements.
293 * @return number of edges.
296 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
298 struct GNUNET_REGEX_Transition *t;
306 for (t = s->transitions_head; NULL != t; t = t->next)
308 if (NULL != t->to_state)
310 edges[count].label = &t->label;
311 edges[count].destination = t->to_state->hash;
320 * Compare to state sets by comparing the id's of the states that are contained
321 * in each set. Both sets are expected to be sorted by id!
323 * @param sset1 first state set
324 * @param sset2 second state set
326 * @return an integer less than, equal to, or greater than zero
327 * if the first argument is considered to be respectively
328 * less than, equal to, or greater than the second.
331 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
332 struct GNUNET_REGEX_StateSet *sset2)
337 if (NULL == sset1 || NULL == sset2)
340 result = sset1->len - sset2->len;
342 for (i = 0; i < sset1->len; i++)
347 result = state_compare (&sset1->states[i], &sset2->states[i]);
354 * Clears the given StateSet 'set'
356 * @param set set to be cleared
359 state_set_clear (struct GNUNET_REGEX_StateSet *set)
363 GNUNET_free_non_null (set->states);
370 * Clears an automaton fragment. Does not destroy the states inside the
373 * @param a automaton to be cleared
376 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
383 a->states_head = NULL;
384 a->states_tail = NULL;
391 * Frees the memory used by State 's'
393 * @param s state that should be destroyed
396 automaton_destroy_state (struct GNUNET_REGEX_State *s)
398 struct GNUNET_REGEX_Transition *t;
399 struct GNUNET_REGEX_Transition *next_t;
404 GNUNET_free_non_null (s->name);
405 GNUNET_free_non_null (s->proof);
407 for (t = s->transitions_head; NULL != t; t = next_t)
410 GNUNET_CONTAINER_DLL_remove (s->transitions_head, s->transitions_tail, t);
414 state_set_clear (s->nfa_set);
421 * Remove a state from the given automaton 'a'. Always use this function when
422 * altering the states of an automaton. Will also remove all transitions leading
423 * to this state, before destroying it.
426 * @param s state to remove
429 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
430 struct GNUNET_REGEX_State *s)
432 struct GNUNET_REGEX_State *ss;
433 struct GNUNET_REGEX_State *s_check;
434 struct GNUNET_REGEX_Transition *t_check;
436 if (NULL == a || NULL == s)
441 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
444 // remove all transitions leading to this state
445 for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
447 for (t_check = s_check->transitions_head; NULL != t_check;
448 t_check = t_check->next)
450 if (t_check->to_state == ss)
452 GNUNET_CONTAINER_DLL_remove (s_check->transitions_head,
453 s_check->transitions_tail, t_check);
454 s_check->transition_count--;
459 automaton_destroy_state (ss);
464 * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
469 * @param s1 first state
470 * @param s2 second state, will be destroyed
473 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
474 struct GNUNET_REGEX_Automaton *a,
475 struct GNUNET_REGEX_State *s1,
476 struct GNUNET_REGEX_State *s2)
478 struct GNUNET_REGEX_State *s_check;
479 struct GNUNET_REGEX_Transition *t_check;
480 struct GNUNET_REGEX_Transition *t;
481 struct GNUNET_REGEX_Transition *t_next;
485 GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
490 // 1. Make all transitions pointing to s2 point to s1, unless this transition
491 // does not already exists, if it already exists remove transition.
492 for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
494 for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next)
496 t_next = t_check->next;
498 if (s2 == t_check->to_state)
501 for (t = t_check->from_state->transitions_head; NULL != t; t = t->next)
503 if (t->to_state == s1 && t_check->label == t->label)
506 if (GNUNET_NO == is_dup)
507 t_check->to_state = s1;
509 state_remove_transition (t_check->from_state, t_check);
514 // 2. Add all transitions from s2 to sX to s1
515 for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
517 if (t_check->to_state != s1)
518 state_add_transition (ctx, s1, t_check->label, t_check->to_state);
521 // 3. Rename s1 to {s1,s2}
523 GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
524 GNUNET_free (new_name);
527 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
529 automaton_destroy_state (s2);
534 * Add a state to the automaton 'a', always use this function to alter the
535 * states DLL of the automaton.
537 * @param a automaton to add the state to
538 * @param s state that should be added
541 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
542 struct GNUNET_REGEX_State *s)
544 GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
550 * Depth-first traversal of all states that are reachable from state 's'. Expects the states to
551 * be unmarked (s->marked == GNUNET_NO). Performs 'action' on each visited
554 * @param s start state.
555 * @param count current count of the state.
556 * @param action action to be performed on each state.
557 * @param action_cls closure for action
560 automaton_state_traverse (struct GNUNET_REGEX_State *s, unsigned int *count,
561 GNUNET_REGEX_traverse_action action, void *action_cls)
563 struct GNUNET_REGEX_Transition *t;
565 if (GNUNET_NO != s->marked)
567 s->marked = GNUNET_YES;
569 action (action_cls, *count, s);
571 for (t = s->transitions_head; NULL != t; t = t->next)
572 automaton_state_traverse (t->to_state, count, action, action_cls);
577 * Traverses the given automaton from it's start state, visiting all reachable
578 * states and calling 'action' on each one of them.
580 * @param a automaton.
581 * @param action action to be performed on each state.
582 * @param action_cls closure for action
585 GNUNET_REGEX_automaton_traverse (struct GNUNET_REGEX_Automaton *a,
586 GNUNET_REGEX_traverse_action action,
590 struct GNUNET_REGEX_State *s;
592 for (s = a->states_head; NULL != s; s = s->next)
593 s->marked = GNUNET_NO;
595 automaton_state_traverse (a->start, &count, action, action_cls);
600 * Check if the given string 'str' needs parentheses around it when
601 * using it to generate a regex.
605 * @return GNUNET_YES if parentheses are needed, GNUNET_NO otherwise
608 needs_parentheses (const char *str)
616 if ((NULL == str) || ((slen = strlen (str)) < 2))
625 cl = strchr (pos, ')');
631 op = strchr (pos, '(');
632 if ((NULL != op) && (op < cl))
642 return (*pos == '\0') ? GNUNET_NO : GNUNET_YES;
647 * Remove parentheses surrounding string 'str'.
648 * Example: "(a)" becomes "a", "(a|b)|(a|c)" stays the same.
649 * You need to GNUNET_free the returned string.
651 * @param str string, free'd or re-used by this function, can be NULL
653 * @return string without surrounding parentheses, string 'str' if no preceding
654 * epsilon could be found, NULL if 'str' was NULL
657 remove_parentheses (char *str)
662 if ((NULL == str) || ('(' != str[0]) ||
663 (str[(slen = strlen (str)) - 1] != ')'))
666 pos = strchr (&str[1], ')');
667 if (pos == &str[slen - 1])
669 memmove (str, &str[1], slen - 2);
670 str[slen - 2] = '\0';
677 * Check if the string 'str' starts with an epsilon (empty string).
678 * Example: "(|a)" is starting with an epsilon.
680 * @param str string to test
682 * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')'
685 has_epsilon (const char *str)
687 return (NULL != str) && ('(' == str[0]) && ('|' == str[1]) &&
688 (')' == str[strlen (str) - 1]);
693 * Remove an epsilon from the string str. Where epsilon is an empty string
694 * Example: str = "(|a|b|c)", result: "a|b|c"
695 * The returned string needs to be freed.
699 * @return string without preceding epsilon, string 'str' if no preceding epsilon
700 * could be found, NULL if 'str' was NULL
703 remove_epsilon (const char *str)
709 if (('(' == str[0]) && ('|' == str[1]))
712 if (')' == str[len - 1])
713 return GNUNET_strndup (&str[2], len - 3);
715 return GNUNET_strdup (str);
720 * Compare 'str1', starting from position 'k', with whole 'str2'
722 * @param str1 first string to compare, starting from position 'k'
723 * @param str2 second string for comparison
724 * @param k starting position in 'str1'
726 * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
729 strkcmp (const char *str1, const char *str2, size_t k)
731 if ((NULL == str1) || (NULL == str2) || (strlen (str1) < k))
733 return strcmp (&str1[k], str2);
738 * Compare two strings for equality. If either is NULL (or if both are
739 * NULL), they are not equal.
741 * @param str1 first string for comparison.
742 * @param str2 second string for comparison.
744 * @return 0 if the strings are the same, 1 or -1 if not
747 nullstrcmp (const char *str1, const char *str2)
749 if ((NULL == str1) || (NULL == str2))
751 return strcmp (str1, str2);
756 * Helper function used as 'action' in 'GNUNET_REGEX_automaton_traverse' function to create
757 * the depth-first numbering of the states.
759 * @param cls states array.
760 * @param count current state counter.
761 * @param s current state.
764 number_states (void *cls, unsigned int count, struct GNUNET_REGEX_State *s)
766 struct GNUNET_REGEX_State **states = cls;
774 * Construct the regular expression given the inductive step,
775 * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^*
776 * R^{(k-1)}_{kj}, and simplify the resulting expression saved in R_cur_ij.
778 * @param R_last_ij value of $R^{(k-1)_{ij}.
779 * @param R_last_ik value of $R^{(k-1)_{ik}.
780 * @param R_last_kk value of $R^{(k-1)_{kk}.
781 * @param R_last_kj value of $R^{(k-1)_{kj}.
782 * @param R_cur_ij result for this inductive step is saved in R_cur_ij, R_cur_ij
783 * is expected to be NULL when called!
786 automaton_create_proofs_simplify (char *R_last_ij, char *R_last_ik,
787 char *R_last_kk, char *R_last_kj,
813 GNUNET_assert (NULL == *R_cur_ij && NULL != R_cur_ij);
815 // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
816 // R_last == R^{(k-1)}, R_cur == R^{(k)}
817 // R_cur_ij = R_cur_l | R_cur_r
818 // R_cur_l == R^{(k-1)}_{ij}
819 // R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
821 if ((NULL == R_last_ij) && ((NULL == R_last_ik) || (NULL == R_last_kk) || /* technically cannot happen, but looks saner */
822 (NULL == R_last_kj)))
824 /* R^{(k)}_{ij} = N | N */
829 if ((NULL == R_last_ik) || (NULL == R_last_kk) || /* technically cannot happen, but looks saner */
832 /* R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */
833 *R_cur_ij = GNUNET_strdup (R_last_ij);
837 // $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
838 // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
843 // cache results from strcmp, we might need these many times
844 ij_kj_cmp = nullstrcmp (R_last_ij, R_last_kj);
845 ij_ik_cmp = nullstrcmp (R_last_ij, R_last_ik);
846 ik_kk_cmp = nullstrcmp (R_last_ik, R_last_kk);
847 kk_kj_cmp = nullstrcmp (R_last_kk, R_last_kj);
849 // Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
850 // as parentheses, so we can better compare the contents
851 R_temp_ik = remove_parentheses (remove_epsilon (R_last_ik));
852 R_temp_kk = remove_parentheses (remove_epsilon (R_last_kk));
853 R_temp_kj = remove_parentheses (remove_epsilon (R_last_kj));
855 clean_ik_kk_cmp = nullstrcmp (R_last_ik, R_temp_kk);
856 clean_kk_kj_cmp = nullstrcmp (R_temp_kk, R_last_kj);
858 // construct R_cur_l (and, if necessary R_cur_r)
859 if (NULL != R_last_ij)
861 // Assign R_temp_ij to R_last_ij and remove epsilon as well
862 // as parentheses, so we can better compare the contents
863 R_temp_ij = remove_parentheses (remove_epsilon (R_last_ij));
865 if (0 == strcmp (R_temp_ij, R_temp_ik) && 0 == strcmp (R_temp_ik, R_temp_kk)
866 && 0 == strcmp (R_temp_kk, R_temp_kj))
868 if (0 == strlen (R_temp_ij))
870 R_cur_r = GNUNET_strdup ("");
872 else if ((0 == strncmp (R_last_ij, "(|", 2)) ||
873 (0 == strncmp (R_last_ik, "(|", 2) &&
874 0 == strncmp (R_last_kj, "(|", 2)))
876 // a|(e|a)a*(e|a) = a*
877 // a|(e|a)(e|a)*(e|a) = a*
879 // (e|a)|aa*(e|a) = a*
880 // (e|a)|(e|a)a*a = a*
881 // (e|a)|(e|a)a*(e|a) = a*
882 // (e|a)|(e|a)(e|a)*(e|a) = a*
883 if (GNUNET_YES == needs_parentheses (R_temp_ij))
884 GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_ij);
886 GNUNET_asprintf (&R_cur_r, "%s*", R_temp_ij);
893 // a|(e|a)(e|a)*a = a+
894 // a|a(e|a)*(e|a) = a+
895 if (GNUNET_YES == needs_parentheses (R_temp_ij))
896 GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_ij);
898 GNUNET_asprintf (&R_cur_r, "%s+", R_temp_ij);
901 else if (0 == ij_ik_cmp && 0 == clean_kk_kj_cmp && 0 != clean_ik_kk_cmp)
904 if (strlen (R_last_kk) < 1)
905 R_cur_r = GNUNET_strdup (R_last_ij);
906 else if (GNUNET_YES == needs_parentheses (R_temp_kk))
907 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
909 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_last_kk);
913 else if (0 == ij_kj_cmp && 0 == clean_ik_kk_cmp && 0 != clean_kk_kj_cmp)
916 if (strlen (R_last_kk) < 1)
917 R_cur_r = GNUNET_strdup (R_last_kj);
918 else if (GNUNET_YES == needs_parentheses (R_temp_kk))
919 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
921 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
925 else if (0 == ij_ik_cmp && 0 == kk_kj_cmp && !has_epsilon (R_last_ij) &&
926 has_epsilon (R_last_kk))
928 // a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab*
929 if (needs_parentheses (R_temp_kk))
930 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
932 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_temp_kk);
936 else if (0 == ij_kj_cmp && 0 == ik_kk_cmp && !has_epsilon (R_last_ij) &&
937 has_epsilon (R_last_kk))
939 // a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|... = b*a
940 if (needs_parentheses (R_temp_kk))
941 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_ij);
943 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_ij);
949 temp_a = (NULL == R_last_ij) ? NULL : GNUNET_strdup (R_last_ij);
950 temp_a = remove_parentheses (temp_a);
954 GNUNET_free_non_null (R_temp_ij);
958 // we have no left side
962 // construct R_cur_r, if not already constructed
965 length = strlen (R_temp_kk) - strlen (R_last_ik);
968 if (length > 0 && NULL != R_last_kk && 0 < strlen (R_last_kk) &&
969 NULL != R_last_kj && 0 < strlen (R_last_kj) && NULL != R_last_ik &&
970 0 < strlen (R_last_ik) && 0 == strkcmp (R_temp_kk, R_last_ik, length) &&
971 0 == strncmp (R_temp_kk, R_last_kj, length))
973 temp_a = GNUNET_malloc (length + 1);
974 temp_b = GNUNET_malloc ((strlen (R_last_kj) - length) + 1);
979 for (cnt = 0; cnt < strlen (R_last_kj); cnt++)
983 temp_a[length_l] = R_last_kj[cnt];
988 temp_b[length_r] = R_last_kj[cnt];
992 temp_a[length_l] = '\0';
993 temp_b[length_r] = '\0';
996 if (NULL != R_cur_l && 0 == strlen (R_cur_l) && 0 == strlen (temp_b))
998 GNUNET_asprintf (&R_cur_r, "(%s%s)*", R_last_ik, temp_a);
999 GNUNET_free (R_cur_l);
1004 GNUNET_asprintf (&R_cur_r, "(%s%s)+%s", R_last_ik, temp_a, temp_b);
1006 GNUNET_free (temp_a);
1007 GNUNET_free (temp_b);
1009 else if (0 == strcmp (R_temp_ik, R_temp_kk) &&
1010 0 == strcmp (R_temp_kk, R_temp_kj))
1012 // (e|a)a*(e|a) = a*
1013 // (e|a)(e|a)*(e|a) = a*
1014 if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj))
1016 if (needs_parentheses (R_temp_kk))
1017 GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_kk);
1019 GNUNET_asprintf (&R_cur_r, "%s*", R_temp_kk);
1022 else if (0 == clean_ik_kk_cmp && 0 == clean_kk_kj_cmp &&
1023 !has_epsilon (R_last_ik))
1025 if (needs_parentheses (R_temp_kk))
1026 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1028 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1032 // a(e|a)*(e|a) = a+
1037 (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
1038 has_epsilon (R_last_kj));
1042 if (needs_parentheses (R_temp_kk))
1043 GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_kk);
1045 GNUNET_asprintf (&R_cur_r, "%s+", R_temp_kk);
1050 // (e|a)(e|a)*b = a*b
1051 else if (0 == strcmp (R_temp_ik, R_temp_kk))
1053 if (has_epsilon (R_last_ik))
1055 if (needs_parentheses (R_temp_kk))
1056 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
1058 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
1062 if (needs_parentheses (R_temp_kk))
1063 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_last_kj);
1065 GNUNET_asprintf (&R_cur_r, "%s+%s", R_temp_kk, R_last_kj);
1069 // b(e|a)*(e|a) = ba*
1070 else if (0 == strcmp (R_temp_kk, R_temp_kj))
1072 if (has_epsilon (R_last_kj))
1074 if (needs_parentheses (R_temp_kk))
1075 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ik, R_temp_kk);
1077 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ik, R_temp_kk);
1081 if (needs_parentheses (R_temp_kk))
1082 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_last_ik, R_temp_kk);
1084 GNUNET_asprintf (&R_cur_r, "%s+%s", R_last_ik, R_temp_kk);
1089 if (strlen (R_temp_kk) > 0)
1091 if (needs_parentheses (R_temp_kk))
1093 GNUNET_asprintf (&R_cur_r, "%s(%s)*%s", R_last_ik, R_temp_kk,
1098 GNUNET_asprintf (&R_cur_r, "%s%s*%s", R_last_ik, R_temp_kk,
1104 GNUNET_asprintf (&R_cur_r, "%s%s", R_last_ik, R_last_kj);
1109 GNUNET_free_non_null (R_temp_ik);
1110 GNUNET_free_non_null (R_temp_kk);
1111 GNUNET_free_non_null (R_temp_kj);
1113 if (NULL == R_cur_l && NULL == R_cur_r)
1119 if (NULL != R_cur_l && NULL == R_cur_r)
1121 *R_cur_ij = R_cur_l;
1125 if (NULL == R_cur_l && NULL != R_cur_r)
1127 *R_cur_ij = R_cur_r;
1131 if (0 == nullstrcmp (R_cur_l, R_cur_r))
1133 *R_cur_ij = R_cur_l;
1134 GNUNET_free (R_cur_r);
1138 GNUNET_asprintf (R_cur_ij, "(%s|%s)", R_cur_l, R_cur_r);
1140 GNUNET_free (R_cur_l);
1141 GNUNET_free (R_cur_r);
1146 * create proofs for all states in the given automaton. Implementation of the
1147 * algorithm descriped in chapter 3.2.1 of "Automata Theory, Languages, and
1148 * Computation 3rd Edition" by Hopcroft, Motwani and Ullman.
1150 * @param a automaton.
1153 automaton_create_proofs (struct GNUNET_REGEX_Automaton *a)
1155 unsigned int n = a->state_count;
1156 struct GNUNET_REGEX_State *states[n];
1160 struct GNUNET_REGEX_Transition *t;
1161 char *complete_regex;
1167 /* create depth-first numbering of the states, initializes 'state' */
1168 GNUNET_REGEX_automaton_traverse (a, &number_states, states);
1170 /* Compute regular expressions of length "1" between each pair of states */
1171 for (i = 0; i < n; i++)
1173 for (j = 0; j < n; j++)
1176 R_last[i][j] = NULL;
1178 for (t = states[i]->transitions_head; NULL != t; t = t->next)
1180 j = t->to_state->proof_id;
1181 if (NULL == R_last[i][j])
1182 GNUNET_asprintf (&R_last[i][j], "%c", t->label);
1185 temp = R_last[i][j];
1186 GNUNET_asprintf (&R_last[i][j], "%s|%c", R_last[i][j], t->label);
1190 if (NULL == R_last[i][i])
1191 GNUNET_asprintf (&R_last[i][i], "");
1194 temp = R_last[i][i];
1195 GNUNET_asprintf (&R_last[i][i], "(|%s)", R_last[i][i]);
1199 for (i = 0; i < n; i++)
1200 for (j = 0; j < n; j++)
1201 if (needs_parentheses (R_last[i][j]))
1203 temp = R_last[i][j];
1204 GNUNET_asprintf (&R_last[i][j], "(%s)", R_last[i][j]);
1208 /* Compute regular expressions of length "k" between each pair of states per induction */
1209 for (k = 0; k < n; k++)
1211 for (i = 0; i < n; i++)
1213 for (j = 0; j < n; j++)
1215 // Basis for the recursion:
1216 // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1217 // R_last == R^{(k-1)}, R_cur == R^{(k)}
1219 // Create R_cur[i][j] and simplify the expression
1220 automaton_create_proofs_simplify (R_last[i][j], R_last[i][k],
1221 R_last[k][k], R_last[k][j],
1226 // set R_last = R_cur
1227 for (i = 0; i < n; i++)
1229 for (j = 0; j < n; j++)
1231 GNUNET_free_non_null (R_last[i][j]);
1232 R_last[i][j] = R_cur[i][j];
1238 // assign proofs and hashes
1239 for (i = 0; i < n; i++)
1241 if (NULL != R_last[a->start->proof_id][i])
1243 states[i]->proof = GNUNET_strdup (R_last[a->start->proof_id][i]);
1244 GNUNET_CRYPTO_hash (states[i]->proof, strlen (states[i]->proof),
1249 // complete regex for whole DFA: union of all pairs (start state/accepting state(s)).
1250 complete_regex = NULL;
1251 for (i = 0; i < n; i++)
1253 if (states[i]->accepting)
1255 if (NULL == complete_regex && 0 < strlen (R_last[a->start->proof_id][i]))
1257 GNUNET_asprintf (&complete_regex, "%s", R_last[a->start->proof_id][i]);
1259 else if (NULL != R_last[a->start->proof_id][i] &&
1260 0 < strlen (R_last[a->start->proof_id][i]))
1262 temp = complete_regex;
1263 GNUNET_asprintf (&complete_regex, "%s|%s", complete_regex,
1264 R_last[a->start->proof_id][i]);
1269 a->canonical_regex = complete_regex;
1272 for (i = 0; i < n; i++)
1274 for (j = 0; j < n; j++)
1275 GNUNET_free_non_null (R_last[i][j]);
1281 * Creates a new DFA state based on a set of NFA states. Needs to be freed using
1282 * automaton_destroy_state.
1284 * @param ctx context
1285 * @param nfa_states set of NFA states on which the DFA should be based on
1287 * @return new DFA state
1289 static struct GNUNET_REGEX_State *
1290 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
1291 struct GNUNET_REGEX_StateSet *nfa_states)
1293 struct GNUNET_REGEX_State *s;
1296 struct GNUNET_REGEX_State *cstate;
1297 struct GNUNET_REGEX_Transition *ctran;
1300 s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1301 s->id = ctx->state_id++;
1311 if (NULL == nfa_states)
1313 GNUNET_asprintf (&s->name, "s%i", s->id);
1317 s->nfa_set = nfa_states;
1319 if (nfa_states->len < 1)
1322 // Create a name based on 'sset'
1323 s->name = GNUNET_malloc (sizeof (char) * 2);
1324 strcat (s->name, "{");
1327 for (i = 0; i < nfa_states->len; i++)
1329 cstate = nfa_states->states[i];
1330 GNUNET_asprintf (&name, "%i,", cstate->id);
1334 len = strlen (s->name) + strlen (name) + 1;
1335 s->name = GNUNET_realloc (s->name, len);
1336 strcat (s->name, name);
1341 // Add a transition for each distinct label to NULL state
1342 for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
1344 if (0 != ctran->label)
1345 state_add_transition (ctx, s, ctran->label, NULL);
1348 // If the nfa_states contain an accepting state, the new dfa state is also
1350 if (cstate->accepting)
1354 s->name[strlen (s->name) - 1] = '}';
1361 * Move from the given state 's' to the next state on transition 'label'
1363 * @param s starting state
1364 * @param label edge label to follow
1366 * @return new state or NULL, if transition on label not possible
1368 static struct GNUNET_REGEX_State *
1369 dfa_move (struct GNUNET_REGEX_State *s, const char label)
1371 struct GNUNET_REGEX_Transition *t;
1372 struct GNUNET_REGEX_State *new_s;
1379 for (t = s->transitions_head; NULL != t; t = t->next)
1381 if (label == t->label)
1383 new_s = t->to_state;
1393 * Remove all unreachable states from DFA 'a'. Unreachable states are those
1394 * states that are not reachable from the starting state.
1396 * @param a DFA automaton
1399 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
1401 struct GNUNET_REGEX_State *s;
1402 struct GNUNET_REGEX_State *s_next;
1404 // 1. unmark all states
1405 for (s = a->states_head; NULL != s; s = s->next)
1406 s->marked = GNUNET_NO;
1408 // 2. traverse dfa from start state and mark all visited states
1409 GNUNET_REGEX_automaton_traverse (a, NULL, NULL);
1411 // 3. delete all states that were not visited
1412 for (s = a->states_head; NULL != s; s = s_next)
1415 if (GNUNET_NO == s->marked)
1416 automaton_remove_state (a, s);
1422 * Remove all dead states from the DFA 'a'. Dead states are those states that do
1423 * not transition to any other state but themselves.
1425 * @param a DFA automaton
1428 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
1430 struct GNUNET_REGEX_State *s;
1431 struct GNUNET_REGEX_Transition *t;
1434 GNUNET_assert (DFA == a->type);
1436 for (s = a->states_head; NULL != s; s = s->next)
1442 for (t = s->transitions_head; NULL != t; t = t->next)
1444 if (NULL != t->to_state && t->to_state != s)
1454 // state s is dead, remove it
1455 automaton_remove_state (a, s);
1461 * Merge all non distinguishable states in the DFA 'a'
1463 * @param ctx context
1464 * @param a DFA automaton
1467 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
1468 struct GNUNET_REGEX_Automaton *a)
1471 int table[a->state_count][a->state_count];
1472 struct GNUNET_REGEX_State *s1;
1473 struct GNUNET_REGEX_State *s2;
1474 struct GNUNET_REGEX_Transition *t1;
1475 struct GNUNET_REGEX_Transition *t2;
1476 struct GNUNET_REGEX_State *s1_next;
1477 struct GNUNET_REGEX_State *s2_next;
1479 unsigned int num_equal_edges;
1481 for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
1487 // Mark all pairs of accepting/!accepting states
1488 for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1490 for (s2 = a->states_head; NULL != s2; s2 = s2->next)
1492 table[s1->marked][s2->marked] = 0;
1494 if ((s1->accepting && !s2->accepting) ||
1495 (!s1->accepting && s2->accepting))
1497 table[s1->marked][s2->marked] = 1;
1502 // Find all equal states
1507 for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1509 for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
1511 if (0 != table[s1->marked][s2->marked])
1514 num_equal_edges = 0;
1515 for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
1517 for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
1519 if (t1->label == t2->label)
1522 if (0 != table[t1->to_state->marked][t2->to_state->marked] ||
1523 0 != table[t2->to_state->marked][t1->to_state->marked])
1525 table[s1->marked][s2->marked] = t1->label != 0 ? t1->label : 1;
1531 if (num_equal_edges != s1->transition_count ||
1532 num_equal_edges != s2->transition_count)
1534 // Make sure ALL edges of possible equal states are the same
1535 table[s1->marked][s2->marked] = -2;
1541 // Merge states that are equal
1542 for (s1 = a->states_head; NULL != s1; s1 = s1_next)
1545 for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
1548 if (table[s1->marked][s2->marked] == 0)
1549 automaton_merge_states (ctx, a, s1, s2);
1556 * Minimize the given DFA 'a' by removing all unreachable states, removing all
1557 * dead states and merging all non distinguishable states
1559 * @param ctx context
1560 * @param a DFA automaton
1563 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
1564 struct GNUNET_REGEX_Automaton *a)
1569 GNUNET_assert (DFA == a->type);
1571 // 1. remove unreachable states
1572 dfa_remove_unreachable_states (a);
1574 // 2. remove dead states
1575 dfa_remove_dead_states (a);
1577 // 3. Merge nondistinguishable states
1578 dfa_merge_nondistinguishable_states (ctx, a);
1583 * Creates a new NFA fragment. Needs to be cleared using
1584 * automaton_fragment_clear.
1586 * @param start starting state
1587 * @param end end state
1589 * @return new NFA fragment
1591 static struct GNUNET_REGEX_Automaton *
1592 nfa_fragment_create (struct GNUNET_REGEX_State *start,
1593 struct GNUNET_REGEX_State *end)
1595 struct GNUNET_REGEX_Automaton *n;
1597 n = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1603 if (NULL == start && NULL == end)
1606 automaton_add_state (n, end);
1607 automaton_add_state (n, start);
1617 * Adds a list of states to the given automaton 'n'.
1619 * @param n automaton to which the states should be added
1620 * @param states_head head of the DLL of states
1621 * @param states_tail tail of the DLL of states
1624 nfa_add_states (struct GNUNET_REGEX_Automaton *n,
1625 struct GNUNET_REGEX_State *states_head,
1626 struct GNUNET_REGEX_State *states_tail)
1628 struct GNUNET_REGEX_State *s;
1630 if (NULL == n || NULL == states_head)
1632 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n");
1636 if (NULL == n->states_head)
1638 n->states_head = states_head;
1639 n->states_tail = states_tail;
1643 if (NULL != states_head)
1645 n->states_tail->next = states_head;
1646 n->states_tail = states_tail;
1649 for (s = states_head; NULL != s; s = s->next)
1655 * Creates a new NFA state. Needs to be freed using automaton_destroy_state.
1657 * @param ctx context
1658 * @param accepting is it an accepting state or not
1660 * @return new NFA state
1662 static struct GNUNET_REGEX_State *
1663 nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
1665 struct GNUNET_REGEX_State *s;
1667 s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1668 s->id = ctx->state_id++;
1669 s->accepting = accepting;
1676 GNUNET_asprintf (&s->name, "s%i", s->id);
1683 * Calculates the NFA closure set for the given state.
1685 * @param nfa the NFA containing 's'
1686 * @param s starting point state
1687 * @param label transitioning label on which to base the closure on,
1688 * pass 0 for epsilon transition
1690 * @return sorted nfa closure on 'label' (epsilon closure if 'label' is 0)
1692 static struct GNUNET_REGEX_StateSet *
1693 nfa_closure_create (struct GNUNET_REGEX_Automaton *nfa,
1694 struct GNUNET_REGEX_State *s, const char label)
1696 struct GNUNET_REGEX_StateSet *cls;
1697 struct GNUNET_REGEX_StateSet *cls_check;
1698 struct GNUNET_REGEX_State *clsstate;
1699 struct GNUNET_REGEX_State *currentstate;
1700 struct GNUNET_REGEX_Transition *ctran;
1705 cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1706 cls_check = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1708 for (clsstate = nfa->states_head; NULL != clsstate; clsstate = clsstate->next)
1709 clsstate->contained = 0;
1711 // Add start state to closure only for epsilon closure
1713 GNUNET_array_append (cls->states, cls->len, s);
1715 GNUNET_array_append (cls_check->states, cls_check->len, s);
1716 while (cls_check->len > 0)
1718 currentstate = cls_check->states[cls_check->len - 1];
1719 GNUNET_array_grow (cls_check->states, cls_check->len, cls_check->len - 1);
1721 for (ctran = currentstate->transitions_head; NULL != ctran;
1722 ctran = ctran->next)
1724 if (NULL != ctran->to_state && label == ctran->label)
1726 clsstate = ctran->to_state;
1728 if (NULL != clsstate && 0 == clsstate->contained)
1730 GNUNET_array_append (cls->states, cls->len, clsstate);
1731 GNUNET_array_append (cls_check->states, cls_check->len, clsstate);
1732 clsstate->contained = 1;
1737 GNUNET_assert (0 == cls_check->len);
1738 GNUNET_free (cls_check);
1742 qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1750 * Calculates the closure set for the given set of states.
1752 * @param nfa the NFA containing 's'
1753 * @param states list of states on which to base the closure on
1754 * @param label transitioning label for which to base the closure on,
1755 * pass 0 for epsilon transition
1757 * @return sorted nfa closure on 'label' (epsilon closure if 'label' is 0)
1759 static struct GNUNET_REGEX_StateSet *
1760 nfa_closure_set_create (struct GNUNET_REGEX_Automaton *nfa,
1761 struct GNUNET_REGEX_StateSet *states, const char label)
1763 struct GNUNET_REGEX_State *s;
1764 struct GNUNET_REGEX_StateSet *sset;
1765 struct GNUNET_REGEX_StateSet *cls;
1769 unsigned int contains;
1774 cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1776 for (i = 0; i < states->len; i++)
1778 s = states->states[i];
1779 sset = nfa_closure_create (nfa, s, label);
1781 for (j = 0; j < sset->len; j++)
1784 for (k = 0; k < cls->len; k++)
1786 if (sset->states[j]->id == cls->states[k]->id)
1793 GNUNET_array_append (cls->states, cls->len, sset->states[j]);
1795 state_set_clear (sset);
1799 qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
1807 * Pops two NFA fragments (a, b) from the stack and concatenates them (ab)
1809 * @param ctx context
1812 nfa_add_concatenation (struct GNUNET_REGEX_Context *ctx)
1814 struct GNUNET_REGEX_Automaton *a;
1815 struct GNUNET_REGEX_Automaton *b;
1816 struct GNUNET_REGEX_Automaton *new;
1818 b = ctx->stack_tail;
1819 GNUNET_assert (NULL != b);
1820 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
1821 a = ctx->stack_tail;
1822 GNUNET_assert (NULL != a);
1823 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1825 state_add_transition (ctx, a->end, 0, b->start);
1826 a->end->accepting = 0;
1827 b->end->accepting = 1;
1829 new = nfa_fragment_create (NULL, NULL);
1830 nfa_add_states (new, a->states_head, a->states_tail);
1831 nfa_add_states (new, b->states_head, b->states_tail);
1832 new->start = a->start;
1834 automaton_fragment_clear (a);
1835 automaton_fragment_clear (b);
1837 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1842 * Pops a NFA fragment from the stack (a) and adds a new fragment (a*)
1844 * @param ctx context
1847 nfa_add_star_op (struct GNUNET_REGEX_Context *ctx)
1849 struct GNUNET_REGEX_Automaton *a;
1850 struct GNUNET_REGEX_Automaton *new;
1851 struct GNUNET_REGEX_State *start;
1852 struct GNUNET_REGEX_State *end;
1854 a = ctx->stack_tail;
1855 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1859 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1860 "nfa_add_star_op failed, because there was no element on the stack");
1864 start = nfa_state_create (ctx, 0);
1865 end = nfa_state_create (ctx, 1);
1867 state_add_transition (ctx, start, 0, a->start);
1868 state_add_transition (ctx, start, 0, end);
1869 state_add_transition (ctx, a->end, 0, a->start);
1870 state_add_transition (ctx, a->end, 0, end);
1872 a->end->accepting = 0;
1875 new = nfa_fragment_create (start, end);
1876 nfa_add_states (new, a->states_head, a->states_tail);
1877 automaton_fragment_clear (a);
1879 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1884 * Pops an NFA fragment (a) from the stack and adds a new fragment (a+)
1886 * @param ctx context
1889 nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
1891 struct GNUNET_REGEX_Automaton *a;
1893 a = ctx->stack_tail;
1894 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1896 state_add_transition (ctx, a->end, 0, a->start);
1898 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a);
1903 * Pops an NFA fragment (a) from the stack and adds a new fragment (a?)
1905 * @param ctx context
1908 nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
1910 struct GNUNET_REGEX_Automaton *a;
1911 struct GNUNET_REGEX_Automaton *new;
1912 struct GNUNET_REGEX_State *start;
1913 struct GNUNET_REGEX_State *end;
1915 a = ctx->stack_tail;
1916 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1920 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1921 "nfa_add_question_op failed, because there was no element on the stack");
1925 start = nfa_state_create (ctx, 0);
1926 end = nfa_state_create (ctx, 1);
1928 state_add_transition (ctx, start, 0, a->start);
1929 state_add_transition (ctx, start, 0, end);
1930 state_add_transition (ctx, a->end, 0, end);
1932 a->end->accepting = 0;
1934 new = nfa_fragment_create (start, end);
1935 nfa_add_states (new, a->states_head, a->states_tail);
1936 automaton_fragment_clear (a);
1938 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1943 * Pops two NFA fragments (a, b) from the stack and adds a new NFA fragment that
1944 * alternates between a and b (a|b)
1946 * @param ctx context
1949 nfa_add_alternation (struct GNUNET_REGEX_Context *ctx)
1951 struct GNUNET_REGEX_Automaton *a;
1952 struct GNUNET_REGEX_Automaton *b;
1953 struct GNUNET_REGEX_Automaton *new;
1954 struct GNUNET_REGEX_State *start;
1955 struct GNUNET_REGEX_State *end;
1957 b = ctx->stack_tail;
1958 GNUNET_assert (NULL != b);
1959 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
1960 a = ctx->stack_tail;
1961 GNUNET_assert (NULL != a);
1962 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
1964 start = nfa_state_create (ctx, 0);
1965 end = nfa_state_create (ctx, 1);
1966 state_add_transition (ctx, start, 0, a->start);
1967 state_add_transition (ctx, start, 0, b->start);
1969 state_add_transition (ctx, a->end, 0, end);
1970 state_add_transition (ctx, b->end, 0, end);
1972 a->end->accepting = 0;
1973 b->end->accepting = 0;
1976 new = nfa_fragment_create (start, end);
1977 nfa_add_states (new, a->states_head, a->states_tail);
1978 nfa_add_states (new, b->states_head, b->states_tail);
1979 automaton_fragment_clear (a);
1980 automaton_fragment_clear (b);
1982 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
1987 * Adds a new nfa fragment to the stack
1989 * @param ctx context
1990 * @param lit label for nfa transition
1993 nfa_add_label (struct GNUNET_REGEX_Context *ctx, const char lit)
1995 struct GNUNET_REGEX_Automaton *n;
1996 struct GNUNET_REGEX_State *start;
1997 struct GNUNET_REGEX_State *end;
1999 GNUNET_assert (NULL != ctx);
2001 start = nfa_state_create (ctx, 0);
2002 end = nfa_state_create (ctx, 1);
2003 state_add_transition (ctx, start, lit, end);
2004 n = nfa_fragment_create (start, end);
2005 GNUNET_assert (NULL != n);
2006 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n);
2011 * Initialize a new context
2013 * @param ctx context
2016 GNUNET_REGEX_context_init (struct GNUNET_REGEX_Context *ctx)
2020 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!");
2024 ctx->transition_id = 0;
2025 ctx->stack_head = NULL;
2026 ctx->stack_tail = NULL;
2031 * Construct an NFA by parsing the regex string of length 'len'.
2033 * @param regex regular expression string
2034 * @param len length of the string
2036 * @return NFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2038 struct GNUNET_REGEX_Automaton *
2039 GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
2041 struct GNUNET_REGEX_Context ctx;
2042 struct GNUNET_REGEX_Automaton *nfa;
2046 unsigned int altcount;
2047 unsigned int atomcount;
2048 unsigned int pcount;
2055 GNUNET_REGEX_context_init (&ctx);
2064 for (count = 0; count < len && *regexp; count++, regexp++)
2072 nfa_add_concatenation (&ctx);
2074 GNUNET_array_grow (p, pcount, pcount + 1);
2075 p[pcount - 1].altcount = altcount;
2076 p[pcount - 1].atomcount = atomcount;
2083 error_msg = "Cannot append '|' to nothing";
2086 while (--atomcount > 0)
2087 nfa_add_concatenation (&ctx);
2093 error_msg = "Missing opening '('";
2098 // Ignore this: "()"
2100 altcount = p[pcount].altcount;
2101 atomcount = p[pcount].atomcount;
2104 while (--atomcount > 0)
2105 nfa_add_concatenation (&ctx);
2106 for (; altcount > 0; altcount--)
2107 nfa_add_alternation (&ctx);
2109 altcount = p[pcount].altcount;
2110 atomcount = p[pcount].atomcount;
2116 error_msg = "Cannot append '*' to nothing";
2119 nfa_add_star_op (&ctx);
2124 error_msg = "Cannot append '+' to nothing";
2127 nfa_add_plus_op (&ctx);
2132 error_msg = "Cannot append '?' to nothing";
2135 nfa_add_question_op (&ctx);
2137 case 92: /* escape: \ */
2144 nfa_add_concatenation (&ctx);
2146 nfa_add_label (&ctx, *regexp);
2153 error_msg = "Unbalanced parenthesis";
2156 while (--atomcount > 0)
2157 nfa_add_concatenation (&ctx);
2158 for (; altcount > 0; altcount--)
2159 nfa_add_alternation (&ctx);
2161 GNUNET_free_non_null (p);
2163 nfa = ctx.stack_tail;
2164 GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2166 if (NULL != ctx.stack_head)
2168 error_msg = "Creating the NFA failed. NFA stack was not empty!";
2172 nfa->regex = GNUNET_strdup (regex);
2177 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: %s\n", regex);
2178 if (NULL != error_msg)
2179 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
2181 GNUNET_free_non_null (p);
2183 while (NULL != (nfa = ctx.stack_head))
2185 GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2186 GNUNET_REGEX_automaton_destroy (nfa);
2194 * Create DFA states based on given 'nfa' and starting with 'dfa_state'.
2196 * @param ctx context.
2197 * @param nfa NFA automaton.
2198 * @param dfa DFA automaton.
2199 * @param dfa_state current dfa state, pass epsilon closure of first nfa state
2203 construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
2204 struct GNUNET_REGEX_Automaton *nfa,
2205 struct GNUNET_REGEX_Automaton *dfa,
2206 struct GNUNET_REGEX_State *dfa_state)
2208 struct GNUNET_REGEX_Transition *ctran;
2209 struct GNUNET_REGEX_State *state_iter;
2210 struct GNUNET_REGEX_State *new_dfa_state;
2211 struct GNUNET_REGEX_State *state_contains;
2212 struct GNUNET_REGEX_StateSet *tmp;
2213 struct GNUNET_REGEX_StateSet *nfa_set;
2215 for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next)
2217 if (0 == ctran->label || NULL != ctran->to_state)
2220 tmp = nfa_closure_set_create (nfa, dfa_state->nfa_set, ctran->label);
2221 nfa_set = nfa_closure_set_create (nfa, tmp, 0);
2222 state_set_clear (tmp);
2223 new_dfa_state = dfa_state_create (ctx, nfa_set);
2224 state_contains = NULL;
2225 for (state_iter = dfa->states_head; NULL != state_iter;
2226 state_iter = state_iter->next)
2228 if (0 == state_set_compare (state_iter->nfa_set, new_dfa_state->nfa_set))
2229 state_contains = state_iter;
2232 if (NULL == state_contains)
2234 automaton_add_state (dfa, new_dfa_state);
2235 ctran->to_state = new_dfa_state;
2236 construct_dfa_states (ctx, nfa, dfa, new_dfa_state);
2240 ctran->to_state = state_contains;
2241 automaton_destroy_state (new_dfa_state);
2248 * Construct DFA for the given 'regex' of length 'len'
2250 * @param regex regular expression string
2251 * @param len length of the regular expression
2253 * @return DFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2255 struct GNUNET_REGEX_Automaton *
2256 GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
2258 struct GNUNET_REGEX_Context ctx;
2259 struct GNUNET_REGEX_Automaton *dfa;
2260 struct GNUNET_REGEX_Automaton *nfa;
2261 struct GNUNET_REGEX_StateSet *nfa_set;
2263 GNUNET_REGEX_context_init (&ctx);
2266 nfa = GNUNET_REGEX_construct_nfa (regex, len);
2270 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2271 "Could not create DFA, because NFA creation failed\n");
2275 dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
2277 dfa->regex = GNUNET_strdup (regex);
2279 // Create DFA start state from epsilon closure
2280 nfa_set = nfa_closure_create (nfa, nfa->start, 0);
2281 dfa->start = dfa_state_create (&ctx, nfa_set);
2282 automaton_add_state (dfa, dfa->start);
2284 construct_dfa_states (&ctx, nfa, dfa, dfa->start);
2286 GNUNET_REGEX_automaton_destroy (nfa);
2289 dfa_minimize (&ctx, dfa);
2291 // Create proofs for all states
2292 automaton_create_proofs (dfa);
2299 * Free the memory allocated by constructing the GNUNET_REGEX_Automaton data
2302 * @param a automaton to be destroyed
2305 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
2307 struct GNUNET_REGEX_State *s;
2308 struct GNUNET_REGEX_State *next_state;
2313 GNUNET_free_non_null (a->regex);
2314 GNUNET_free_non_null (a->canonical_regex);
2316 for (s = a->states_head; NULL != s;)
2318 next_state = s->next;
2319 automaton_destroy_state (s);
2328 * Evaluates the given string using the given DFA automaton
2330 * @param a automaton, type must be DFA
2331 * @param string string that should be evaluated
2333 * @return 0 if string matches, non 0 otherwise
2336 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2339 struct GNUNET_REGEX_State *s;
2343 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2344 "Tried to evaluate DFA, but NFA automaton given");
2350 // If the string is empty but the starting state is accepting, we accept.
2351 if ((NULL == string || 0 == strlen (string)) && s->accepting)
2354 for (strp = string; NULL != strp && *strp; strp++)
2356 s = dfa_move (s, *strp);
2361 if (NULL != s && s->accepting)
2369 * Evaluates the given string using the given NFA automaton
2371 * @param a automaton, type must be NFA
2372 * @param string string that should be evaluated
2374 * @return 0 if string matches, non 0 otherwise
2377 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2380 struct GNUNET_REGEX_State *s;
2381 struct GNUNET_REGEX_StateSet *sset;
2382 struct GNUNET_REGEX_StateSet *new_sset;
2388 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2389 "Tried to evaluate NFA, but DFA automaton given");
2393 // If the string is empty but the starting state is accepting, we accept.
2394 if ((NULL == string || 0 == strlen (string)) && a->start->accepting)
2398 sset = nfa_closure_create (a, a->start, 0);
2400 for (strp = string; NULL != strp && *strp; strp++)
2402 new_sset = nfa_closure_set_create (a, sset, *strp);
2403 state_set_clear (sset);
2404 sset = nfa_closure_set_create (a, new_sset, 0);
2405 state_set_clear (new_sset);
2408 for (i = 0; i < sset->len; i++)
2410 s = sset->states[i];
2411 if (NULL != s && s->accepting)
2418 state_set_clear (sset);
2424 * Evaluates the given 'string' against the given compiled regex
2426 * @param a automaton
2427 * @param string string to check
2429 * @return 0 if string matches, non 0 otherwise
2432 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
2439 result = evaluate_dfa (a, string);
2442 result = evaluate_nfa (a, string);
2445 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2446 "Evaluating regex failed, automaton has no type!\n");
2447 result = GNUNET_SYSERR;
2456 * Get the canonical regex of the given automaton.
2457 * When constructing the automaton a proof is computed for each state,
2458 * consisting of the regular expression leading to this state. A complete
2459 * regex for the automaton can be computed by combining these proofs.
2460 * As of now this function is only useful for testing.
2462 * @param a automaton for which the canonical regex should be returned.
2467 GNUNET_REGEX_get_canonical_regex (struct GNUNET_REGEX_Automaton *a)
2472 return a->canonical_regex;
2477 * Get the first key for the given 'input_string'. This hashes the first x bits
2478 * of the 'input_string'.
2480 * @param input_string string.
2481 * @param string_len length of the 'input_string'.
2482 * @param key pointer to where to write the hash code.
2484 * @return number of bits of 'input_string' that have been consumed
2485 * to construct the key
2488 GNUNET_REGEX_get_first_key (const char *input_string, size_t string_len,
2489 struct GNUNET_HashCode * key)
2493 size = string_len < INITIAL_BITS ? string_len : INITIAL_BITS;
2495 if (NULL == input_string)
2497 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
2501 GNUNET_CRYPTO_hash (input_string, size, key);
2508 * Check if the given 'proof' matches the given 'key'.
2510 * @param proof partial regex of a state.
2511 * @param key hash of a state.
2513 * @return GNUNET_OK if the proof is valid for the given key.
2516 GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
2518 struct GNUNET_HashCode key_check;
2520 GNUNET_CRYPTO_hash (proof, strlen (proof), &key_check);
2522 GNUNET_CRYPTO_hash_cmp (key, &key_check)) ? GNUNET_OK : GNUNET_NO;
2527 * Recursive helper function for iterate_initial_edges. Will call iterator
2528 * function for each initial state.
2530 * @param min_len minimum length of the path in the graph.
2531 * @param max_len maximum length of the path in the graph.
2532 * @param cur_len current length of the path already traversed.
2533 * @param consumed_string string consumed by traversing the graph till this state.
2534 * @param state current state of the automaton.
2535 * @param iterator iterator function called for each edge.
2536 * @param iterator_cls closure for the iterator function.
2539 iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
2540 unsigned int cur_len, char *consumed_string,
2541 struct GNUNET_REGEX_State *state,
2542 GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
2545 char label[state->transition_count][2];
2547 struct GNUNET_REGEX_Transition *t;
2548 unsigned int num_edges = state->transition_count;
2549 struct GNUNET_REGEX_Edge edges[num_edges];
2550 struct GNUNET_HashCode hash;
2552 if (cur_len > min_len && NULL != consumed_string && cur_len <= max_len)
2554 for (i = 0, t = state->transitions_head; NULL != t; t = t->next, i++)
2556 label[i][0] = t->label;
2558 edges[i].label = label[i];
2559 edges[i].destination = t->to_state->hash;
2562 GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash);
2563 iterator (iterator_cls, &hash, consumed_string, state->accepting, num_edges,
2567 if (cur_len < max_len)
2570 for (t = state->transitions_head; NULL != t; t = t->next)
2572 if (NULL != consumed_string)
2573 GNUNET_asprintf (&temp, "%s%c", consumed_string, t->label);
2575 GNUNET_asprintf (&temp, "%c", t->label);
2577 iterate_initial_edge (min_len, max_len, cur_len, temp, t->to_state,
2578 iterator, iterator_cls);
2586 * Iterate over all initial edges that aren't actually part of the automaton.
2587 * This is needed to find the initial states returned by
2588 * GNUNET_REGEX_get_first_key. Iteration will start at the first branch state (a
2589 * state that has more than one outgoing edge, can be the first state), because
2590 * all previous states will have the same proof and be iterated over in
2591 * iterate_all_edges.
2593 * @param a the automaton for which the initial states should be computed.
2594 * @param initial_len length of the initial state string.
2595 * @param iterator iterator function called for each edge.
2596 * @param iterator_cls closure for the iterator function.
2599 iterate_initial_edges (struct GNUNET_REGEX_Automaton *a,
2600 const unsigned int initial_len,
2601 GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
2603 char *consumed_string;
2605 struct GNUNET_REGEX_State *s;
2606 unsigned int cur_len;
2608 if (1 > initial_len)
2611 consumed_string = NULL;
2615 if (1 == s->transition_count)
2619 if (NULL != consumed_string)
2621 temp = consumed_string;
2622 GNUNET_asprintf (&consumed_string, "%s%c", consumed_string,
2623 s->transitions_head->label);
2627 GNUNET_asprintf (&consumed_string, "%c", s->transitions_head->label);
2629 s = s->transitions_head->to_state;
2632 while (cur_len < initial_len && 1 == s->transition_count);
2635 iterate_initial_edge (cur_len, initial_len, cur_len, consumed_string, s,
2636 iterator, iterator_cls);
2638 GNUNET_free_non_null (consumed_string);
2643 * Iterate over all edges helper function starting from state 's', calling
2644 * iterator on for each edge.
2647 * @param iterator iterator function called for each edge.
2648 * @param iterator_cls closure.
2651 iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
2654 struct GNUNET_REGEX_Transition *t;
2655 struct GNUNET_REGEX_Edge edges[s->transition_count];
2656 unsigned int num_edges;
2658 if (GNUNET_YES != s->marked)
2660 s->marked = GNUNET_YES;
2662 num_edges = state_get_edges (s, edges);
2664 if (0 < strlen (s->proof) || s->accepting)
2665 iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges,
2668 for (t = s->transitions_head; NULL != t; t = t->next)
2669 iterate_edge (t->to_state, iterator, iterator_cls);
2675 * Iterate over all edges starting from start state of automaton 'a'. Calling
2676 * iterator for each edge.
2678 * @param a automaton.
2679 * @param iterator iterator called for each edge.
2680 * @param iterator_cls closure.
2683 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2684 GNUNET_REGEX_KeyIterator iterator,
2687 struct GNUNET_REGEX_State *s;
2689 for (s = a->states_head; NULL != s; s = s->next)
2690 s->marked = GNUNET_NO;
2692 iterate_initial_edges (a, INITIAL_BITS, iterator, iterator_cls);
2693 iterate_edge (a->start, iterator, iterator_cls);