Debian Codegraph @

crt/aws-c-sdkutils/source/endpoints_regex.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/sdkutils/private/endpoints_regex.h>
7
8 /*
9 * Minimal regex implementation.
10 * Inspired by
11 * https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html and
12 * https://github.com/kokke/tiny-regex-c.
13 *
14 * Why write our own regex implementation?
15 * Unfortunately, state of cross-platform regex support for c is rather limited.
16 * Posix has regex support, but implementation support varies cross platform.
17 * Windows supports regex, but only exposes it through C++ interface.
18 * For 3p implementations tiny-regex-c comes closest to what we need, but has
19 * several deal-breaking limitations, ex. not being thread safe, lack of
20 * alternations support.
21 * Other 3p C implementations are very bloated for what we need.
22 * Hence, since we need a very minimal regex support for endpoint resolution we
23 * just implement our own.
24 *
25 * What is supported?
26 * - ascii only matching (no unicode or other encoding support)
27 * - multithread safe iterative matching (stack friendly, since this is
28 * typically called deep in call stack)
29 * - char matching (plain ascii chars, alpha/digit wildcards)
30 * - star and plus (refer to limitations sections for limitations on how they work)
31 * - alternation groups
32 *
33 * Limitations?
34 * - star and plus are greedy (match as much as they can), but do not backtrace.
35 * This is major deviation from how regex matching should work.
36 * Note: regions in aws have a predefined pattern where sections are separated
37 * by '-', so current implementation just matches until it hits separator.
38 * - grouping using ( and ) is only supported for alternations.
39 * - regex must match the whole text, i.e. start with ^ and end with $
40 * - features not called out above are not supported
41 * - alternations pick first occurrence that matches and do not backtrack to see
42 * if there are any other occurrences
43 *
44 * Examples
45 * current implementation is targeted towards matching typical aws region
46 * patterns like "^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$" (aws partition) or
47 * "^us\\-gov\\-\\w+\\-\\d+$" (aws gov partition).
48 * All current regions follow
49 * "country code(2 chars)-meta(like gov or iso, optional)-direction-digit"
50 * and implementation should provide enough features to match those regions.
51 * Patterns that would not match correctly are things like "a*a" (star will
52 * exhaustively match a and will not give last a back) or (ab|abc), which will
53 * not match abc because alternation will lock into ab.
54 */
55
56 enum regex_symbol_type {
57 AWS_ENDPOINTS_REGEX_SYMBOL_DOT,
58 AWS_ENDPOINTS_REGEX_SYMBOL_STAR,
59 AWS_ENDPOINTS_REGEX_SYMBOL_PLUS,
60 AWS_ENDPOINTS_REGEX_SYMBOL_DIGIT,
61 AWS_ENDPOINTS_REGEX_SYMBOL_ALPHA,
62 AWS_ENDPOINTS_REGEX_SYMBOL_CHAR,
63 AWS_ENDPOINTS_REGEX_SYMBOL_ALTERNATION_GROUP,
64 };
65
66 struct aws_endpoints_regex_symbol {
67 enum regex_symbol_type type;
68
69 union {
70 uint8_t ch;
71 struct aws_string *alternation;
72 } info;
73 };
74
75 struct aws_endpoints_regex {
76 struct aws_array_list symbols;
77 };
78
79 /* Somewhat arbitrary limits on size of regex and text to avoid overly large
80 * inputs. */
81 enum {
82 s_max_regex_length = 60,
83 s_max_text_length = 50,
84 s_max_elements_per_alteration = 20,
85 };
86
87 static void s_clean_up_symbols(struct aws_array_list *symbols) {
88 for (size_t i = 0; i < aws_array_list_length(symbols); ++i) {
89 struct aws_endpoints_regex_symbol *element = NULL;
90 aws_array_list_get_at_ptr(symbols, (void **)&element, i);
91
92 if (element->type == AWS_ENDPOINTS_REGEX_SYMBOL_ALTERNATION_GROUP) {
93 aws_string_destroy(element->info.alternation);
94 }
95 }
96 }
97
98 int s_validate_regex(const struct aws_endpoints_regex *regex) {
99 AWS_FATAL_PRECONDITION(regex != NULL);
100
101 for (size_t sym_idx = 0; sym_idx < aws_array_list_length(&regex->symbols); ++sym_idx) {
102 struct aws_endpoints_regex_symbol *symbol = NULL;
103 aws_array_list_get_at_ptr(&regex->symbols, (void **)&symbol, sym_idx);
104
105 if (symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_PLUS || symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_STAR) {
106
107 /* first symbol */
108 if (sym_idx == 0) {
109 AWS_LOGF_ERROR(
110 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid regex pattern. Regex cannot start with star or plus.");
111 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
112 }
113
114 struct aws_endpoints_regex_symbol *prev_symbol = NULL;
115 aws_array_list_get_at_ptr(&regex->symbols, (void **)&prev_symbol, sym_idx - 1);
116
117 /* reasonable symbol before */
118 enum regex_symbol_type prev_type = prev_symbol->type;
119 if (!(prev_type == AWS_ENDPOINTS_REGEX_SYMBOL_DOT || prev_type == AWS_ENDPOINTS_REGEX_SYMBOL_DIGIT ||
120 prev_type == AWS_ENDPOINTS_REGEX_SYMBOL_ALPHA || prev_type == AWS_ENDPOINTS_REGEX_SYMBOL_CHAR ||
121 prev_type == AWS_ENDPOINTS_REGEX_SYMBOL_ALTERNATION_GROUP)) {
122 AWS_LOGF_ERROR(
123 AWS_LS_SDKUTILS_ENDPOINTS_REGEX,
124 "Unsupported regex pattern. Star or plus after unsupported character.");
125 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
126 }
127
128 /* ends with - delimiter */
129 if (sym_idx != aws_array_list_length(&regex->symbols) - 1) {
130 struct aws_endpoints_regex_symbol *next_symbol = NULL;
131 aws_array_list_get_at_ptr(&regex->symbols, (void **)&next_symbol, sym_idx + 1);
132
133 if (next_symbol->type != AWS_ENDPOINTS_REGEX_SYMBOL_CHAR || next_symbol->info.ch != '-') {
134 AWS_LOGF_ERROR(
135 AWS_LS_SDKUTILS_ENDPOINTS_REGEX,
136 "Unsupported regex pattern. Star or plus must be followed by - delimiter.");
137 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
138 }
139 }
140 } else if (symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_ALTERNATION_GROUP) {
141
142 struct aws_byte_cursor alternation = aws_byte_cursor_from_string(symbol->info.alternation);
143
144 /* Not empty */
145 if (alternation.len == 0) {
146 AWS_LOGF_ERROR(AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid regex pattern. Empty group.");
147 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
148 }
149
150 /* Verify that group is only used for alternation. */
151 for (size_t i = 0; i < alternation.len; ++i) {
152 if (!aws_isalnum(alternation.ptr[i]) && alternation.ptr[i] != '|') {
153 AWS_LOGF_ERROR(
154 AWS_LS_SDKUTILS_ENDPOINTS_REGEX,
155 "Unsupported regex pattern. Only alternation groups are supported.");
156 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
157 }
158 }
159
160 /* alternation elements are unique and not subsets of each other */
161 struct aws_byte_cursor elements[s_max_elements_per_alteration];
162 size_t num_elements = 0;
163 struct aws_byte_cursor split = {0};
164 while (aws_byte_cursor_next_split(&alternation, '|', &split)) {
165 if (num_elements == s_max_elements_per_alteration) {
166 AWS_LOGF_ERROR(
167 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Unsupported regex pattern. Too many element in alternation");
168 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
169 }
170
171 if (split.len == 0) {
172 AWS_LOGF_ERROR(
173 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid regex pattern. Alternation element cannot be empty");
174 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
175 }
176
177 elements[num_elements] = split;
178 ++num_elements;
179 }
180
181 struct aws_byte_cursor input;
182 struct aws_byte_cursor prefix;
183 for (size_t i = 0; i < num_elements; ++i) {
184 for (size_t j = i + 1; j < num_elements; ++j) {
185
186 if (elements[i].len <= elements[j].len) {
187 input = elements[j];
188 prefix = elements[i];
189 } else {
190 input = elements[i];
191 prefix = elements[j];
192 }
193
194 if (aws_byte_cursor_starts_with(&input, &prefix)) {
195 AWS_LOGF_ERROR(
196 AWS_LS_SDKUTILS_ENDPOINTS_REGEX,
197 "Unsupported regex pattern. One alternation element cannot be a prefix of another "
198 "element.");
199 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
200 }
201 }
202 }
203 }
204 }
205
206 return AWS_OP_SUCCESS;
207 }
208
209 struct aws_endpoints_regex *aws_endpoints_regex_new(
210 struct aws_allocator *allocator,
211 struct aws_byte_cursor regex_pattern) {
212
213 if (regex_pattern.len == 0 || regex_pattern.len > s_max_regex_length) {
214 AWS_LOGF_ERROR(
215 AWS_LS_SDKUTILS_ENDPOINTS_REGEX,
216 "Invalid regex pattern size. Must be between 1 and %d",
217 s_max_regex_length);
218 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
219 return NULL;
220 }
221
222 if (regex_pattern.ptr[0] != '^' || regex_pattern.ptr[regex_pattern.len - 1] != '$') {
223 AWS_LOGF_ERROR(
224 AWS_LS_SDKUTILS_ENDPOINTS_REGEX,
225 "Unsupported regex pattern. Supported patterns must match the whole text.");
226 aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
227 return NULL;
228 }
229
230 /* Ignore begin/end chars */
231 aws_byte_cursor_advance(&regex_pattern, 1);
232 --regex_pattern.len;
233
234 struct aws_endpoints_regex *re = aws_mem_calloc(allocator, 1, sizeof(struct aws_endpoints_regex));
235 aws_array_list_init_dynamic(&re->symbols, allocator, regex_pattern.len, sizeof(struct aws_endpoints_regex_symbol));
236
237 while (regex_pattern.len > 0) {
238 uint8_t ch = regex_pattern.ptr[0];
239 aws_byte_cursor_advance(&regex_pattern, 1);
240
241 struct aws_endpoints_regex_symbol symbol;
242 switch (ch) {
243 case '.':
244 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_DOT;
245 break;
246 case '*':
247 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_STAR;
248 break;
249 case '+':
250 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_PLUS;
251 break;
252 case '\\':
253 if (regex_pattern.len == 0) {
254 AWS_LOGF_ERROR(
255 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid regex pattern. Pattern ends with escape character.");
256 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
257 goto on_error;
258 }
259 switch (regex_pattern.ptr[0]) {
260 /* Predefined patterns */
261 case 'd':
262 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_DIGIT;
263 break;
264 case 'w':
265 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_ALPHA;
266 break;
267
268 /* Escaped chars, ex. * or + */
269 default:
270 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_CHAR;
271 symbol.info.ch = regex_pattern.ptr[0];
272 break;
273 }
274 aws_byte_cursor_advance(&regex_pattern, 1);
275 break;
276 case '(': {
277 struct aws_byte_cursor group = {0};
278 if (!aws_byte_cursor_next_split(&regex_pattern, ')', &group)) {
279 AWS_LOGF_ERROR(AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid regex pattern. Invalid group syntax.");
280 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
281 goto on_error;
282 }
283
284 aws_byte_cursor_advance(&regex_pattern, group.len);
285 if (regex_pattern.len == 0 || regex_pattern.ptr[0] != ')') {
286 AWS_LOGF_ERROR(
287 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid regex pattern. Missing closing parenthesis.");
288 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
289 goto on_error;
290 }
291 aws_byte_cursor_advance(&regex_pattern, 1);
292
293 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_ALTERNATION_GROUP;
294 symbol.info.alternation = aws_string_new_from_cursor(allocator, &group);
295 break;
296 }
297
298 default: {
299 if (!aws_isalnum(ch)) {
300 AWS_LOGF_ERROR(
301 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Unsupported regex pattern. Unknown character %c", ch);
302 aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_UNSUPPORTED_REGEX);
303 goto on_error;
304 }
305
306 symbol.type = AWS_ENDPOINTS_REGEX_SYMBOL_CHAR;
307 symbol.info.ch = ch;
308 break;
309 }
310 }
311
312 aws_array_list_push_back(&re->symbols, &symbol);
313 }
314
315 if (s_validate_regex(re)) {
316 goto on_error;
317 }
318
319 return re;
320
321 on_error:
322 aws_endpoints_regex_destroy(re);
323 return NULL;
324 }
325
326 void aws_endpoints_regex_destroy(struct aws_endpoints_regex *regex) {
327 if (regex == NULL) {
328 return;
329 }
330
331 struct aws_allocator *allocator = regex->symbols.alloc;
332 s_clean_up_symbols(&regex->symbols);
333 aws_array_list_clean_up(&regex->symbols);
334 aws_mem_release(allocator, &regex->symbols);
335 }
336
337 static bool s_match_one(const struct aws_endpoints_regex_symbol *symbol, struct aws_byte_cursor *text) {
338 if (text->len == 0) {
339 return false;
340 }
341
342 uint8_t ch = text->ptr[0];
343 switch (symbol->type) {
344 case AWS_ENDPOINTS_REGEX_SYMBOL_ALPHA:
345 return aws_isalpha(ch);
346 case AWS_ENDPOINTS_REGEX_SYMBOL_DIGIT:
347 return aws_isdigit(ch);
348 case AWS_ENDPOINTS_REGEX_SYMBOL_CHAR:
349 return ch == symbol->info.ch;
350 case AWS_ENDPOINTS_REGEX_SYMBOL_DOT:
351 return true;
352 default:
353 AWS_FATAL_ASSERT(true);
354 }
355
356 return false;
357 }
358
359 static void s_match_star(const struct aws_endpoints_regex_symbol *symbol, struct aws_byte_cursor *text) {
360 while (s_match_one(symbol, text)) {
361 aws_byte_cursor_advance(text, 1);
362 }
363 }
364
365 static bool s_match_plus(const struct aws_endpoints_regex_symbol *symbol, struct aws_byte_cursor *text) {
366 if (!s_match_one(symbol, text)) {
367 return false;
368 }
369
370 aws_byte_cursor_advance(text, 1);
371 s_match_star(symbol, text);
372 return true;
373 }
374
375 int aws_endpoints_regex_match(const struct aws_endpoints_regex *regex, struct aws_byte_cursor text) {
376 AWS_PRECONDITION(regex);
377
378 if (text.len == 0 || text.len > s_max_text_length) {
379 AWS_LOGF_ERROR(
380 AWS_LS_SDKUTILS_ENDPOINTS_REGEX, "Invalid text size. Must be between 1 and %d", s_max_text_length);
381 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
382 }
383
384 for (size_t i = 0; i < aws_array_list_length(&regex->symbols); ++i) {
385 struct aws_endpoints_regex_symbol *symbol = NULL;
386 aws_array_list_get_at_ptr(&regex->symbols, (void **)&symbol, i);
387
388 /* looks forward to check if symbol has * or + modifier */
389 if (i + 1 < aws_array_list_length(&regex->symbols)) {
390 struct aws_endpoints_regex_symbol *next_symbol = NULL;
391 aws_array_list_get_at_ptr(&regex->symbols, (void **)&next_symbol, i + 1);
392
393 if (next_symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_STAR ||
394 next_symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_PLUS) {
395 if (next_symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_STAR) {
396 s_match_star(symbol, &text);
397 } else if (next_symbol->type == AWS_ENDPOINTS_REGEX_SYMBOL_PLUS) {
398 if (!s_match_plus(symbol, &text)) {
399 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_REGEX_NO_MATCH);
400 }
401 }
402 ++i;
403 continue;
404 }
405 }
406
407 switch (symbol->type) {
408 case AWS_ENDPOINTS_REGEX_SYMBOL_ALTERNATION_GROUP: {
409 struct aws_byte_cursor variant = {0};
410 struct aws_byte_cursor alternation = aws_byte_cursor_from_string(symbol->info.alternation);
411 size_t chars_in_match = 0;
412 while (aws_byte_cursor_next_split(&alternation, '|', &variant)) {
413 if (aws_byte_cursor_starts_with(&text, &variant)) {
414 chars_in_match = variant.len;
415 break;
416 }
417 }
418
419 if (chars_in_match == 0) {
420 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_REGEX_NO_MATCH);
421 }
422 aws_byte_cursor_advance(&text, chars_in_match);
423 break;
424 }
425 default:
426 if (!s_match_one(symbol, &text)) {
427 return aws_raise_error(AWS_ERROR_SDKUTILS_ENDPOINTS_REGEX_NO_MATCH);
428 }
429 aws_byte_cursor_advance(&text, 1);
430 break;
431 }
432 }
433
434 return AWS_OP_SUCCESS;
435 }