1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
22 #include "tool_setup.h"
24 #define ENABLE_CURLX_PRINTF
25 /* use our own printf() functions */
27 #include "tool_cfgable.h"
28 #include "tool_doswin.h"
29 #include "tool_urlglob.h"
32 #include "memdebug.h" /* keep this as LAST include */
34 #define GLOBERROR(string, column, code) \
35 glob->error = string, glob->pos = column, code
37 void glob_cleanup(URLGlob* glob);
39 static CURLcode glob_fixed(URLGlob *glob, char *fixed, size_t len)
41 URLPattern *pat = &glob->pattern[glob->size];
43 pat->content.Set.size = 1;
44 pat->content.Set.ptr_s = 0;
47 pat->content.Set.elements = malloc(sizeof(char *));
49 if(!pat->content.Set.elements)
50 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
52 pat->content.Set.elements[0] = malloc(len + 1);
53 if(!pat->content.Set.elements[0])
54 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
56 memcpy(pat->content.Set.elements[0], fixed, len);
57 pat->content.Set.elements[0][len] = 0;
64 * Multiplies and checks for overflow.
66 static int multiply(unsigned long *amount, long with)
68 unsigned long sum = *amount * with;
73 if(sum/with != *amount)
74 return 1; /* didn't fit, bail out */
79 static CURLcode glob_set(URLGlob *glob, char **patternp,
80 size_t *posp, unsigned long *amount,
83 /* processes a set expression with the point behind the opening '{'
84 ','-separated elements are collected until the next closing '}'
88 char *buf = glob->glob_buffer;
89 char *pattern = *patternp;
90 char *opattern = pattern;
91 size_t opos = *posp-1;
93 pat = &glob->pattern[glob->size];
94 /* patterns 0,1,2,... correspond to size=1,3,5,... */
96 pat->content.Set.size = 0;
97 pat->content.Set.ptr_s = 0;
98 pat->content.Set.elements = NULL;
99 pat->globindex = globindex;
103 case '\0': /* URL ended while set was still open */
104 return GLOBERROR("unmatched brace", opos, CURLE_URL_MALFORMAT);
107 case '[': /* no nested expressions at this time */
108 return GLOBERROR("nested brace", *posp, CURLE_URL_MALFORMAT);
110 case '}': /* set element completed */
111 if(opattern == pattern)
112 return GLOBERROR("empty string within braces", *posp,
113 CURLE_URL_MALFORMAT);
115 /* add 1 to size since it'll be incremented below */
116 if(multiply(amount, pat->content.Set.size + 1))
117 return GLOBERROR("range overflow", 0, CURLE_URL_MALFORMAT);
123 if(pat->content.Set.elements) {
124 char **new_arr = realloc(pat->content.Set.elements,
125 (pat->content.Set.size + 1) * sizeof(char *));
127 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
129 pat->content.Set.elements = new_arr;
132 pat->content.Set.elements = malloc(sizeof(char *));
134 if(!pat->content.Set.elements)
135 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
137 pat->content.Set.elements[pat->content.Set.size] =
138 strdup(glob->glob_buffer);
139 if(!pat->content.Set.elements[pat->content.Set.size])
140 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
141 ++pat->content.Set.size;
143 if(*pattern == '}') {
144 pattern++; /* pass the closing brace */
149 buf = glob->glob_buffer;
154 case ']': /* illegal closing bracket */
155 return GLOBERROR("unexpected close bracket", *posp, CURLE_URL_MALFORMAT);
157 case '\\': /* escaped character, skip '\' */
162 /* intentional fallthrough */
164 *buf++ = *pattern++; /* copy character to set element */
169 *patternp = pattern; /* return with the new position */
173 static CURLcode glob_range(URLGlob *glob, char **patternp,
174 size_t *posp, unsigned long *amount,
177 /* processes a range expression with the point behind the opening '['
178 - char range: e.g. "a-z]", "B-Q]"
179 - num range: e.g. "0-9]", "17-2000]"
180 - num range with leading zeros: e.g. "001-999]"
181 expression is checked for well-formedness and collected until the next ']'
185 char *pattern = *patternp;
188 pat = &glob->pattern[glob->size];
189 pat->globindex = globindex;
191 if(ISALPHA(*pattern)) {
192 /* character range detected */
196 unsigned long step = 1;
198 pat->type = UPTCharRange;
200 rc = sscanf(pattern, "%c-%c%c", &min_c, &max_c, &end_c);
206 step = strtoul(&pattern[4], &endp, 10);
207 if(errno || &pattern[4] == endp || *endp != ']')
212 else if(end_c != ']')
213 /* then this is wrong */
220 *posp += (pattern - *patternp);
222 if(rc != 3 || !step || step > (unsigned)INT_MAX ||
223 (min_c == max_c && step != 1) ||
224 (min_c != max_c && (min_c > max_c || step > (unsigned)(max_c - min_c) ||
225 (max_c - min_c) > ('z' - 'a'))))
226 /* the pattern is not well-formed */
227 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
229 /* if there was a ":[num]" thing, use that as step or else use 1 */
230 pat->content.CharRange.step = (int)step;
231 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c = min_c;
232 pat->content.CharRange.max_c = max_c;
234 if(multiply(amount, ((pat->content.CharRange.max_c -
235 pat->content.CharRange.min_c) /
236 pat->content.CharRange.step + 1)))
237 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
239 else if(ISDIGIT(*pattern)) {
240 /* numeric range detected */
242 unsigned long max_n = 0;
243 unsigned long step_n = 0;
246 pat->type = UPTNumRange;
247 pat->content.NumRange.padlength = 0;
249 if(*pattern == '0') {
250 /* leading zero specified, count them! */
254 ++pat->content.NumRange.padlength; /* padding length is set for all
255 instances of this pattern */
260 min_n = strtoul(pattern, &endp, 10);
261 if(errno || (endp == pattern))
268 while(*pattern && ISBLANK(*pattern))
270 if(!ISDIGIT(*pattern)) {
275 max_n = strtoul(pattern, &endp, 10);
279 else if(*endp == ':') {
282 step_n = strtoul(pattern, &endp, 10);
284 /* over/underflow situation */
289 if(endp && (*endp == ']')) {
298 *posp += (pattern - *patternp);
300 if(!endp || !step_n ||
301 (min_n == max_n && step_n != 1) ||
302 (min_n != max_n && (min_n > max_n || step_n > (max_n - min_n))))
303 /* the pattern is not well-formed */
304 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
306 /* typecasting to ints are fine here since we make sure above that we
307 are within 31 bits */
308 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n = min_n;
309 pat->content.NumRange.max_n = max_n;
310 pat->content.NumRange.step = step_n;
312 if(multiply(amount, ((pat->content.NumRange.max_n -
313 pat->content.NumRange.min_n) /
314 pat->content.NumRange.step + 1)))
315 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
318 return GLOBERROR("bad range specification", *posp, CURLE_URL_MALFORMAT);
324 static bool peek_ipv6(const char *str, size_t *skip)
327 * Scan for a potential IPv6 literal.
328 * - Valid globs contain a hyphen and <= 1 colon.
329 * - IPv6 literals contain no hyphens and >= 2 colons.
333 if(str[i++] != '[') {
337 const char c = str[i++];
338 if(ISALNUM(c) || c == '.' || c == '%') {
346 return colons >= 2 ? TRUE : FALSE;
354 static CURLcode glob_parse(URLGlob *glob, char *pattern,
355 size_t pos, unsigned long *amount)
357 /* processes a literal string component of a URL
358 special characters '{' and '[' branch to set/range processing functions
360 CURLcode res = CURLE_OK;
361 int globindex = 0; /* count "actual" globs */
365 while(*pattern && !res) {
366 char *buf = glob->glob_buffer;
368 while(*pattern && *pattern != '{') {
369 if(*pattern == '[') {
370 /* skip over IPv6 literals and [] */
372 if(!peek_ipv6(pattern, &skip) && (pattern[1] == ']'))
375 memcpy(buf, pattern, skip);
383 if(*pattern == '}' || *pattern == ']')
384 return GLOBERROR("unmatched close brace/bracket", pos,
385 CURLE_URL_MALFORMAT);
387 /* only allow \ to escape known "special letters" */
388 if(*pattern == '\\' &&
389 (*(pattern + 1) == '{' || *(pattern + 1) == '[' ||
390 *(pattern + 1) == '}' || *(pattern + 1) == ']') ) {
392 /* escape character, skip '\' */
396 *buf++ = *pattern++; /* copy character to literal */
401 /* we got a literal string, add it as a single-item list */
403 res = glob_fixed(glob, glob->glob_buffer, sublen);
407 case '\0': /* done */
411 /* process set pattern */
414 res = glob_set(glob, &pattern, &pos, amount, globindex++);
418 /* process range pattern */
421 res = glob_range(glob, &pattern, &pos, amount, globindex++);
426 if(++glob->size >= GLOB_PATTERN_NUM)
427 return GLOBERROR("too many globs", pos, CURLE_URL_MALFORMAT);
432 CURLcode glob_url(URLGlob **glob, char *url, unsigned long *urlnum,
436 * We can deal with any-size, just make a buffer with the same length
437 * as the specified URL!
439 URLGlob *glob_expand;
440 unsigned long amount = 0;
446 glob_buffer = malloc(strlen(url) + 1);
448 return CURLE_OUT_OF_MEMORY;
451 glob_expand = calloc(1, sizeof(URLGlob));
453 Curl_safefree(glob_buffer);
454 return CURLE_OUT_OF_MEMORY;
456 glob_expand->urllen = strlen(url);
457 glob_expand->glob_buffer = glob_buffer;
459 res = glob_parse(glob_expand, url, 1, &amount);
463 if(error && glob_expand->error) {
466 if(glob_expand->pos) {
467 snprintf(text, sizeof(text), "%s in column %zu", glob_expand->error,
472 t = glob_expand->error;
474 /* send error description to the error-stream */
475 fprintf(error, "curl: (%d) [globbing] %s\n", res, t);
477 /* it failed, we cleanup */
478 glob_cleanup(glob_expand);
487 void glob_cleanup(URLGlob* glob)
492 for(i = 0; i < glob->size; i++) {
493 if((glob->pattern[i].type == UPTSet) &&
494 (glob->pattern[i].content.Set.elements)) {
495 for(elem = glob->pattern[i].content.Set.size - 1;
498 Curl_safefree(glob->pattern[i].content.Set.elements[elem]);
500 Curl_safefree(glob->pattern[i].content.Set.elements);
503 Curl_safefree(glob->glob_buffer);
507 CURLcode glob_next_url(char **globbed, URLGlob *glob)
512 size_t buflen = glob->urllen + 1;
513 char *buf = glob->glob_buffer;
522 /* implement a counter over the index ranges of all patterns, starting
523 with the rightmost pattern */
524 for(i = 0; carry && (i < glob->size); i++) {
526 pat = &glob->pattern[glob->size - 1 - i];
529 if((pat->content.Set.elements) &&
530 (++pat->content.Set.ptr_s == pat->content.Set.size)) {
531 pat->content.Set.ptr_s = 0;
536 pat->content.CharRange.ptr_c =
537 (char)(pat->content.CharRange.step +
538 (int)((unsigned char)pat->content.CharRange.ptr_c));
539 if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
540 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
545 pat->content.NumRange.ptr_n += pat->content.NumRange.step;
546 if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
547 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
552 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
553 return CURLE_FAILED_INIT;
556 if(carry) { /* first pattern ptr has run into overflow, done! */
557 /* TODO: verify if this should actally return CURLE_OK. */
558 return CURLE_OK; /* CURLE_OK to match previous behavior */
562 for(i = 0; i < glob->size; ++i) {
563 pat = &glob->pattern[i];
566 if(pat->content.Set.elements) {
567 snprintf(buf, buflen, "%s",
568 pat->content.Set.elements[pat->content.Set.ptr_s]);
576 *buf++ = pat->content.CharRange.ptr_c;
582 snprintf(buf, buflen, "%0*ld",
583 pat->content.NumRange.padlength,
584 pat->content.NumRange.ptr_n);
590 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
591 return CURLE_FAILED_INIT;
595 *globbed = strdup(glob->glob_buffer);
597 return CURLE_OUT_OF_MEMORY;
602 CURLcode glob_match_url(char **result, char *filename, URLGlob *glob)
607 char *appendthis = NULL;
608 size_t appendlen = 0;
609 size_t stringlen = 0;
613 /* We cannot use the glob_buffer for storage here since the filename may
614 * be longer than the URL we use. We allocate a good start size, then
615 * we need to realloc in case of need.
617 allocsize = strlen(filename) + 1; /* make it at least one byte to store the
619 target = malloc(allocsize);
621 return CURLE_OUT_OF_MEMORY;
624 if(*filename == '#' && ISDIGIT(filename[1])) {
626 char *ptr = filename;
627 unsigned long num = strtoul(&filename[1], &filename, 10);
628 URLPattern *pat = NULL;
630 if(num < glob->size) {
631 num--; /* make it zero based */
632 /* find the correct glob entry */
633 for(i = 0; i<glob->size; i++) {
634 if(glob->pattern[i].globindex == (int)num) {
635 pat = &glob->pattern[i];
644 if(pat->content.Set.elements) {
645 appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
647 strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
651 numbuf[0] = pat->content.CharRange.ptr_c;
657 snprintf(numbuf, sizeof(numbuf), "%0*lu",
658 pat->content.NumRange.padlength,
659 pat->content.NumRange.ptr_n);
661 appendlen = strlen(numbuf);
664 fprintf(stderr, "internal error: invalid pattern type (%d)\n",
666 Curl_safefree(target);
667 return CURLE_FAILED_INIT;
671 /* #[num] out of range, use the #[num] in the output */
673 appendthis = filename++;
678 appendthis = filename++;
681 if(appendlen + stringlen >= allocsize) {
683 /* we append a single byte to allow for the trailing byte to be appended
684 at the end of this function outside the while() loop */
685 allocsize = (appendlen + stringlen) * 2;
686 newstr = realloc(target, allocsize + 1);
688 Curl_safefree(target);
689 return CURLE_OUT_OF_MEMORY;
693 memcpy(&target[stringlen], appendthis, appendlen);
694 stringlen += appendlen;
696 target[stringlen]= '\0';
698 #if defined(MSDOS) || defined(WIN32)
701 SANITIZEcode sc = sanitize_file_name(&sanitized, target,
702 (SANITIZE_ALLOW_PATH |
703 SANITIZE_ALLOW_RESERVED));
704 Curl_safefree(target);
706 return CURLE_URL_MALFORMAT;
709 #endif /* MSDOS || WIN32 */