xref: /freebsd/lib/libc/gen/fnmatch.c (revision 273c26a3c3bea87a241d6879abd4f991db180bf0)
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 	const char *bt_pattern, *bt_string;
91 	mbstate_t bt_patmbs, bt_strmbs;
92 	char *newp;
93 	char c;
94 	wchar_t pc, sc;
95 	size_t pclen, sclen;
96 
97 	bt_pattern = bt_string = NULL;
98 	for (;;) {
99 		pclen = mbrtowc(&pc, pattern, MB_LEN_MAX, &patmbs);
100 		if (pclen == (size_t)-1 || pclen == (size_t)-2)
101 			return (FNM_NOMATCH);
102 		pattern += pclen;
103 		sclen = mbrtowc(&sc, string, MB_LEN_MAX, &strmbs);
104 		if (sclen == (size_t)-1 || sclen == (size_t)-2) {
105 			sc = (unsigned char)*string;
106 			sclen = 1;
107 			memset(&strmbs, 0, sizeof(strmbs));
108 		}
109 		switch (pc) {
110 		case EOS:
111 			if ((flags & FNM_LEADING_DIR) && sc == '/')
112 				return (0);
113 			if (sc == EOS)
114 				return (0);
115 			goto backtrack;
116 		case '?':
117 			if (sc == EOS)
118 				return (FNM_NOMATCH);
119 			if (sc == '/' && (flags & FNM_PATHNAME))
120 				goto backtrack;
121 			if (sc == '.' && (flags & FNM_PERIOD) &&
122 			    (string == stringstart ||
123 			    ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
124 				goto backtrack;
125 			string += sclen;
126 			break;
127 		case '*':
128 			c = *pattern;
129 			/* Collapse multiple stars. */
130 			while (c == '*')
131 				c = *++pattern;
132 
133 			if (sc == '.' && (flags & FNM_PERIOD) &&
134 			    (string == stringstart ||
135 			    ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
136 				goto backtrack;
137 
138 			/* Optimize for pattern with * at end or before /. */
139 			if (c == EOS)
140 				if (flags & FNM_PATHNAME)
141 					return ((flags & FNM_LEADING_DIR) ||
142 					    strchr(string, '/') == NULL ?
143 					    0 : FNM_NOMATCH);
144 				else
145 					return (0);
146 			else if (c == '/' && flags & FNM_PATHNAME) {
147 				if ((string = strchr(string, '/')) == NULL)
148 					return (FNM_NOMATCH);
149 				break;
150 			}
151 
152 			/*
153 			 * First try the shortest match for the '*' that
154 			 * could work. We can forget any earlier '*' since
155 			 * there is no way having it match more characters
156 			 * can help us, given that we are already here.
157 			 */
158 			bt_pattern = pattern, bt_patmbs = patmbs;
159 			bt_string = string, bt_strmbs = strmbs;
160 			break;
161 		case '[':
162 			if (sc == EOS)
163 				return (FNM_NOMATCH);
164 			if (sc == '/' && (flags & FNM_PATHNAME))
165 				goto backtrack;
166 			if (sc == '.' && (flags & FNM_PERIOD) &&
167 			    (string == stringstart ||
168 			    ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
169 				goto backtrack;
170 
171 			switch (rangematch(pattern, sc, flags, &newp,
172 			    &patmbs)) {
173 			case RANGE_ERROR:
174 				goto norm;
175 			case RANGE_MATCH:
176 				pattern = newp;
177 				break;
178 			case RANGE_NOMATCH:
179 				goto backtrack;
180 			}
181 			string += sclen;
182 			break;
183 		case '\\':
184 			if (!(flags & FNM_NOESCAPE)) {
185 				pclen = mbrtowc(&pc, pattern, MB_LEN_MAX,
186 				    &patmbs);
187 				if (pclen == (size_t)-1 || pclen == (size_t)-2)
188 					return (FNM_NOMATCH);
189 				pattern += pclen;
190 			}
191 			/* FALLTHROUGH */
192 		default:
193 		norm:
194 			string += sclen;
195 			if (pc == sc)
196 				;
197 			else if ((flags & FNM_CASEFOLD) &&
198 				 (towlower(pc) == towlower(sc)))
199 				;
200 			else {
201 		backtrack:
202 				/*
203 				 * If we have a mismatch (other than hitting
204 				 * the end of the string), go back to the last
205 				 * '*' seen and have it match one additional
206 				 * character.
207 				 */
208 				if (bt_pattern == NULL)
209 					return (FNM_NOMATCH);
210 				sclen = mbrtowc(&sc, bt_string, MB_LEN_MAX,
211 				    &bt_strmbs);
212 				if (sclen == (size_t)-1 ||
213 				    sclen == (size_t)-2) {
214 					sc = (unsigned char)*bt_string;
215 					sclen = 1;
216 					memset(&bt_strmbs, 0,
217 					    sizeof(bt_strmbs));
218 				}
219 				if (sc == EOS)
220 					return (FNM_NOMATCH);
221 				if (sc == '/' && flags & FNM_PATHNAME)
222 					return (FNM_NOMATCH);
223 				bt_string += sclen;
224 				pattern = bt_pattern, patmbs = bt_patmbs;
225 				string = bt_string, strmbs = bt_strmbs;
226 			}
227 			break;
228 		}
229 	}
230 	/* NOTREACHED */
231 }
232 
233 static int
234 rangematch(const char *pattern, wchar_t test, int flags, char **newp,
235     mbstate_t *patmbs)
236 {
237 	int negate, ok;
238 	wchar_t c, c2;
239 	size_t pclen;
240 	const char *origpat;
241 	struct xlocale_collate *table =
242 		(struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
243 
244 	/*
245 	 * A bracket expression starting with an unquoted circumflex
246 	 * character produces unspecified results (IEEE 1003.2-1992,
247 	 * 3.13.2).  This implementation treats it like '!', for
248 	 * consistency with the regular expression syntax.
249 	 * J.T. Conklin (conklin@ngai.kaleida.com)
250 	 */
251 	if ( (negate = (*pattern == '!' || *pattern == '^')) )
252 		++pattern;
253 
254 	if (flags & FNM_CASEFOLD)
255 		test = towlower(test);
256 
257 	/*
258 	 * A right bracket shall lose its special meaning and represent
259 	 * itself in a bracket expression if it occurs first in the list.
260 	 * -- POSIX.2 2.8.3.2
261 	 */
262 	ok = 0;
263 	origpat = pattern;
264 	for (;;) {
265 		if (*pattern == ']' && pattern > origpat) {
266 			pattern++;
267 			break;
268 		} else if (*pattern == '\0') {
269 			return (RANGE_ERROR);
270 		} else if (*pattern == '/' && (flags & FNM_PATHNAME)) {
271 			return (RANGE_NOMATCH);
272 		} else if (*pattern == '\\' && !(flags & FNM_NOESCAPE))
273 			pattern++;
274 		pclen = mbrtowc(&c, pattern, MB_LEN_MAX, patmbs);
275 		if (pclen == (size_t)-1 || pclen == (size_t)-2)
276 			return (RANGE_NOMATCH);
277 		pattern += pclen;
278 
279 		if (flags & FNM_CASEFOLD)
280 			c = towlower(c);
281 
282 		if (*pattern == '-' && *(pattern + 1) != EOS &&
283 		    *(pattern + 1) != ']') {
284 			if (*++pattern == '\\' && !(flags & FNM_NOESCAPE))
285 				if (*pattern != EOS)
286 					pattern++;
287 			pclen = mbrtowc(&c2, pattern, MB_LEN_MAX, patmbs);
288 			if (pclen == (size_t)-1 || pclen == (size_t)-2)
289 				return (RANGE_NOMATCH);
290 			pattern += pclen;
291 			if (c2 == EOS)
292 				return (RANGE_ERROR);
293 
294 			if (flags & FNM_CASEFOLD)
295 				c2 = towlower(c2);
296 
297 			if (table->__collate_load_error ?
298 			    c <= test && test <= c2 :
299 			       __wcollate_range_cmp(c, test) <= 0
300 			    && __wcollate_range_cmp(test, c2) <= 0
301 			   )
302 				ok = 1;
303 		} else if (c == test)
304 			ok = 1;
305 	}
306 
307 	*newp = (char *)pattern;
308 	return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH);
309 }
310