blob: 6b1ece008b35da069210b02c99f14d6bf336d83c [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
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.
13 *
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.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ***************************************************************************/
22#include "tool_setup.h"
23
24#define ENABLE_CURLX_PRINTF
25/* use our own printf() functions */
26#include "curlx.h"
27#include "tool_cfgable.h"
28#include "tool_doswin.h"
29#include "tool_urlglob.h"
30#include "tool_vms.h"
31
32#include "memdebug.h" /* keep this as LAST include */
33
34#define GLOBERROR(string, column, code) \
35 glob->error = string, glob->pos = column, code
36
37void glob_cleanup(URLGlob* glob);
38
39static CURLcode glob_fixed(URLGlob *glob, char *fixed, size_t len)
40{
41 URLPattern *pat = &glob->pattern[glob->size];
42 pat->type = UPTSet;
43 pat->content.Set.size = 1;
44 pat->content.Set.ptr_s = 0;
45 pat->globindex = -1;
46
47 pat->content.Set.elements = malloc(sizeof(char *));
48
49 if(!pat->content.Set.elements)
50 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
51
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);
55
56 memcpy(pat->content.Set.elements[0], fixed, len);
57 pat->content.Set.elements[0][len] = 0;
58
59 return CURLE_OK;
60}
61
62/* multiply
63 *
64 * Multiplies and checks for overflow.
65 */
66static int multiply(unsigned long *amount, long with)
67{
68 unsigned long sum = *amount * with;
69 if(!with) {
70 *amount = 0;
71 return 0;
72 }
73 if(sum/with != *amount)
74 return 1; /* didn't fit, bail out */
75 *amount = sum;
76 return 0;
77}
78
79static CURLcode glob_set(URLGlob *glob, char **patternp,
80 size_t *posp, unsigned long *amount,
81 int globindex)
82{
83 /* processes a set expression with the point behind the opening '{'
84 ','-separated elements are collected until the next closing '}'
85 */
86 URLPattern *pat;
87 bool done = FALSE;
88 char *buf = glob->glob_buffer;
89 char *pattern = *patternp;
90 char *opattern = pattern;
91 size_t opos = *posp-1;
92
93 pat = &glob->pattern[glob->size];
94 /* patterns 0,1,2,... correspond to size=1,3,5,... */
95 pat->type = UPTSet;
96 pat->content.Set.size = 0;
97 pat->content.Set.ptr_s = 0;
98 pat->content.Set.elements = NULL;
99 pat->globindex = globindex;
100
101 while(!done) {
102 switch (*pattern) {
103 case '\0': /* URL ended while set was still open */
104 return GLOBERROR("unmatched brace", opos, CURLE_URL_MALFORMAT);
105
106 case '{':
107 case '[': /* no nested expressions at this time */
108 return GLOBERROR("nested brace", *posp, CURLE_URL_MALFORMAT);
109
110 case '}': /* set element completed */
111 if(opattern == pattern)
112 return GLOBERROR("empty string within braces", *posp,
113 CURLE_URL_MALFORMAT);
114
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);
118
119 /* fall-through */
120 case ',':
121
122 *buf = '\0';
123 if(pat->content.Set.elements) {
124 char **new_arr = realloc(pat->content.Set.elements,
125 (pat->content.Set.size + 1) * sizeof(char *));
126 if(!new_arr)
127 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
128
129 pat->content.Set.elements = new_arr;
130 }
131 else
132 pat->content.Set.elements = malloc(sizeof(char *));
133
134 if(!pat->content.Set.elements)
135 return GLOBERROR("out of memory", 0, CURLE_OUT_OF_MEMORY);
136
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;
142
143 if(*pattern == '}') {
144 pattern++; /* pass the closing brace */
145 done = TRUE;
146 continue;
147 }
148
149 buf = glob->glob_buffer;
150 ++pattern;
151 ++(*posp);
152 break;
153
154 case ']': /* illegal closing bracket */
155 return GLOBERROR("unexpected close bracket", *posp, CURLE_URL_MALFORMAT);
156
157 case '\\': /* escaped character, skip '\' */
158 if(pattern[1]) {
159 ++pattern;
160 ++(*posp);
161 }
162 /* intentional fallthrough */
163 default:
164 *buf++ = *pattern++; /* copy character to set element */
165 ++(*posp);
166 }
167 }
168
169 *patternp = pattern; /* return with the new position */
170 return CURLE_OK;
171}
172
173static CURLcode glob_range(URLGlob *glob, char **patternp,
174 size_t *posp, unsigned long *amount,
175 int globindex)
176{
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 ']'
182 */
183 URLPattern *pat;
184 int rc;
185 char *pattern = *patternp;
186 char *c;
187
188 pat = &glob->pattern[glob->size];
189 pat->globindex = globindex;
190
191 if(ISALPHA(*pattern)) {
192 /* character range detected */
193 char min_c;
194 char max_c;
195 char end_c;
196 unsigned long step = 1;
197
198 pat->type = UPTCharRange;
199
200 rc = sscanf(pattern, "%c-%c%c", &min_c, &max_c, &end_c);
201
202 if(rc == 3) {
203 if(end_c == ':') {
204 char *endp;
205 errno = 0;
206 step = strtoul(&pattern[4], &endp, 10);
207 if(errno || &pattern[4] == endp || *endp != ']')
208 step = 0;
209 else
210 pattern = endp+1;
211 }
212 else if(end_c != ']')
213 /* then this is wrong */
214 rc = 0;
215 else
216 /* end_c == ']' */
217 pattern += 4;
218 }
219
220 *posp += (pattern - *patternp);
221
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);
228
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;
233
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);
238 }
239 else if(ISDIGIT(*pattern)) {
240 /* numeric range detected */
241 unsigned long min_n;
242 unsigned long max_n = 0;
243 unsigned long step_n = 0;
244 char *endp;
245
246 pat->type = UPTNumRange;
247 pat->content.NumRange.padlength = 0;
248
249 if(*pattern == '0') {
250 /* leading zero specified, count them! */
251 c = pattern;
252 while(ISDIGIT(*c)) {
253 c++;
254 ++pat->content.NumRange.padlength; /* padding length is set for all
255 instances of this pattern */
256 }
257 }
258
259 errno = 0;
260 min_n = strtoul(pattern, &endp, 10);
261 if(errno || (endp == pattern))
262 endp=NULL;
263 else {
264 if(*endp != '-')
265 endp = NULL;
266 else {
267 pattern = endp+1;
268 while(*pattern && ISBLANK(*pattern))
269 pattern++;
270 if(!ISDIGIT(*pattern)) {
271 endp = NULL;
272 goto fail;
273 }
274 errno = 0;
275 max_n = strtoul(pattern, &endp, 10);
276 if(errno || (*endp == ':')) {
277 pattern = endp+1;
278 errno = 0;
279 step_n = strtoul(pattern, &endp, 10);
280 if(errno)
281 /* over/underflow situation */
282 endp = NULL;
283 }
284 else
285 step_n = 1;
286 if(endp && (*endp == ']')) {
287 pattern= endp+1;
288 }
289 else
290 endp = NULL;
291 }
292 }
293
294 fail:
295 *posp += (pattern - *patternp);
296
297 if(!endp || !step_n ||
298 (min_n == max_n && step_n != 1) ||
299 (min_n != max_n && (min_n > max_n || step_n > (max_n - min_n))))
300 /* the pattern is not well-formed */
301 return GLOBERROR("bad range", *posp, CURLE_URL_MALFORMAT);
302
303 /* typecasting to ints are fine here since we make sure above that we
304 are within 31 bits */
305 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n = min_n;
306 pat->content.NumRange.max_n = max_n;
307 pat->content.NumRange.step = step_n;
308
309 if(multiply(amount, ((pat->content.NumRange.max_n -
310 pat->content.NumRange.min_n) /
311 pat->content.NumRange.step + 1)))
312 return GLOBERROR("range overflow", *posp, CURLE_URL_MALFORMAT);
313 }
314 else
315 return GLOBERROR("bad range specification", *posp, CURLE_URL_MALFORMAT);
316
317 *patternp = pattern;
318 return CURLE_OK;
319}
320
321static bool peek_ipv6(const char *str, size_t *skip)
322{
323 /*
324 * Scan for a potential IPv6 literal.
325 * - Valid globs contain a hyphen and <= 1 colon.
326 * - IPv6 literals contain no hyphens and >= 2 colons.
327 */
328 size_t i = 0;
329 size_t colons = 0;
330 if(str[i++] != '[') {
331 return FALSE;
332 }
333 for(;;) {
334 const char c = str[i++];
335 if(ISALNUM(c) || c == '.' || c == '%') {
336 /* ok */
337 }
338 else if(c == ':') {
339 colons++;
340 }
341 else if(c == ']') {
342 *skip = i;
343 return colons >= 2 ? TRUE : FALSE;
344 }
345 else {
346 return FALSE;
347 }
348 }
349}
350
351static CURLcode glob_parse(URLGlob *glob, char *pattern,
352 size_t pos, unsigned long *amount)
353{
354 /* processes a literal string component of a URL
355 special characters '{' and '[' branch to set/range processing functions
356 */
357 CURLcode res = CURLE_OK;
358 int globindex = 0; /* count "actual" globs */
359
360 *amount = 1;
361
362 while(*pattern && !res) {
363 char *buf = glob->glob_buffer;
364 size_t sublen = 0;
365 while(*pattern && *pattern != '{') {
366 if(*pattern == '[') {
367 /* Skip over potential IPv6 literals. */
368 size_t skip;
369 if(peek_ipv6(pattern, &skip)) {
370 memcpy(buf, pattern, skip);
371 buf += skip;
372 pattern += skip;
373 sublen += skip;
374 continue;
375 }
376 break;
377 }
378 if(*pattern == '}' || *pattern == ']')
379 return GLOBERROR("unmatched close brace/bracket", pos,
380 CURLE_URL_MALFORMAT);
381
382 /* only allow \ to escape known "special letters" */
383 if(*pattern == '\\' &&
384 (*(pattern+1) == '{' || *(pattern+1) == '[' ||
385 *(pattern+1) == '}' || *(pattern+1) == ']') ) {
386
387 /* escape character, skip '\' */
388 ++pattern;
389 ++pos;
390 }
391 *buf++ = *pattern++; /* copy character to literal */
392 ++pos;
393 sublen++;
394 }
395 if(sublen) {
396 /* we got a literal string, add it as a single-item list */
397 *buf = '\0';
398 res = glob_fixed(glob, glob->glob_buffer, sublen);
399 }
400 else {
401 switch (*pattern) {
402 case '\0': /* done */
403 break;
404
405 case '{':
406 /* process set pattern */
407 pattern++;
408 pos++;
409 res = glob_set(glob, &pattern, &pos, amount, globindex++);
410 break;
411
412 case '[':
413 /* process range pattern */
414 pattern++;
415 pos++;
416 res = glob_range(glob, &pattern, &pos, amount, globindex++);
417 break;
418 }
419 }
420
421 if(++glob->size >= GLOB_PATTERN_NUM)
422 return GLOBERROR("too many globs", pos, CURLE_URL_MALFORMAT);
423 }
424 return res;
425}
426
427CURLcode glob_url(URLGlob **glob, char *url, unsigned long *urlnum,
428 FILE *error)
429{
430 /*
431 * We can deal with any-size, just make a buffer with the same length
432 * as the specified URL!
433 */
434 URLGlob *glob_expand;
435 unsigned long amount = 0;
436 char *glob_buffer;
437 CURLcode res;
438
439 *glob = NULL;
440
441 glob_buffer = malloc(strlen(url) + 1);
442 if(!glob_buffer)
443 return CURLE_OUT_OF_MEMORY;
444 glob_buffer[0]=0;
445
446 glob_expand = calloc(1, sizeof(URLGlob));
447 if(!glob_expand) {
448 Curl_safefree(glob_buffer);
449 return CURLE_OUT_OF_MEMORY;
450 }
451 glob_expand->urllen = strlen(url);
452 glob_expand->glob_buffer = glob_buffer;
453
454 res = glob_parse(glob_expand, url, 1, &amount);
455 if(!res)
456 *urlnum = amount;
457 else {
458 if(error && glob_expand->error) {
459 char text[128];
460 const char *t;
461 if(glob_expand->pos) {
462 snprintf(text, sizeof(text), "%s in column %zu", glob_expand->error,
463 glob_expand->pos);
464 t = text;
465 }
466 else
467 t = glob_expand->error;
468
469 /* send error description to the error-stream */
470 fprintf(error, "curl: (%d) [globbing] %s\n", res, t);
471 }
472 /* it failed, we cleanup */
473 glob_cleanup(glob_expand);
474 *urlnum = 1;
475 return res;
476 }
477
478 *glob = glob_expand;
479 return CURLE_OK;
480}
481
482void glob_cleanup(URLGlob* glob)
483{
484 size_t i;
485 int elem;
486
487 for(i = 0; i < glob->size; i++) {
488 if((glob->pattern[i].type == UPTSet) &&
489 (glob->pattern[i].content.Set.elements)) {
490 for(elem = glob->pattern[i].content.Set.size - 1;
491 elem >= 0;
492 --elem) {
493 Curl_safefree(glob->pattern[i].content.Set.elements[elem]);
494 }
495 Curl_safefree(glob->pattern[i].content.Set.elements);
496 }
497 }
498 Curl_safefree(glob->glob_buffer);
499 Curl_safefree(glob);
500}
501
502CURLcode glob_next_url(char **globbed, URLGlob *glob)
503{
504 URLPattern *pat;
505 size_t i;
506 size_t len;
507 size_t buflen = glob->urllen + 1;
508 char *buf = glob->glob_buffer;
509
510 *globbed = NULL;
511
512 if(!glob->beenhere)
513 glob->beenhere = 1;
514 else {
515 bool carry = TRUE;
516
517 /* implement a counter over the index ranges of all patterns, starting
518 with the rightmost pattern */
519 for(i = 0; carry && (i < glob->size); i++) {
520 carry = FALSE;
521 pat = &glob->pattern[glob->size - 1 - i];
522 switch(pat->type) {
523 case UPTSet:
524 if((pat->content.Set.elements) &&
525 (++pat->content.Set.ptr_s == pat->content.Set.size)) {
526 pat->content.Set.ptr_s = 0;
527 carry = TRUE;
528 }
529 break;
530 case UPTCharRange:
531 pat->content.CharRange.ptr_c =
532 (char)(pat->content.CharRange.step +
533 (int)((unsigned char)pat->content.CharRange.ptr_c));
534 if(pat->content.CharRange.ptr_c > pat->content.CharRange.max_c) {
535 pat->content.CharRange.ptr_c = pat->content.CharRange.min_c;
536 carry = TRUE;
537 }
538 break;
539 case UPTNumRange:
540 pat->content.NumRange.ptr_n += pat->content.NumRange.step;
541 if(pat->content.NumRange.ptr_n > pat->content.NumRange.max_n) {
542 pat->content.NumRange.ptr_n = pat->content.NumRange.min_n;
543 carry = TRUE;
544 }
545 break;
546 default:
547 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
548 return CURLE_FAILED_INIT;
549 }
550 }
551 if(carry) { /* first pattern ptr has run into overflow, done! */
552 /* TODO: verify if this should actally return CURLE_OK. */
553 return CURLE_OK; /* CURLE_OK to match previous behavior */
554 }
555 }
556
557 for(i = 0; i < glob->size; ++i) {
558 pat = &glob->pattern[i];
559 switch(pat->type) {
560 case UPTSet:
561 if(pat->content.Set.elements) {
562 snprintf(buf, buflen, "%s",
563 pat->content.Set.elements[pat->content.Set.ptr_s]);
564 len = strlen(buf);
565 buf += len;
566 buflen -= len;
567 }
568 break;
569 case UPTCharRange:
570 if(buflen) {
571 *buf++ = pat->content.CharRange.ptr_c;
572 *buf = '\0';
573 buflen--;
574 }
575 break;
576 case UPTNumRange:
577 snprintf(buf, buflen, "%0*ld",
578 pat->content.NumRange.padlength,
579 pat->content.NumRange.ptr_n);
580 len = strlen(buf);
581 buf += len;
582 buflen -= len;
583 break;
584 default:
585 printf("internal error: invalid pattern type (%d)\n", (int)pat->type);
586 return CURLE_FAILED_INIT;
587 }
588 }
589
590 *globbed = strdup(glob->glob_buffer);
591 if(!*globbed)
592 return CURLE_OUT_OF_MEMORY;
593
594 return CURLE_OK;
595}
596
597CURLcode glob_match_url(char **result, char *filename, URLGlob *glob)
598{
599 char *target;
600 size_t allocsize;
601 char numbuf[18];
602 char *appendthis = NULL;
603 size_t appendlen = 0;
604 size_t stringlen = 0;
605
606 *result = NULL;
607
608 /* We cannot use the glob_buffer for storage here since the filename may
609 * be longer than the URL we use. We allocate a good start size, then
610 * we need to realloc in case of need.
611 */
612 allocsize = strlen(filename) + 1; /* make it at least one byte to store the
613 trailing zero */
614 target = malloc(allocsize);
615 if(!target)
616 return CURLE_OUT_OF_MEMORY;
617
618 while(*filename) {
619 if(*filename == '#' && ISDIGIT(filename[1])) {
620 unsigned long i;
621 char *ptr = filename;
622 unsigned long num = strtoul(&filename[1], &filename, 10);
623 URLPattern *pat =NULL;
624
625 if(num < glob->size) {
626 num--; /* make it zero based */
627 /* find the correct glob entry */
628 for(i=0; i<glob->size; i++) {
629 if(glob->pattern[i].globindex == (int)num) {
630 pat = &glob->pattern[i];
631 break;
632 }
633 }
634 }
635
636 if(pat) {
637 switch(pat->type) {
638 case UPTSet:
639 if(pat->content.Set.elements) {
640 appendthis = pat->content.Set.elements[pat->content.Set.ptr_s];
641 appendlen =
642 strlen(pat->content.Set.elements[pat->content.Set.ptr_s]);
643 }
644 break;
645 case UPTCharRange:
646 numbuf[0] = pat->content.CharRange.ptr_c;
647 numbuf[1] = 0;
648 appendthis = numbuf;
649 appendlen = 1;
650 break;
651 case UPTNumRange:
652 snprintf(numbuf, sizeof(numbuf), "%0*lu",
653 pat->content.NumRange.padlength,
654 pat->content.NumRange.ptr_n);
655 appendthis = numbuf;
656 appendlen = strlen(numbuf);
657 break;
658 default:
659 fprintf(stderr, "internal error: invalid pattern type (%d)\n",
660 (int)pat->type);
661 Curl_safefree(target);
662 return CURLE_FAILED_INIT;
663 }
664 }
665 else {
666 /* #[num] out of range, use the #[num] in the output */
667 filename = ptr;
668 appendthis = filename++;
669 appendlen = 1;
670 }
671 }
672 else {
673 appendthis = filename++;
674 appendlen = 1;
675 }
676 if(appendlen + stringlen >= allocsize) {
677 char *newstr;
678 /* we append a single byte to allow for the trailing byte to be appended
679 at the end of this function outside the while() loop */
680 allocsize = (appendlen + stringlen) * 2;
681 newstr = realloc(target, allocsize + 1);
682 if(!newstr) {
683 Curl_safefree(target);
684 return CURLE_OUT_OF_MEMORY;
685 }
686 target = newstr;
687 }
688 memcpy(&target[stringlen], appendthis, appendlen);
689 stringlen += appendlen;
690 }
691 target[stringlen]= '\0';
692
693#if defined(MSDOS) || defined(WIN32)
694 {
695 char *sanitized;
696 SANITIZEcode sc = sanitize_file_name(&sanitized, target,
697 (SANITIZE_ALLOW_PATH |
698 SANITIZE_ALLOW_RESERVED));
699 Curl_safefree(target);
700 if(sc)
701 return CURLE_URL_MALFORMAT;
702 target = sanitized;
703 }
704#endif /* MSDOS || WIN32 */
705
706 *result = target;
707 return CURLE_OK;
708}