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