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