1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2014, 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 http://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 _MPRINTF_REPLACE /* we want curl-functions instead of native ones */
25 #include <curl/mprintf.h>
27 #include "tool_urlglob.h"
30 #include "memdebug.h" /* keep this as LAST include */
34 GLOB_NO_MEM = CURLE_OUT_OF_MEMORY,
35 GLOB_ERROR = CURLE_URL_MALFORMAT
38 #define GLOBERROR(string, column, code) \
39 glob->error = string, glob->pos = column, code
41 void glob_cleanup(URLGlob* glob);
43 static GlobCode glob_fixed(URLGlob *glob, char *fixed, size_t len)
45 URLPattern *pat = &glob->pattern[glob->size];
47 pat->content.Set.size = 1;
48 pat->content.Set.ptr_s = 0;
51 pat->content.Set.elements = malloc(sizeof(char*));
53 if(!pat->content.Set.elements)
54 return GLOBERROR("out of memory", 0, GLOB_NO_MEM);
56 pat->content.Set.elements[0] = malloc(len+1);
57 if(!pat->content.Set.elements[0])
58 return GLOBERROR("out of memory", 0, GLOB_NO_MEM);
60 memcpy(pat->content.Set.elements[0], fixed, len);
61 pat->content.Set.elements[0][len] = 0;
68 * Multiplies and checks for overflow.
70 static int multiply(unsigned long *amount, long with)
72 unsigned long sum = *amount * with;
73 if(sum/with != *amount)
74 return 1; /* didn't fit, bail out */
79 static GlobCode 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, GLOB_ERROR);
107 case '[': /* no nested expressions at this time */
108 return GLOBERROR("nested brace", *posp, GLOB_ERROR);
110 case '}': /* set element completed */
111 if(opattern == pattern)
112 return GLOBERROR("empty string within braces", *posp, GLOB_ERROR);
114 /* add 1 to size since it'll be incremented below */
115 if(multiply(amount, pat->content.Set.size+1))
116 return GLOBERROR("range overflow", 0, GLOB_ERROR);
122 if(pat->content.Set.elements) {
123 char **new_arr = realloc(pat->content.Set.elements,
124 (pat->content.Set.size + 1) * sizeof(char*));
126 return GLOBERROR("out of memory", 0, GLOB_NO_MEM);
128 pat->content.Set.elements = new_arr;
131 pat->content.Set.elements = malloc(sizeof(char*));
133 if(!pat->content.Set.elements)
134 return GLOBERROR("out of memory", 0, GLOB_NO_MEM);
136 pat->content.Set.elements[pat->content.Set.size] =
137 strdup(glob->glob_buffer);
138 if(!pat->content.Set.elements[pat->content.Set.size])
139 return GLOBERROR("out of memory", 0, GLOB_NO_MEM);
140 ++pat->content.Set.size;
142 if(*pattern == '}') {
143 pattern++; /* pass the closing brace */
148 buf = glob->glob_buffer;
153 case ']': /* illegal closing bracket */
154 return GLOBERROR("unexpected close bracket", *posp, GLOB_ERROR);
156 case '\\': /* escaped character, skip '\' */
161 /* intentional fallthrough */
163 *buf++ = *pattern++; /* copy character to set element */
168 *patternp = pattern; /* return with the new position */
172 static GlobCode glob_range(URLGlob *glob, char **patternp,
173 size_t *posp, unsigned long *amount,
176 /* processes a range expression with the point behind the opening '['
177 - char range: e.g. "a-z]", "B-Q]"
178 - num range: e.g. "0-9]", "17-2000]"
179 - num range with leading zeros: e.g. "001-999]"
180 expression is checked for well-formedness and collected until the next ']'
184 char *pattern = *patternp;
187 pat = &glob->pattern[glob->size];
188 pat->globindex = globindex;
190 if(ISALPHA(*pattern)) {
191 /* character range detected */
196 pat->type = UPTCharRange;
198 rc = sscanf(pattern, "%c-%c", &min_c, &max_c);
200 if((rc == 2) && (pattern[3] == ':')) {
204 lstep = strtoul(&pattern[3], &endp, 10);
205 if(errno || (*endp != ']'))
210 if(step > (max_c - min_c))
217 *posp += (pattern - *patternp);
219 if((rc != 2) || (min_c >= max_c) || ((max_c - min_c) > ('z' - 'a')) ||
221 /* the pattern is not well-formed */
222 return GLOBERROR("bad range", *posp, GLOB_ERROR);
224 /* if there was a ":[num]" thing, use that as step or else use 1 */
225 pat->content.CharRange.step = step;
226 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c = min_c;
227 pat->content.CharRange.max_c = max_c;
229 if(multiply(amount, (pat->content.CharRange.max_c -
230 pat->content.CharRange.min_c + 1)))
231 return GLOBERROR("range overflow", *posp, GLOB_ERROR);
233 else if(ISDIGIT(*pattern)) {
234 /* numeric range detected */
236 unsigned long max_n = 0;
237 unsigned long step_n = 0;
240 pat->type = UPTNumRange;
241 pat->content.NumRange.padlength = 0;
243 if(*pattern == '0') {
244 /* leading zero specified, count them! */
248 ++pat->content.NumRange.padlength; /* padding length is set for all
249 instances of this pattern */
254 min_n = strtoul(pattern, &endp, 10);
255 if(errno || (endp == pattern))
263 max_n = strtoul(pattern, &endp, 10);
264 if(errno || (*endp == ':')) {
267 step_n = strtoul(pattern, &endp, 10);
269 /* over/underflow situation */
274 if(endp && (*endp == ']')) {
282 *posp += (pattern - *patternp);
284 if(!endp || (min_n > max_n) || (step_n > (max_n - min_n)))
285 /* the pattern is not well-formed */
286 return GLOBERROR("bad range", *posp, GLOB_ERROR);
288 /* typecasting to ints are fine here since we make sure above that we
289 are within 31 bits */
290 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n = min_n;
291 pat->content.NumRange.max_n = max_n;
292 pat->content.NumRange.step = step_n;
294 if(multiply(amount, (pat->content.NumRange.max_n -
295 pat->content.NumRange.min_n + 1)))
296 return GLOBERROR("range overflow", *posp, GLOB_ERROR);
299 return GLOBERROR("bad range specification", *posp, GLOB_ERROR);
305 static bool peek_ipv6(const char *str, size_t *skip)
308 * Scan for a potential IPv6 literal.
309 * - Valid globs contain a hyphen and <= 1 colon.
310 * - IPv6 literals contain no hyphens and >= 2 colons.
314 if(str[i++] != '[') {
318 const char c = str[i++];
319 if(ISALNUM(c) || c == '.' || c == '%') {
327 return colons >= 2 ? TRUE : FALSE;
335 static GlobCode glob_parse(URLGlob *glob, char *pattern,
336 size_t pos, unsigned long *amount)
338 /* processes a literal string component of a URL
339 special characters '{' and '[' branch to set/range processing functions
341 GlobCode res = GLOB_OK;
342 int globindex = 0; /* count "actual" globs */
346 while(*pattern && !res) {
347 char *buf = glob->glob_buffer;
349 while(*pattern && *pattern != '{') {
350 if(*pattern == '[') {
351 /* Skip over potential IPv6 literals. */
353 if(peek_ipv6(pattern, &skip)) {
354 memcpy(buf, pattern, skip);
362 if(*pattern == '}' || *pattern == ']')
363 return GLOBERROR("unmatched close brace/bracket", pos, GLOB_ERROR);
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, GLOB_ERROR);
410 int glob_url(URLGlob** glob, char* url, unsigned long *urlnum, FILE *error)
413 * We can deal with any-size, just make a buffer with the same length
414 * as the specified URL!
416 URLGlob *glob_expand;
417 unsigned long amount = 0;
423 glob_buffer = malloc(strlen(url) + 1);
425 return CURLE_OUT_OF_MEMORY;
427 glob_expand = calloc(1, sizeof(URLGlob));
429 Curl_safefree(glob_buffer);
430 return CURLE_OUT_OF_MEMORY;
432 glob_expand->urllen = strlen(url);
433 glob_expand->glob_buffer = glob_buffer;
435 res = glob_parse(glob_expand, url, 1, &amount);
439 if(error && glob_expand->error) {
442 if(glob_expand->pos) {
443 snprintf(text, sizeof(text), "%s in column %zu", glob_expand->error,
448 t = glob_expand->error;
450 /* send error description to the error-stream */
451 fprintf(error, "curl: (%d) [globbing] %s\n", res, t);
453 /* it failed, we cleanup */
454 glob_cleanup(glob_expand);
463 void glob_cleanup(URLGlob* glob)
468 /* the < condition is required since i underflows! */
469 for(i = glob->size - 1; 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 int glob_next_url(char **globbed, URLGlob *glob)
490 size_t buflen = glob->urllen + 1;
491 char *buf = glob->glob_buffer;
500 /* implement a counter over the index ranges of all patterns,
501 starting with the rightmost pattern */
502 /* the < condition is required since i underflows! */
503 for(i = glob->size - 1; carry && (i < glob->size); --i) {
505 pat = &glob->pattern[i];
508 if((pat->content.Set.elements) &&
509 (++pat->content.Set.ptr_s == pat->content.Set.size)) {
510 pat->content.Set.ptr_s = 0;
515 pat->content.CharRange.ptr_c = (char)(pat->content.CharRange.step +
516 (int)((unsigned char)pat->content.CharRange.ptr_c));
517 if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
518 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
523 pat->content.NumRange.ptr_n += pat->content.NumRange.step;
524 if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
525 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
530 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
531 return CURLE_FAILED_INIT;
534 if(carry) { /* first pattern ptr has run into overflow, done! */
535 /* TODO: verify if this should actally return CURLE_OK. */
536 return CURLE_OK; /* CURLE_OK to match previous behavior */
540 for(j = 0; j < glob->size; ++j) {
541 pat = &glob->pattern[j];
544 if(pat->content.Set.elements) {
545 len = strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
546 snprintf(buf, buflen, "%s",
547 pat->content.Set.elements[pat->content.Set.ptr_s]);
553 *buf++ = pat->content.CharRange.ptr_c;
556 len = snprintf(buf, buflen, "%0*ld",
557 pat->content.NumRange.padlength,
558 pat->content.NumRange.ptr_n);
563 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
564 return CURLE_FAILED_INIT;
569 *globbed = strdup(glob->glob_buffer);
571 return CURLE_OUT_OF_MEMORY;
576 int glob_match_url(char **result, char *filename, URLGlob *glob)
581 char *appendthis = NULL;
582 size_t appendlen = 0;
583 size_t stringlen = 0;
587 /* We cannot use the glob_buffer for storage here since the filename may
588 * be longer than the URL we use. We allocate a good start size, then
589 * we need to realloc in case of need.
591 allocsize = strlen(filename) + 1; /* make it at least one byte to store the
593 target = malloc(allocsize);
595 return CURLE_OUT_OF_MEMORY;
598 if(*filename == '#' && ISDIGIT(filename[1])) {
600 char *ptr = filename;
601 unsigned long num = strtoul(&filename[1], &filename, 10);
602 URLPattern *pat =NULL;
604 if(num < glob->size) {
605 num--; /* make it zero based */
606 /* find the correct glob entry */
607 for(i=0; i<glob->size; i++) {
608 if(glob->pattern[i].globindex == (int)num) {
609 pat = &glob->pattern[i];
618 if(pat->content.Set.elements) {
619 appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
621 strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
625 numbuf[0] = pat->content.CharRange.ptr_c;
631 snprintf(numbuf, sizeof(numbuf), "%0*d",
632 pat->content.NumRange.padlength,
633 pat->content.NumRange.ptr_n);
635 appendlen = strlen(numbuf);
638 fprintf(stderr, "internal error: invalid pattern type (%d)\n",
640 Curl_safefree(target);
641 return CURLE_FAILED_INIT;
645 /* #[num] out of range, use the #[num] in the output */
647 appendthis = filename++;
652 appendthis = filename++;
655 if(appendlen + stringlen >= allocsize) {
657 /* we append a single byte to allow for the trailing byte to be appended
658 at the end of this function outside the while() loop */
659 allocsize = (appendlen + stringlen) * 2;
660 newstr = realloc(target, allocsize + 1);
662 Curl_safefree(target);
663 return CURLE_OUT_OF_MEMORY;
667 memcpy(&target[stringlen], appendthis, appendlen);
668 stringlen += appendlen;
670 target[stringlen]= '\0';