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 Deterministic Finite Automatons (DFAs) from regular
23 * expressions (regexes). Used by mesh for announcing regexes in the network and
24 * matching strings against published regexes.
25 * @author Maximilian Szengel
28 #include "gnunet_container_lib.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_regex_lib.h"
31 #include "regex_internal.h"
34 * Set this to GNUNET_YES to enable state naming. Used to debug NFA->DFA
35 * creation. Disabled by default for better performance.
37 #define REGEX_DEBUG_DFA GNUNET_NO
41 * Set of states using MDLL API.
43 struct GNUNET_REGEX_StateSet_MDLL
48 struct GNUNET_REGEX_State *head;
53 struct GNUNET_REGEX_State *tail;
63 * Append state to the given StateSet '
65 * @param set set to be modified
66 * @param state state to be appended
69 state_set_append (struct GNUNET_REGEX_StateSet *set,
70 struct GNUNET_REGEX_State *state)
72 if (set->off == set->size)
73 GNUNET_array_grow (set->states, set->size, set->size * 2 + 4);
74 set->states[set->off++] = state;
79 * Compare two strings for equality. If either is NULL they are not equal.
81 * @param str1 first string for comparison.
82 * @param str2 second string for comparison.
84 * @return 0 if the strings are the same or both NULL, 1 or -1 if not.
87 nullstrcmp (const char *str1, const char *str2)
89 if ((NULL == str1) != (NULL == str2))
91 if ((NULL == str1) && (NULL == str2))
94 return strcmp (str1, str2);
99 * Adds a transition from one state to another on 'label'. Does not add
103 * @param from_state starting state for the transition
104 * @param label transition label
105 * @param to_state state to where the transition should point to
108 state_add_transition (struct GNUNET_REGEX_Context *ctx,
109 struct GNUNET_REGEX_State *from_state, const char *label,
110 struct GNUNET_REGEX_State *to_state)
112 struct GNUNET_REGEX_Transition *t;
113 struct GNUNET_REGEX_Transition *oth;
115 if (NULL == from_state)
117 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n");
121 /* Do not add duplicate state transitions */
122 for (t = from_state->transitions_head; NULL != t; t = t->next)
124 if (t->to_state == to_state && 0 == nullstrcmp (t->label, label) &&
125 t->from_state == from_state)
129 /* sort transitions by label */
130 for (oth = from_state->transitions_head; NULL != oth; oth = oth->next)
132 if (0 < nullstrcmp (oth->label, label))
136 t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
138 t->id = ctx->transition_id++;
140 t->label = GNUNET_strdup (label);
143 t->to_state = to_state;
144 t->from_state = from_state;
146 /* Add outgoing transition to 'from_state' */
147 from_state->transition_count++;
148 GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head,
149 from_state->transitions_tail, oth, t);
154 * Remove a 'transition' from 'state'.
156 * @param state state from which the to-be-removed transition originates.
157 * @param transition transition that should be removed from state 'state'.
160 state_remove_transition (struct GNUNET_REGEX_State *state,
161 struct GNUNET_REGEX_Transition *transition)
163 if (NULL == state || NULL == transition)
166 if (transition->from_state != state)
169 GNUNET_free_non_null (transition->label);
171 state->transition_count--;
172 GNUNET_CONTAINER_DLL_remove (state->transitions_head, state->transitions_tail,
175 GNUNET_free (transition);
180 * Compare two states. Used for sorting.
182 * @param a first state
183 * @param b second state
185 * @return an integer less than, equal to, or greater than zero
186 * if the first argument is considered to be respectively
187 * less than, equal to, or greater than the second.
190 state_compare (const void *a, const void *b)
192 struct GNUNET_REGEX_State **s1 = (struct GNUNET_REGEX_State **) a;
193 struct GNUNET_REGEX_State **s2 = (struct GNUNET_REGEX_State **) b;
195 return (*s1)->id - (*s2)->id;
200 * Get all edges leaving state 's'.
203 * @param edges all edges leaving 's', expected to be allocated and have enough
204 * space for s->transitions_count elements.
206 * @return number of edges.
209 state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
211 struct GNUNET_REGEX_Transition *t;
219 for (t = s->transitions_head; NULL != t; t = t->next)
221 if (NULL != t->to_state)
223 edges[count].label = t->label;
224 edges[count].destination = t->to_state->hash;
233 * Compare to state sets by comparing the id's of the states that are contained
234 * in each set. Both sets are expected to be sorted by id!
236 * @param sset1 first state set
237 * @param sset2 second state set
238 * @return 0 if the sets are equal, otherwise non-zero
241 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
242 struct GNUNET_REGEX_StateSet *sset2)
247 if (NULL == sset1 || NULL == sset2)
250 result = sset1->off - sset2->off;
255 for (i = 0; i < sset1->off; i++)
256 if (0 != (result = state_compare (&sset1->states[i], &sset2->states[i])))
263 * Clears the given StateSet 'set'
265 * @param set set to be cleared
268 state_set_clear (struct GNUNET_REGEX_StateSet *set)
270 GNUNET_array_grow (set->states, set->size, 0);
276 * Clears an automaton fragment. Does not destroy the states inside the
279 * @param a automaton to be cleared
282 automaton_fragment_clear (struct GNUNET_REGEX_Automaton *a)
289 a->states_head = NULL;
290 a->states_tail = NULL;
297 * Frees the memory used by State 's'
299 * @param s state that should be destroyed
302 automaton_destroy_state (struct GNUNET_REGEX_State *s)
304 struct GNUNET_REGEX_Transition *t;
305 struct GNUNET_REGEX_Transition *next_t;
310 GNUNET_free_non_null (s->name);
311 GNUNET_free_non_null (s->proof);
312 state_set_clear (&s->nfa_set);
313 for (t = s->transitions_head; NULL != t; t = next_t)
316 state_remove_transition (s, t);
324 * Remove a state from the given automaton 'a'. Always use this function when
325 * altering the states of an automaton. Will also remove all transitions leading
326 * to this state, before destroying it.
329 * @param s state to remove
332 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
333 struct GNUNET_REGEX_State *s)
335 struct GNUNET_REGEX_State *s_check;
336 struct GNUNET_REGEX_Transition *t_check;
337 struct GNUNET_REGEX_Transition *t_check_next;
339 if (NULL == a || NULL == s)
342 /* remove all transitions leading to this state */
343 for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
345 for (t_check = s_check->transitions_head; NULL != t_check;
346 t_check = t_check_next)
348 t_check_next = t_check->next;
349 if (t_check->to_state == s)
350 state_remove_transition (s_check, t_check);
355 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
358 automaton_destroy_state (s);
363 * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
364 * 's2'. 's1' will contain all (non-duplicate) outgoing transitions of 's2'.
368 * @param s1 first state
369 * @param s2 second state, will be destroyed
372 automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
373 struct GNUNET_REGEX_Automaton *a,
374 struct GNUNET_REGEX_State *s1,
375 struct GNUNET_REGEX_State *s2)
377 struct GNUNET_REGEX_State *s_check;
378 struct GNUNET_REGEX_Transition *t_check;
379 struct GNUNET_REGEX_Transition *t;
380 struct GNUNET_REGEX_Transition *t_next;
386 /* 1. Make all transitions pointing to s2 point to s1, unless this transition
387 * does not already exists, if it already exists remove transition. */
388 for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
390 for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next)
392 t_next = t_check->next;
394 if (s2 == t_check->to_state)
397 for (t = t_check->from_state->transitions_head; NULL != t; t = t->next)
399 if (t->to_state == s1 && 0 == strcmp (t_check->label, t->label))
402 if (GNUNET_NO == is_dup)
403 t_check->to_state = s1;
405 state_remove_transition (t_check->from_state, t_check);
410 /* 2. Add all transitions from s2 to sX to s1 */
411 for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
413 if (t_check->to_state != s1)
414 state_add_transition (ctx, s1, t_check->label, t_check->to_state);
417 /* 3. Rename s1 to {s1,s2} */
422 GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
423 GNUNET_free (new_name);
427 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
429 automaton_destroy_state (s2);
434 * Add a state to the automaton 'a', always use this function to alter the
435 * states DLL of the automaton.
437 * @param a automaton to add the state to
438 * @param s state that should be added
441 automaton_add_state (struct GNUNET_REGEX_Automaton *a,
442 struct GNUNET_REGEX_State *s)
444 GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s);
450 * Depth-first traversal (DFS) of all states that are reachable from state
451 * 's'. Performs 'action' on each visited state.
453 * @param s start state.
454 * @param marks an array of size a->state_count to remember which state was
456 * @param count current count of the state.
457 * @param check function that is checked before advancing on each transition
459 * @param check_cls closure for check.
460 * @param action action to be performed on each state.
461 * @param action_cls closure for action.
464 automaton_state_traverse (struct GNUNET_REGEX_State *s, int *marks,
466 GNUNET_REGEX_traverse_check check, void *check_cls,
467 GNUNET_REGEX_traverse_action action, void *action_cls)
469 struct GNUNET_REGEX_Transition *t;
471 if (GNUNET_YES == marks[s->traversal_id])
474 marks[s->traversal_id] = GNUNET_YES;
477 action (action_cls, *count, s);
481 for (t = s->transitions_head; NULL != t; t = t->next)
484 (NULL != check && GNUNET_YES == check (check_cls, s, t)))
486 automaton_state_traverse (t->to_state, marks, count, check, check_cls,
494 * Traverses the given automaton using depth-first-search (DFS) from it's start
495 * state, visiting all reachable states and calling 'action' on each one of
498 * @param a automaton to be traversed.
499 * @param start start state, pass a->start or NULL to traverse the whole automaton.
500 * @param check function that is checked before advancing on each transition
502 * @param check_cls closure for check.
503 * @param action action to be performed on each state.
504 * @param action_cls closure for action
507 GNUNET_REGEX_automaton_traverse (const struct GNUNET_REGEX_Automaton *a,
508 struct GNUNET_REGEX_State *start,
509 GNUNET_REGEX_traverse_check check,
511 GNUNET_REGEX_traverse_action action,
515 struct GNUNET_REGEX_State *s;
517 if (NULL == a || 0 == a->state_count)
520 int marks[a->state_count];
522 for (count = 0, s = a->states_head; NULL != s && count < a->state_count;
523 s = s->next, count++)
525 s->traversal_id = count;
526 marks[s->traversal_id] = GNUNET_NO;
536 automaton_state_traverse (s, marks, &count, check, check_cls, action,
542 * String container for faster string operations.
547 * Buffer holding the string.
552 * Length of the string in the buffer.
557 * Number of bytes allocated for 'sbuf'
567 * Check if the given string 'str' needs parentheses around it when
568 * using it to generate a regex.
572 * @return GNUNET_YES if parentheses are needed, GNUNET_NO otherwise
575 needs_parentheses (const char *str)
583 if ((NULL == str) || ((slen = strlen (str)) < 2))
592 cl = strchr (pos, ')');
598 op = strchr (pos, '(');
599 if ((NULL != op) && (op < cl))
609 return (*pos == '\0') ? GNUNET_NO : GNUNET_YES;
614 * Remove parentheses surrounding string 'str'.
615 * Example: "(a)" becomes "a", "(a|b)|(a|c)" stays the same.
616 * You need to GNUNET_free the returned string.
618 * @param str string, free'd or re-used by this function, can be NULL
620 * @return string without surrounding parentheses, string 'str' if no preceding
621 * epsilon could be found, NULL if 'str' was NULL
624 remove_parentheses (char *str)
629 if ((NULL == str) || ('(' != str[0]) ||
630 (str[(slen = strlen (str)) - 1] != ')'))
633 pos = strchr (&str[1], ')');
634 if (pos == &str[slen - 1])
636 memmove (str, &str[1], slen - 2);
637 str[slen - 2] = '\0';
644 * Check if the string 'str' starts with an epsilon (empty string).
645 * Example: "(|a)" is starting with an epsilon.
647 * @param str string to test
649 * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')'
652 has_epsilon (const char *str)
654 return (NULL != str) && ('(' == str[0]) && ('|' == str[1]) &&
655 (')' == str[strlen (str) - 1]);
660 * Remove an epsilon from the string str. Where epsilon is an empty string
661 * Example: str = "(|a|b|c)", result: "a|b|c"
662 * The returned string needs to be freed.
666 * @return string without preceding epsilon, string 'str' if no preceding
667 * epsilon could be found, NULL if 'str' was NULL
670 remove_epsilon (const char *str)
676 if (('(' == str[0]) && ('|' == str[1]))
679 if (')' == str[len - 1])
680 return GNUNET_strndup (&str[2], len - 3);
682 return GNUNET_strdup (str);
687 * Compare 'str1', starting from position 'k', with whole 'str2'
689 * @param str1 first string to compare, starting from position 'k'
690 * @param str2 second string for comparison
691 * @param k starting position in 'str1'
693 * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
696 strkcmp (const char *str1, const char *str2, size_t k)
698 if ((NULL == str1) || (NULL == str2) || (strlen (str1) < k))
700 return strcmp (&str1[k], str2);
705 * Helper function used as 'action' in 'GNUNET_REGEX_automaton_traverse'
706 * function to create the depth-first numbering of the states.
708 * @param cls states array.
709 * @param count current state counter.
710 * @param s current state.
713 number_states (void *cls, const unsigned int count,
714 struct GNUNET_REGEX_State *s)
716 struct GNUNET_REGEX_State **states = cls;
725 * Construct the regular expression given the inductive step,
726 * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^*
727 * R^{(k-1)}_{kj}, and simplify the resulting expression saved in R_cur_ij.
729 * @param R_last_ij value of $R^{(k-1)_{ij}.
730 * @param R_last_ik value of $R^{(k-1)_{ik}.
731 * @param R_last_kk value of $R^{(k-1)_{kk}.
732 * @param R_last_kj value of $R^{(k-1)_{kj}.
733 * @param R_cur_ij result for this inductive step is saved in R_cur_ij, R_cur_ij
734 * is expected to be NULL when called!
737 automaton_create_proofs_simplify (const char *R_last_ij,
738 const char *R_last_ik,
739 const char *R_last_kk,
740 const char *R_last_kj,
766 GNUNET_assert (NULL == *R_cur_ij && NULL != R_cur_ij);
768 * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
769 * R_last == R^{(k-1)}, R_cur == R^{(k)}
770 * R_cur_ij = R_cur_l | R_cur_r
771 * R_cur_l == R^{(k-1)}_{ij}
772 * R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
775 if ((NULL == R_last_ij) && ((NULL == R_last_ik) || (NULL == R_last_kk) || /* technically cannot happen, but looks saner */
776 (NULL == R_last_kj)))
778 /* R^{(k)}_{ij} = N | N */
783 if ((NULL == R_last_ik) || (NULL == R_last_kk) || /* technically cannot happen, but looks saner */
786 /* R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */
787 *R_cur_ij = GNUNET_strdup (R_last_ij);
791 /* $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
792 * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} */
797 /* cache results from strcmp, we might need these many times */
798 ij_kj_cmp = nullstrcmp (R_last_ij, R_last_kj);
799 ij_ik_cmp = nullstrcmp (R_last_ij, R_last_ik);
800 ik_kk_cmp = nullstrcmp (R_last_ik, R_last_kk);
801 kk_kj_cmp = nullstrcmp (R_last_kk, R_last_kj);
803 /* Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
804 * as parentheses, so we can better compare the contents */
805 R_temp_ik = remove_parentheses (remove_epsilon (R_last_ik));
806 R_temp_kk = remove_parentheses (remove_epsilon (R_last_kk));
807 R_temp_kj = remove_parentheses (remove_epsilon (R_last_kj));
809 clean_ik_kk_cmp = nullstrcmp (R_last_ik, R_temp_kk);
810 clean_kk_kj_cmp = nullstrcmp (R_temp_kk, R_last_kj);
812 /* construct R_cur_l (and, if necessary R_cur_r) */
813 if (NULL != R_last_ij)
815 /* Assign R_temp_ij to R_last_ij and remove epsilon as well
816 * as parentheses, so we can better compare the contents */
817 R_temp_ij = remove_parentheses (remove_epsilon (R_last_ij));
819 if ( (0 == strcmp (R_temp_ij, R_temp_ik)) &&
820 (0 == strcmp (R_temp_ik, R_temp_kk)) &&
821 (0 == strcmp (R_temp_kk, R_temp_kj)) )
823 if (0 == strlen (R_temp_ij))
825 R_cur_r = GNUNET_strdup ("");
827 else if ((0 == strncmp (R_last_ij, "(|", 2)) ||
828 (0 == strncmp (R_last_ik, "(|", 2) &&
829 0 == strncmp (R_last_kj, "(|", 2)))
832 * a|(e|a)a*(e|a) = a*
833 * a|(e|a)(e|a)*(e|a) = a*
835 * (e|a)|aa*(e|a) = a*
836 * (e|a)|(e|a)a*a = a*
837 * (e|a)|(e|a)a*(e|a) = a*
838 * (e|a)|(e|a)(e|a)*(e|a) = a*
840 if (GNUNET_YES == needs_parentheses (R_temp_ij))
841 GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_ij);
843 GNUNET_asprintf (&R_cur_r, "%s*", R_temp_ij);
851 * a|(e|a)(e|a)*a = a+
852 * a|a(e|a)*(e|a) = a+
854 if (GNUNET_YES == needs_parentheses (R_temp_ij))
855 GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_ij);
857 GNUNET_asprintf (&R_cur_r, "%s+", R_temp_ij);
860 else if (0 == ij_ik_cmp && 0 == clean_kk_kj_cmp && 0 != clean_ik_kk_cmp)
863 if (strlen (R_last_kk) < 1)
864 R_cur_r = GNUNET_strdup (R_last_ij);
865 else if (GNUNET_YES == needs_parentheses (R_temp_kk))
866 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
868 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_last_kk);
872 else if (0 == ij_kj_cmp && 0 == clean_ik_kk_cmp && 0 != clean_kk_kj_cmp)
875 if (strlen (R_last_kk) < 1)
876 R_cur_r = GNUNET_strdup (R_last_kj);
877 else if (GNUNET_YES == needs_parentheses (R_temp_kk))
878 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
880 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
884 else if (0 == ij_ik_cmp && 0 == kk_kj_cmp && !has_epsilon (R_last_ij) &&
885 has_epsilon (R_last_kk))
887 /* a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab* */
888 if (needs_parentheses (R_temp_kk))
889 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
891 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_temp_kk);
895 else if (0 == ij_kj_cmp && 0 == ik_kk_cmp && !has_epsilon (R_last_ij) &&
896 has_epsilon (R_last_kk))
898 /* a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|... = b*a */
899 if (needs_parentheses (R_temp_kk))
900 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_ij);
902 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_ij);
908 temp_a = (NULL == R_last_ij) ? NULL : GNUNET_strdup (R_last_ij);
909 temp_a = remove_parentheses (temp_a);
913 GNUNET_free_non_null (R_temp_ij);
917 /* we have no left side */
921 /* construct R_cur_r, if not already constructed */
924 length = strlen (R_temp_kk) - strlen (R_last_ik);
926 /* a(ba)*bx = (ab)+x */
927 if (length > 0 && NULL != R_last_kk && 0 < strlen (R_last_kk) &&
928 NULL != R_last_kj && 0 < strlen (R_last_kj) && NULL != R_last_ik &&
929 0 < strlen (R_last_ik) && 0 == strkcmp (R_temp_kk, R_last_ik, length) &&
930 0 == strncmp (R_temp_kk, R_last_kj, length))
932 temp_a = GNUNET_malloc (length + 1);
933 temp_b = GNUNET_malloc ((strlen (R_last_kj) - length) + 1);
938 for (cnt = 0; cnt < strlen (R_last_kj); cnt++)
942 temp_a[length_l] = R_last_kj[cnt];
947 temp_b[length_r] = R_last_kj[cnt];
951 temp_a[length_l] = '\0';
952 temp_b[length_r] = '\0';
954 /* e|(ab)+ = (ab)* */
955 if (NULL != R_cur_l && 0 == strlen (R_cur_l) && 0 == strlen (temp_b))
957 GNUNET_asprintf (&R_cur_r, "(%s%s)*", R_last_ik, temp_a);
958 GNUNET_free (R_cur_l);
963 GNUNET_asprintf (&R_cur_r, "(%s%s)+%s", R_last_ik, temp_a, temp_b);
965 GNUNET_free (temp_a);
966 GNUNET_free (temp_b);
968 else if (0 == strcmp (R_temp_ik, R_temp_kk) &&
969 0 == strcmp (R_temp_kk, R_temp_kj))
973 * (e|a)(e|a)*(e|a) = a*
975 if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj))
977 if (needs_parentheses (R_temp_kk))
978 GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_kk);
980 GNUNET_asprintf (&R_cur_r, "%s*", R_temp_kk);
983 else if (0 == clean_ik_kk_cmp && 0 == clean_kk_kj_cmp &&
984 !has_epsilon (R_last_ik))
986 if (needs_parentheses (R_temp_kk))
987 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
989 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
1000 (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
1001 has_epsilon (R_last_kj));
1005 if (needs_parentheses (R_temp_kk))
1006 GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_kk);
1008 GNUNET_asprintf (&R_cur_r, "%s+", R_temp_kk);
1014 * (e|a)(e|a)*b = a*b
1016 else if (0 == strcmp (R_temp_ik, R_temp_kk))
1018 if (has_epsilon (R_last_ik))
1020 if (needs_parentheses (R_temp_kk))
1021 GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
1023 GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
1027 if (needs_parentheses (R_temp_kk))
1028 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_last_kj);
1030 GNUNET_asprintf (&R_cur_r, "%s+%s", R_temp_kk, R_last_kj);
1035 * b(e|a)*(e|a) = ba*
1037 else if (0 == strcmp (R_temp_kk, R_temp_kj))
1039 if (has_epsilon (R_last_kj))
1041 if (needs_parentheses (R_temp_kk))
1042 GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ik, R_temp_kk);
1044 GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ik, R_temp_kk);
1048 if (needs_parentheses (R_temp_kk))
1049 GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_last_ik, R_temp_kk);
1051 GNUNET_asprintf (&R_cur_r, "%s+%s", R_last_ik, R_temp_kk);
1056 if (strlen (R_temp_kk) > 0)
1058 if (needs_parentheses (R_temp_kk))
1060 GNUNET_asprintf (&R_cur_r, "%s(%s)*%s", R_last_ik, R_temp_kk,
1065 GNUNET_asprintf (&R_cur_r, "%s%s*%s", R_last_ik, R_temp_kk,
1071 GNUNET_asprintf (&R_cur_r, "%s%s", R_last_ik, R_last_kj);
1076 GNUNET_free_non_null (R_temp_ik);
1077 GNUNET_free_non_null (R_temp_kk);
1078 GNUNET_free_non_null (R_temp_kj);
1080 if (NULL == R_cur_l && NULL == R_cur_r)
1086 if (NULL != R_cur_l && NULL == R_cur_r)
1088 *R_cur_ij = R_cur_l;
1092 if (NULL == R_cur_l && NULL != R_cur_r)
1094 *R_cur_ij = R_cur_r;
1098 if (0 == nullstrcmp (R_cur_l, R_cur_r))
1100 *R_cur_ij = R_cur_l;
1101 GNUNET_free (R_cur_r);
1105 GNUNET_asprintf (R_cur_ij, "(%s|%s)", R_cur_l, R_cur_r);
1107 GNUNET_free (R_cur_l);
1108 GNUNET_free (R_cur_r);
1113 * Create proofs for all states in the given automaton. Implementation of the
1114 * algorithm descriped in chapter 3.2.1 of "Automata Theory, Languages, and
1115 * Computation 3rd Edition" by Hopcroft, Motwani and Ullman.
1117 * Each state in the automaton gets assigned 'proof' and 'hash' (hash of the
1118 * proof) fields. The starting state will only have a valid proof/hash if it has
1119 * any incoming transitions.
1121 * @param a automaton for which to assign proofs and hashes, must not be NULL
1124 automaton_create_proofs (struct GNUNET_REGEX_Automaton *a)
1126 unsigned int n = a->state_count;
1127 struct GNUNET_REGEX_State *states[n];
1132 struct GNUNET_REGEX_Transition *t;
1133 char *complete_regex;
1138 R_last = GNUNET_malloc_large (sizeof (char *) * n * n);
1139 R_cur = GNUNET_malloc_large (sizeof (char *) * n * n);
1140 if ( (NULL == R_last) ||
1143 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "malloc");
1144 GNUNET_free_non_null (R_cur);
1145 GNUNET_free_non_null (R_last);
1146 return GNUNET_SYSERR;
1149 /* create depth-first numbering of the states, initializes 'state' */
1150 GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &number_states,
1153 for (i = 0; i < n; i++)
1154 GNUNET_assert (NULL != states[i]);
1156 /* Compute regular expressions of length "1" between each pair of states */
1157 for (i = 0; i < n; i++)
1159 for (t = states[i]->transitions_head; NULL != t; t = t->next)
1161 j = t->to_state->dfs_id;
1162 if (NULL == R_last[i * n + j])
1164 GNUNET_asprintf (&R_last[i * n + j], "%s", t->label);
1168 temp = R_last[i * n + j];
1169 GNUNET_asprintf (&R_last[i * n + j], "%s|%s", R_last[i * n + j],
1174 /* add self-loop: i is reachable from i via epsilon-transition */
1175 if (NULL == R_last[i * n + i])
1177 GNUNET_asprintf (&R_last[i * n + i], "");
1181 temp = R_last[i * n + i];
1182 GNUNET_asprintf (&R_last[i * n + i], "(|%s)", R_last[i * n + i]);
1186 for (i = 0; i < n; i++)
1187 for (j = 0; j < n; j++)
1188 if (needs_parentheses (R_last[i * n + j]))
1190 temp = R_last[i * n + j];
1191 GNUNET_asprintf (&R_last[i * n + j], "(%s)", R_last[i * n + j]);
1195 /* Compute regular expressions of length "k" between each pair of states per
1197 for (k = 0; k < n; k++)
1199 for (i = 0; i < n; i++)
1201 for (j = 0; j < n; j++)
1203 /* Basis for the recursion:
1204 * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
1205 * R_last == R^{(k-1)}, R_cur == R^{(k)}
1208 /* Create R_cur[i][j] and simplify the expression */
1209 automaton_create_proofs_simplify (R_last[i * n + j], R_last[i * n + k],
1210 R_last[k * n + k], R_last[k * n + j],
1215 /* set R_last = R_cur */
1219 /* clear 'R_cur' for next iteration */
1220 for (i = 0; i < n; i++)
1222 for (j = 0; j < n; j++)
1224 GNUNET_free_non_null (R_cur[i * n + j]);
1225 R_cur[i * n + j] = NULL;
1230 /* assign proofs and hashes */
1231 for (i = 0; i < n; i++)
1233 if (NULL != R_last[a->start->dfs_id * n + i])
1235 states[i]->proof = GNUNET_strdup (R_last[a->start->dfs_id * n + i]);
1236 GNUNET_CRYPTO_hash (states[i]->proof, strlen (states[i]->proof),
1241 /* complete regex for whole DFA: union of all pairs (start state/accepting
1243 complete_regex = NULL;
1244 for (i = 0; i < n; i++)
1246 if (states[i]->accepting)
1248 if (NULL == complete_regex &&
1249 0 < strlen (R_last[a->start->dfs_id * n + i]))
1251 GNUNET_asprintf (&complete_regex, "%s",
1252 R_last[a->start->dfs_id * n + i]);
1254 else if (NULL != R_last[a->start->dfs_id * n + i] &&
1255 0 < strlen (R_last[a->start->dfs_id * n + i]))
1257 temp = complete_regex;
1258 GNUNET_asprintf (&complete_regex, "%s|%s", complete_regex,
1259 R_last[a->start->dfs_id * n + i]);
1264 a->canonical_regex = complete_regex;
1267 for (i = 0; i < n; i++)
1268 for (j = 0; j < n; j++)
1269 GNUNET_free_non_null (R_last[i * n + j]);
1270 GNUNET_free (R_cur);
1271 GNUNET_free (R_last);
1277 * Creates a new DFA state based on a set of NFA states. Needs to be freed using
1278 * automaton_destroy_state.
1280 * @param ctx context
1281 * @param nfa_states set of NFA states on which the DFA should be based on
1283 * @return new DFA state
1285 static struct GNUNET_REGEX_State *
1286 dfa_state_create (struct GNUNET_REGEX_Context *ctx,
1287 struct GNUNET_REGEX_StateSet *nfa_states)
1289 struct GNUNET_REGEX_State *s;
1292 struct GNUNET_REGEX_State *cstate;
1293 struct GNUNET_REGEX_Transition *ctran;
1296 s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1297 s->id = ctx->state_id++;
1301 if (NULL == nfa_states)
1303 GNUNET_asprintf (&s->name, "s%i", s->id);
1307 s->nfa_set = *nfa_states;
1309 if (nfa_states->off < 1)
1312 /* Create a name based on 'nfa_states' */
1313 len = nfa_states->off * 14 + 4;
1314 s->name = GNUNET_malloc (len);
1315 strcat (s->name, "{");
1318 for (i = 0; i < nfa_states->off; i++)
1320 cstate = nfa_states->states[i];
1321 GNUNET_snprintf (pos, pos - s->name + len,
1323 pos += strlen (pos);
1325 /* Add a transition for each distinct label to NULL state */
1326 for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
1327 if (NULL != ctran->label)
1328 state_add_transition (ctx, s, ctran->label, NULL);
1330 /* If the nfa_states contain an accepting state, the new dfa state is also
1332 if (cstate->accepting)
1336 s->name = GNUNET_realloc (s->name, strlen (s->name) + 1);
1338 memset (nfa_states, 0, sizeof (struct GNUNET_REGEX_StateSet));
1344 * Move from the given state 's' to the next state on transition 'str'. Consumes
1345 * as much of the given 'str' as possible (usefull for strided DFAs). On return
1346 * 's' will point to the next state, and the length of the substring used for
1347 * this transition will be returned. If no transition possible 0 is returned and
1348 * 's' points to NULL.
1350 * @param s starting state, will point to the next state or NULL (if no
1351 * transition possible)
1352 * @param str edge label to follow (will match longest common prefix)
1354 * @return length of the substring comsumed from 'str'
1357 dfa_move (struct GNUNET_REGEX_State **s, const char *str)
1359 struct GNUNET_REGEX_Transition *t;
1360 struct GNUNET_REGEX_State *new_s;
1362 unsigned int max_len;
1369 for (t = (*s)->transitions_head; NULL != t; t = t->next)
1371 len = strlen (t->label);
1373 if (0 == strncmp (t->label, str, len))
1378 new_s = t->to_state;
1389 * Set the given state 'marked' to GNUNET_YES. Used by the
1390 * 'dfa_remove_unreachable_states' function to detect unreachable states in the
1393 * @param cls closure, not used.
1394 * @param count count, not used.
1395 * @param s state where the marked attribute will be set to GNUNET_YES.
1398 mark_states (void *cls, const unsigned int count, struct GNUNET_REGEX_State *s)
1400 s->marked = GNUNET_YES;
1405 * Remove all unreachable states from DFA 'a'. Unreachable states are those
1406 * states that are not reachable from the starting state.
1408 * @param a DFA automaton
1411 dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
1413 struct GNUNET_REGEX_State *s;
1414 struct GNUNET_REGEX_State *s_next;
1416 /* 1. unmark all states */
1417 for (s = a->states_head; NULL != s; s = s->next)
1418 s->marked = GNUNET_NO;
1420 /* 2. traverse dfa from start state and mark all visited states */
1421 GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &mark_states, NULL);
1423 /* 3. delete all states that were not visited */
1424 for (s = a->states_head; NULL != s; s = s_next)
1427 if (GNUNET_NO == s->marked)
1428 automaton_remove_state (a, s);
1434 * Remove all dead states from the DFA 'a'. Dead states are those states that do
1435 * not transition to any other state but themselves.
1437 * @param a DFA automaton
1440 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
1442 struct GNUNET_REGEX_State *s;
1443 struct GNUNET_REGEX_State *s_next;
1444 struct GNUNET_REGEX_Transition *t;
1447 GNUNET_assert (DFA == a->type);
1449 for (s = a->states_head; NULL != s; s = s_next)
1457 for (t = s->transitions_head; NULL != t; t = t->next)
1459 if (NULL != t->to_state && t->to_state != s)
1469 /* state s is dead, remove it */
1470 automaton_remove_state (a, s);
1476 * Merge all non distinguishable states in the DFA 'a'
1478 * @param ctx context
1479 * @param a DFA automaton
1480 * @return GNUNET_OK on success
1483 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
1484 struct GNUNET_REGEX_Automaton *a)
1487 struct GNUNET_REGEX_State *s1;
1488 struct GNUNET_REGEX_State *s2;
1489 struct GNUNET_REGEX_Transition *t1;
1490 struct GNUNET_REGEX_Transition *t2;
1491 struct GNUNET_REGEX_State *s1_next;
1492 struct GNUNET_REGEX_State *s2_next;
1494 unsigned int num_equal_edges;
1496 unsigned int state_cnt;
1497 unsigned long long idx;
1498 unsigned long long idx1;
1500 if ( (NULL == a) || (0 == a->state_count) )
1502 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1503 "Could not merge nondistinguishable states, automaton was NULL.\n");
1504 return GNUNET_SYSERR;
1507 state_cnt = a->state_count;
1508 table = GNUNET_malloc_large ((sizeof (uint32_t) * state_cnt * a->state_count / 32) + 1);
1511 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "malloc");
1512 return GNUNET_SYSERR;
1515 for (i = 0, s1 = a->states_head; NULL != s1; s1 = s1->next)
1518 /* Mark all pairs of accepting/!accepting states */
1519 for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1520 for (s2 = a->states_head; NULL != s2; s2 = s2->next)
1521 if ( (s1->accepting && !s2->accepting) ||
1522 (!s1->accepting && s2->accepting) )
1524 idx = s1->marked * state_cnt + s2->marked;
1525 table[idx / 32] |= (1 << (idx % 32));
1528 /* Find all equal states */
1533 for (s1 = a->states_head; NULL != s1; s1 = s1->next)
1535 for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
1537 idx = s1->marked * state_cnt + s2->marked;
1538 if (0 != (table[idx / 32] & (1 << (idx % 32))))
1540 num_equal_edges = 0;
1541 for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
1543 for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
1545 if (0 == strcmp (t1->label, t2->label))
1548 /* same edge, but targets definitively different, so we're different
1550 if (t1->to_state->marked > t2->to_state->marked)
1551 idx1 = t1->to_state->marked * state_cnt + t2->to_state->marked;
1553 idx1 = t2->to_state->marked * state_cnt + t1->to_state->marked;
1554 if (0 != (table[idx1 / 32] & (1 << (idx1 % 32))))
1556 table[idx / 32] |= (1 << (idx % 32));
1557 change = 1; /* changed a marker, need to run again */
1562 if ( (num_equal_edges != s1->transition_count) ||
1563 (num_equal_edges != s2->transition_count) )
1565 /* Make sure ALL edges of possible equal states are the same */
1566 table[idx / 32] |= (1 << (idx % 32));
1567 change = 1; /* changed a marker, need to run again */
1573 /* Merge states that are equal */
1574 for (s1 = a->states_head; NULL != s1; s1 = s1_next)
1577 for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
1580 idx = s1->marked * state_cnt + s2->marked;
1581 if (0 == (table[idx / 32] & (1 << (idx % 32))))
1582 automaton_merge_states (ctx, a, s1, s2);
1586 GNUNET_free (table);
1592 * Minimize the given DFA 'a' by removing all unreachable states, removing all
1593 * dead states and merging all non distinguishable states
1595 * @param ctx context
1596 * @param a DFA automaton
1597 * @return GNUNET_OK on success
1600 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
1601 struct GNUNET_REGEX_Automaton *a)
1604 return GNUNET_SYSERR;
1606 GNUNET_assert (DFA == a->type);
1608 /* 1. remove unreachable states */
1609 dfa_remove_unreachable_states (a);
1611 /* 2. remove dead states */
1612 dfa_remove_dead_states (a);
1614 /* 3. Merge nondistinguishable states */
1615 if (GNUNET_OK != dfa_merge_nondistinguishable_states (ctx, a))
1616 return GNUNET_SYSERR;
1622 * Context for adding strided transitions to a DFA.
1624 struct GNUNET_REGEX_Strided_Context
1627 * Length of the strides.
1629 const unsigned int stride;
1632 * Strided transitions DLL. New strided transitions will be stored in this DLL
1633 * and afterwards added to the DFA.
1635 struct GNUNET_REGEX_Transition *transitions_head;
1638 * Strided transitions DLL.
1640 struct GNUNET_REGEX_Transition *transitions_tail;
1645 * Recursive helper function to add strides to a DFA.
1647 * @param cls context, contains stride length and strided transitions DLL.
1648 * @param depth current depth of the depth-first traversal of the graph.
1649 * @param label current label, string that contains all labels on the path from
1651 * @param start start state for the depth-first traversal of the graph.
1652 * @param s current state in the depth-first traversal
1655 dfa_add_multi_strides_helper (void *cls, const unsigned int depth, char *label,
1656 struct GNUNET_REGEX_State *start,
1657 struct GNUNET_REGEX_State *s)
1659 struct GNUNET_REGEX_Strided_Context *ctx = cls;
1660 struct GNUNET_REGEX_Transition *t;
1663 if (depth == ctx->stride)
1665 t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
1666 t->label = GNUNET_strdup (label);
1668 t->from_state = start;
1669 GNUNET_CONTAINER_DLL_insert (ctx->transitions_head, ctx->transitions_tail,
1674 for (t = s->transitions_head; NULL != t; t = t->next)
1676 /* Do not consider self-loops, because it end's up in too many
1678 if (t->to_state == t->from_state)
1683 GNUNET_asprintf (&new_label, "%s%s", label, t->label);
1686 new_label = GNUNET_strdup (t->label);
1688 dfa_add_multi_strides_helper (cls, (depth + 1), new_label, start,
1692 GNUNET_free_non_null (label);
1697 * Function called for each state in the DFA. Starts a traversal of depth set in
1698 * context starting from state 's'.
1700 * @param cls context.
1701 * @param count not used.
1702 * @param s current state.
1705 dfa_add_multi_strides (void *cls, const unsigned int count,
1706 struct GNUNET_REGEX_State *s)
1708 dfa_add_multi_strides_helper (cls, 0, NULL, s, s);
1713 * Adds multi-strided transitions to the given 'dfa'.
1715 * @param regex_ctx regex context needed to add transitions to the automaton.
1716 * @param dfa DFA to which the multi strided transitions should be added.
1717 * @param stride_len length of the strides.
1720 GNUNET_REGEX_dfa_add_multi_strides (struct GNUNET_REGEX_Context *regex_ctx,
1721 struct GNUNET_REGEX_Automaton *dfa,
1722 const unsigned int stride_len)
1724 struct GNUNET_REGEX_Strided_Context ctx = { stride_len, NULL, NULL };
1725 struct GNUNET_REGEX_Transition *t;
1726 struct GNUNET_REGEX_Transition *t_next;
1728 if (1 > stride_len || GNUNET_YES == dfa->is_multistrided)
1731 /* Compute the new transitions of given stride_len */
1732 GNUNET_REGEX_automaton_traverse (dfa, dfa->start, NULL, NULL,
1733 &dfa_add_multi_strides, &ctx);
1735 /* Add all the new transitions to the automaton. */
1736 for (t = ctx.transitions_head; NULL != t; t = t_next)
1739 state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
1740 GNUNET_CONTAINER_DLL_remove (ctx.transitions_head, ctx.transitions_tail, t);
1741 GNUNET_free_non_null (t->label);
1745 /* Mark this automaton as multistrided */
1746 dfa->is_multistrided = GNUNET_YES;
1750 * Recursive Helper function for DFA path compression. Does DFS on the DFA graph
1751 * and adds new transitions to the given transitions DLL and marks states that
1752 * should be removed by setting state->contained to GNUNET_YES.
1754 * @param dfa DFA for which the paths should be compressed.
1755 * @param start starting state for linear path search.
1756 * @param cur current state in the recursive DFS.
1757 * @param label current label (string of traversed labels).
1758 * @param max_len maximal path compression length.
1759 * @param transitions_head transitions DLL.
1760 * @param transitions_tail transitions DLL.
1763 dfa_compress_paths_helper (struct GNUNET_REGEX_Automaton *dfa,
1764 struct GNUNET_REGEX_State *start,
1765 struct GNUNET_REGEX_State *cur, char *label,
1766 unsigned int max_len,
1767 struct GNUNET_REGEX_Transition **transitions_head,
1768 struct GNUNET_REGEX_Transition **transitions_tail)
1770 struct GNUNET_REGEX_Transition *t;
1774 if (NULL != label &&
1775 ((cur->incoming_transition_count > 1 || GNUNET_YES == cur->accepting ||
1776 GNUNET_YES == cur->marked) || (start != dfa->start && max_len > 0 &&
1777 max_len == strlen (label)) ||
1778 (start == dfa->start && GNUNET_REGEX_INITIAL_BYTES == strlen (label))))
1780 t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
1781 t->label = GNUNET_strdup (label);
1783 t->from_state = start;
1784 GNUNET_CONTAINER_DLL_insert (*transitions_head, *transitions_tail, t);
1786 if (GNUNET_NO == cur->marked)
1788 dfa_compress_paths_helper (dfa, cur, cur, NULL, max_len, transitions_head,
1793 else if (cur != start)
1794 cur->contained = GNUNET_YES;
1796 if (GNUNET_YES == cur->marked && cur != start)
1799 cur->marked = GNUNET_YES;
1802 for (t = cur->transitions_head; NULL != t; t = t->next)
1805 GNUNET_asprintf (&new_label, "%s%s", label, t->label);
1807 new_label = GNUNET_strdup (t->label);
1809 if (t->to_state != cur)
1811 dfa_compress_paths_helper (dfa, start, t->to_state, new_label, max_len,
1812 transitions_head, transitions_tail);
1814 GNUNET_free (new_label);
1820 * Compress paths in the given 'dfa'. Linear paths like 0->1->2->3 will be
1821 * compressed to 0->3 by combining transitions.
1823 * @param regex_ctx context for adding new transitions.
1824 * @param dfa DFA representation, will directly modify the given DFA.
1825 * @param max_len maximal length of the compressed paths.
1828 dfa_compress_paths (struct GNUNET_REGEX_Context *regex_ctx,
1829 struct GNUNET_REGEX_Automaton *dfa, unsigned int max_len)
1831 struct GNUNET_REGEX_State *s;
1832 struct GNUNET_REGEX_State *s_next;
1833 struct GNUNET_REGEX_Transition *t;
1834 struct GNUNET_REGEX_Transition *t_next;
1835 struct GNUNET_REGEX_Transition *transitions_head = NULL;
1836 struct GNUNET_REGEX_Transition *transitions_tail = NULL;
1841 /* Count the incoming transitions on each state. */
1842 for (s = dfa->states_head; NULL != s; s = s->next)
1844 for (t = s->transitions_head; NULL != t; t = t->next)
1846 if (NULL != t->to_state)
1847 t->to_state->incoming_transition_count++;
1851 /* Unmark all states. */
1852 for (s = dfa->states_head; NULL != s; s = s->next)
1854 s->marked = GNUNET_NO;
1855 s->contained = GNUNET_NO;
1858 /* Add strides and mark states that can be deleted. */
1859 dfa_compress_paths_helper (dfa, dfa->start, dfa->start, NULL, max_len,
1860 &transitions_head, &transitions_tail);
1862 /* Add all the new transitions to the automaton. */
1863 for (t = transitions_head; NULL != t; t = t_next)
1866 state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
1867 GNUNET_CONTAINER_DLL_remove (transitions_head, transitions_tail, t);
1868 GNUNET_free_non_null (t->label);
1872 /* Remove marked states (including their incoming and outgoing transitions). */
1873 for (s = dfa->states_head; NULL != s; s = s_next)
1876 if (GNUNET_YES == s->contained)
1877 automaton_remove_state (dfa, s);
1883 * Creates a new NFA fragment. Needs to be cleared using
1884 * automaton_fragment_clear.
1886 * @param start starting state
1887 * @param end end state
1889 * @return new NFA fragment
1891 static struct GNUNET_REGEX_Automaton *
1892 nfa_fragment_create (struct GNUNET_REGEX_State *start,
1893 struct GNUNET_REGEX_State *end)
1895 struct GNUNET_REGEX_Automaton *n;
1897 n = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
1904 if (NULL == start || NULL == end)
1907 automaton_add_state (n, end);
1908 automaton_add_state (n, start);
1920 * Adds a list of states to the given automaton 'n'.
1922 * @param n automaton to which the states should be added
1923 * @param states_head head of the DLL of states
1924 * @param states_tail tail of the DLL of states
1927 nfa_add_states (struct GNUNET_REGEX_Automaton *n,
1928 struct GNUNET_REGEX_State *states_head,
1929 struct GNUNET_REGEX_State *states_tail)
1931 struct GNUNET_REGEX_State *s;
1933 if (NULL == n || NULL == states_head)
1935 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n");
1939 if (NULL == n->states_head)
1941 n->states_head = states_head;
1942 n->states_tail = states_tail;
1946 if (NULL != states_head)
1948 n->states_tail->next = states_head;
1949 n->states_tail = states_tail;
1952 for (s = states_head; NULL != s; s = s->next)
1958 * Creates a new NFA state. Needs to be freed using automaton_destroy_state.
1960 * @param ctx context
1961 * @param accepting is it an accepting state or not
1963 * @return new NFA state
1965 static struct GNUNET_REGEX_State *
1966 nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
1968 struct GNUNET_REGEX_State *s;
1970 s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
1971 s->id = ctx->state_id++;
1972 s->accepting = accepting;
1973 s->marked = GNUNET_NO;
1979 GNUNET_asprintf (&s->name, "s%i", s->id);
1986 * Calculates the closure set for the given set of states.
1988 * @param ret set to sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
1989 * @param nfa the NFA containing 's'
1990 * @param states list of states on which to base the closure on
1991 * @param label transitioning label for which to base the closure on,
1992 * pass NULL for epsilon transition
1995 nfa_closure_set_create (struct GNUNET_REGEX_StateSet *ret,
1996 struct GNUNET_REGEX_Automaton *nfa,
1997 struct GNUNET_REGEX_StateSet *states, const char *label)
1999 struct GNUNET_REGEX_State *s;
2001 struct GNUNET_REGEX_StateSet_MDLL cls_stack;
2002 struct GNUNET_REGEX_State *clsstate;
2003 struct GNUNET_REGEX_State *currentstate;
2004 struct GNUNET_REGEX_Transition *ctran;
2006 memset (ret, 0, sizeof (struct GNUNET_REGEX_StateSet));
2010 for (i = 0; i < states->off; i++)
2012 s = states->states[i];
2014 /* Add start state to closure only for epsilon closure */
2016 state_set_append (ret, s);
2018 /* initialize work stack */
2019 cls_stack.head = NULL;
2020 cls_stack.tail = NULL;
2021 GNUNET_CONTAINER_MDLL_insert (ST, cls_stack.head, cls_stack.tail, s);
2024 while (NULL != (currentstate = cls_stack.tail))
2026 GNUNET_CONTAINER_MDLL_remove (ST, cls_stack.head, cls_stack.tail,
2029 for (ctran = currentstate->transitions_head; NULL != ctran;
2030 ctran = ctran->next)
2032 if (NULL == (clsstate = ctran->to_state))
2034 if (0 != clsstate->contained)
2036 if (0 != nullstrcmp (label, ctran->label))
2038 state_set_append (ret, clsstate);
2039 GNUNET_CONTAINER_MDLL_insert_tail (ST, cls_stack.head, cls_stack.tail,
2042 clsstate->contained = 1;
2046 for (i = 0; i < ret->off; i++)
2047 ret->states[i]->contained = 0;
2050 qsort (ret->states, ret->off, sizeof (struct GNUNET_REGEX_State *),
2056 * Pops two NFA fragments (a, b) from the stack and concatenates them (ab)
2058 * @param ctx context
2061 nfa_add_concatenation (struct GNUNET_REGEX_Context *ctx)
2063 struct GNUNET_REGEX_Automaton *a;
2064 struct GNUNET_REGEX_Automaton *b;
2065 struct GNUNET_REGEX_Automaton *new_nfa;
2067 b = ctx->stack_tail;
2068 GNUNET_assert (NULL != b);
2069 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2070 a = ctx->stack_tail;
2071 GNUNET_assert (NULL != a);
2072 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2074 state_add_transition (ctx, a->end, NULL, b->start);
2075 a->end->accepting = 0;
2076 b->end->accepting = 1;
2078 new_nfa = nfa_fragment_create (NULL, NULL);
2079 nfa_add_states (new_nfa, a->states_head, a->states_tail);
2080 nfa_add_states (new_nfa, b->states_head, b->states_tail);
2081 new_nfa->start = a->start;
2082 new_nfa->end = b->end;
2083 new_nfa->state_count += a->state_count + b->state_count;
2084 automaton_fragment_clear (a);
2085 automaton_fragment_clear (b);
2087 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2092 * Pops a NFA fragment from the stack (a) and adds a new fragment (a*)
2094 * @param ctx context
2097 nfa_add_star_op (struct GNUNET_REGEX_Context *ctx)
2099 struct GNUNET_REGEX_Automaton *a;
2100 struct GNUNET_REGEX_Automaton *new_nfa;
2101 struct GNUNET_REGEX_State *start;
2102 struct GNUNET_REGEX_State *end;
2104 a = ctx->stack_tail;
2108 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2109 "nfa_add_star_op failed, because there was no element on the stack");
2113 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2115 start = nfa_state_create (ctx, 0);
2116 end = nfa_state_create (ctx, 1);
2118 state_add_transition (ctx, start, NULL, a->start);
2119 state_add_transition (ctx, start, NULL, end);
2120 state_add_transition (ctx, a->end, NULL, a->start);
2121 state_add_transition (ctx, a->end, NULL, end);
2123 a->end->accepting = 0;
2126 new_nfa = nfa_fragment_create (start, end);
2127 nfa_add_states (new_nfa, a->states_head, a->states_tail);
2128 automaton_fragment_clear (a);
2130 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2135 * Pops an NFA fragment (a) from the stack and adds a new fragment (a+)
2137 * @param ctx context
2140 nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
2142 struct GNUNET_REGEX_Automaton *a;
2144 a = ctx->stack_tail;
2148 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2149 "nfa_add_plus_op failed, because there was no element on the stack");
2153 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2155 state_add_transition (ctx, a->end, NULL, a->start);
2157 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a);
2162 * Pops an NFA fragment (a) from the stack and adds a new fragment (a?)
2164 * @param ctx context
2167 nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
2169 struct GNUNET_REGEX_Automaton *a;
2170 struct GNUNET_REGEX_Automaton *new_nfa;
2171 struct GNUNET_REGEX_State *start;
2172 struct GNUNET_REGEX_State *end;
2174 a = ctx->stack_tail;
2178 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2179 "nfa_add_question_op failed, because there was no element on the stack");
2183 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2185 start = nfa_state_create (ctx, 0);
2186 end = nfa_state_create (ctx, 1);
2188 state_add_transition (ctx, start, NULL, a->start);
2189 state_add_transition (ctx, start, NULL, end);
2190 state_add_transition (ctx, a->end, NULL, end);
2192 a->end->accepting = 0;
2194 new_nfa = nfa_fragment_create (start, end);
2195 nfa_add_states (new_nfa, a->states_head, a->states_tail);
2196 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2197 automaton_fragment_clear (a);
2202 * Pops two NFA fragments (a, b) from the stack and adds a new NFA fragment that
2203 * alternates between a and b (a|b)
2205 * @param ctx context
2208 nfa_add_alternation (struct GNUNET_REGEX_Context *ctx)
2210 struct GNUNET_REGEX_Automaton *a;
2211 struct GNUNET_REGEX_Automaton *b;
2212 struct GNUNET_REGEX_Automaton *new_nfa;
2213 struct GNUNET_REGEX_State *start;
2214 struct GNUNET_REGEX_State *end;
2216 b = ctx->stack_tail;
2217 GNUNET_assert (NULL != b);
2218 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b);
2219 a = ctx->stack_tail;
2220 GNUNET_assert (NULL != a);
2221 GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
2223 start = nfa_state_create (ctx, 0);
2224 end = nfa_state_create (ctx, 1);
2225 state_add_transition (ctx, start, NULL, a->start);
2226 state_add_transition (ctx, start, NULL, b->start);
2228 state_add_transition (ctx, a->end, NULL, end);
2229 state_add_transition (ctx, b->end, NULL, end);
2231 a->end->accepting = 0;
2232 b->end->accepting = 0;
2235 new_nfa = nfa_fragment_create (start, end);
2236 nfa_add_states (new_nfa, a->states_head, a->states_tail);
2237 nfa_add_states (new_nfa, b->states_head, b->states_tail);
2238 automaton_fragment_clear (a);
2239 automaton_fragment_clear (b);
2241 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
2246 * Adds a new nfa fragment to the stack
2248 * @param ctx context
2249 * @param label label for nfa transition
2252 nfa_add_label (struct GNUNET_REGEX_Context *ctx, const char *label)
2254 struct GNUNET_REGEX_Automaton *n;
2255 struct GNUNET_REGEX_State *start;
2256 struct GNUNET_REGEX_State *end;
2258 GNUNET_assert (NULL != ctx);
2260 start = nfa_state_create (ctx, 0);
2261 end = nfa_state_create (ctx, 1);
2262 state_add_transition (ctx, start, label, end);
2263 n = nfa_fragment_create (start, end);
2264 GNUNET_assert (NULL != n);
2265 GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n);
2270 * Initialize a new context
2272 * @param ctx context
2275 GNUNET_REGEX_context_init (struct GNUNET_REGEX_Context *ctx)
2279 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!");
2283 ctx->transition_id = 0;
2284 ctx->stack_head = NULL;
2285 ctx->stack_tail = NULL;
2290 * Construct an NFA by parsing the regex string of length 'len'.
2292 * @param regex regular expression string
2293 * @param len length of the string
2295 * @return NFA, needs to be freed using GNUNET_REGEX_destroy_automaton
2297 struct GNUNET_REGEX_Automaton *
2298 GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
2300 struct GNUNET_REGEX_Context ctx;
2301 struct GNUNET_REGEX_Automaton *nfa;
2306 unsigned int altcount;
2307 unsigned int atomcount;
2316 if (NULL == regex || 0 == strlen (regex) || 0 == len)
2318 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2319 "Could not parse regex. Empty regex string provided.\n");
2324 GNUNET_REGEX_context_init (&ctx);
2335 for (count = 0; count < len && *regexp; count++, regexp++)
2343 nfa_add_concatenation (&ctx);
2346 GNUNET_array_grow (p, psize, psize * 2 + 4);
2347 p[poff].altcount = altcount;
2348 p[poff].atomcount = atomcount;
2356 error_msg = "Cannot append '|' to nothing";
2359 while (--atomcount > 0)
2360 nfa_add_concatenation (&ctx);
2366 error_msg = "Missing opening '('";
2371 /* Ignore this: "()" */
2373 altcount = p[poff].altcount;
2374 atomcount = p[poff].atomcount;
2377 while (--atomcount > 0)
2378 nfa_add_concatenation (&ctx);
2379 for (; altcount > 0; altcount--)
2380 nfa_add_alternation (&ctx);
2382 altcount = p[poff].altcount;
2383 atomcount = p[poff].atomcount;
2389 error_msg = "Cannot append '*' to nothing";
2392 nfa_add_star_op (&ctx);
2397 error_msg = "Cannot append '+' to nothing";
2400 nfa_add_plus_op (&ctx);
2405 error_msg = "Cannot append '?' to nothing";
2408 nfa_add_question_op (&ctx);
2414 nfa_add_concatenation (&ctx);
2416 curlabel[0] = *regexp;
2417 nfa_add_label (&ctx, curlabel);
2424 error_msg = "Unbalanced parenthesis";
2427 while (--atomcount > 0)
2428 nfa_add_concatenation (&ctx);
2429 for (; altcount > 0; altcount--)
2430 nfa_add_alternation (&ctx);
2432 GNUNET_array_grow (p, psize, 0);
2434 nfa = ctx.stack_tail;
2435 GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2437 if (NULL != ctx.stack_head)
2439 error_msg = "Creating the NFA failed. NFA stack was not empty!";
2443 /* Remember the regex that was used to generate this NFA */
2444 nfa->regex = GNUNET_strdup (regex);
2446 /* create depth-first numbering of the states for pretty printing */
2447 GNUNET_REGEX_automaton_traverse (nfa, NULL, NULL, NULL, &number_states, NULL);
2449 /* No multistriding added so far */
2450 nfa->is_multistrided = GNUNET_NO;
2455 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: %s\n", regex);
2456 if (NULL != error_msg)
2457 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
2459 GNUNET_free_non_null (p);
2461 while (NULL != (nfa = ctx.stack_head))
2463 GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
2464 GNUNET_REGEX_automaton_destroy (nfa);
2472 * Create DFA states based on given 'nfa' and starting with 'dfa_state'.
2474 * @param ctx context.
2475 * @param nfa NFA automaton.
2476 * @param dfa DFA automaton.
2477 * @param dfa_state current dfa state, pass epsilon closure of first nfa state
2481 construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
2482 struct GNUNET_REGEX_Automaton *nfa,
2483 struct GNUNET_REGEX_Automaton *dfa,
2484 struct GNUNET_REGEX_State *dfa_state)
2486 struct GNUNET_REGEX_Transition *ctran;
2487 struct GNUNET_REGEX_State *new_dfa_state;
2488 struct GNUNET_REGEX_State *state_contains;
2489 struct GNUNET_REGEX_State *state_iter;
2490 struct GNUNET_REGEX_StateSet tmp;
2491 struct GNUNET_REGEX_StateSet nfa_set;
2493 for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next)
2495 if (NULL == ctran->label || NULL != ctran->to_state)
2498 nfa_closure_set_create (&tmp, nfa, &dfa_state->nfa_set, ctran->label);
2499 nfa_closure_set_create (&nfa_set, nfa, &tmp, NULL);
2500 state_set_clear (&tmp);
2502 state_contains = NULL;
2503 for (state_iter = dfa->states_head; NULL != state_iter;
2504 state_iter = state_iter->next)
2506 if (0 == state_set_compare (&state_iter->nfa_set, &nfa_set))
2508 state_contains = state_iter;
2512 if (NULL == state_contains)
2514 new_dfa_state = dfa_state_create (ctx, &nfa_set);
2515 automaton_add_state (dfa, new_dfa_state);
2516 ctran->to_state = new_dfa_state;
2517 construct_dfa_states (ctx, nfa, dfa, new_dfa_state);
2521 ctran->to_state = state_contains;
2528 * Construct DFA for the given 'regex' of length 'len'.
2530 * Path compression means, that for example a DFA o -> a -> b -> c -> o will be
2531 * compressed to o -> abc -> o. Note that this parameter influences the
2532 * non-determinism of states of the resulting NFA in the DHT (number of outgoing
2533 * edges with the same label). For example for an application that stores IPv4
2534 * addresses as bitstrings it could make sense to limit the path compression to
2537 * @param regex regular expression string.
2538 * @param len length of the regular expression.
2539 * @param max_path_len limit the path compression length to the
2540 * given value. If set to 1, no path compression is applied. Set to 0 for
2541 * maximal possible path compression (generally not desireable).
2542 * @return DFA, needs to be freed using GNUNET_REGEX_automaton_destroy.
2544 struct GNUNET_REGEX_Automaton *
2545 GNUNET_REGEX_construct_dfa (const char *regex, const size_t len,
2546 unsigned int max_path_len)
2548 struct GNUNET_REGEX_Context ctx;
2549 struct GNUNET_REGEX_Automaton *dfa;
2550 struct GNUNET_REGEX_Automaton *nfa;
2551 struct GNUNET_REGEX_StateSet nfa_start_eps_cls;
2552 struct GNUNET_REGEX_StateSet singleton_set;
2554 GNUNET_REGEX_context_init (&ctx);
2557 // fprintf (stderr, "N");
2558 nfa = GNUNET_REGEX_construct_nfa (regex, len);
2562 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2563 "Could not create DFA, because NFA creation failed\n");
2567 dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
2569 dfa->regex = GNUNET_strdup (regex);
2571 /* Create DFA start state from epsilon closure */
2572 memset (&singleton_set, 0, sizeof (struct GNUNET_REGEX_StateSet));
2573 state_set_append (&singleton_set, nfa->start);
2574 nfa_closure_set_create (&nfa_start_eps_cls, nfa, &singleton_set, NULL);
2575 state_set_clear (&singleton_set);
2576 dfa->start = dfa_state_create (&ctx, &nfa_start_eps_cls);
2577 automaton_add_state (dfa, dfa->start);
2579 // fprintf (stderr, "D");
2580 construct_dfa_states (&ctx, nfa, dfa, dfa->start);
2581 GNUNET_REGEX_automaton_destroy (nfa);
2584 // fprintf (stderr, "M");
2585 if (GNUNET_OK != dfa_minimize (&ctx, dfa))
2587 GNUNET_REGEX_automaton_destroy (dfa);
2591 /* Create proofs and hashes for all states */
2592 if (GNUNET_OK != automaton_create_proofs (dfa))
2594 GNUNET_REGEX_automaton_destroy (dfa);
2598 /* Compress linear DFA paths */
2599 if (1 != max_path_len)
2600 dfa_compress_paths (&ctx, dfa, max_path_len);
2607 * Free the memory allocated by constructing the GNUNET_REGEX_Automaton data
2610 * @param a automaton to be destroyed
2613 GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
2615 struct GNUNET_REGEX_State *s;
2616 struct GNUNET_REGEX_State *next_state;
2621 GNUNET_free_non_null (a->regex);
2622 GNUNET_free_non_null (a->canonical_regex);
2624 for (s = a->states_head; NULL != s; s = next_state)
2626 next_state = s->next;
2627 GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
2628 automaton_destroy_state (s);
2636 * Evaluates the given string using the given DFA automaton
2638 * @param a automaton, type must be DFA
2639 * @param string string that should be evaluated
2641 * @return 0 if string matches, non 0 otherwise
2644 evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2647 struct GNUNET_REGEX_State *s;
2648 unsigned int step_len;
2652 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2653 "Tried to evaluate DFA, but NFA automaton given");
2659 /* If the string is empty but the starting state is accepting, we accept. */
2660 if ((NULL == string || 0 == strlen (string)) && s->accepting)
2663 for (strp = string; NULL != strp && *strp; strp += step_len)
2665 step_len = dfa_move (&s, strp);
2671 if (NULL != s && s->accepting)
2679 * Evaluates the given string using the given NFA automaton
2681 * @param a automaton, type must be NFA
2682 * @param string string that should be evaluated
2684 * @return 0 if string matches, non 0 otherwise
2687 evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
2691 struct GNUNET_REGEX_State *s;
2692 struct GNUNET_REGEX_StateSet sset;
2693 struct GNUNET_REGEX_StateSet new_sset;
2694 struct GNUNET_REGEX_StateSet singleton_set;
2700 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2701 "Tried to evaluate NFA, but DFA automaton given");
2705 /* If the string is empty but the starting state is accepting, we accept. */
2706 if ((NULL == string || 0 == strlen (string)) && a->start->accepting)
2710 memset (&singleton_set, 0, sizeof (struct GNUNET_REGEX_StateSet));
2711 state_set_append (&singleton_set, a->start);
2712 nfa_closure_set_create (&sset, a, &singleton_set, NULL);
2713 state_set_clear (&singleton_set);
2716 for (strp = string; NULL != strp && *strp; strp++)
2719 nfa_closure_set_create (&new_sset, a, &sset, str);
2720 state_set_clear (&sset);
2721 nfa_closure_set_create (&sset, a, &new_sset, 0);
2722 state_set_clear (&new_sset);
2725 for (i = 0; i < sset.off; i++)
2728 if ( (NULL != s) && (s->accepting) )
2735 state_set_clear (&sset);
2741 * Evaluates the given 'string' against the given compiled regex
2743 * @param a automaton
2744 * @param string string to check
2746 * @return 0 if string matches, non 0 otherwise
2749 GNUNET_REGEX_eval (struct GNUNET_REGEX_Automaton *a, const char *string)
2756 result = evaluate_dfa (a, string);
2759 result = evaluate_nfa (a, string);
2762 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2763 "Evaluating regex failed, automaton has no type!\n");
2764 result = GNUNET_SYSERR;
2773 * Get the canonical regex of the given automaton.
2774 * When constructing the automaton a proof is computed for each state,
2775 * consisting of the regular expression leading to this state. A complete
2776 * regex for the automaton can be computed by combining these proofs.
2777 * As of now this function is only useful for testing.
2779 * @param a automaton for which the canonical regex should be returned.
2784 GNUNET_REGEX_get_canonical_regex (struct GNUNET_REGEX_Automaton *a)
2789 return a->canonical_regex;
2794 * Get the number of transitions that are contained in the given automaton.
2796 * @param a automaton for which the number of transitions should be returned.
2798 * @return number of transitions in the given automaton.
2801 GNUNET_REGEX_get_transition_count (struct GNUNET_REGEX_Automaton *a)
2803 unsigned int t_count;
2804 struct GNUNET_REGEX_State *s;
2810 for (s = a->states_head; NULL != s; s = s->next)
2811 t_count += s->transition_count;
2818 * Get the first key for the given 'input_string'. This hashes the first x bits
2819 * of the 'input_string'.
2821 * @param input_string string.
2822 * @param string_len length of the 'input_string'.
2823 * @param key pointer to where to write the hash code.
2825 * @return number of bits of 'input_string' that have been consumed
2826 * to construct the key
2829 GNUNET_REGEX_get_first_key (const char *input_string, size_t string_len,
2830 struct GNUNET_HashCode * key)
2836 GNUNET_REGEX_INITIAL_BYTES ? string_len : GNUNET_REGEX_INITIAL_BYTES;
2838 if (NULL == input_string)
2840 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n");
2844 GNUNET_CRYPTO_hash (input_string, size, key);
2851 * Check if the given 'proof' matches the given 'key'.
2853 * @param proof partial regex of a state.
2854 * @param key hash of a state.
2856 * @return GNUNET_OK if the proof is valid for the given key.
2859 GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
2861 struct GNUNET_HashCode key_check;
2863 if (NULL == proof || NULL == key)
2865 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Proof check failed, was NULL.\n");
2869 GNUNET_CRYPTO_hash (proof, strlen (proof), &key_check);
2871 GNUNET_CRYPTO_hash_cmp (key, &key_check)) ? GNUNET_OK : GNUNET_NO;
2876 * Recursive function that calls the iterator for each synthetic start state.
2878 * @param min_len minimum length of the path in the graph.
2879 * @param max_len maximum length of the path in the graph.
2880 * @param consumed_string string consumed by traversing the graph till this state.
2881 * @param state current state of the automaton.
2882 * @param iterator iterator function called for each edge.
2883 * @param iterator_cls closure for the iterator function.
2886 iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
2887 char *consumed_string, struct GNUNET_REGEX_State *state,
2888 GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
2892 struct GNUNET_REGEX_Transition *t;
2893 unsigned int num_edges = state->transition_count;
2894 struct GNUNET_REGEX_Edge edges[num_edges];
2895 struct GNUNET_REGEX_Edge edge[1];
2896 struct GNUNET_HashCode hash;
2897 struct GNUNET_HashCode hash_new;
2899 unsigned int cur_len;
2901 if (NULL != consumed_string)
2902 cur_len = strlen (consumed_string);
2906 if ((cur_len >= min_len || GNUNET_YES == state->accepting) && cur_len > 0 &&
2907 NULL != consumed_string)
2909 if (cur_len <= max_len)
2911 if (state->proof != NULL && 0 != strcmp (consumed_string, state->proof))
2913 for (i = 0, t = state->transitions_head; NULL != t && i < num_edges;
2916 edges[i].label = t->label;
2917 edges[i].destination = t->to_state->hash;
2919 GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash);
2920 iterator (iterator_cls, &hash, consumed_string, state->accepting,
2924 if (GNUNET_YES == state->accepting && cur_len > 1 &&
2925 state->transition_count < 1 && cur_len < max_len)
2927 /* Special case for regex consisting of just a string that is shorter than
2929 edge[0].label = &consumed_string[cur_len - 1];
2930 edge[0].destination = state->hash;
2931 temp = GNUNET_strdup (consumed_string);
2932 temp[cur_len - 1] = '\0';
2933 GNUNET_CRYPTO_hash (temp, cur_len - 1, &hash_new);
2934 iterator (iterator_cls, &hash_new, temp, GNUNET_NO, 1, edge);
2938 else if (max_len < cur_len)
2940 /* Case where the concatenated labels are longer than max_len, then split. */
2941 edge[0].label = &consumed_string[max_len];
2942 edge[0].destination = state->hash;
2943 temp = GNUNET_strdup (consumed_string);
2944 temp[max_len] = '\0';
2945 GNUNET_CRYPTO_hash (temp, max_len, &hash);
2946 iterator (iterator_cls, &hash, temp, GNUNET_NO, 1, edge);
2951 if (cur_len < max_len)
2953 for (t = state->transitions_head; NULL != t; t = t->next)
2955 if (NULL != consumed_string)
2956 GNUNET_asprintf (&temp, "%s%s", consumed_string, t->label);
2958 GNUNET_asprintf (&temp, "%s", t->label);
2960 iterate_initial_edge (min_len, max_len, temp, t->to_state, iterator,
2969 * Iterate over all edges starting from start state of automaton 'a'. Calling
2970 * iterator for each edge.
2972 * @param a automaton.
2973 * @param iterator iterator called for each edge.
2974 * @param iterator_cls closure.
2977 GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
2978 GNUNET_REGEX_KeyIterator iterator,
2981 struct GNUNET_REGEX_State *s;
2983 for (s = a->states_head; NULL != s; s = s->next)
2985 struct GNUNET_REGEX_Edge edges[s->transition_count];
2986 unsigned int num_edges;
2988 num_edges = state_get_edges (s, edges);
2990 if ((NULL != s->proof && 0 < strlen (s->proof)) || s->accepting)
2991 iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges,
2994 s->marked = GNUNET_NO;
2997 iterate_initial_edge (GNUNET_REGEX_INITIAL_BYTES, GNUNET_REGEX_INITIAL_BYTES,
2998 NULL, a->start, iterator, iterator_cls);
3003 * Create a string with binary IP notation for the given 'addr' in 'str'.
3005 * @param af address family of the given 'addr'.
3006 * @param addr address that should be converted to a string.
3007 * struct in_addr * for IPv4 and struct in6_addr * for IPv6.
3008 * @param str string that will contain binary notation of 'addr'. Expected
3009 * to be at least 33 bytes long for IPv4 and 129 bytes long for IPv6.
3012 iptobinstr (const int af, const void *addr, char *str)
3020 uint32_t b = htonl (((struct in_addr *) addr)->s_addr);
3024 for (i = 31; i >= 0; i--)
3026 *str = (b & 1) + '0';
3034 struct in6_addr b = *(const struct in6_addr *) addr;
3038 for (i = 127; i >= 0; i--)
3040 *str = (b.s6_addr[i / 8] & 1) + '0';
3042 b.s6_addr[i / 8] >>= 1;
3051 * Get the ipv4 network prefix from the given 'netmask'.
3053 * @param netmask netmask for which to get the prefix len.
3055 * @return length of ipv4 prefix for 'netmask'.
3058 ipv4netmasktoprefixlen (const char *netmask)
3064 if (1 != inet_pton (AF_INET, netmask, &a))
3067 for (t = htonl (~a.s_addr); 0 != t; t >>= 1)
3074 * Create a regex in 'rxstr' from the given 'ip' and 'netmask'.
3076 * @param ip IPv4 representation.
3077 * @param netmask netmask for the ip.
3078 * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV4_REGEXLEN
3082 GNUNET_REGEX_ipv4toregex (const struct in_addr *ip, const char *netmask,
3085 unsigned int pfxlen;
3087 pfxlen = ipv4netmasktoprefixlen (netmask);
3088 iptobinstr (AF_INET, ip, rxstr);
3089 rxstr[pfxlen] = '\0';
3091 strcat (rxstr, "(0|1)+");
3096 * Create a regex in 'rxstr' from the given 'ipv6' and 'prefixlen'.
3098 * @param ipv6 IPv6 representation.
3099 * @param prefixlen length of the ipv6 prefix.
3100 * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV6_REGEXLEN
3104 GNUNET_REGEX_ipv6toregex (const struct in6_addr *ipv6, unsigned int prefixlen,
3107 iptobinstr (AF_INET6, ipv6, rxstr);
3108 rxstr[prefixlen] = '\0';
3109 if (prefixlen < 128)
3110 strcat (rxstr, "(0|1)+");
3114 struct RegexCombineCtx {
3115 struct RegexCombineCtx *next;
3116 struct RegexCombineCtx *prev;
3118 struct RegexCombineCtx *head;
3119 struct RegexCombineCtx *tail;
3126 regex_combine (struct RegexCombineCtx *ctx)
3128 struct RegexCombineCtx *p;
3135 GNUNET_asprintf (®ex, "%s(", ctx->s);
3137 regex = GNUNET_strdup ("(");
3138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "prefix: %s\n", regex);
3140 for (p = ctx->head; NULL != p; p = p->next)
3142 s = regex_combine (p);
3143 GNUNET_asprintf (&tmp, "%s%s|", regex, s);
3144 GNUNET_free_non_null (s);
3145 GNUNET_free_non_null (regex);
3148 len = strlen (regex);
3150 return GNUNET_strdup ("");
3152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pre-partial: %s\n", regex);
3153 if ('|' == regex[len - 1])
3154 regex[len - 1] = ')';
3155 if ('(' == regex[len - 1])
3156 regex[len - 1] = '\0';
3158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "partial: %s\n", regex);
3163 regex_add (struct RegexCombineCtx *ctx, const char *regex)
3165 struct RegexCombineCtx *p;
3169 for (p = ctx->head; NULL != p; p = p->next)
3171 if (p->s[0] == regex[0])
3173 if (1 == strlen(p->s))
3175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "common char %s\n", p->s);
3176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding %s\n", rest);
3177 regex_add (p, rest);
3181 struct RegexCombineCtx *new;
3182 new = GNUNET_malloc (sizeof (struct RegexCombineCtx));
3183 new->s = GNUNET_strdup (&p->s[1]);
3184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " p has now %s\n", p->s);
3185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " p will have %.1s\n", p->s);
3186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regex is %s\n", regex);
3187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " new has now %s\n", new->s);
3188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " rest is now %s\n", rest);
3189 p->s[1] = '\0'; /* dont realloc */
3190 GNUNET_CONTAINER_DLL_insert (p->head, p->tail, new);
3191 regex_add (p, rest);
3196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no match\n");
3197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " new state %s\n", regex);
3198 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " under %s\n", ctx->s);
3199 p = GNUNET_malloc (sizeof (struct RegexCombineCtx));
3200 p->s = GNUNET_strdup (regex);
3201 GNUNET_CONTAINER_DLL_insert (ctx->head, ctx->tail, p);
3205 debug (struct RegexCombineCtx *ctx, int lvl)
3207 struct RegexCombineCtx *p;
3210 for (i = 0; i < lvl; i++) fprintf (stderr, " ");
3211 fprintf (stderr, "%s\n", ctx->s);
3213 for (p = ctx->head; NULL != p; p = p->next)
3220 GNUNET_REGEX_combine (char * const regexes[])
3224 const char *current;
3225 struct RegexCombineCtx *ctx;
3227 ctx = GNUNET_malloc (sizeof (struct RegexCombineCtx));
3228 for (i = 0; regexes[i]; i++)
3230 current = regexes[i];
3231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex %u: %s\n", i, current);
3232 regex_add (ctx, current);
3234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\nCombining...\n");
3236 combined = regex_combine (ctx);