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