1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2016, 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;
69 if(sum/with != *amount)
70 return 1; /* didn't fit, bail out */
75 static CURLcode glob_set(URLGlob *glob, char **patternp,
76 size_t *posp, unsigned long *amount,
79 /* processes a set expression with the point behind the opening '{'
80 ','-separated elements are collected until the next closing '}'
84 char *buf = glob->glob_buffer;
85 char *pattern = *patternp;
86 char *opattern = pattern;
87 size_t opos = *posp-1;
89 pat = &glob->pattern[glob->size];
90 /* patterns 0,1,2,... correspond to size=1,3,5,... */
92 pat->content.Set.size = 0;
93 pat->content.Set.ptr_s = 0;
94 pat->content.Set.elements = NULL;
95 pat->globindex = globindex;
99 case '\0': /* URL ended while set was still open */
100 return GLOBERROR("unmatched brace", opos, CURLE_URL_MALFORMAT);
103 case '[': /* no nested expressions at this time */
104 return GLOBERROR("nested brace", *posp, CURLE_URL_MALFORMAT);
106 case '}': /* set element completed */
107 if(opattern == pattern)
108 return GLOBERROR("empty string within braces", *posp,
109 CURLE_URL_MALFORMAT);
111 /* add 1 to size since it'll be incremented below */
112 if(multiply(amount, pat->content.Set.size+1))
113 return GLOBERROR("range overflow", 0, CURLE_URL_MALFORMAT);
119 if(pat->content.Set.elements) {
120 char **new_arr = realloc(pat->content.Set.elements,
121 (pat->content.Set.size + 1) * sizeof(char *));
123 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
125 pat->content.Set.elements = new_arr;
128 pat->content.Set.elements = malloc(sizeof(char *));
130 if(!pat->content.Set.elements)
131 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
133 pat->content.Set.elements[pat->content.Set.size] =
134 strdup(glob->glob_buffer);
135 if(!pat->content.Set.elements[pat->content.Set.size])
136 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
137 ++pat->content.Set.size;
139 if(*pattern == '}') {
140 pattern++; /* pass the closing brace */
145 buf = glob->glob_buffer;
150 case ']': /* illegal closing bracket */
151 return GLOBERROR("unexpected close bracket", *posp, CURLE_URL_MALFORMAT);
153 case '\\': /* escaped character, skip '\' */
158 /* intentional fallthrough */
160 *buf++ = *pattern++; /* copy character to set element */
165 *patternp = pattern; /* return with the new position */
169 static CURLcode glob_range(URLGlob *glob, char **patternp,
170 size_t *posp, unsigned long *amount,
173 /* processes a range expression with the point behind the opening '['
174 - char range: e.g. "a-z]", "B-Q]"
175 - num range: e.g. "0-9]", "17-2000]"
176 - num range with leading zeros: e.g. "001-999]"
177 expression is checked for well-formedness and collected until the next ']'
181 char *pattern = *patternp;
184 pat = &glob->pattern[glob->size];
185 pat->globindex = globindex;
187 if(ISALPHA(*pattern)) {
188 /* character range detected */
192 unsigned long step = 1;
194 pat->type = UPTCharRange;
196 rc = sscanf(pattern, "%c-%c%c", &min_c, &max_c, &end_c);
202 step = strtoul(&pattern[4], &endp, 10);
203 if(errno || &pattern[4] == endp || *endp != ']')
208 else if(end_c != ']')
209 /* then this is wrong */
216 *posp += (pattern - *patternp);
218 if(rc != 3 || !step || step > (unsigned)INT_MAX ||
219 (min_c == max_c && step != 1) ||
220 (min_c != max_c && (min_c > max_c || step > (unsigned)(max_c - min_c) ||
221 (max_c - min_c) > ('z' - 'a'))))
222 /* the pattern is not well-formed */
223 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
225 /* if there was a ":[num]" thing, use that as step or else use 1 */
226 pat->content.CharRange.step = (int)step;
227 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c = min_c;
228 pat->content.CharRange.max_c = max_c;
230 if(multiply(amount, ((pat->content.CharRange.max_c -
231 pat->content.CharRange.min_c) /
232 pat->content.CharRange.step + 1)))
233 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
235 else if(ISDIGIT(*pattern)) {
236 /* numeric range detected */
238 unsigned long max_n = 0;
239 unsigned long step_n = 0;
242 pat->type = UPTNumRange;
243 pat->content.NumRange.padlength = 0;
245 if(*pattern == '0') {
246 /* leading zero specified, count them! */
250 ++pat->content.NumRange.padlength; /* padding length is set for all
251 instances of this pattern */
256 min_n = strtoul(pattern, &endp, 10);
257 if(errno || (endp == pattern))
264 while(*pattern && ISBLANK(*pattern))
266 if(!ISDIGIT(*pattern)) {
271 max_n = strtoul(pattern, &endp, 10);
272 if(errno || (*endp == ':')) {
275 step_n = strtoul(pattern, &endp, 10);
277 /* over/underflow situation */
282 if(endp && (*endp == ']')) {
291 *posp += (pattern - *patternp);
293 if(!endp || !step_n ||
294 (min_n == max_n && step_n != 1) ||
295 (min_n != max_n && (min_n > max_n || step_n > (max_n - min_n))))
296 /* the pattern is not well-formed */
297 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
299 /* typecasting to ints are fine here since we make sure above that we
300 are within 31 bits */
301 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n = min_n;
302 pat->content.NumRange.max_n = max_n;
303 pat->content.NumRange.step = step_n;
305 if(multiply(amount, ((pat->content.NumRange.max_n -
306 pat->content.NumRange.min_n) /
307 pat->content.NumRange.step + 1)))
308 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
311 return GLOBERROR("bad range specification", *posp, CURLE_URL_MALFORMAT);
317 static bool peek_ipv6(const char *str, size_t *skip)
320 * Scan for a potential IPv6 literal.
321 * - Valid globs contain a hyphen and <= 1 colon.
322 * - IPv6 literals contain no hyphens and >= 2 colons.
326 if(str[i++] != '[') {
330 const char c = str[i++];
331 if(ISALNUM(c) || c == '.' || c == '%') {
339 return colons >= 2 ? TRUE : FALSE;
347 static CURLcode glob_parse(URLGlob *glob, char *pattern,
348 size_t pos, unsigned long *amount)
350 /* processes a literal string component of a URL
351 special characters '{' and '[' branch to set/range processing functions
353 CURLcode res = CURLE_OK;
354 int globindex = 0; /* count "actual" globs */
358 while(*pattern && !res) {
359 char *buf = glob->glob_buffer;
361 while(*pattern && *pattern != '{') {
362 if(*pattern == '[') {
363 /* Skip over potential IPv6 literals. */
365 if(peek_ipv6(pattern, &skip)) {
366 memcpy(buf, pattern, skip);
374 if(*pattern == '}' || *pattern == ']')
375 return GLOBERROR("unmatched close brace/bracket", pos,
376 CURLE_URL_MALFORMAT);
378 /* only allow \ to escape known "special letters" */
379 if(*pattern == '\\' &&
380 (*(pattern+1) == '{' || *(pattern+1) == '[' ||
381 *(pattern+1) == '}' || *(pattern+1) == ']') ) {
383 /* escape character, skip '\' */
387 *buf++ = *pattern++; /* copy character to literal */
392 /* we got a literal string, add it as a single-item list */
394 res = glob_fixed(glob, glob->glob_buffer, sublen);
398 case '\0': /* done */
402 /* process set pattern */
405 res = glob_set(glob, &pattern, &pos, amount, globindex++);
409 /* process range pattern */
412 res = glob_range(glob, &pattern, &pos, amount, globindex++);
417 if(++glob->size >= GLOB_PATTERN_NUM)
418 return GLOBERROR("too many globs", pos, CURLE_URL_MALFORMAT);
423 CURLcode glob_url(URLGlob **glob, char *url, unsigned long *urlnum,
427 * We can deal with any-size, just make a buffer with the same length
428 * as the specified URL!
430 URLGlob *glob_expand;
431 unsigned long amount = 0;
437 glob_buffer = malloc(strlen(url) + 1);
439 return CURLE_OUT_OF_MEMORY;
442 glob_expand = calloc(1, sizeof(URLGlob));
444 Curl_safefree(glob_buffer);
445 return CURLE_OUT_OF_MEMORY;
447 glob_expand->urllen = strlen(url);
448 glob_expand->glob_buffer = glob_buffer;
450 res = glob_parse(glob_expand, url, 1, &amount);
454 if(error && glob_expand->error) {
457 if(glob_expand->pos) {
458 snprintf(text, sizeof(text), "%s in column %zu", glob_expand->error,
463 t = glob_expand->error;
465 /* send error description to the error-stream */
466 fprintf(error, "curl: (%d) [globbing] %s\n", res, t);
468 /* it failed, we cleanup */
469 glob_cleanup(glob_expand);
478 void glob_cleanup(URLGlob* glob)
483 for(i = 0; i < glob->size; i++) {
484 if((glob->pattern[i].type == UPTSet) &&
485 (glob->pattern[i].content.Set.elements)) {
486 for(elem = glob->pattern[i].content.Set.size - 1;
489 Curl_safefree(glob->pattern[i].content.Set.elements[elem]);
491 Curl_safefree(glob->pattern[i].content.Set.elements);
494 Curl_safefree(glob->glob_buffer);
498 CURLcode glob_next_url(char **globbed, URLGlob *glob)
503 size_t buflen = glob->urllen + 1;
504 char *buf = glob->glob_buffer;
513 /* implement a counter over the index ranges of all patterns, starting
514 with the rightmost pattern */
515 for(i = 0; carry && (i < glob->size); i++) {
517 pat = &glob->pattern[glob->size - 1 - i];
520 if((pat->content.Set.elements) &&
521 (++pat->content.Set.ptr_s == pat->content.Set.size)) {
522 pat->content.Set.ptr_s = 0;
527 pat->content.CharRange.ptr_c =
528 (char)(pat->content.CharRange.step +
529 (int)((unsigned char)pat->content.CharRange.ptr_c));
530 if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
531 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
536 pat->content.NumRange.ptr_n += pat->content.NumRange.step;
537 if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
538 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
543 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
544 return CURLE_FAILED_INIT;
547 if(carry) { /* first pattern ptr has run into overflow, done! */
548 /* TODO: verify if this should actally return CURLE_OK. */
549 return CURLE_OK; /* CURLE_OK to match previous behavior */
553 for(i = 0; i < glob->size; ++i) {
554 pat = &glob->pattern[i];
557 if(pat->content.Set.elements) {
558 snprintf(buf, buflen, "%s",
559 pat->content.Set.elements[pat->content.Set.ptr_s]);
567 *buf++ = pat->content.CharRange.ptr_c;
573 snprintf(buf, buflen, "%0*ld",
574 pat->content.NumRange.padlength,
575 pat->content.NumRange.ptr_n);
581 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
582 return CURLE_FAILED_INIT;
586 *globbed = strdup(glob->glob_buffer);
588 return CURLE_OUT_OF_MEMORY;
593 CURLcode glob_match_url(char **result, char *filename, URLGlob *glob)
598 char *appendthis = NULL;
599 size_t appendlen = 0;
600 size_t stringlen = 0;
604 /* We cannot use the glob_buffer for storage here since the filename may
605 * be longer than the URL we use. We allocate a good start size, then
606 * we need to realloc in case of need.
608 allocsize = strlen(filename) + 1; /* make it at least one byte to store the
610 target = malloc(allocsize);
612 return CURLE_OUT_OF_MEMORY;
615 if(*filename == '#' && ISDIGIT(filename[1])) {
617 char *ptr = filename;
618 unsigned long num = strtoul(&filename[1], &filename, 10);
619 URLPattern *pat =NULL;
621 if(num < glob->size) {
622 num--; /* make it zero based */
623 /* find the correct glob entry */
624 for(i=0; i<glob->size; i++) {
625 if(glob->pattern[i].globindex == (int)num) {
626 pat = &glob->pattern[i];
635 if(pat->content.Set.elements) {
636 appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
638 strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
642 numbuf[0] = pat->content.CharRange.ptr_c;
648 snprintf(numbuf, sizeof(numbuf), "%0*lu",
649 pat->content.NumRange.padlength,
650 pat->content.NumRange.ptr_n);
652 appendlen = strlen(numbuf);
655 fprintf(stderr, "internal error: invalid pattern type (%d)\n",
657 Curl_safefree(target);
658 return CURLE_FAILED_INIT;
662 /* #[num] out of range, use the #[num] in the output */
664 appendthis = filename++;
669 appendthis = filename++;
672 if(appendlen + stringlen >= allocsize) {
674 /* we append a single byte to allow for the trailing byte to be appended
675 at the end of this function outside the while() loop */
676 allocsize = (appendlen + stringlen) * 2;
677 newstr = realloc(target, allocsize + 1);
679 Curl_safefree(target);
680 return CURLE_OUT_OF_MEMORY;
684 memcpy(&target[stringlen], appendthis, appendlen);
685 stringlen += appendlen;
687 target[stringlen]= '\0';
689 #if defined(MSDOS) || defined(WIN32)
692 SANITIZEcode sc = sanitize_file_name(&sanitized, target,
693 (SANITIZE_ALLOW_PATH |
694 SANITIZE_ALLOW_RESERVED));
695 Curl_safefree(target);
697 return CURLE_URL_MALFORMAT;
700 #endif /* MSDOS || WIN32 */