xref: /freebsd/lib/libc/gen/fnmatch.c (revision 5ca34122ecdd5abc62bdae39663fec9ac8523d87)
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Guido van Rossum.
7  *
8  * Copyright (c) 2011 The FreeBSD Foundation
9  * All rights reserved.
10  * Portions of this software were developed by David Chisnall
11  * under sponsorship from the FreeBSD Foundation.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)fnmatch.c	8.2 (Berkeley) 4/16/94";
40 #endif /* LIBC_SCCS and not lint */
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 /*
45  * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6.
46  * Compares a filename or pathname to a pattern.
47  */
48 
49 /*
50  * Some notes on multibyte character support:
51  * 1. Patterns with illegal byte sequences match nothing.
52  * 2. Illegal byte sequences in the "string" argument are handled by treating
53  *    them as single-byte characters with a value of the first byte of the
54  *    sequence cast to wchar_t.
55  * 3. Multibyte conversion state objects (mbstate_t) are passed around and
56  *    used for most, but not all, conversions. Further work will be required
57  *    to support state-dependent encodings.
58  */
59 
60 #include <fnmatch.h>
61 #include <limits.h>
62 #include <string.h>
63 #include <wchar.h>
64 #include <wctype.h>
65 
66 #include "collate.h"
67 
68 #define	EOS	'\0'
69 
70 #define RANGE_MATCH     1
71 #define RANGE_NOMATCH   0
72 #define RANGE_ERROR     (-1)
73 
74 static int rangematch(const char *, wchar_t, int, char **, mbstate_t *);
75 static int fnmatch1(const char *, const char *, const char *, int, mbstate_t,
76 		mbstate_t);
77 
78 int
79 fnmatch(const char *pattern, const char *string, int flags)
80 {
81 	static const mbstate_t initial;
82 
83 	return (fnmatch1(pattern, string, string, flags, initial, initial));
84 }
85 
86 static int
87 fnmatch1(const char *pattern, const char *string, const char *stringstart,
88     int flags, mbstate_t patmbs, mbstate_t strmbs)
89 {
90 	char *newp;
91 	char c;
92 	wchar_t pc, sc;
93 	size_t pclen, sclen;
94 
95 	for (;;) {
96 		pclen = mbrtowc(&pc, pattern, MB_LEN_MAX, &patmbs);
97 		if (pclen == (size_t)-1 || pclen == (size_t)-2)
98 			return (FNM_NOMATCH);
99 		pattern += pclen;
100 		sclen = mbrtowc(&sc, string, MB_LEN_MAX, &strmbs);
101 		if (sclen == (size_t)-1 || sclen == (size_t)-2) {
102 			sc = (unsigned char)*string;
103 			sclen = 1;
104 			memset(&strmbs, 0, sizeof(strmbs));
105 		}
106 		switch (pc) {
107 		case EOS:
108 			if ((flags & FNM_LEADING_DIR) && sc == '/')
109 				return (0);
110 			return (sc == EOS ? 0 : FNM_NOMATCH);
111 		case '?':
112 			if (sc == EOS)
113 				return (FNM_NOMATCH);
114 			if (sc == '/' && (flags & FNM_PATHNAME))
115 				return (FNM_NOMATCH);
116 			if (sc == '.' && (flags & FNM_PERIOD) &&
117 			    (string == stringstart ||
118 			    ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
119 				return (FNM_NOMATCH);
120 			string += sclen;
121 			break;
122 		case '*':
123 			c = *pattern;
124 			/* Collapse multiple stars. */
125 			while (c == '*')
126 				c = *++pattern;
127 
128 			if (sc == '.' && (flags & FNM_PERIOD) &&
129 			    (string == stringstart ||
130 			    ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
131 				return (FNM_NOMATCH);
132 
133 			/* Optimize for pattern with * at end or before /. */
134 			if (c == EOS)
135 				if (flags & FNM_PATHNAME)
136 					return ((flags & FNM_LEADING_DIR) ||
137 					    strchr(string, '/') == NULL ?
138 					    0 : FNM_NOMATCH);
139 				else
140 					return (0);
141 			else if (c == '/' && flags & FNM_PATHNAME) {
142 				if ((string = strchr(string, '/')) == NULL)
143 					return (FNM_NOMATCH);
144 				break;
145 			}
146 
147 			/* General case, use recursion. */
148 			while (sc != EOS) {
149 				if (!fnmatch1(pattern, string, stringstart,
150 				    flags, patmbs, strmbs))
151 					return (0);
152 				sclen = mbrtowc(&sc, string, MB_LEN_MAX,
153 				    &strmbs);
154 				if (sclen == (size_t)-1 ||
155 				    sclen == (size_t)-2) {
156 					sc = (unsigned char)*string;
157 					sclen = 1;
158 					memset(&strmbs, 0, sizeof(strmbs));
159 				}
160 				if (sc == '/' && flags & FNM_PATHNAME)
161 					break;
162 				string += sclen;
163 			}
164 			return (FNM_NOMATCH);
165 		case '[':
166 			if (sc == EOS)
167 				return (FNM_NOMATCH);
168 			if (sc == '/' && (flags & FNM_PATHNAME))
169 				return (FNM_NOMATCH);
170 			if (sc == '.' && (flags & FNM_PERIOD) &&
171 			    (string == stringstart ||
172 			    ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
173 				return (FNM_NOMATCH);
174 
175 			switch (rangematch(pattern, sc, flags, &newp,
176 			    &patmbs)) {
177 			case RANGE_ERROR:
178 				goto norm;
179 			case RANGE_MATCH:
180 				pattern = newp;
181 				break;
182 			case RANGE_NOMATCH:
183 				return (FNM_NOMATCH);
184 			}
185 			string += sclen;
186 			break;
187 		case '\\':
188 			if (!(flags & FNM_NOESCAPE)) {
189 				pclen = mbrtowc(&pc, pattern, MB_LEN_MAX,
190 				    &patmbs);
191 				if (pclen == (size_t)-1 || pclen == (size_t)-2)
192 					return (FNM_NOMATCH);
193 				pattern += pclen;
194 			}
195 			/* FALLTHROUGH */
196 		default:
197 		norm:
198 			if (pc == sc)
199 				;
200 			else if ((flags & FNM_CASEFOLD) &&
201 				 (towlower(pc) == towlower(sc)))
202 				;
203 			else
204 				return (FNM_NOMATCH);
205 			string += sclen;
206 			break;
207 		}
208 	}
209 	/* NOTREACHED */
210 }
211 
212 static int
213 rangematch(const char *pattern, wchar_t test, int flags, char **newp,
214     mbstate_t *patmbs)
215 {
216 	int negate, ok;
217 	wchar_t c, c2;
218 	size_t pclen;
219 	const char *origpat;
220 	struct xlocale_collate *table =
221 		(struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
222 
223 	/*
224 	 * A bracket expression starting with an unquoted circumflex
225 	 * character produces unspecified results (IEEE 1003.2-1992,
226 	 * 3.13.2).  This implementation treats it like '!', for
227 	 * consistency with the regular expression syntax.
228 	 * J.T. Conklin (conklin@ngai.kaleida.com)
229 	 */
230 	if ( (negate = (*pattern == '!' || *pattern == '^')) )
231 		++pattern;
232 
233 	if (flags & FNM_CASEFOLD)
234 		test = towlower(test);
235 
236 	/*
237 	 * A right bracket shall lose its special meaning and represent
238 	 * itself in a bracket expression if it occurs first in the list.
239 	 * -- POSIX.2 2.8.3.2
240 	 */
241 	ok = 0;
242 	origpat = pattern;
243 	for (;;) {
244 		if (*pattern == ']' && pattern > origpat) {
245 			pattern++;
246 			break;
247 		} else if (*pattern == '\0') {
248 			return (RANGE_ERROR);
249 		} else if (*pattern == '/' && (flags & FNM_PATHNAME)) {
250 			return (RANGE_NOMATCH);
251 		} else if (*pattern == '\\' && !(flags & FNM_NOESCAPE))
252 			pattern++;
253 		pclen = mbrtowc(&c, pattern, MB_LEN_MAX, patmbs);
254 		if (pclen == (size_t)-1 || pclen == (size_t)-2)
255 			return (RANGE_NOMATCH);
256 		pattern += pclen;
257 
258 		if (flags & FNM_CASEFOLD)
259 			c = towlower(c);
260 
261 		if (*pattern == '-' && *(pattern + 1) != EOS &&
262 		    *(pattern + 1) != ']') {
263 			if (*++pattern == '\\' && !(flags & FNM_NOESCAPE))
264 				if (*pattern != EOS)
265 					pattern++;
266 			pclen = mbrtowc(&c2, pattern, MB_LEN_MAX, patmbs);
267 			if (pclen == (size_t)-1 || pclen == (size_t)-2)
268 				return (RANGE_NOMATCH);
269 			pattern += pclen;
270 			if (c2 == EOS)
271 				return (RANGE_ERROR);
272 
273 			if (flags & FNM_CASEFOLD)
274 				c2 = towlower(c2);
275 
276 			if (table->__collate_load_error ?
277 			    c <= test && test <= c2 :
278 			       __collate_range_cmp(table, c, test) <= 0
279 			    && __collate_range_cmp(table, test, c2) <= 0
280 			   )
281 				ok = 1;
282 		} else if (c == test)
283 			ok = 1;
284 	}
285 
286 	*newp = (char *)pattern;
287 	return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH);
288 }
289