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 "emul/charclass.h"
88#include "emul/fnmatch.h"
89
90#define	RANGE_MATCH	1
91#define	RANGE_NOMATCH	0
92#define	RANGE_ERROR	(-1)
93
94static int
95#ifdef __STDC__
96classmatch(const char *pattern, int test, int foldcase, const char **ep)
97#else
98classmatch(pattern, test, foldcase, ep)
99        const char *pattern;
100        int test;
101        int foldcase;
102        const char **ep;
103#endif
104{
105	const char * const mismatch = pattern;
106	const char *colon;
107	struct cclass *cc;
108	int rval = RANGE_NOMATCH;
109	size_t len;
110
111	if (pattern[0] != '[' || pattern[1] != ':') {
112		*ep = mismatch;
113		return RANGE_ERROR;
114	}
115	pattern += 2;
116
117	if ((colon = strchr(pattern, ':')) == NULL || colon[1] != ']') {
118		*ep = mismatch;
119		return RANGE_ERROR;
120	}
121	*ep = colon + 2;
122	len = (size_t)(colon - pattern);
123
124	if (foldcase && strncmp(pattern, "upper:]", 7) == 0)
125		pattern = "lower:]";
126	for (cc = cclasses; cc->name != NULL; cc++) {
127		if (!strncmp(pattern, cc->name, len) && cc->name[len] == '\0') {
128			if (cc->isctype((unsigned char)test))
129				rval = RANGE_MATCH;
130			break;
131		}
132	}
133	if (cc->name == NULL) {
134		/* invalid character class, treat as normal text */
135		*ep = mismatch;
136		rval = RANGE_ERROR;
137	}
138	return rval;
139}
140
141/* Most MBCS/collation/case issues handled here.  Wildcard '*' is not handled.
142 * EOS '\0' and the FNM_PATHNAME '/' delimiters are not advanced over,
143 * however the "\/" sequence is advanced to '/'.
144 *
145 * Both pattern and string are **char to support pointer increment of arbitrary
146 * multibyte characters for the given locale, in a later iteration of this code
147 */
148
149static int
150#ifdef __STDC__
151fnmatch_ch(const char **pattern, const char **string, int flags)
152#else
153fnmatch_ch(pattern, string, flags)
154    const char **pattern;
155    const char **string;
156    int flags;
157#endif
158{
159    const char * const mismatch = *pattern;
160    const int nocase = !!(flags & FNM_CASEFOLD);
161    const int escape = !(flags & FNM_NOESCAPE);
162    const int slash = !!(flags & FNM_PATHNAME);
163    int result = FNM_NOMATCH;
164    const char *startch;
165    int negate;
166
167    if (**pattern == '[')
168    {
169        ++*pattern;
170
171        /* Handle negation, either leading ! or ^ operators (never both) */
172        negate = ((**pattern == '!') || (**pattern == '^'));
173        if (negate)
174            ++*pattern;
175
176        /* ']' is an ordinary character at the start of the range pattern */
177        if (**pattern == ']')
178            goto leadingclosebrace;
179
180        while (**pattern)
181        {
182            if (**pattern == ']') {
183                ++*pattern;
184                /* XXX: Fix for MBCS character width */
185                ++*string;
186                return (result ^ negate);
187            }
188
189            if (escape && (**pattern == '\\')) {
190                ++*pattern;
191
192                /* Patterns must be terminated with ']', not EOS */
193                if (!**pattern)
194                    break;
195            }
196
197            /* Patterns must be terminated with ']' not '/' */
198            if (slash && (**pattern == '/'))
199                break;
200
201            /* Match character classes. */
202            if (classmatch(*pattern, **string, nocase, pattern)
203                == RANGE_MATCH) {
204                result = 0;
205                continue;
206            }
207
208leadingclosebrace:
209            /* Look at only well-formed range patterns;
210             * "x-]" is not allowed unless escaped ("x-\]")
211             * XXX: Fix for locale/MBCS character width
212             */
213            if (((*pattern)[1] == '-') && ((*pattern)[2] != ']'))
214            {
215                startch = *pattern;
216                *pattern += (escape && ((*pattern)[2] == '\\')) ? 3 : 2;
217
218                /* NOT a properly balanced [expr] pattern, EOS terminated
219                 * or ranges containing a slash in FNM_PATHNAME mode pattern
220                 * fall out to to the rewind and test '[' literal code path
221                 */
222                if (!**pattern || (slash && (**pattern == '/')))
223                    break;
224
225                /* XXX: handle locale/MBCS comparison, advance by MBCS char width */
226                if ((**string >= *startch) && (**string <= **pattern))
227                    result = 0;
228                else if (nocase && (isupper((unsigned char)**string) ||
229				    isupper((unsigned char)*startch) ||
230				    isupper((unsigned char)**pattern))
231                            && (tolower((unsigned char)**string) >= tolower((unsigned char)*startch))
232                            && (tolower((unsigned char)**string) <= tolower((unsigned char)**pattern)))
233                    result = 0;
234
235                ++*pattern;
236                continue;
237            }
238
239            /* XXX: handle locale/MBCS comparison, advance by MBCS char width */
240            if ((**string == **pattern))
241                result = 0;
242            else if (nocase && (isupper((unsigned char)**string) ||
243				isupper((unsigned char)**pattern))
244                            && (tolower((unsigned char)**string) == tolower((unsigned char)**pattern)))
245                result = 0;
246
247            ++*pattern;
248        }
249
250        /* NOT a properly balanced [expr] pattern; Rewind
251         * and reset result to test '[' literal
252         */
253        *pattern = mismatch;
254        result = FNM_NOMATCH;
255    }
256    else if (**pattern == '?') {
257        /* Optimize '?' match before unescaping **pattern */
258        if (!**string || (slash && (**string == '/')))
259            return FNM_NOMATCH;
260        result = 0;
261        goto fnmatch_ch_success;
262    }
263    else if (escape && (**pattern == '\\') && (*pattern)[1]) {
264        ++*pattern;
265    }
266
267    /* XXX: handle locale/MBCS comparison, advance by the MBCS char width */
268    if (**string == **pattern)
269        result = 0;
270    else if (nocase && (isupper((unsigned char)**string) || isupper((unsigned char)**pattern))
271                    && (tolower((unsigned char)**string) == tolower((unsigned char)**pattern)))
272        result = 0;
273
274    /* Refuse to advance over trailing slash or nulls
275     */
276    if (!**string || !**pattern || (slash && ((**string == '/') || (**pattern == '/'))))
277        return result;
278
279fnmatch_ch_success:
280    ++*pattern;
281    ++*string;
282    return result;
283}
284
285int
286#ifdef __STDC__
287fnmatch(const char *pattern, const char *string, int flags)
288#else
289fnmatch(pattern, string, flags)
290    const char *pattern;
291    const char *string;
292    int flags;
293#endif
294{
295    static const char dummystring[2] = {' ', 0};
296    const int escape = !(flags & FNM_NOESCAPE);
297    const int slash = !!(flags & FNM_PATHNAME);
298    const int leading_dir = !!(flags & FNM_LEADING_DIR);
299    const char *strendseg;
300    const char *dummyptr;
301    const char *matchptr;
302    int wild;
303    /* For '*' wild processing only; surpress 'used before initialization'
304     * warnings with dummy initialization values;
305     */
306    const char *strstartseg = NULL;
307    const char *mismatch = NULL;
308    int matchlen = 0;
309
310    if (strlen(pattern) > PATH_MAX || strlen(string) > PATH_MAX)
311	return FNM_NOMATCH;
312
313    if (*pattern == '*')
314        goto firstsegment;
315
316    while (*pattern && *string)
317    {
318        /* Pre-decode "\/" which has no special significance, and
319         * match balanced slashes, starting a new segment pattern
320         */
321        if (slash && escape && (*pattern == '\\') && (pattern[1] == '/'))
322            ++pattern;
323        if (slash && (*pattern == '/') && (*string == '/')) {
324            ++pattern;
325            ++string;
326        }
327
328firstsegment:
329        /* At the beginning of each segment, validate leading period behavior.
330         */
331        if ((flags & FNM_PERIOD) && (*string == '.'))
332        {
333            if (*pattern == '.')
334                ++pattern;
335            else if (escape && (*pattern == '\\') && (pattern[1] == '.'))
336                pattern += 2;
337            else
338                return FNM_NOMATCH;
339            ++string;
340        }
341
342        /* Determine the end of string segment
343         *
344         * Presumes '/' character is unique, not composite in any MBCS encoding
345         */
346        if (slash) {
347            strendseg = strchr(string, '/');
348            if (!strendseg)
349                strendseg = strchr(string, '\0');
350        }
351        else {
352            strendseg = strchr(string, '\0');
353        }
354
355        /* Allow pattern '*' to be consumed even with no remaining string to match
356         */
357        while (*pattern)
358        {
359            if ((string > strendseg)
360                || ((string == strendseg) && (*pattern != '*')))
361                break;
362
363            if (slash && ((*pattern == '/')
364                           || (escape && (*pattern == '\\')
365                                      && (pattern[1] == '/'))))
366                break;
367
368            /* Reduce groups of '*' and '?' to n '?' matches
369             * followed by one '*' test for simplicity
370             */
371            for (wild = 0; ((*pattern == '*') || (*pattern == '?')); ++pattern)
372            {
373                if (*pattern == '*') {
374                    wild = 1;
375                }
376                else if (string < strendseg) {  /* && (*pattern == '?') */
377                    /* XXX: Advance 1 char for MBCS locale */
378                    ++string;
379                }
380                else {  /* (string >= strendseg) && (*pattern == '?') */
381                    return FNM_NOMATCH;
382                }
383            }
384
385            if (wild)
386            {
387                strstartseg = string;
388                mismatch = pattern;
389
390                /* Count fixed (non '*') char matches remaining in pattern
391                 * excluding '/' (or "\/") and '*'
392                 */
393                for (matchptr = pattern, matchlen = 0; 1; ++matchlen)
394                {
395                    if ((*matchptr == '\0')
396                        || (slash && ((*matchptr == '/')
397                                      || (escape && (*matchptr == '\\')
398                                                 && (matchptr[1] == '/')))))
399                    {
400                        /* Compare precisely this many trailing string chars,
401                         * the resulting match needs no wildcard loop
402                         */
403                        /* XXX: Adjust for MBCS */
404                        if (string + matchlen > strendseg)
405                            return FNM_NOMATCH;
406
407                        string = strendseg - matchlen;
408                        wild = 0;
409                        break;
410                    }
411
412                    if (*matchptr == '*')
413                    {
414                        /* Ensure at least this many trailing string chars remain
415                         * for the first comparison
416                         */
417                        /* XXX: Adjust for MBCS */
418                        if (string + matchlen > strendseg)
419                            return FNM_NOMATCH;
420
421                        /* Begin first wild comparison at the current position */
422                        break;
423                    }
424
425                    /* Skip forward in pattern by a single character match
426                     * Use a dummy fnmatch_ch() test to count one "[range]" escape
427                     */
428                    /* XXX: Adjust for MBCS */
429                    if (escape && (*matchptr == '\\') && matchptr[1]) {
430                        matchptr += 2;
431                    }
432                    else if (*matchptr == '[') {
433                        dummyptr = dummystring;
434                        fnmatch_ch(&matchptr, &dummyptr, flags);
435                    }
436                    else {
437                        ++matchptr;
438                    }
439                }
440            }
441
442            /* Incrementally match string against the pattern
443             */
444            while (*pattern && (string < strendseg))
445            {
446                /* Success; begin a new wild pattern search
447                 */
448                if (*pattern == '*')
449                    break;
450
451                if (slash && ((*string == '/')
452                              || (*pattern == '/')
453                              || (escape && (*pattern == '\\')
454                                         && (pattern[1] == '/'))))
455                    break;
456
457                /* Compare ch's (the pattern is advanced over "\/" to the '/',
458                 * but slashes will mismatch, and are not consumed)
459                 */
460                if (!fnmatch_ch(&pattern, &string, flags))
461                    continue;
462
463                /* Failed to match, loop against next char offset of string segment
464                 * until not enough string chars remain to match the fixed pattern
465                 */
466                if (wild) {
467                    /* XXX: Advance 1 char for MBCS locale */
468                    string = ++strstartseg;
469                    if (string + matchlen > strendseg)
470                        return FNM_NOMATCH;
471
472                    pattern = mismatch;
473                    continue;
474                }
475                else
476                    return FNM_NOMATCH;
477            }
478        }
479
480        if (*string && !((slash || leading_dir) && (*string == '/')))
481            return FNM_NOMATCH;
482
483        if (*pattern && !(slash && ((*pattern == '/')
484                                    || (escape && (*pattern == '\\')
485                                               && (pattern[1] == '/')))))
486            return FNM_NOMATCH;
487
488        if (leading_dir && !*pattern && *string == '/')
489            return 0;
490    }
491
492    /* Where both pattern and string are at EOS, declare success
493     */
494    if (!*string && !*pattern)
495        return 0;
496
497    /* pattern didn't match to the end of string */
498    return FNM_NOMATCH;
499}
500