Imported Upstream version 1.8.4p4
[debian/sudo] / compat / fnmatch.c
1 /*      $OpenBSD: fnmatch.c,v 1.15 2011/02/10 21:31:59 stsp Exp $       */
2
3 /* Copyright (c) 2011, VMware, Inc.
4  * All rights reserved.
5  * 
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *     * Redistributions of source code must retain the above copyright
9  *       notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above copyright
11  *       notice, this list of conditions and the following disclaimer in the
12  *       documentation and/or other materials provided with the distribution.
13  *     * Neither the name of the VMware, Inc. nor the names of its contributors
14  *       may be used to endorse or promote products derived from this software
15  *       without specific prior written permission.
16  * 
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 /* Authored by William A. Rowe Jr. <wrowe; apache.org, vmware.com>, April 2011
30  *
31  * Derived from The Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008
32  * as described in;
33  *   http://pubs.opengroup.org/onlinepubs/9699919799/functions/fnmatch.html
34  *
35  * Filename pattern matches defined in section 2.13, "Pattern Matching Notation"
36  * from chapter 2. "Shell Command Language"
37  *   http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13
38  * where; 1. A bracket expression starting with an unquoted <circumflex> '^' 
39  * character CONTINUES to specify a non-matching list; 2. an explicit <period> '.' 
40  * in a bracket expression matching list, e.g. "[.abc]" does NOT match a leading 
41  * <period> in a filename; 3. a <left-square-bracket> '[' which does not introduce
42  * a valid bracket expression is treated as an ordinary character; 4. a differing
43  * number of consecutive slashes within pattern and string will NOT match;
44  * 5. a trailing '\' in FNM_ESCAPE mode is treated as an ordinary '\' character.
45  *
46  * Bracket expansion defined in section 9.3.5, "RE Bracket Expression",
47  * from chapter 9, "Regular Expressions"
48  *   http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03_05
49  * with no support for collating symbols, equivalence class expressions or 
50  * character class expressions.  A partial range expression with a leading 
51  * hyphen following a valid range expression will match only the ordinary
52  * <hyphen> and the ending character (e.g. "[a-m-z]" will match characters 
53  * 'a' through 'm', a <hyphen> '-', or a 'z').
54  *
55  * Supports BSD extensions FNM_LEADING_DIR to match pattern to the end of one
56  * path segment of string, and FNM_CASEFOLD to ignore alpha case.
57  *
58  * NOTE: Only POSIX/C single byte locales are correctly supported at this time.
59  * Notably, non-POSIX locales with FNM_CASEFOLD produce undefined results,
60  * particularly in ranges of mixed case (e.g. "[A-z]") or spanning alpha and
61  * nonalpha characters within a range.
62  *
63  * XXX comments below indicate porting required for multi-byte character sets
64  * and non-POSIX locale collation orders; requires mbr* APIs to track shift
65  * state of pattern and string (rewinding pattern and string repeatedly).
66  *
67  * Certain parts of the code assume 0x00-0x3F are unique with any MBCS (e.g.
68  * UTF-8, SHIFT-JIS, etc).  Any implementation allowing '\' as an alternate
69  * path delimiter must be aware that 0x5C is NOT unique within SHIFT-JIS.
70  */
71
72 #include <config.h>
73
74 #include <sys/types.h>
75
76 #include <stdio.h>
77 #include <ctype.h>
78 #ifdef HAVE_STRING_H
79 # include <string.h>
80 #endif /* HAVE_STRING_H */
81 #ifdef HAVE_STRINGS_H
82 # include <strings.h>
83 #endif /* HAVE_STRINGS_H */
84 #include <limits.h>
85
86 #include "missing.h"
87 #include "compat/charclass.h"
88 #include "compat/fnmatch.h"
89
90 #define RANGE_MATCH     1
91 #define RANGE_NOMATCH   0
92 #define RANGE_ERROR     (-1)
93
94 static int
95 classmatch(const char *pattern, char test, int foldcase, const char **ep)
96 {
97         const char * const mismatch = pattern;
98         const char *colon;
99         struct cclass *cc;
100         int rval = RANGE_NOMATCH;
101         size_t len;
102
103         if (pattern[0] != '[' || pattern[1] != ':') {
104                 *ep = mismatch;
105                 return RANGE_ERROR;
106         }
107         pattern += 2;
108
109         if ((colon = strchr(pattern, ':')) == NULL || colon[1] != ']') {
110                 *ep = mismatch;
111                 return RANGE_ERROR;
112         }
113         *ep = colon + 2;
114         len = (size_t)(colon - pattern);
115
116         if (foldcase && strncmp(pattern, "upper:]", 7) == 0)
117                 pattern = "lower:]";
118         for (cc = cclasses; cc->name != NULL; cc++) {
119                 if (!strncmp(pattern, cc->name, len) && cc->name[len] == '\0') {
120                         if (cc->isctype((unsigned char)test))
121                                 rval = RANGE_MATCH;
122                         break;
123                 }
124         }
125         if (cc->name == NULL) {
126                 /* invalid character class, treat as normal text */
127                 *ep = mismatch;
128                 rval = RANGE_ERROR;
129         }
130         return rval;
131 }
132
133 /* Most MBCS/collation/case issues handled here.  Wildcard '*' is not handled.
134  * EOS '\0' and the FNM_PATHNAME '/' delimiters are not advanced over, 
135  * however the "\/" sequence is advanced to '/'.
136  *
137  * Both pattern and string are **char to support pointer increment of arbitrary
138  * multibyte characters for the given locale, in a later iteration of this code
139  */
140 static int fnmatch_ch(const char **pattern, const char **string, int flags)
141 {
142     const char * const mismatch = *pattern;
143     const int nocase = !!(flags & FNM_CASEFOLD);
144     const int escape = !(flags & FNM_NOESCAPE);
145     const int slash = !!(flags & FNM_PATHNAME);
146     int result = FNM_NOMATCH;
147     const char *startch;
148     int negate;
149
150     if (**pattern == '[')
151     {
152         ++*pattern;
153
154         /* Handle negation, either leading ! or ^ operators (never both) */
155         negate = ((**pattern == '!') || (**pattern == '^'));
156         if (negate)
157             ++*pattern;
158
159         /* ']' is an ordinary character at the start of the range pattern */
160         if (**pattern == ']')
161             goto leadingclosebrace;
162
163         while (**pattern)
164         {
165             if (**pattern == ']') {
166                 ++*pattern;
167                 /* XXX: Fix for MBCS character width */
168                 ++*string;
169                 return (result ^ negate);
170             }
171
172             if (escape && (**pattern == '\\')) {
173                 ++*pattern;
174
175                 /* Patterns must be terminated with ']', not EOS */
176                 if (!**pattern)
177                     break;
178             }
179
180             /* Patterns must be terminated with ']' not '/' */
181             if (slash && (**pattern == '/'))
182                 break;
183
184             /* Match character classes. */
185             if (classmatch(*pattern, **string, nocase, pattern)
186                 == RANGE_MATCH) {
187                 result = 0;
188                 continue;
189             }
190
191 leadingclosebrace:
192             /* Look at only well-formed range patterns; 
193              * "x-]" is not allowed unless escaped ("x-\]")
194              * XXX: Fix for locale/MBCS character width
195              */
196             if (((*pattern)[1] == '-') && ((*pattern)[2] != ']'))
197             {
198                 startch = *pattern;
199                 *pattern += (escape && ((*pattern)[2] == '\\')) ? 3 : 2;
200
201                 /* NOT a properly balanced [expr] pattern, EOS terminated 
202                  * or ranges containing a slash in FNM_PATHNAME mode pattern
203                  * fall out to to the rewind and test '[' literal code path
204                  */
205                 if (!**pattern || (slash && (**pattern == '/')))
206                     break;
207
208                 /* XXX: handle locale/MBCS comparison, advance by MBCS char width */
209                 if ((**string >= *startch) && (**string <= **pattern))
210                     result = 0;
211                 else if (nocase && (isupper(**string) || isupper(*startch)
212                                                       || isupper(**pattern))
213                             && (tolower(**string) >= tolower(*startch)) 
214                             && (tolower(**string) <= tolower(**pattern)))
215                     result = 0;
216
217                 ++*pattern;
218                 continue;
219             }
220
221             /* XXX: handle locale/MBCS comparison, advance by MBCS char width */
222             if ((**string == **pattern))
223                 result = 0;
224             else if (nocase && (isupper(**string) || isupper(**pattern))
225                             && (tolower(**string) == tolower(**pattern)))
226                 result = 0;
227
228             ++*pattern;
229         }
230
231         /* NOT a properly balanced [expr] pattern; Rewind
232          * and reset result to test '[' literal
233          */
234         *pattern = mismatch;
235         result = FNM_NOMATCH;
236     }
237     else if (**pattern == '?') {
238         /* Optimize '?' match before unescaping **pattern */
239         if (!**string || (slash && (**string == '/')))
240             return FNM_NOMATCH;
241         result = 0;
242         goto fnmatch_ch_success;
243     }
244     else if (escape && (**pattern == '\\') && (*pattern)[1]) {
245         ++*pattern;
246     }
247
248     /* XXX: handle locale/MBCS comparison, advance by the MBCS char width */
249     if (**string == **pattern)
250         result = 0;
251     else if (nocase && (isupper(**string) || isupper(**pattern))
252                     && (tolower(**string) == tolower(**pattern)))
253         result = 0;
254
255     /* Refuse to advance over trailing slash or nulls
256      */
257     if (!**string || !**pattern || (slash && ((**string == '/') || (**pattern == '/'))))
258         return result;
259
260 fnmatch_ch_success:
261     ++*pattern;
262     ++*string;
263     return result;
264 }
265
266 int rpl_fnmatch(const char *pattern, const char *string, int flags)
267 {
268     static const char dummystring[2] = {' ', 0};
269     const int escape = !(flags & FNM_NOESCAPE);
270     const int slash = !!(flags & FNM_PATHNAME);
271     const int leading_dir = !!(flags & FNM_LEADING_DIR);
272     const char *strendseg;
273     const char *dummyptr;
274     const char *matchptr;
275     int wild;
276     /* For '*' wild processing only; surpress 'used before initialization'
277      * warnings with dummy initialization values;
278      */
279     const char *strstartseg = NULL;
280     const char *mismatch = NULL;
281     int matchlen = 0;
282
283     if (strlen(pattern) > PATH_MAX || strlen(string) > PATH_MAX)
284         return FNM_NOMATCH;
285
286     if (*pattern == '*')
287         goto firstsegment;
288
289     while (*pattern && *string)
290     {
291         /* Pre-decode "\/" which has no special significance, and
292          * match balanced slashes, starting a new segment pattern
293          */
294         if (slash && escape && (*pattern == '\\') && (pattern[1] == '/'))
295             ++pattern;
296         if (slash && (*pattern == '/') && (*string == '/')) {
297             ++pattern;
298             ++string;
299         }            
300
301 firstsegment:
302         /* At the beginning of each segment, validate leading period behavior.
303          */
304         if ((flags & FNM_PERIOD) && (*string == '.'))
305         {
306             if (*pattern == '.')
307                 ++pattern;
308             else if (escape && (*pattern == '\\') && (pattern[1] == '.'))
309                 pattern += 2;
310             else
311                 return FNM_NOMATCH;
312             ++string;
313         }
314
315         /* Determine the end of string segment
316          *
317          * Presumes '/' character is unique, not composite in any MBCS encoding
318          */
319         if (slash) {
320             strendseg = strchr(string, '/');
321             if (!strendseg)
322                 strendseg = strchr(string, '\0');
323         }
324         else {
325             strendseg = strchr(string, '\0');
326         }
327
328         /* Allow pattern '*' to be consumed even with no remaining string to match
329          */
330         while (*pattern)
331         {
332             if ((string > strendseg)
333                 || ((string == strendseg) && (*pattern != '*')))
334                 break;
335
336             if (slash && ((*pattern == '/')
337                            || (escape && (*pattern == '\\')
338                                       && (pattern[1] == '/'))))
339                 break;
340
341             /* Reduce groups of '*' and '?' to n '?' matches
342              * followed by one '*' test for simplicity
343              */
344             for (wild = 0; ((*pattern == '*') || (*pattern == '?')); ++pattern)
345             {
346                 if (*pattern == '*') {
347                     wild = 1;
348                 }
349                 else if (string < strendseg) {  /* && (*pattern == '?') */
350                     /* XXX: Advance 1 char for MBCS locale */
351                     ++string;
352                 }
353                 else {  /* (string >= strendseg) && (*pattern == '?') */
354                     return FNM_NOMATCH;
355                 }
356             }
357
358             if (wild)
359             {
360                 strstartseg = string;
361                 mismatch = pattern;
362
363                 /* Count fixed (non '*') char matches remaining in pattern
364                  * excluding '/' (or "\/") and '*'
365                  */
366                 for (matchptr = pattern, matchlen = 0; 1; ++matchlen)
367                 {
368                     if ((*matchptr == '\0') 
369                         || (slash && ((*matchptr == '/')
370                                       || (escape && (*matchptr == '\\')
371                                                  && (matchptr[1] == '/')))))
372                     {
373                         /* Compare precisely this many trailing string chars,
374                          * the resulting match needs no wildcard loop
375                          */
376                         /* XXX: Adjust for MBCS */
377                         if (string + matchlen > strendseg)
378                             return FNM_NOMATCH;
379
380                         string = strendseg - matchlen;
381                         wild = 0;
382                         break;
383                     }
384
385                     if (*matchptr == '*')
386                     {
387                         /* Ensure at least this many trailing string chars remain
388                          * for the first comparison
389                          */
390                         /* XXX: Adjust for MBCS */
391                         if (string + matchlen > strendseg)
392                             return FNM_NOMATCH;
393
394                         /* Begin first wild comparison at the current position */
395                         break;
396                     }
397
398                     /* Skip forward in pattern by a single character match
399                      * Use a dummy fnmatch_ch() test to count one "[range]" escape
400                      */ 
401                     /* XXX: Adjust for MBCS */
402                     if (escape && (*matchptr == '\\') && matchptr[1]) {
403                         matchptr += 2;
404                     }
405                     else if (*matchptr == '[') {
406                         dummyptr = dummystring;
407                         fnmatch_ch(&matchptr, &dummyptr, flags);
408                     }
409                     else {
410                         ++matchptr;
411                     }
412                 }
413             }
414
415             /* Incrementally match string against the pattern
416              */
417             while (*pattern && (string < strendseg))
418             {
419                 /* Success; begin a new wild pattern search
420                  */
421                 if (*pattern == '*')
422                     break;
423
424                 if (slash && ((*string == '/')
425                               || (*pattern == '/')
426                               || (escape && (*pattern == '\\')
427                                          && (pattern[1] == '/'))))
428                     break;
429
430                 /* Compare ch's (the pattern is advanced over "\/" to the '/',
431                  * but slashes will mismatch, and are not consumed)
432                  */
433                 if (!fnmatch_ch(&pattern, &string, flags))
434                     continue;
435
436                 /* Failed to match, loop against next char offset of string segment 
437                  * until not enough string chars remain to match the fixed pattern
438                  */
439                 if (wild) {
440                     /* XXX: Advance 1 char for MBCS locale */
441                     string = ++strstartseg;
442                     if (string + matchlen > strendseg)
443                         return FNM_NOMATCH;
444
445                     pattern = mismatch;
446                     continue;
447                 }
448                 else
449                     return FNM_NOMATCH;
450             }
451         }
452
453         if (*string && !((slash || leading_dir) && (*string == '/')))
454             return FNM_NOMATCH;
455
456         if (*pattern && !(slash && ((*pattern == '/')
457                                     || (escape && (*pattern == '\\')
458                                                && (pattern[1] == '/')))))
459             return FNM_NOMATCH;
460
461         if (leading_dir && !*pattern && *string == '/')
462             return 0;
463     }
464
465     /* Where both pattern and string are at EOS, declare success
466      */
467     if (!*string && !*pattern)
468         return 0;
469
470     /* pattern didn't match to the end of string */
471     return FNM_NOMATCH;
472 }