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"
32 * Constant for how many bits the initial string regex should have.
34 #define INITIAL_BITS 10
37 * Context that contains an id counter for states and transitions as well as a
38 * DLL of automatons used as a stack for NFA construction.
40 struct GNUNET_REGEX_Context
45 unsigned int state_id;
48 * Unique transition id.
50 unsigned int transition_id;
53 * DLL of GNUNET_REGEX_Automaton's used as a stack.
55 struct GNUNET_REGEX_Automaton *stack_head;
58 * DLL of GNUNET_REGEX_Automaton's used as a stack.
60 struct GNUNET_REGEX_Automaton *stack_tail;
64 * Type of an automaton.
66 enum GNUNET_REGEX_AutomatonType
73 * Automaton representation.
75 struct GNUNET_REGEX_Automaton
78 * Linked list of NFAs used for partial NFA creation.
80 struct GNUNET_REGEX_Automaton *prev;
83 * Linked list of NFAs used for partial NFA creation.
85 struct GNUNET_REGEX_Automaton *next;
88 * First state of the automaton. This is mainly used for constructing an NFA,
89 * where each NFA itself consists of one or more NFAs linked together.
91 struct GNUNET_REGEX_State *start;
94 * End state of the partial NFA. This is undefined for DFAs
96 struct GNUNET_REGEX_State *end;
99 * Number of states in the automaton.
101 unsigned int state_count;
106 struct GNUNET_REGEX_State *states_head;
111 struct GNUNET_REGEX_State *states_tail;
114 * Type of the automaton.
116 enum GNUNET_REGEX_AutomatonType type;
124 * Canonical regex (result of RX->NFA->DFA->RX)
126 char *canonical_regex;
130 * A state. Can be used in DFA and NFA automatons.
132 struct GNUNET_REGEX_State
135 * This is a linked list.
137 struct GNUNET_REGEX_State *prev;
140 * This is a linked list.
142 struct GNUNET_REGEX_State *next;
150 * If this is an accepting state or not.
155 * Marking of the state. This is used for marking all visited states when
156 * traversing all states of an automaton and for cases where the state id
157 * cannot be used (dfa minimization).
162 * Marking the state as contained. This is used for checking, if the state is
163 * contained in a set in constant time
168 * Marking the state as part of an SCC (Strongly Connected Component). All
169 * states with the same scc_id are part of the same SCC. scc_id is 0, if state
170 * is not a part of any SCC.
175 * Used for SCC detection.
180 * Used for SCC detection.
185 * Human readable name of the automaton. Used for debugging and graph
193 struct GNUNET_HashCode hash;
196 * State ID for proof creation.
198 unsigned int proof_id;
201 * Proof for this state.
206 * Number of transitions from this state to other states.
208 unsigned int transition_count;
211 * DLL of transitions.
213 struct Transition *transitions_head;
216 * DLL of transitions.
218 struct Transition *transitions_tail;
221 * Set of states on which this state is based on. Used when creating a DFA out
222 * of several NFA states.
224 struct GNUNET_REGEX_StateSet *nfa_set;
228 * Transition between two states. Each state can have 0-n transitions. If label
229 * is 0, this is considered to be an epsilon transition.
234 * This is a linked list.
236 struct Transition *prev;
239 * This is a linked list.
241 struct Transition *next;
244 * Unique id of this transition.
249 * Label for this transition. This is basically the edge label for the graph.
254 * State to which this transition leads.
256 struct GNUNET_REGEX_State *to_state;
259 * State from which this transition origins.
261 struct GNUNET_REGEX_State *from_state;
264 * Mark this transition. For example when reversing the automaton.
272 struct GNUNET_REGEX_StateSet
277 struct GNUNET_REGEX_State **states;
280 * Length of the 'states' array.
286 * Debug helper functions
290 * Print all the transitions of state 's'.
292 * @param s state for which to print it's transitions.
295 debug_print_transitions (struct GNUNET_REGEX_State *s);
298 * Print information of the given state 's'.
300 * @param s state for which debug information should be printed.
303 debug_print_state (struct GNUNET_REGEX_State *s)
307 if (NULL == s->proof)
312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
313 "State %i: %s marked: %i accepting: %i scc_id: %i transitions: %i proof: %s\n",
314 s->id, s->name, s->marked, s->accepting, s->scc_id,
315 s->transition_count, proof);
317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transitions:\n");
318 debug_print_transitions (s);
322 * Print debug information for all states contained in the automaton 'a'.
324 * @param a automaton for which debug information of it's states should be printed.
327 debug_print_states (struct GNUNET_REGEX_Automaton *a)
329 struct GNUNET_REGEX_State *s;
331 for (s = a->states_head; NULL != s; s = s->next)
332 debug_print_state (s);
336 * Print debug information for given transition 't'.
338 * @param t transition for which to print debug info.
341 debug_print_transition (struct Transition *t)
355 if (NULL == t->to_state)
358 to_state = t->to_state->name;
360 if (NULL == t->from_state)
363 from_state = t->from_state->name;
365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transition %i: From %s on %c to %s\n",
366 t->id, from_state, label, to_state);
370 debug_print_transitions (struct GNUNET_REGEX_State *s)
372 struct Transition *t;
374 for (t = s->transitions_head; NULL != t; t = t->next)
375 debug_print_transition (t);
380 * Recursive function doing DFS with 'v' as a start, detecting all SCCs inside
381 * the subgraph reachable from 'v'. Used with scc_tarjan function to detect all
382 * SCCs inside an automaton.
384 * @param scc_counter counter for numbering the sccs
385 * @param v start vertex
386 * @param index current index
387 * @param stack stack for saving all SCCs
388 * @param stack_size current size of the stack
391 scc_tarjan_strongconnect (unsigned int *scc_counter,
392 struct GNUNET_REGEX_State *v, unsigned int *index,
393 struct GNUNET_REGEX_State **stack,
394 unsigned int *stack_size)
396 struct GNUNET_REGEX_State *w;
397 struct Transition *t;
402 stack[(*stack_size)++] = v;
405 for (t = v->transitions_head; NULL != t; t = t->next)
408 if (NULL != w && w->index < 0)
410 scc_tarjan_strongconnect (scc_counter, w, index, stack, stack_size);
411 v->lowlink = (v->lowlink > w->lowlink) ? w->lowlink : v->lowlink;
413 else if (0 != w->contained)
414 v->lowlink = (v->lowlink > w->index) ? w->index : v->lowlink;
417 if (v->lowlink == v->index)
419 w = stack[--(*stack_size)];
427 w->scc_id = *scc_counter;
428 w = stack[--(*stack_size)];
431 w->scc_id = *scc_counter;
438 * Detect all SCCs (Strongly Connected Components) inside the given automaton.
439 * SCCs will be marked using the scc_id on each state.
441 * @param a the automaton for which SCCs should be computed and assigned.
444 scc_tarjan (struct GNUNET_REGEX_Automaton *a)
447 unsigned int scc_counter;
448 struct GNUNET_REGEX_State *v;
449 struct GNUNET_REGEX_State *stack[a->state_count];
450 unsigned int stack_size;
452 for (v = a->states_head; NULL != v; v = v->next)
463 for (v = a->states_head; NULL != v; v = v->next)
466 scc_tarjan_strongconnect (&scc_counter, v, &index, stack, &stack_size);
471 * Adds a transition from one state to another on 'label'. Does not add
475 * @param from_state starting state for the transition
476 * @param label transition label
477 * @param to_state state to where the transition should point to
480 state_add_transition (struct GNUNET_REGEX_Context *ctx,
481 struct GNUNET_REGEX_State *from_state, const char label,
482 struct GNUNET_REGEX_State *to_state)
485 struct Transition *t;
486 struct Transition *oth;
488 if (NULL == from_state)
490 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
494 // Do not add duplicate state transitions
496 for (t = from_state->transitions_head; NULL != t; t = t->next)
498 if (t->to_state == to_state && t->label == label &&
499 t->from_state == from_state)
506 if (GNUNET_YES == is_dup)
509 // sort transitions by label
510 for (oth = from_state->transitions_head; NULL != oth; oth = oth->next)
512 if (oth->label > label)
516 t = GNUNET_malloc (sizeof (struct Transition));
517 t->id = ctx->transition_id++;
519 t->to_state = to_state;
520 t->from_state = from_state;
522 // Add outgoing transition to 'from_state'
523 from_state->transition_count++;
524 GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head,
525 from_state->transitions_tail, oth, t);
529 * Compare two states. Used for sorting.
531 * @param a first state
532 * @param b second state
534 * @return an integer less than, equal to, or greater than zero
535 * if the first argument is considered to be respectively
536 * less than, equal to, or greater than the second.
539 state_compare (const void *a, const void *b)
541 struct GNUNET_REGEX_State **s1;
542 struct GNUNET_REGEX_State **s2;
544 s1 = (struct GNUNET_REGEX_State **) a;
545 s2 = (struct GNUNET_REGEX_State **) b;
547 return (*s1)->id - (*s2)->id;
551 * Get all edges leaving state 's'.
554 * @param edges all edges leaving 's'.
556 * @return number of edges.
559 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
561 struct Transition *t;
569 for (t = s->transitions_head; NULL != t; t = t->next)
571 if (NULL != t->to_state)
573 edges[count].label = &t->label;
574 edges[count].destination = t->to_state->hash;
582 * Compare to state sets by comparing the id's of the states that are contained
583 * in each set. Both sets are expected to be sorted by id!
585 * @param sset1 first state set
586 * @param sset2 second state set
588 * @return an integer less than, equal to, or greater than zero
589 * if the first argument is considered to be respectively
590 * less than, equal to, or greater than the second.
593 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
594 struct GNUNET_REGEX_StateSet *sset2)
599 if (NULL == sset1 || NULL == sset2)
602 result = sset1->len - sset2->len;
604 for (i = 0; i < sset1->len; i++)
609 result = state_compare (&sset1->states[i], &sset2->states[i]);
615 * Clears the given StateSet 'set'
617 * @param set set to be cleared
620 state_set_clear (struct GNUNET_REGEX_StateSet *set)
624 GNUNET_free_non_null (set->states);
630 * Clears an automaton fragment. Does not destroy the states inside the
633 * @param a automaton to be cleared
636 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
643 a->states_head = NULL;
644 a->states_tail = NULL;
650 * Frees the memory used by State 's'
652 * @param s state that should be destroyed
655 automaton_destroy_state (struct GNUNET_REGEX_State *s)
657 struct Transition *t;
658 struct Transition *next_t;
663 GNUNET_free_non_null (s->name);
664 GNUNET_free_non_null (s->proof);
666 for (t = s->transitions_head; NULL != t; t = next_t)
669 GNUNET_CONTAINER_DLL_remove (s->transitions_head, s->transitions_tail, t);
673 state_set_clear (s->nfa_set);
679 * Remove a state from the given automaton 'a'. Always use this function when
680 * altering the states of an automaton. Will also remove all transitions leading
681 * to this state, before destroying it.
684 * @param s state to remove
687 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
688 struct GNUNET_REGEX_State *s)
690 struct GNUNET_REGEX_State *ss;
691 struct GNUNET_REGEX_State *s_check;
692 struct Transition *t_check;
694 if (NULL == a || NULL == s)
699 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
702 // remove all transitions leading to this state
703 for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
705 for (t_check = s_check->transitions_head; NULL != t_check;
706 t_check = t_check->next)
708 if (t_check->to_state == ss)
710 GNUNET_CONTAINER_DLL_remove (s_check->transitions_head,
711 s_check->transitions_tail, t_check);
712 s_check->transition_count--;
717 automaton_destroy_state (ss);
721 * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
726 * @param s1 first state
727 * @param s2 second state, will be destroyed
730 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
731 struct GNUNET_REGEX_Automaton *a,
732 struct GNUNET_REGEX_State *s1,
733 struct GNUNET_REGEX_State *s2)
735 struct GNUNET_REGEX_State *s_check;
736 struct Transition *t_check;
737 struct Transition *t;
738 struct Transition *t_next;
742 GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
747 // 1. Make all transitions pointing to s2 point to s1, unless this transition
748 // does not already exists, if it already exists remove transition.
749 for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
751 for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next)
753 t_next = t_check->next;
755 if (s2 == t_check->to_state)
758 for (t = t_check->from_state->transitions_head; NULL != t; t = t->next)
760 if (t->to_state == s1 && t_check->label == t->label)
763 if (GNUNET_NO == is_dup)
764 t_check->to_state = s1;
767 GNUNET_CONTAINER_DLL_remove (t_check->from_state->transitions_head,
768 t_check->from_state->transitions_tail,
775 // 2. Add all transitions from s2 to sX to s1
776 for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
778 if (t_check->to_state != s1)
779 state_add_transition (ctx, s1, t_check->label, t_check->to_state);
782 // 3. Rename s1 to {s1,s2}
784 GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
785 GNUNET_free (new_name);
788 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
790 automaton_destroy_state (s2);
794 * Add a state to the automaton 'a', always use this function to alter the
795 * states DLL of the automaton.
797 * @param a automaton to add the state to
798 * @param s state that should be added
801 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
802 struct GNUNET_REGEX_State *s)
804 GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
809 * Function that is called with each state, when traversing an automaton.
811 * @param cls closure.
812 * @param count current count of the state, from 0 to a->state_count -1.
815 typedef void (*GNUNET_REGEX_traverse_action) (void *cls, unsigned int count,
816 struct GNUNET_REGEX_State * s);
819 * Depth-first traversal of all states that are reachable from state 's'. Expects the states to
820 * be unmarked (s->marked == GNUNET_NO). Performs 'action' on each visited
823 * @param s start state.
824 * @param count current count of the state.
825 * @param action action to be performed on each state.
826 * @param action_cls closure for action
829 automaton_state_traverse (struct GNUNET_REGEX_State *s, unsigned int *count,
830 GNUNET_REGEX_traverse_action action, void *action_cls)
832 struct Transition *t;
834 if (GNUNET_NO != s->marked)
836 s->marked = GNUNET_YES;
838 action (action_cls, *count, s);
840 for (t = s->transitions_head; NULL != t; t = t->next)
841 automaton_state_traverse (t->to_state, count, action, action_cls);
846 * Traverses the given automaton from it's start state, visiting all reachable
847 * states and calling 'action' on each one of them.
849 * @param a automaton.
850 * @param action action to be performed on each state.
851 * @param action_cls closure for action
854 automaton_traverse (struct GNUNET_REGEX_Automaton *a,
855 GNUNET_REGEX_traverse_action action, void *action_cls)
858 struct GNUNET_REGEX_State *s;
860 for (s = a->states_head; NULL != s; s = s->next)
861 s->marked = GNUNET_NO;
863 automaton_state_traverse (a->start, &count, action, action_cls);
868 * Check if the given string 'str' needs parentheses around it when
869 * using it to generate a regex.
871 * Currently only tests for first and last characters being '()' respectively.
872 * FIXME: What about "(ab)|(cd)"?
876 * @return GNUNET_YES if parentheses are needed, GNUNET_NO otherwise
879 needs_parentheses (const char *str)
887 if ((NULL == str) || ((slen = strlen (str)) < 2))
896 cl = strchr (pos, ')');
902 op = strchr (pos, '(');
903 if ((NULL != op) && (op < cl))
913 return (*pos == '\0') ? GNUNET_NO : GNUNET_YES;
918 * Remove parentheses surrounding string 'str'.
919 * Example: "(a)" becomes "a".
920 * You need to GNUNET_free the returned string.
922 * Currently only tests for first and last characters being '()' respectively.
923 * FIXME: What about "(ab)|(cd)"?
925 * @param str string, free'd or re-used by this function, can be NULL
927 * @return string without surrounding parentheses, string 'str' if no preceding
928 * epsilon could be found, NULL if 'str' was NULL
931 remove_parentheses (char *str)
935 if ((NULL == str) || ('(' != str[0]) ||
936 (str[(slen = strlen (str)) - 1] != ')'))
938 memmove (str, &str[1], slen - 2);
939 str[slen - 2] = '\0';
945 * Check if the string 'str' starts with an epsilon (empty string).
946 * Example: "(|a)" is starting with an epsilon.
948 * @param str string to test
950 * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')'
953 has_epsilon (const char *str)
955 return (NULL != str) && ('(' == str[0]) && ('|' == str[1]) &&
956 (')' == str[strlen (str) - 1]);
961 * Remove an epsilon from the string str. Where epsilon is an empty string
962 * Example: str = "(|a|b|c)", result: "a|b|c"
963 * The returned string needs to be freed.
967 * @return string without preceding epsilon, string 'str' if no preceding epsilon
968 * could be found, NULL if 'str' was NULL
971 remove_epsilon (const char *str)
977 if (('(' == str[0]) && ('|' == str[1]))
980 if (')' == str[len - 1])
981 return GNUNET_strndup (&str[2], len - 3);
983 return GNUNET_strdup (str);
987 * Compare 'str1', starting from position 'k', with whole 'str2'
989 * @param str1 first string to compare, starting from position 'k'
990 * @param str2 second string for comparison
991 * @param k starting position in 'str1'
993 * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
996 strkcmp (const char *str1, const char *str2, size_t k)
998 if ((NULL == str1) || (NULL == str2) || (strlen (str1) < k))
1000 return strcmp (&str1[k], str2);
1005 * Compare two strings for equality. If either is NULL (or if both are
1006 * NULL), they are not equal.
1008 * @param str1 first string for comparison.
1009 * @param str2 second string for comparison.
1011 * @return 0 if the strings are the same, 1 or -1 if not
1014 nullstrcmp (const char *str1, const char *str2)
1016 if ((NULL == str1) || (NULL == str2))
1018 return strcmp (str1, str2);
1022 * Helper function used as 'action' in 'automaton_traverse' function to create
1023 * the depth-first numbering of the states.
1025 * @param cls states array.
1026 * @param count current state counter.
1027 * @param s current state.
1030 number_states (void *cls, unsigned int count, struct GNUNET_REGEX_State *s)
1032 struct GNUNET_REGEX_State **states = cls;
1034 s->proof_id = count;
1039 * Construct the regular expression given the inductive step,
1040 * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^*
1041 * R^{(k-1)}_{kj}, and simplify the resulting expression saved in R_cur_ij.
1043 * @param R_last_ij value of $R^{(k-1)_{ij}.
1044 * @param R_last_ik value of $R^{(k-1)_{ik}.
1045 * @param R_last_kk value of $R^{(k-1)_{kk}.
1046 * @param R_last_kj value of $R^{(k-1)_{kj}.
1047 * @param R_cur_ij result for this inductive step is saved in R_cur_ij, R_cur_ij
1048 * is expected to be NULL when called!
1051 automaton_create_proofs_simplify (char *R_last_ij, char *R_last_ik,
1052 char *R_last_kk, char *R_last_kj,
1071 int clean_ik_kk_cmp;
1072 int clean_kk_kj_cmp;
1079 GNUNET_assert (NULL == *R_cur_ij && NULL != R_cur_ij);
1081 // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1082 // R_last == R^{(k-1)}, R_cur == R^{(k)}
1083 // R_cur_ij = R_cur_l | R_cur_r
1084 // R_cur_l == R^{(k-1)}_{ij}
1085 // R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1087 if ((NULL == R_last_ij) && ((NULL == R_last_ik) || (NULL == R_last_kk) || /* technically cannot happen, but looks saner */
1088 (NULL == R_last_kj)))
1090 /* R^{(k)}_{ij} = N | N */
1095 if ((NULL == R_last_ik) || (NULL == R_last_kk) || /* technically cannot happen, but looks saner */
1096 (NULL == R_last_kj))
1098 /* R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */
1099 *R_cur_ij = GNUNET_strdup (R_last_ij);
1103 // $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
1104 // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1109 // cache results from strcmp, we might need these many times
1110 ij_kj_cmp = nullstrcmp (R_last_ij, R_last_kj);
1111 ij_ik_cmp = nullstrcmp (R_last_ij, R_last_ik);
1112 ik_kk_cmp = nullstrcmp (R_last_ik, R_last_kk);
1113 //ik_kj_cmp = nullstrcmp (R_last_ik, R_last_kj);
1114 kk_kj_cmp = nullstrcmp (R_last_kk, R_last_kj);
1116 // Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
1117 // as parentheses, so we can better compare the contents
1118 R_temp_ik = remove_parentheses (remove_epsilon (R_last_ik));
1119 R_temp_kk = remove_parentheses (remove_epsilon (R_last_kk));
1120 R_temp_kj = remove_parentheses (remove_epsilon (R_last_kj));
1122 clean_ik_kk_cmp = nullstrcmp (R_last_ik, R_temp_kk);
1123 clean_kk_kj_cmp = nullstrcmp (R_temp_kk, R_last_kj);
1125 // construct R_cur_l (and, if necessary R_cur_r)
1126 if (NULL != R_last_ij)
1128 // Assign R_temp_ij to R_last_ij and remove epsilon as well
1129 // as parentheses, so we can better compare the contents
1130 R_temp_ij = remove_parentheses (remove_epsilon (R_last_ij));
1132 if (0 == strcmp (R_temp_ij, R_temp_ik) && 0 == strcmp (R_temp_ik, R_temp_kk)
1133 && 0 == strcmp (R_temp_kk, R_temp_kj))
1135 if (0 == strlen (R_temp_ij))
1137 R_cur_r = GNUNET_strdup ("");
1139 else if ((0 == strncmp (R_last_ij, "(|", 2)) ||
1140 (0 == strncmp (R_last_ik, "(|", 2) &&
1141 0 == strncmp (R_last_kj, "(|", 2)))
1143 // a|(e|a)a*(e|a) = a*
1144 // a|(e|a)(e|a)*(e|a) = a*
1146 // (e|a)|aa*(e|a) = a*
1147 // (e|a)|(e|a)a*a = a*
1148 // (e|a)|(e|a)a*(e|a) = a*
1149 // (e|a)|(e|a)(e|a)*(e|a) = a*
1150 if (GNUNET_YES == needs_parentheses (R_temp_ij))
1151 GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_ij);
1153 GNUNET_asprintf (&R_cur_r, "%s*", R_temp_ij);
1160 // a|(e|a)(e|a)*a = a+
1161 // a|a(e|a)*(e|a) = a+
1162 if (GNUNET_YES == needs_parentheses (R_temp_ij))
1163 GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_ij);
1165 GNUNET_asprintf (&R_cur_r, "%s+", R_temp_ij);
1168 else if (0 == ij_ik_cmp && 0 == clean_kk_kj_cmp && 0 != clean_ik_kk_cmp)
1171 if (strlen (R_last_kk) < 1)
1172 R_cur_r = GNUNET_strdup (R_last_ij);
1173 else if (GNUNET_YES == needs_parentheses (R_temp_kk))
1174 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
1176 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_last_kk);
1180 else if (0 == ij_kj_cmp && 0 == clean_ik_kk_cmp && 0 != clean_kk_kj_cmp)
1183 if (strlen (R_last_kk) < 1)
1184 R_cur_r = GNUNET_strdup (R_last_kj);
1185 else if (GNUNET_YES == needs_parentheses (R_temp_kk))
1186 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
1188 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
1192 else if (0 == ij_ik_cmp && 0 == kk_kj_cmp && !has_epsilon (R_last_ij) &&
1193 has_epsilon (R_last_kk))
1195 // a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab*
1196 if (needs_parentheses (R_temp_kk))
1197 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
1199 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_temp_kk);
1203 else if (0 == ij_kj_cmp && 0 == ik_kk_cmp && !has_epsilon (R_last_ij) &&
1204 has_epsilon (R_last_kk))
1206 // a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|... = b*a
1207 if (needs_parentheses (R_temp_kk))
1208 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_ij);
1210 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_ij);
1216 temp_a = (NULL == R_last_ij) ? NULL : GNUNET_strdup (R_last_ij);
1217 temp_a = remove_parentheses (temp_a);
1221 GNUNET_free_non_null (R_temp_ij);
1225 // we have no left side
1229 // construct R_cur_r, if not already constructed
1230 if (NULL == R_cur_r)
1232 length = strlen (R_temp_kk) - strlen (R_last_ik);
1234 // a(ba)*bx = (ab)+x
1235 if (length > 0 && NULL != R_last_kk && 0 < strlen (R_last_kk) &&
1236 NULL != R_last_kj && 0 < strlen (R_last_kj) && NULL != R_last_ik &&
1237 0 < strlen (R_last_ik) && 0 == strkcmp (R_temp_kk, R_last_ik, length) &&
1238 0 == strncmp (R_temp_kk, R_last_kj, length))
1240 temp_a = GNUNET_malloc (length + 1);
1241 temp_b = GNUNET_malloc ((strlen (R_last_kj) - length) + 1);
1246 for (cnt = 0; cnt < strlen (R_last_kj); cnt++)
1250 temp_a[length_l] = R_last_kj[cnt];
1255 temp_b[length_r] = R_last_kj[cnt];
1259 temp_a[length_l] = '\0';
1260 temp_b[length_r] = '\0';
1263 if (NULL != R_cur_l && 0 == strlen (R_cur_l) && 0 == strlen (temp_b))
1265 GNUNET_asprintf (&R_cur_r, "(%s%s)*", R_last_ik, temp_a);
1266 GNUNET_free (R_cur_l);
1271 GNUNET_asprintf (&R_cur_r, "(%s%s)+%s", R_last_ik, temp_a, temp_b);
1273 GNUNET_free (temp_a);
1274 GNUNET_free (temp_b);
1276 else if (0 == strcmp (R_temp_ik, R_temp_kk) &&
1277 0 == strcmp (R_temp_kk, R_temp_kj))
1279 // (e|a)a*(e|a) = a*
1280 // (e|a)(e|a)*(e|a) = a*
1281 if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj))
1283 if (needs_parentheses (R_temp_kk))
1284 GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_kk);
1286 GNUNET_asprintf (&R_cur_r, "%s*", R_temp_kk);
1289 else if (0 == clean_ik_kk_cmp && 0 == clean_kk_kj_cmp &&
1290 !has_epsilon (R_last_ik))
1292 if (needs_parentheses (R_temp_kk))
1293 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1295 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1299 // a(e|a)*(e|a) = a+
1304 (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
1305 has_epsilon (R_last_kj));
1309 if (needs_parentheses (R_temp_kk))
1310 GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_kk);
1312 GNUNET_asprintf (&R_cur_r, "%s+", R_temp_kk);
1317 // (e|a)(e|a)*b = a*b
1318 else if (0 == strcmp (R_temp_ik, R_temp_kk))
1320 if (has_epsilon (R_last_ik))
1322 if (needs_parentheses (R_temp_kk))
1323 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
1325 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
1329 if (needs_parentheses (R_temp_kk))
1330 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_last_kj);
1332 GNUNET_asprintf (&R_cur_r, "%s+%s", R_temp_kk, R_last_kj);
1336 // b(e|a)*(e|a) = ba*
1337 else if (0 == strcmp (R_temp_kk, R_temp_kj))
1339 if (has_epsilon (R_last_kj))
1341 if (needs_parentheses (R_temp_kk))
1342 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ik, R_temp_kk);
1344 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ik, R_temp_kk);
1348 if (needs_parentheses (R_temp_kk))
1349 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_last_ik, R_temp_kk);
1351 GNUNET_asprintf (&R_cur_r, "%s+%s", R_last_ik, R_temp_kk);
1356 if (strlen (R_temp_kk) > 0)
1358 if (needs_parentheses (R_temp_kk))
1360 GNUNET_asprintf (&R_cur_r, "%s(%s)*%s", R_last_ik, R_temp_kk,
1365 GNUNET_asprintf (&R_cur_r, "%s%s*%s", R_last_ik, R_temp_kk,
1371 GNUNET_asprintf (&R_cur_r, "%s%s", R_last_ik, R_last_kj);
1376 if (NULL == R_cur_l && NULL == R_cur_r)
1382 if (NULL != R_cur_l && NULL == R_cur_r)
1384 *R_cur_ij = GNUNET_strdup (R_cur_l);
1388 if (NULL == R_cur_l && NULL != R_cur_r)
1390 *R_cur_ij = GNUNET_strdup (R_cur_r);
1394 if (0 == nullstrcmp (R_cur_l, R_cur_r))
1396 *R_cur_ij = GNUNET_strdup (R_cur_l);
1400 GNUNET_asprintf (R_cur_ij, "(%s|%s)", R_cur_l, R_cur_r);
1402 GNUNET_free_non_null (R_cur_l);
1403 GNUNET_free_non_null (R_cur_r);
1405 GNUNET_free_non_null (R_temp_ik);
1406 GNUNET_free_non_null (R_temp_kk);
1407 GNUNET_free_non_null (R_temp_kj);
1412 * create proofs for all states in the given automaton. Implementation of the
1413 * algorithm descriped in chapter 3.2.1 of "Automata Theory, Languages, and
1414 * Computation 3rd Edition" by Hopcroft, Motwani and Ullman.
1416 * @param a automaton.
1419 automaton_create_proofs (struct GNUNET_REGEX_Automaton *a)
1421 unsigned int n = a->state_count;
1422 struct GNUNET_REGEX_State *states[n];
1426 struct Transition *t;
1427 char *complete_regex;
1433 /* create depth-first numbering of the states, initializes 'state' */
1434 automaton_traverse (a, &number_states, states);
1436 /* Compute regular expressions of length "1" between each pair of states */
1437 for (i = 0; i < n; i++)
1439 for (j = 0; j < n; j++)
1442 R_last[i][j] = NULL;
1444 for (t = states[i]->transitions_head; NULL != t; t = t->next)
1446 j = t->to_state->proof_id;
1447 if (NULL == R_last[i][j])
1448 GNUNET_asprintf (&R_last[i][j], "%c", t->label);
1451 temp = R_last[i][j];
1452 GNUNET_asprintf (&R_last[i][j], "%s|%c", R_last[i][j], t->label);
1456 if (NULL == R_last[i][i])
1457 GNUNET_asprintf (&R_last[i][i], "");
1460 temp = R_last[i][i];
1461 GNUNET_asprintf (&R_last[i][i], "(|%s)", R_last[i][i]);
1465 for (i = 0; i < n; i++)
1466 for (j = 0; j < n; j++)
1467 if (needs_parentheses (R_last[i][j]))
1469 temp = R_last[i][j];
1470 GNUNET_asprintf (&R_last[i][j], "(%s)", R_last[i][j]);
1474 /* Compute regular expressions of length "k" between each pair of states per induction */
1475 for (k = 0; k < n; k++)
1477 for (i = 0; i < n; i++)
1479 for (j = 0; j < n; j++)
1481 // Basis for the recursion:
1482 // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1483 // R_last == R^{(k-1)}, R_cur == R^{(k)}
1485 // Create R_cur[i][j] and simplify the expression
1486 automaton_create_proofs_simplify (R_last[i][j], R_last[i][k],
1487 R_last[k][k], R_last[k][j],
1492 // set R_last = R_cur
1493 for (i = 0; i < n; i++)
1495 for (j = 0; j < n; j++)
1497 GNUNET_free_non_null (R_last[i][j]);
1498 R_last[i][j] = R_cur[i][j];
1504 // assign proofs and hashes
1505 for (i = 0; i < n; i++)
1507 if (NULL != R_last[a->start->proof_id][i])
1509 states[i]->proof = GNUNET_strdup (R_last[a->start->proof_id][i]);
1510 GNUNET_CRYPTO_hash (states[i]->proof, strlen (states[i]->proof),
1515 // complete regex for whole DFA: union of all pairs (start state/accepting state(s)).
1516 complete_regex = NULL;
1517 for (i = 0; i < n; i++)
1519 if (states[i]->accepting)
1521 if (NULL == complete_regex && 0 < strlen (R_last[a->start->proof_id][i]))
1523 GNUNET_asprintf (&complete_regex, "%s", R_last[a->start->proof_id][i]);
1525 else if (NULL != R_last[a->start->proof_id][i] &&
1526 0 < strlen (R_last[a->start->proof_id][i]))
1528 temp = complete_regex;
1529 GNUNET_asprintf (&complete_regex, "%s|%s", complete_regex,
1530 R_last[a->start->proof_id][i]);
1535 a->canonical_regex = complete_regex;
1537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1538 "---------------------------------------------\n");
1539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex: %s\n", a->regex);
1540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Complete Regex: %s\n", complete_regex);
1541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1542 "---------------------------------------------\n");
1545 for (i = 0; i < n; i++)
1547 for (j = 0; j < n; j++)
1548 GNUNET_free_non_null (R_last[i][j]);
1553 * Creates a new DFA state based on a set of NFA states. Needs to be freed using
1554 * automaton_destroy_state.
1556 * @param ctx context
1557 * @param nfa_states set of NFA states on which the DFA should be based on
1559 * @return new DFA state
1561 static struct GNUNET_REGEX_State *
1562 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
1563 struct GNUNET_REGEX_StateSet *nfa_states)
1565 struct GNUNET_REGEX_State *s;
1568 struct GNUNET_REGEX_State *cstate;
1569 struct Transition *ctran;
1572 s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1573 s->id = ctx->state_id++;
1583 if (NULL == nfa_states)
1585 GNUNET_asprintf (&s->name, "s%i", s->id);
1589 s->nfa_set = nfa_states;
1591 if (nfa_states->len < 1)
1594 // Create a name based on 'sset'
1595 s->name = GNUNET_malloc (sizeof (char) * 2);
1596 strcat (s->name, "{");
1599 for (i = 0; i < nfa_states->len; i++)
1601 cstate = nfa_states->states[i];
1602 GNUNET_asprintf (&name, "%i,", cstate->id);
1606 len = strlen (s->name) + strlen (name) + 1;
1607 s->name = GNUNET_realloc (s->name, len);
1608 strcat (s->name, name);
1613 // Add a transition for each distinct label to NULL state
1614 for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
1616 if (0 != ctran->label)
1617 state_add_transition (ctx, s, ctran->label, NULL);
1620 // If the nfa_states contain an accepting state, the new dfa state is also
1622 if (cstate->accepting)
1626 s->name[strlen (s->name) - 1] = '}';
1632 * Move from the given state 's' to the next state on transition 'label'
1634 * @param s starting state
1635 * @param label edge label to follow
1637 * @return new state or NULL, if transition on label not possible
1639 static struct GNUNET_REGEX_State *
1640 dfa_move (struct GNUNET_REGEX_State *s, const char label)
1642 struct Transition *t;
1643 struct GNUNET_REGEX_State *new_s;
1650 for (t = s->transitions_head; NULL != t; t = t->next)
1652 if (label == t->label)
1654 new_s = t->to_state;
1663 * Remove all unreachable states from DFA 'a'. Unreachable states are those
1664 * states that are not reachable from the starting state.
1666 * @param a DFA automaton
1669 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
1671 struct GNUNET_REGEX_State *s;
1672 struct GNUNET_REGEX_State *s_next;
1674 // 1. unmark all states
1675 for (s = a->states_head; NULL != s; s = s->next)
1676 s->marked = GNUNET_NO;
1678 // 2. traverse dfa from start state and mark all visited states
1679 automaton_traverse (a, NULL, NULL);
1681 // 3. delete all states that were not visited
1682 for (s = a->states_head; NULL != s; s = s_next)
1685 if (GNUNET_NO == s->marked)
1686 automaton_remove_state (a, s);
1691 * Remove all dead states from the DFA 'a'. Dead states are those states that do
1692 * not transition to any other state but themselfes.
1694 * @param a DFA automaton
1697 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
1699 struct GNUNET_REGEX_State *s;
1700 struct Transition *t;
1703 GNUNET_assert (DFA == a->type);
1705 for (s = a->states_head; NULL != s; s = s->next)
1711 for (t = s->transitions_head; NULL != t; t = t->next)
1713 if (NULL != t->to_state && t->to_state != s)
1723 // state s is dead, remove it
1724 automaton_remove_state (a, s);
1729 * Merge all non distinguishable states in the DFA 'a'
1731 * @param ctx context
1732 * @param a DFA automaton
1735 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
1736 struct GNUNET_REGEX_Automaton *a)
1739 int table[a->state_count][a->state_count];
1740 struct GNUNET_REGEX_State *s1;
1741 struct GNUNET_REGEX_State *s2;
1742 struct Transition *t1;
1743 struct Transition *t2;
1744 struct GNUNET_REGEX_State *s1_next;
1745 struct GNUNET_REGEX_State *s2_next;
1747 unsigned int num_equal_edges;
1749 for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
1755 // Mark all pairs of accepting/!accepting states
1756 for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1758 for (s2 = a->states_head; NULL != s2; s2 = s2->next)
1760 table[s1->marked][s2->marked] = 0;
1762 if ((s1->accepting && !s2->accepting) ||
1763 (!s1->accepting && s2->accepting))
1765 table[s1->marked][s2->marked] = 1;
1770 // Find all equal states
1775 for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1777 for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
1779 if (0 != table[s1->marked][s2->marked])
1782 num_equal_edges = 0;
1783 for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
1785 for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
1787 if (t1->label == t2->label)
1790 if (0 != table[t1->to_state->marked][t2->to_state->marked] ||
1791 0 != table[t2->to_state->marked][t1->to_state->marked])
1793 table[s1->marked][s2->marked] = t1->label != 0 ? t1->label : 1;
1799 if (num_equal_edges != s1->transition_count ||
1800 num_equal_edges != s2->transition_count)
1802 // Make sure ALL edges of possible equal states are the same
1803 table[s1->marked][s2->marked] = -2;
1809 // Merge states that are equal
1810 for (s1 = a->states_head; NULL != s1; s1 = s1_next)
1813 for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
1816 if (table[s1->marked][s2->marked] == 0)
1817 automaton_merge_states (ctx, a, s1, s2);
1823 * Minimize the given DFA 'a' by removing all unreachable states, removing all
1824 * dead states and merging all non distinguishable states
1826 * @param ctx context
1827 * @param a DFA automaton
1830 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
1831 struct GNUNET_REGEX_Automaton *a)
1836 GNUNET_assert (DFA == a->type);
1838 // 1. remove unreachable states
1839 dfa_remove_unreachable_states (a);
1841 // 2. remove dead states
1842 dfa_remove_dead_states (a);
1844 // 3. Merge nondistinguishable states
1845 dfa_merge_nondistinguishable_states (ctx, a);
1849 * Creates a new NFA fragment. Needs to be cleared using
1850 * automaton_fragment_clear.
1852 * @param start starting state
1853 * @param end end state
1855 * @return new NFA fragment
1857 static struct GNUNET_REGEX_Automaton *
1858 nfa_fragment_create (struct GNUNET_REGEX_State *start,
1859 struct GNUNET_REGEX_State *end)
1861 struct GNUNET_REGEX_Automaton *n;
1863 n = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1869 if (NULL == start && NULL == end)
1872 automaton_add_state (n, end);
1873 automaton_add_state (n, start);
1882 * Adds a list of states to the given automaton 'n'.
1884 * @param n automaton to which the states should be added
1885 * @param states_head head of the DLL of states
1886 * @param states_tail tail of the DLL of states
1889 nfa_add_states (struct GNUNET_REGEX_Automaton *n,
1890 struct GNUNET_REGEX_State *states_head,
1891 struct GNUNET_REGEX_State *states_tail)
1893 struct GNUNET_REGEX_State *s;
1895 if (NULL == n || NULL == states_head)
1897 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n");
1901 if (NULL == n->states_head)
1903 n->states_head = states_head;
1904 n->states_tail = states_tail;
1908 if (NULL != states_head)
1910 n->states_tail->next = states_head;
1911 n->states_tail = states_tail;
1914 for (s = states_head; NULL != s; s = s->next)
1919 * Creates a new NFA state. Needs to be freed using automaton_destroy_state.
1921 * @param ctx context
1922 * @param accepting is it an accepting state or not
1924 * @return new NFA state
1926 static struct GNUNET_REGEX_State *
1927 nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
1929 struct GNUNET_REGEX_State *s;
1931 s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1932 s->id = ctx->state_id++;
1933 s->accepting = accepting;
1940 GNUNET_asprintf (&s->name, "s%i", s->id);
1946 * Calculates the NFA closure set for the given state.
1948 * @param nfa the NFA containing 's'
1949 * @param s starting point state
1950 * @param label transitioning label on which to base the closure on,
1951 * pass 0 for epsilon transition
1953 * @return sorted nfa closure on 'label' (epsilon closure if 'label' is 0)
1955 static struct GNUNET_REGEX_StateSet *
1956 nfa_closure_create (struct GNUNET_REGEX_Automaton *nfa,
1957 struct GNUNET_REGEX_State *s, const char label)
1959 struct GNUNET_REGEX_StateSet *cls;
1960 struct GNUNET_REGEX_StateSet *cls_check;
1961 struct GNUNET_REGEX_State *clsstate;
1962 struct GNUNET_REGEX_State *currentstate;
1963 struct Transition *ctran;
1968 cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1969 cls_check = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
1971 for (clsstate = nfa->states_head; NULL != clsstate; clsstate = clsstate->next)
1972 clsstate->contained = 0;
1974 // Add start state to closure only for epsilon closure
1976 GNUNET_array_append (cls->states, cls->len, s);
1978 GNUNET_array_append (cls_check->states, cls_check->len, s);
1979 while (cls_check->len > 0)
1981 currentstate = cls_check->states[cls_check->len - 1];
1982 GNUNET_array_grow (cls_check->states, cls_check->len, cls_check->len - 1);
1984 for (ctran = currentstate->transitions_head; NULL != ctran;
1985 ctran = ctran->next)
1987 if (NULL != ctran->to_state && label == ctran->label)
1989 clsstate = ctran->to_state;
1991 if (NULL != clsstate && 0 == clsstate->contained)
1993 GNUNET_array_append (cls->states, cls->len, clsstate);
1994 GNUNET_array_append (cls_check->states, cls_check->len, clsstate);
1995 clsstate->contained = 1;
2000 GNUNET_assert (0 == cls_check->len);
2001 GNUNET_free (cls_check);
2005 qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
2012 * Calculates the closure set for the given set of states.
2014 * @param nfa the NFA containing 's'
2015 * @param states list of states on which to base the closure on
2016 * @param label transitioning label for which to base the closure on,
2017 * pass 0 for epsilon transition
2019 * @return sorted nfa closure on 'label' (epsilon closure if 'label' is 0)
2021 static struct GNUNET_REGEX_StateSet *
2022 nfa_closure_set_create (struct GNUNET_REGEX_Automaton *nfa,
2023 struct GNUNET_REGEX_StateSet *states, const char label)
2025 struct GNUNET_REGEX_State *s;
2026 struct GNUNET_REGEX_StateSet *sset;
2027 struct GNUNET_REGEX_StateSet *cls;
2031 unsigned int contains;
2036 cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
2038 for (i = 0; i < states->len; i++)
2040 s = states->states[i];
2041 sset = nfa_closure_create (nfa, s, label);
2043 for (j = 0; j < sset->len; j++)
2046 for (k = 0; k < cls->len; k++)
2048 if (sset->states[j]->id == cls->states[k]->id)
2055 GNUNET_array_append (cls->states, cls->len, sset->states[j]);
2057 state_set_clear (sset);
2061 qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
2068 * Pops two NFA fragments (a, b) from the stack and concatenates them (ab)
2070 * @param ctx context
2073 nfa_add_concatenation (struct GNUNET_REGEX_Context *ctx)
2075 struct GNUNET_REGEX_Automaton *a;
2076 struct GNUNET_REGEX_Automaton *b;
2077 struct GNUNET_REGEX_Automaton *new;
2079 b = ctx->stack_tail;
2080 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2081 a = ctx->stack_tail;
2082 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2084 state_add_transition (ctx, a->end, 0, b->start);
2085 a->end->accepting = 0;
2086 b->end->accepting = 1;
2088 new = nfa_fragment_create (NULL, NULL);
2089 nfa_add_states (new, a->states_head, a->states_tail);
2090 nfa_add_states (new, b->states_head, b->states_tail);
2091 new->start = a->start;
2093 automaton_fragment_clear (a);
2094 automaton_fragment_clear (b);
2096 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
2100 * Pops a NFA fragment from the stack (a) and adds a new fragment (a*)
2102 * @param ctx context
2105 nfa_add_star_op (struct GNUNET_REGEX_Context *ctx)
2107 struct GNUNET_REGEX_Automaton *a;
2108 struct GNUNET_REGEX_Automaton *new;
2109 struct GNUNET_REGEX_State *start;
2110 struct GNUNET_REGEX_State *end;
2112 a = ctx->stack_tail;
2113 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2117 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2118 "nfa_add_star_op failed, because there was no element on the stack");
2122 start = nfa_state_create (ctx, 0);
2123 end = nfa_state_create (ctx, 1);
2125 state_add_transition (ctx, start, 0, a->start);
2126 state_add_transition (ctx, start, 0, end);
2127 state_add_transition (ctx, a->end, 0, a->start);
2128 state_add_transition (ctx, a->end, 0, end);
2130 a->end->accepting = 0;
2133 new = nfa_fragment_create (start, end);
2134 nfa_add_states (new, a->states_head, a->states_tail);
2135 automaton_fragment_clear (a);
2137 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
2141 * Pops an NFA fragment (a) from the stack and adds a new fragment (a+)
2143 * @param ctx context
2146 nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
2148 struct GNUNET_REGEX_Automaton *a;
2150 a = ctx->stack_tail;
2151 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2153 state_add_transition (ctx, a->end, 0, a->start);
2155 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a);
2159 * Pops an NFA fragment (a) from the stack and adds a new fragment (a?)
2161 * @param ctx context
2164 nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
2166 struct GNUNET_REGEX_Automaton *a;
2167 struct GNUNET_REGEX_Automaton *new;
2168 struct GNUNET_REGEX_State *start;
2169 struct GNUNET_REGEX_State *end;
2171 a = ctx->stack_tail;
2172 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2176 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2177 "nfa_add_question_op failed, because there was no element on the stack");
2181 start = nfa_state_create (ctx, 0);
2182 end = nfa_state_create (ctx, 1);
2184 state_add_transition (ctx, start, 0, a->start);
2185 state_add_transition (ctx, start, 0, end);
2186 state_add_transition (ctx, a->end, 0, end);
2188 a->end->accepting = 0;
2190 new = nfa_fragment_create (start, end);
2191 nfa_add_states (new, a->states_head, a->states_tail);
2192 automaton_fragment_clear (a);
2194 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
2198 * Pops two NFA fragments (a, b) from the stack and adds a new NFA fragment that
2199 * alternates between a and b (a|b)
2201 * @param ctx context
2204 nfa_add_alternation (struct GNUNET_REGEX_Context *ctx)
2206 struct GNUNET_REGEX_Automaton *a;
2207 struct GNUNET_REGEX_Automaton *b;
2208 struct GNUNET_REGEX_Automaton *new;
2209 struct GNUNET_REGEX_State *start;
2210 struct GNUNET_REGEX_State *end;
2212 b = ctx->stack_tail;
2213 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2214 a = ctx->stack_tail;
2215 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2217 start = nfa_state_create (ctx, 0);
2218 end = nfa_state_create (ctx, 1);
2219 state_add_transition (ctx, start, 0, a->start);
2220 state_add_transition (ctx, start, 0, b->start);
2222 state_add_transition (ctx, a->end, 0, end);
2223 state_add_transition (ctx, b->end, 0, end);
2225 a->end->accepting = 0;
2226 b->end->accepting = 0;
2229 new = nfa_fragment_create (start, end);
2230 nfa_add_states (new, a->states_head, a->states_tail);
2231 nfa_add_states (new, b->states_head, b->states_tail);
2232 automaton_fragment_clear (a);
2233 automaton_fragment_clear (b);
2235 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new);
2239 * Adds a new nfa fragment to the stack
2241 * @param ctx context
2242 * @param lit label for nfa transition
2245 nfa_add_label (struct GNUNET_REGEX_Context *ctx, const char lit)
2247 struct GNUNET_REGEX_Automaton *n;
2248 struct GNUNET_REGEX_State *start;
2249 struct GNUNET_REGEX_State *end;
2251 GNUNET_assert (NULL != ctx);
2253 start = nfa_state_create (ctx, 0);
2254 end = nfa_state_create (ctx, 1);
2255 state_add_transition (ctx, start, lit, end);
2256 n = nfa_fragment_create (start, end);
2257 GNUNET_assert (NULL != n);
2258 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n);
2262 * Initialize a new context
2264 * @param ctx context
2267 GNUNET_REGEX_context_init (struct GNUNET_REGEX_Context *ctx)
2271 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!");
2275 ctx->transition_id = 0;
2276 ctx->stack_head = NULL;
2277 ctx->stack_tail = NULL;
2281 * Construct an NFA by parsing the regex string of length 'len'.
2283 * @param regex regular expression string
2284 * @param len length of the string
2286 * @return NFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2288 struct GNUNET_REGEX_Automaton *
2289 GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
2291 struct GNUNET_REGEX_Context ctx;
2292 struct GNUNET_REGEX_Automaton *nfa;
2296 unsigned int altcount;
2297 unsigned int atomcount;
2298 unsigned int pcount;
2305 GNUNET_REGEX_context_init (&ctx);
2314 for (count = 0; count < len && *regexp; count++, regexp++)
2322 nfa_add_concatenation (&ctx);
2324 GNUNET_array_grow (p, pcount, pcount + 1);
2325 p[pcount - 1].altcount = altcount;
2326 p[pcount - 1].atomcount = atomcount;
2333 error_msg = "Cannot append '|' to nothing";
2336 while (--atomcount > 0)
2337 nfa_add_concatenation (&ctx);
2343 error_msg = "Missing opening '('";
2348 // Ignore this: "()"
2350 altcount = p[pcount].altcount;
2351 atomcount = p[pcount].atomcount;
2354 while (--atomcount > 0)
2355 nfa_add_concatenation (&ctx);
2356 for (; altcount > 0; altcount--)
2357 nfa_add_alternation (&ctx);
2359 altcount = p[pcount].altcount;
2360 atomcount = p[pcount].atomcount;
2366 error_msg = "Cannot append '*' to nothing";
2369 nfa_add_star_op (&ctx);
2374 error_msg = "Cannot append '+' to nothing";
2377 nfa_add_plus_op (&ctx);
2382 error_msg = "Cannot append '?' to nothing";
2385 nfa_add_question_op (&ctx);
2387 case 92: /* escape: \ */
2394 nfa_add_concatenation (&ctx);
2396 nfa_add_label (&ctx, *regexp);
2403 error_msg = "Unbalanced parenthesis";
2406 while (--atomcount > 0)
2407 nfa_add_concatenation (&ctx);
2408 for (; altcount > 0; altcount--)
2409 nfa_add_alternation (&ctx);
2411 GNUNET_free_non_null (p);
2413 nfa = ctx.stack_tail;
2414 GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2416 if (NULL != ctx.stack_head)
2418 error_msg = "Creating the NFA failed. NFA stack was not empty!";
2422 nfa->regex = GNUNET_strdup (regex);
2427 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: %s\n", regex);
2428 if (NULL != error_msg)
2429 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
2431 GNUNET_free_non_null (p);
2433 while (NULL != (nfa = ctx.stack_head))
2435 GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2436 GNUNET_REGEX_automaton_destroy (nfa);
2443 * Create DFA states based on given 'nfa' and starting with 'dfa_state'.
2445 * @param ctx context.
2446 * @param nfa NFA automaton.
2447 * @param dfa DFA automaton.
2448 * @param dfa_state current dfa state, pass epsilon closure of first nfa state
2452 construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
2453 struct GNUNET_REGEX_Automaton *nfa,
2454 struct GNUNET_REGEX_Automaton *dfa,
2455 struct GNUNET_REGEX_State *dfa_state)
2457 struct Transition *ctran;
2458 struct GNUNET_REGEX_State *state_iter;
2459 struct GNUNET_REGEX_State *new_dfa_state;
2460 struct GNUNET_REGEX_State *state_contains;
2461 struct GNUNET_REGEX_StateSet *tmp;
2462 struct GNUNET_REGEX_StateSet *nfa_set;
2464 for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next)
2466 if (0 == ctran->label || NULL != ctran->to_state)
2469 tmp = nfa_closure_set_create (nfa, dfa_state->nfa_set, ctran->label);
2470 nfa_set = nfa_closure_set_create (nfa, tmp, 0);
2471 state_set_clear (tmp);
2472 new_dfa_state = dfa_state_create (ctx, nfa_set);
2473 state_contains = NULL;
2474 for (state_iter = dfa->states_head; NULL != state_iter;
2475 state_iter = state_iter->next)
2477 if (0 == state_set_compare (state_iter->nfa_set, new_dfa_state->nfa_set))
2478 state_contains = state_iter;
2481 if (NULL == state_contains)
2483 automaton_add_state (dfa, new_dfa_state);
2484 ctran->to_state = new_dfa_state;
2485 construct_dfa_states (ctx, nfa, dfa, new_dfa_state);
2489 ctran->to_state = state_contains;
2490 automaton_destroy_state (new_dfa_state);
2496 * Construct DFA for the given 'regex' of length 'len'
2498 * @param regex regular expression string
2499 * @param len length of the regular expression
2501 * @return DFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2503 struct GNUNET_REGEX_Automaton *
2504 GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
2506 struct GNUNET_REGEX_Context ctx;
2507 struct GNUNET_REGEX_Automaton *dfa;
2508 struct GNUNET_REGEX_Automaton *nfa;
2509 struct GNUNET_REGEX_StateSet *nfa_set;
2511 GNUNET_REGEX_context_init (&ctx);
2514 nfa = GNUNET_REGEX_construct_nfa (regex, len);
2518 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2519 "Could not create DFA, because NFA creation failed\n");
2523 dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
2525 dfa->regex = GNUNET_strdup (regex);
2527 // Create DFA start state from epsilon closure
2528 nfa_set = nfa_closure_create (nfa, nfa->start, 0);
2529 dfa->start = dfa_state_create (&ctx, nfa_set);
2530 automaton_add_state (dfa, dfa->start);
2532 construct_dfa_states (&ctx, nfa, dfa, dfa->start);
2534 GNUNET_REGEX_automaton_destroy (nfa);
2537 dfa_minimize (&ctx, dfa);
2539 // Create proofs for all states
2540 automaton_create_proofs (dfa);
2546 * Free the memory allocated by constructing the GNUNET_REGEX_Automaton data
2549 * @param a automaton to be destroyed
2552 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
2554 struct GNUNET_REGEX_State *s;
2555 struct GNUNET_REGEX_State *next_state;
2560 GNUNET_free_non_null (a->regex);
2561 GNUNET_free_non_null (a->canonical_regex);
2563 for (s = a->states_head; NULL != s;)
2565 next_state = s->next;
2566 automaton_destroy_state (s);
2574 * Save a state to an open file pointer. cls is expected to be a file pointer to
2575 * an open file. Used only in conjunction with
2576 * GNUNET_REGEX_automaton_save_graph.
2578 * @param cls file pointer.
2579 * @param count current count of the state, not used.
2583 GNUNET_REGEX_automaton_save_graph_step (void *cls, unsigned int count,
2584 struct GNUNET_REGEX_State *s)
2587 struct Transition *ctran;
2589 char *s_tran = NULL;
2595 GNUNET_asprintf (&s_acc,
2596 "\"%s(%i)\" [shape=doublecircle, color=\"0.%i 0.8 0.95\"];\n",
2597 s->name, s->proof_id, s->scc_id);
2601 GNUNET_asprintf (&s_acc, "\"%s(%i)\" [color=\"0.%i 0.8 0.95\"];\n", s->name,
2602 s->proof_id, s->scc_id);
2607 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print state %s\n", s->name);
2610 fwrite (s_acc, strlen (s_acc), 1, p);
2611 GNUNET_free (s_acc);
2614 for (ctran = s->transitions_head; NULL != ctran; ctran = ctran->next)
2616 if (NULL == ctran->to_state)
2618 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2619 "Transition from State %i has no state for transitioning\n",
2624 if (ctran->label == 0)
2626 GNUNET_asprintf (&s_tran,
2627 "\"%s(%i)\" -> \"%s(%i)\" [label = \"epsilon\", color=\"0.%i 0.8 0.95\"];\n",
2628 s->name, s->proof_id, ctran->to_state->name,
2629 ctran->to_state->proof_id, s->scc_id);
2633 GNUNET_asprintf (&s_tran,
2634 "\"%s(%i)\" -> \"%s(%i)\" [label = \"%c\", color=\"0.%i 0.8 0.95\"];\n",
2635 s->name, s->proof_id, ctran->to_state->name,
2636 ctran->to_state->proof_id, ctran->label, s->scc_id);
2641 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print state %s\n",
2646 fwrite (s_tran, strlen (s_tran), 1, p);
2647 GNUNET_free (s_tran);
2653 * Save the given automaton as a GraphViz dot file
2655 * @param a the automaton to be saved
2656 * @param filename where to save the file
2659 GNUNET_REGEX_automaton_save_graph (struct GNUNET_REGEX_Automaton *a,
2660 const char *filename)
2668 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print NFA, was NULL!");
2672 if (NULL == filename || strlen (filename) < 1)
2674 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No Filename given!");
2678 p = fopen (filename, "w");
2682 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not open file for writing: %s",
2687 /* First add the SCCs to the automaton, so we can color them nicely */
2690 start = "digraph G {\nrankdir=LR\n";
2691 fwrite (start, strlen (start), 1, p);
2693 automaton_traverse (a, &GNUNET_REGEX_automaton_save_graph_step, p);
2696 fwrite (end, strlen (end), 1, p);
2701 * Evaluates the given string using the given DFA automaton
2703 * @param a automaton, type must be DFA
2704 * @param string string that should be evaluated
2706 * @return 0 if string matches, non 0 otherwise
2709 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2712 struct GNUNET_REGEX_State *s;
2716 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2717 "Tried to evaluate DFA, but NFA automaton given");
2723 // If the string is empty but the starting state is accepting, we accept.
2724 if ((NULL == string || 0 == strlen (string)) && s->accepting)
2727 for (strp = string; NULL != strp && *strp; strp++)
2729 s = dfa_move (s, *strp);
2734 if (NULL != s && s->accepting)
2741 * Evaluates the given string using the given NFA automaton
2743 * @param a automaton, type must be NFA
2744 * @param string string that should be evaluated
2746 * @return 0 if string matches, non 0 otherwise
2749 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2752 struct GNUNET_REGEX_State *s;
2753 struct GNUNET_REGEX_StateSet *sset;
2754 struct GNUNET_REGEX_StateSet *new_sset;
2760 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2761 "Tried to evaluate NFA, but DFA automaton given");
2765 // If the string is empty but the starting state is accepting, we accept.
2766 if ((NULL == string || 0 == strlen (string)) && a->start->accepting)
2771 sset = nfa_closure_create (a, a->start, 0);
2773 for (strp = string; NULL != strp && *strp; strp++)
2775 new_sset = nfa_closure_set_create (a, sset, *strp);
2776 state_set_clear (sset);
2777 sset = nfa_closure_set_create (a, new_sset, 0);
2778 state_set_clear (new_sset);
2781 for (i = 0; i < sset->len; i++)
2783 s = sset->states[i];
2784 if (NULL != s && s->accepting)
2791 state_set_clear (sset);
2796 * Evaluates the given 'string' against the given compiled regex
2798 * @param a automaton
2799 * @param string string to check
2801 * @return 0 if string matches, non 0 otherwise
2804 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
2811 result = evaluate_dfa (a, string);
2814 result = evaluate_nfa (a, string);
2817 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2818 "Evaluating regex failed, automaton has no type!\n");
2819 result = GNUNET_SYSERR;
2828 * Get the canonical regex of the given automaton.
2829 * When constructing the automaton a proof is computed for each state,
2830 * consisting of the regular expression leading to this state. A complete
2831 * regex for the automaton can be computed by combining these proofs.
2832 * As of now this function is only useful for testing.
2834 * @param a automaton for which the canonical regex should be returned.
2839 GNUNET_REGEX_get_canonical_regex (struct GNUNET_REGEX_Automaton *a)
2844 return a->canonical_regex;
2848 * Get the first key for the given 'input_string'. This hashes the first x bits
2849 * of the 'input_strings'.
2851 * @param input_string string.
2852 * @param string_len length of the 'input_string'.
2853 * @param key pointer to where to write the hash code.
2855 * @return number of bits of 'input_string' that have been consumed
2856 * to construct the key
2859 GNUNET_REGEX_get_first_key (const char *input_string, unsigned int string_len,
2860 struct GNUNET_HashCode *key)
2864 size = string_len < INITIAL_BITS ? string_len : INITIAL_BITS;
2866 if (NULL == input_string)
2868 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
2872 GNUNET_CRYPTO_hash (input_string, size, key);
2878 * Check if the given 'proof' matches the given 'key'.
2880 * @param proof partial regex
2883 * @return GNUNET_OK if the proof is valid for the given key
2886 GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
2892 * Iterate over all edges helper function starting from state 's', calling
2893 * iterator on for each edge.
2896 * @param iterator iterator function called for each edge.
2897 * @param iterator_cls closure.
2900 iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
2903 struct Transition *t;
2904 struct GNUNET_REGEX_Edge edges[s->transition_count];
2905 unsigned int num_edges;
2907 if (GNUNET_YES != s->marked)
2909 s->marked = GNUNET_YES;
2911 num_edges = state_get_edges (s, edges);
2913 iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges, edges);
2915 for (t = s->transitions_head; NULL != t; t = t->next)
2916 iterate_edge (t->to_state, iterator, iterator_cls);
2921 * Iterate over all edges starting from start state of automaton 'a'. Calling
2922 * iterator for each edge.
2924 * @param a automaton.
2925 * @param iterator iterator called for each edge.
2926 * @param iterator_cls closure.
2929 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2930 GNUNET_REGEX_KeyIterator iterator,
2933 struct GNUNET_REGEX_State *s;
2935 for (s = a->states_head; NULL != s; s = s->next)
2936 s->marked = GNUNET_NO;
2938 iterate_edge (a->start, iterator, iterator_cls);