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 */
193 pat->type = UPTCharRange;
195 rc = sscanf(pattern, "%c-%c", &min_c, &max_c);
197 if((rc == 2) && (pattern[3] == ':')) {
201 lstep = strtoul(&pattern[4], &endp, 10);
202 if(errno || (*endp != ']'))
207 if(step > (max_c - min_c))
214 *posp += (pattern - *patternp);
216 if((rc != 2) || (min_c >= max_c) || ((max_c - min_c) > ('z' - 'a')) ||
218 /* the pattern is not well-formed */
219 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
221 /* if there was a ":[num]" thing, use that as step or else use 1 */
222 pat->content.CharRange.step = step;
223 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c = min_c;
224 pat->content.CharRange.max_c = max_c;
226 if(multiply(amount, (pat->content.CharRange.max_c -
227 pat->content.CharRange.min_c) /
228 pat->content.CharRange.step + 1) )
229 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
231 else if(ISDIGIT(*pattern)) {
232 /* numeric range detected */
234 unsigned long max_n = 0;
235 unsigned long step_n = 0;
238 pat->type = UPTNumRange;
239 pat->content.NumRange.padlength = 0;
241 if(*pattern == '0') {
242 /* leading zero specified, count them! */
246 ++pat->content.NumRange.padlength; /* padding length is set for all
247 instances of this pattern */
252 min_n = strtoul(pattern, &endp, 10);
253 if(errno || (endp == pattern))
261 max_n = strtoul(pattern, &endp, 10);
262 if(errno || (*endp == ':')) {
265 step_n = strtoul(pattern, &endp, 10);
267 /* over/underflow situation */
272 if(endp && (*endp == ']')) {
280 *posp += (pattern - *patternp);
282 if(!endp || (min_n > max_n) || (step_n > (max_n - min_n)) || !step_n)
283 /* the pattern is not well-formed */
284 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
286 /* typecasting to ints are fine here since we make sure above that we
287 are within 31 bits */
288 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n = min_n;
289 pat->content.NumRange.max_n = max_n;
290 pat->content.NumRange.step = step_n;
292 if(multiply(amount, (pat->content.NumRange.max_n -
293 pat->content.NumRange.min_n) /
294 pat->content.NumRange.step + 1) )
295 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
298 return GLOBERROR("bad range specification", *posp, CURLE_URL_MALFORMAT);
304 static bool peek_ipv6(const char *str, size_t *skip)
307 * Scan for a potential IPv6 literal.
308 * - Valid globs contain a hyphen and <= 1 colon.
309 * - IPv6 literals contain no hyphens and >= 2 colons.
313 if(str[i++] != '[') {
317 const char c = str[i++];
318 if(ISALNUM(c) || c == '.' || c == '%') {
326 return colons >= 2 ? TRUE : FALSE;
334 static CURLcode glob_parse(URLGlob *glob, char *pattern,
335 size_t pos, unsigned long *amount)
337 /* processes a literal string component of a URL
338 special characters '{' and '[' branch to set/range processing functions
340 CURLcode res = CURLE_OK;
341 int globindex = 0; /* count "actual" globs */
345 while(*pattern && !res) {
346 char *buf = glob->glob_buffer;
348 while(*pattern && *pattern != '{') {
349 if(*pattern == '[') {
350 /* Skip over potential IPv6 literals. */
352 if(peek_ipv6(pattern, &skip)) {
353 memcpy(buf, pattern, skip);
361 if(*pattern == '}' || *pattern == ']')
362 return GLOBERROR("unmatched close brace/bracket", pos,
363 CURLE_URL_MALFORMAT);
365 /* only allow \ to escape known "special letters" */
366 if(*pattern == '\\' &&
367 (*(pattern+1) == '{' || *(pattern+1) == '[' ||
368 *(pattern+1) == '}' || *(pattern+1) == ']') ) {
370 /* escape character, skip '\' */
374 *buf++ = *pattern++; /* copy character to literal */
379 /* we got a literal string, add it as a single-item list */
381 res = glob_fixed(glob, glob->glob_buffer, sublen);
385 case '\0': /* done */
389 /* process set pattern */
392 res = glob_set(glob, &pattern, &pos, amount, globindex++);
396 /* process range pattern */
399 res = glob_range(glob, &pattern, &pos, amount, globindex++);
404 if(++glob->size >= GLOB_PATTERN_NUM)
405 return GLOBERROR("too many globs", pos, CURLE_URL_MALFORMAT);
410 CURLcode glob_url(URLGlob** glob, char* url, unsigned long *urlnum,
414 * We can deal with any-size, just make a buffer with the same length
415 * as the specified URL!
417 URLGlob *glob_expand;
418 unsigned long amount = 0;
424 glob_buffer = malloc(strlen(url) + 1);
426 return CURLE_OUT_OF_MEMORY;
428 glob_expand = calloc(1, sizeof(URLGlob));
430 Curl_safefree(glob_buffer);
431 return CURLE_OUT_OF_MEMORY;
433 glob_expand->urllen = strlen(url);
434 glob_expand->glob_buffer = glob_buffer;
436 res = glob_parse(glob_expand, url, 1, &amount);
440 if(error && glob_expand->error) {
443 if(glob_expand->pos) {
444 snprintf(text, sizeof(text), "%s in column %zu", glob_expand->error,
449 t = glob_expand->error;
451 /* send error description to the error-stream */
452 fprintf(error, "curl: (%d) [globbing] %s\n", res, t);
454 /* it failed, we cleanup */
455 glob_cleanup(glob_expand);
464 void glob_cleanup(URLGlob* glob)
469 for(i = 0; i < glob->size; i++) {
470 if((glob->pattern[i].type == UPTSet) &&
471 (glob->pattern[i].content.Set.elements)) {
472 for(elem = glob->pattern[i].content.Set.size - 1;
475 Curl_safefree(glob->pattern[i].content.Set.elements[elem]);
477 Curl_safefree(glob->pattern[i].content.Set.elements);
480 Curl_safefree(glob->glob_buffer);
484 CURLcode glob_next_url(char **globbed, URLGlob *glob)
489 size_t buflen = glob->urllen + 1;
490 char *buf = glob->glob_buffer;
499 /* implement a counter over the index ranges of all patterns, starting
500 with the rightmost pattern */
501 for(i = 0; carry && (i < glob->size); i++) {
503 pat = &glob->pattern[glob->size - 1 - i];
506 if((pat->content.Set.elements) &&
507 (++pat->content.Set.ptr_s == pat->content.Set.size)) {
508 pat->content.Set.ptr_s = 0;
513 pat->content.CharRange.ptr_c =
514 (char)(pat->content.CharRange.step +
515 (int)((unsigned char)pat->content.CharRange.ptr_c));
516 if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
517 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
522 pat->content.NumRange.ptr_n += pat->content.NumRange.step;
523 if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
524 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
529 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
530 return CURLE_FAILED_INIT;
533 if(carry) { /* first pattern ptr has run into overflow, done! */
534 /* TODO: verify if this should actally return CURLE_OK. */
535 return CURLE_OK; /* CURLE_OK to match previous behavior */
539 for(i = 0; i < glob->size; ++i) {
540 pat = &glob->pattern[i];
543 if(pat->content.Set.elements) {
544 len = strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
545 snprintf(buf, buflen, "%s",
546 pat->content.Set.elements[pat->content.Set.ptr_s]);
552 *buf++ = pat->content.CharRange.ptr_c;
555 len = snprintf(buf, buflen, "%0*ld",
556 pat->content.NumRange.padlength,
557 pat->content.NumRange.ptr_n);
562 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
563 return CURLE_FAILED_INIT;
568 *globbed = strdup(glob->glob_buffer);
570 return CURLE_OUT_OF_MEMORY;
575 CURLcode glob_match_url(char **result, char *filename, URLGlob *glob)
580 char *appendthis = NULL;
581 size_t appendlen = 0;
582 size_t stringlen = 0;
586 /* We cannot use the glob_buffer for storage here since the filename may
587 * be longer than the URL we use. We allocate a good start size, then
588 * we need to realloc in case of need.
590 allocsize = strlen(filename) + 1; /* make it at least one byte to store the
592 target = malloc(allocsize);
594 return CURLE_OUT_OF_MEMORY;
597 if(*filename == '#' && ISDIGIT(filename[1])) {
599 char *ptr = filename;
600 unsigned long num = strtoul(&filename[1], &filename, 10);
601 URLPattern *pat =NULL;
603 if(num < glob->size) {
604 num--; /* make it zero based */
605 /* find the correct glob entry */
606 for(i=0; i<glob->size; i++) {
607 if(glob->pattern[i].globindex == (int)num) {
608 pat = &glob->pattern[i];
617 if(pat->content.Set.elements) {
618 appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
620 strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
624 numbuf[0] = pat->content.CharRange.ptr_c;
630 snprintf(numbuf, sizeof(numbuf), "%0*d",
631 pat->content.NumRange.padlength,
632 pat->content.NumRange.ptr_n);
634 appendlen = strlen(numbuf);
637 fprintf(stderr, "internal error: invalid pattern type (%d)\n",
639 Curl_safefree(target);
640 return CURLE_FAILED_INIT;
644 /* #[num] out of range, use the #[num] in the output */
646 appendthis = filename++;
651 appendthis = filename++;
654 if(appendlen + stringlen >= allocsize) {
656 /* we append a single byte to allow for the trailing byte to be appended
657 at the end of this function outside the while() loop */
658 allocsize = (appendlen + stringlen) * 2;
659 newstr = realloc(target, allocsize + 1);
661 Curl_safefree(target);
662 return CURLE_OUT_OF_MEMORY;
666 memcpy(&target[stringlen], appendthis, appendlen);
667 stringlen += appendlen;
669 target[stringlen]= '\0';
671 #if defined(MSDOS) || defined(WIN32)
674 SANITIZEcode sc = sanitize_file_name(&sanitized, target,
675 (SANITIZE_ALLOW_PATH |
676 SANITIZE_ALLOW_RESERVED));
677 Curl_safefree(target);
679 return CURLE_URL_MALFORMAT;
682 #endif /* MSDOS || WIN32 */