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