ESAPI-C 1.0
The OWASP Enterprise Security API for C
|
00001 00008 #include <stdio.h> 00009 #include <stdlib.h> 00010 #include <string.h> 00011 #include <regex.h> 00012 00013 #include "validate.h" 00014 00018 typedef struct element { 00019 char *pattern; 00020 regex_t r; 00021 struct element *prev; 00022 struct element *next; 00023 } element; 00024 00028 element *pattern_list = NULL; 00029 00030 int _cmp_ele(element *a, element *b) { 00031 return strcmp(a->pattern, b->pattern); 00032 } 00033 00034 int contains_char(char *s, char c) { 00035 return (strchr(s, (int) c)) ? 1 : 0; 00036 } 00037 00038 char *strip_chars(char *s, char *valid_chars) { 00039 char *buf; 00040 char *p = s; 00041 int i = 0; 00042 00043 if ((buf = (char *) malloc(strlen(s) + 1)) == 0) { 00044 fprintf(stderr, "malloc failure in %s\n", __func__); 00045 exit(EXIT_FAILURE); 00046 } 00047 00048 while (*p) { 00049 if (!contains_char(valid_chars, *p)) { 00050 buf[i++] = *p; 00051 } 00052 p++; 00053 } 00054 00055 buf[i] = 0; 00056 00057 return buf; 00058 } 00059 00060 int is_valid(char *input, char *regex, int flags) { 00061 00062 regex_t r; 00063 int compile_rc; 00064 static element search; 00065 element *found, *new_pattern; 00066 00067 found = 0; 00068 00069 if (!input) { 00070 return -1; 00071 } 00072 00073 /* 00074 * Check if we already compiled this regexp. If we have 00075 * then use it. Otherwise, compile it and store it for 00076 * later. 00077 */ 00078 00079 search.pattern = regex; 00080 DL_SEARCH(pattern_list,found,&search,_cmp_ele); 00081 00082 if (found) { 00083 r = found->r; 00084 } else { 00085 /* Add it to the list of already-compiled patterns. */ 00086 compile_rc = regcomp(&r, regex, flags); 00087 00088 if (compile_rc) { 00089 return compile_rc; 00090 } 00091 00092 if ((new_pattern = (element *) malloc(sizeof(element))) == 0) { 00093 fprintf(stderr, "malloc failure in %s\n", __func__); 00094 exit(EXIT_FAILURE); 00095 } 00096 00097 if ((new_pattern->pattern = strdup(input)) == 0) { 00098 fprintf(stderr, "strdup failure in %s\n", __func__); 00099 exit(EXIT_FAILURE); 00100 } 00101 00102 new_pattern->r = r; 00103 DL_APPEND(pattern_list,new_pattern); 00104 } 00105 00106 /* Execute the regular expression against the input. */ 00107 00108 free(new_pattern->pattern); 00109 free(new_pattern); 00110 00111 return regexec(&r, input, 0, NULL, 0); 00112 }