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 potential IPv6 literals. */
372 if(peek_ipv6(pattern, &skip)) {
373 memcpy(buf, pattern, skip);
381 if(*pattern == '}' || *pattern == ']')
382 return GLOBERROR("unmatched close brace/bracket", pos,
383 CURLE_URL_MALFORMAT);
385 /* only allow \ to escape known "special letters" */
386 if(*pattern == '\\' &&
387 (*(pattern + 1) == '{' || *(pattern + 1) == '[' ||
388 *(pattern + 1) == '}' || *(pattern + 1) == ']') ) {
390 /* escape character, skip '\' */
394 *buf++ = *pattern++; /* copy character to literal */
399 /* we got a literal string, add it as a single-item list */
401 res = glob_fixed(glob, glob->glob_buffer, sublen);
405 case '\0': /* done */
409 /* process set pattern */
412 res = glob_set(glob, &pattern, &pos, amount, globindex++);
416 /* process range pattern */
419 res = glob_range(glob, &pattern, &pos, amount, globindex++);
424 if(++glob->size >= GLOB_PATTERN_NUM)
425 return GLOBERROR("too many globs", pos, CURLE_URL_MALFORMAT);
430 CURLcode glob_url(URLGlob **glob, char *url, unsigned long *urlnum,
434 * We can deal with any-size, just make a buffer with the same length
435 * as the specified URL!
437 URLGlob *glob_expand;
438 unsigned long amount = 0;
444 glob_buffer = malloc(strlen(url) + 1);
446 return CURLE_OUT_OF_MEMORY;
449 glob_expand = calloc(1, sizeof(URLGlob));
451 Curl_safefree(glob_buffer);
452 return CURLE_OUT_OF_MEMORY;
454 glob_expand->urllen = strlen(url);
455 glob_expand->glob_buffer = glob_buffer;
457 res = glob_parse(glob_expand, url, 1, &amount);
461 if(error && glob_expand->error) {
464 if(glob_expand->pos) {
465 snprintf(text, sizeof(text), "%s in column %zu", glob_expand->error,
470 t = glob_expand->error;
472 /* send error description to the error-stream */
473 fprintf(error, "curl: (%d) [globbing] %s\n", res, t);
475 /* it failed, we cleanup */
476 glob_cleanup(glob_expand);
485 void glob_cleanup(URLGlob* glob)
490 for(i = 0; i < glob->size; i++) {
491 if((glob->pattern[i].type == UPTSet) &&
492 (glob->pattern[i].content.Set.elements)) {
493 for(elem = glob->pattern[i].content.Set.size - 1;
496 Curl_safefree(glob->pattern[i].content.Set.elements[elem]);
498 Curl_safefree(glob->pattern[i].content.Set.elements);
501 Curl_safefree(glob->glob_buffer);
505 CURLcode glob_next_url(char **globbed, URLGlob *glob)
510 size_t buflen = glob->urllen + 1;
511 char *buf = glob->glob_buffer;
520 /* implement a counter over the index ranges of all patterns, starting
521 with the rightmost pattern */
522 for(i = 0; carry && (i < glob->size); i++) {
524 pat = &glob->pattern[glob->size - 1 - i];
527 if((pat->content.Set.elements) &&
528 (++pat->content.Set.ptr_s == pat->content.Set.size)) {
529 pat->content.Set.ptr_s = 0;
534 pat->content.CharRange.ptr_c =
535 (char)(pat->content.CharRange.step +
536 (int)((unsigned char)pat->content.CharRange.ptr_c));
537 if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
538 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
543 pat->content.NumRange.ptr_n += pat->content.NumRange.step;
544 if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
545 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
550 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
551 return CURLE_FAILED_INIT;
554 if(carry) { /* first pattern ptr has run into overflow, done! */
555 /* TODO: verify if this should actally return CURLE_OK. */
556 return CURLE_OK; /* CURLE_OK to match previous behavior */
560 for(i = 0; i < glob->size; ++i) {
561 pat = &glob->pattern[i];
564 if(pat->content.Set.elements) {
565 snprintf(buf, buflen, "%s",
566 pat->content.Set.elements[pat->content.Set.ptr_s]);
574 *buf++ = pat->content.CharRange.ptr_c;
580 snprintf(buf, buflen, "%0*ld",
581 pat->content.NumRange.padlength,
582 pat->content.NumRange.ptr_n);
588 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
589 return CURLE_FAILED_INIT;
593 *globbed = strdup(glob->glob_buffer);
595 return CURLE_OUT_OF_MEMORY;
600 CURLcode glob_match_url(char **result, char *filename, URLGlob *glob)
605 char *appendthis = NULL;
606 size_t appendlen = 0;
607 size_t stringlen = 0;
611 /* We cannot use the glob_buffer for storage here since the filename may
612 * be longer than the URL we use. We allocate a good start size, then
613 * we need to realloc in case of need.
615 allocsize = strlen(filename) + 1; /* make it at least one byte to store the
617 target = malloc(allocsize);
619 return CURLE_OUT_OF_MEMORY;
622 if(*filename == '#' && ISDIGIT(filename[1])) {
624 char *ptr = filename;
625 unsigned long num = strtoul(&filename[1], &filename, 10);
626 URLPattern *pat = NULL;
628 if(num < glob->size) {
629 num--; /* make it zero based */
630 /* find the correct glob entry */
631 for(i = 0; i<glob->size; i++) {
632 if(glob->pattern[i].globindex == (int)num) {
633 pat = &glob->pattern[i];
642 if(pat->content.Set.elements) {
643 appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
645 strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
649 numbuf[0] = pat->content.CharRange.ptr_c;
655 snprintf(numbuf, sizeof(numbuf), "%0*lu",
656 pat->content.NumRange.padlength,
657 pat->content.NumRange.ptr_n);
659 appendlen = strlen(numbuf);
662 fprintf(stderr, "internal error: invalid pattern type (%d)\n",
664 Curl_safefree(target);
665 return CURLE_FAILED_INIT;
669 /* #[num] out of range, use the #[num] in the output */
671 appendthis = filename++;
676 appendthis = filename++;
679 if(appendlen + stringlen >= allocsize) {
681 /* we append a single byte to allow for the trailing byte to be appended
682 at the end of this function outside the while() loop */
683 allocsize = (appendlen + stringlen) * 2;
684 newstr = realloc(target, allocsize + 1);
686 Curl_safefree(target);
687 return CURLE_OUT_OF_MEMORY;
691 memcpy(&target[stringlen], appendthis, appendlen);
692 stringlen += appendlen;
694 target[stringlen]= '\0';
696 #if defined(MSDOS) || defined(WIN32)
699 SANITIZEcode sc = sanitize_file_name(&sanitized, target,
700 (SANITIZE_ALLOW_PATH |
701 SANITIZE_ALLOW_RESERVED));
702 Curl_safefree(target);
704 return CURLE_URL_MALFORMAT;
707 #endif /* MSDOS || WIN32 */