xref: /freebsd/lib/libc/gen/glob-compat11.c (revision b7f7cc25c01aeacaafb86ebcffdeb258b7933b08)
1 /*
2  * Copyright (c) 1989, 1993
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  * 3. 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  * From: @(#)glob.c	8.3 (Berkeley) 10/13/93
38  * From: FreeBSD: head/lib/libc/gen/glob.c 317913 2017-05-07 19:52:56Z jilles
39  */
40 
41 #include <sys/param.h>
42 #define	_WANT_FREEBSD11_STAT
43 #include <sys/stat.h>
44 
45 #include <ctype.h>
46 #define	_WANT_FREEBSD11_DIRENT
47 #include <dirent.h>
48 #include <errno.h>
49 #include <glob.h>
50 #include <limits.h>
51 #include <pwd.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <wchar.h>
58 
59 #include "collate.h"
60 #include "gen-compat.h"
61 #include "glob-compat11.h"
62 
63 /*
64  * glob(3) expansion limits. Stop the expansion if any of these limits
65  * is reached. This caps the runtime in the face of DoS attacks. See
66  * also CVE-2010-2632
67  */
68 #define	GLOB_LIMIT_BRACE	128	/* number of brace calls */
69 #define	GLOB_LIMIT_PATH		65536	/* number of path elements */
70 #define	GLOB_LIMIT_READDIR	16384	/* number of readdirs */
71 #define	GLOB_LIMIT_STAT		1024	/* number of stat system calls */
72 #define	GLOB_LIMIT_STRING	ARG_MAX	/* maximum total size for paths */
73 
74 struct glob_limit {
75 	size_t	l_brace_cnt;
76 	size_t	l_path_lim;
77 	size_t	l_readdir_cnt;
78 	size_t	l_stat_cnt;
79 	size_t	l_string_cnt;
80 };
81 
82 #define	DOT		L'.'
83 #define	EOS		L'\0'
84 #define	LBRACKET	L'['
85 #define	NOT		L'!'
86 #define	QUESTION	L'?'
87 #define	QUOTE		L'\\'
88 #define	RANGE		L'-'
89 #define	RBRACKET	L']'
90 #define	SEP		L'/'
91 #define	STAR		L'*'
92 #define	TILDE		L'~'
93 #define	LBRACE		L'{'
94 #define	RBRACE		L'}'
95 #define	COMMA		L','
96 
97 #define	M_QUOTE		0x8000000000ULL
98 #define	M_PROTECT	0x4000000000ULL
99 #define	M_MASK		0xffffffffffULL
100 #define	M_CHAR		0x00ffffffffULL
101 
102 typedef uint_fast64_t Char;
103 
104 #define	CHAR(c)		((Char)((c)&M_CHAR))
105 #define	META(c)		((Char)((c)|M_QUOTE))
106 #define	UNPROT(c)	((c) & ~M_PROTECT)
107 #define	M_ALL		META(L'*')
108 #define	M_END		META(L']')
109 #define	M_NOT		META(L'!')
110 #define	M_ONE		META(L'?')
111 #define	M_RNG		META(L'-')
112 #define	M_SET		META(L'[')
113 #define	ismeta(c)	(((c)&M_QUOTE) != 0)
114 #ifdef DEBUG
115 #define	isprot(c)	(((c)&M_PROTECT) != 0)
116 #endif
117 
118 static int	 compare(const void *, const void *);
119 static int	 g_Ctoc(const Char *, char *, size_t);
120 static int	 g_lstat(Char *, struct freebsd11_stat *, glob11_t *);
121 static DIR	*g_opendir(Char *, glob11_t *);
122 static const Char *g_strchr(const Char *, wchar_t);
123 #ifdef notdef
124 static Char	*g_strcat(Char *, const Char *);
125 #endif
126 static int	 g_stat(Char *, struct freebsd11_stat *, glob11_t *);
127 static int	 glob0(const Char *, glob11_t *, struct glob_limit *,
128     const char *);
129 static int	 glob1(Char *, glob11_t *, struct glob_limit *);
130 static int	 glob2(Char *, Char *, Char *, Char *, glob11_t *,
131     struct glob_limit *);
132 static int	 glob3(Char *, Char *, Char *, Char *, Char *, glob11_t *,
133     struct glob_limit *);
134 static int	 globextend(const Char *, glob11_t *, struct glob_limit *,
135     const char *);
136 static const Char *
137 		 globtilde(const Char *, Char *, size_t, glob11_t *);
138 static int	 globexp0(const Char *, glob11_t *, struct glob_limit *,
139     const char *);
140 static int	 globexp1(const Char *, glob11_t *, struct glob_limit *);
141 static int	 globexp2(const Char *, const Char *, glob11_t *,
142     struct glob_limit *);
143 static int	 globfinal(glob11_t *, struct glob_limit *, size_t,
144     const char *);
145 static int	 match(Char *, Char *, Char *);
146 static int	 err_nomatch(glob11_t *, struct glob_limit *, const char *);
147 static int	 err_aborted(glob11_t *, int, char *);
148 #ifdef DEBUG
149 static void	 qprintf(const char *, Char *);
150 #endif
151 
152 int
153 freebsd11_glob(const char * __restrict pattern, int flags,
154 	 int (*errfunc)(const char *, int), glob11_t * __restrict pglob)
155 {
156 	struct glob_limit limit = { 0, 0, 0, 0, 0 };
157 	const char *patnext;
158 	Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
159 	mbstate_t mbs;
160 	wchar_t wc;
161 	size_t clen;
162 	int too_long;
163 
164 	patnext = pattern;
165 	if (!(flags & GLOB_APPEND)) {
166 		pglob->gl_pathc = 0;
167 		pglob->gl_pathv = NULL;
168 		if (!(flags & GLOB_DOOFFS))
169 			pglob->gl_offs = 0;
170 	}
171 	if (flags & GLOB_LIMIT) {
172 		limit.l_path_lim = pglob->gl_matchc;
173 		if (limit.l_path_lim == 0)
174 			limit.l_path_lim = GLOB_LIMIT_PATH;
175 	}
176 	pglob->gl_flags = flags & ~GLOB_MAGCHAR;
177 	pglob->gl_errfunc = errfunc;
178 	pglob->gl_matchc = 0;
179 
180 	bufnext = patbuf;
181 	bufend = bufnext + MAXPATHLEN - 1;
182 	too_long = 1;
183 	if (flags & GLOB_NOESCAPE) {
184 		memset(&mbs, 0, sizeof(mbs));
185 		while (bufnext <= bufend) {
186 			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
187 			if (clen == (size_t)-1 || clen == (size_t)-2)
188 				return (err_nomatch(pglob, &limit, pattern));
189 			else if (clen == 0) {
190 				too_long = 0;
191 				break;
192 			}
193 			*bufnext++ = wc;
194 			patnext += clen;
195 		}
196 	} else {
197 		/* Protect the quoted characters. */
198 		memset(&mbs, 0, sizeof(mbs));
199 		while (bufnext <= bufend) {
200 			if (*patnext == '\\') {
201 				if (*++patnext == '\0') {
202 					*bufnext++ = QUOTE;
203 					continue;
204 				}
205 				prot = M_PROTECT;
206 			} else
207 				prot = 0;
208 			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
209 			if (clen == (size_t)-1 || clen == (size_t)-2)
210 				return (err_nomatch(pglob, &limit, pattern));
211 			else if (clen == 0) {
212 				too_long = 0;
213 				break;
214 			}
215 			*bufnext++ = wc | prot;
216 			patnext += clen;
217 		}
218 	}
219 	if (too_long)
220 		return (err_nomatch(pglob, &limit, pattern));
221 	*bufnext = EOS;
222 
223 	if (flags & GLOB_BRACE)
224 	    return (globexp0(patbuf, pglob, &limit, pattern));
225 	else
226 	    return (glob0(patbuf, pglob, &limit, pattern));
227 }
228 
229 static int
230 globexp0(const Char *pattern, glob11_t *pglob, struct glob_limit *limit,
231     const char *origpat) {
232 	int rv;
233 	size_t oldpathc;
234 
235 	/* Protect a single {}, for find(1), like csh */
236 	if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) {
237 		if ((pglob->gl_flags & GLOB_LIMIT) &&
238 		    limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
239 			errno = E2BIG;
240 			return (GLOB_NOSPACE);
241 		}
242 		return (glob0(pattern, pglob, limit, origpat));
243 	}
244 
245 	oldpathc = pglob->gl_pathc;
246 
247 	if ((rv = globexp1(pattern, pglob, limit)) != 0)
248 		return rv;
249 
250 	return (globfinal(pglob, limit, oldpathc, origpat));
251 }
252 
253 /*
254  * Expand recursively a glob {} pattern. When there is no more expansion
255  * invoke the standard globbing routine to glob the rest of the magic
256  * characters
257  */
258 static int
259 globexp1(const Char *pattern, glob11_t *pglob, struct glob_limit *limit)
260 {
261 	const Char* ptr;
262 
263 	if ((ptr = g_strchr(pattern, LBRACE)) != NULL) {
264 		if ((pglob->gl_flags & GLOB_LIMIT) &&
265 		    limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
266 			errno = E2BIG;
267 			return (GLOB_NOSPACE);
268 		}
269 		return (globexp2(ptr, pattern, pglob, limit));
270 	}
271 
272 	return (glob0(pattern, pglob, limit, NULL));
273 }
274 
275 
276 /*
277  * Recursive brace globbing helper. Tries to expand a single brace.
278  * If it succeeds then it invokes globexp1 with the new pattern.
279  * If it fails then it tries to glob the rest of the pattern and returns.
280  */
281 static int
282 globexp2(const Char *ptr, const Char *pattern, glob11_t *pglob,
283     struct glob_limit *limit)
284 {
285 	int     i, rv;
286 	Char   *lm, *ls;
287 	const Char *pe, *pm, *pm1, *pl;
288 	Char    patbuf[MAXPATHLEN];
289 
290 	/* copy part up to the brace */
291 	for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
292 		continue;
293 	*lm = EOS;
294 	ls = lm;
295 
296 	/* Find the balanced brace */
297 	for (i = 0, pe = ++ptr; *pe != EOS; pe++)
298 		if (*pe == LBRACKET) {
299 			/* Ignore everything between [] */
300 			for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
301 				continue;
302 			if (*pe == EOS) {
303 				/*
304 				 * We could not find a matching RBRACKET.
305 				 * Ignore and just look for RBRACE
306 				 */
307 				pe = pm;
308 			}
309 		}
310 		else if (*pe == LBRACE)
311 			i++;
312 		else if (*pe == RBRACE) {
313 			if (i == 0)
314 				break;
315 			i--;
316 		}
317 
318 	/* Non matching braces; just glob the pattern */
319 	if (i != 0 || *pe == EOS)
320 		return (glob0(pattern, pglob, limit, NULL));
321 
322 	for (i = 0, pl = pm = ptr; pm <= pe; pm++)
323 		switch (*pm) {
324 		case LBRACKET:
325 			/* Ignore everything between [] */
326 			for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
327 				continue;
328 			if (*pm == EOS) {
329 				/*
330 				 * We could not find a matching RBRACKET.
331 				 * Ignore and just look for RBRACE
332 				 */
333 				pm = pm1;
334 			}
335 			break;
336 
337 		case LBRACE:
338 			i++;
339 			break;
340 
341 		case RBRACE:
342 			if (i) {
343 			    i--;
344 			    break;
345 			}
346 			/* FALLTHROUGH */
347 		case COMMA:
348 			if (i && *pm == COMMA)
349 				break;
350 			else {
351 				/* Append the current string */
352 				for (lm = ls; (pl < pm); *lm++ = *pl++)
353 					continue;
354 				/*
355 				 * Append the rest of the pattern after the
356 				 * closing brace
357 				 */
358 				for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
359 					continue;
360 
361 				/* Expand the current pattern */
362 #ifdef DEBUG
363 				qprintf("globexp2:", patbuf);
364 #endif
365 				rv = globexp1(patbuf, pglob, limit);
366 				if (rv)
367 					return (rv);
368 
369 				/* move after the comma, to the next string */
370 				pl = pm + 1;
371 			}
372 			break;
373 
374 		default:
375 			break;
376 		}
377 	return (0);
378 }
379 
380 
381 
382 /*
383  * expand tilde from the passwd file.
384  */
385 static const Char *
386 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob11_t *pglob)
387 {
388 	struct passwd *pwd;
389 	char *h, *sc;
390 	const Char *p;
391 	Char *b, *eb;
392 	wchar_t wc;
393 	wchar_t wbuf[MAXPATHLEN];
394 	wchar_t *wbufend, *dc;
395 	size_t clen;
396 	mbstate_t mbs;
397 	int too_long;
398 
399 	if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
400 		return (pattern);
401 
402 	/*
403 	 * Copy up to the end of the string or /
404 	 */
405 	eb = &patbuf[patbuf_len - 1];
406 	for (p = pattern + 1, b = patbuf;
407 	    b < eb && *p != EOS && UNPROT(*p) != SEP; *b++ = *p++)
408 		continue;
409 
410 	if (*p != EOS && UNPROT(*p) != SEP)
411 		return (NULL);
412 
413 	*b = EOS;
414 	h = NULL;
415 
416 	if (patbuf[0] == EOS) {
417 		/*
418 		 * handle a plain ~ or ~/ by expanding $HOME first (iff
419 		 * we're not running setuid or setgid) and then trying
420 		 * the password file
421 		 */
422 		if ((h = secure_getenv("HOME")) == NULL) {
423 			if (((h = getlogin()) != NULL &&
424 			     (pwd = getpwnam(h)) != NULL) ||
425 			    (pwd = getpwuid(getuid())) != NULL)
426 				h = pwd->pw_dir;
427 			else
428 				return (pattern);
429 		}
430 	}
431 	else {
432 		/*
433 		 * Expand a ~user
434 		 */
435 		if (g_Ctoc(patbuf, (char *)wbuf, sizeof(wbuf)))
436 			return (NULL);
437 		if ((pwd = getpwnam((char *)wbuf)) == NULL)
438 			return (pattern);
439 		else
440 			h = pwd->pw_dir;
441 	}
442 
443 	/* Copy the home directory */
444 	dc = wbuf;
445 	sc = h;
446 	wbufend = wbuf + MAXPATHLEN - 1;
447 	too_long = 1;
448 	memset(&mbs, 0, sizeof(mbs));
449 	while (dc <= wbufend) {
450 		clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
451 		if (clen == (size_t)-1 || clen == (size_t)-2) {
452 			/* XXX See initial comment #2. */
453 			wc = (unsigned char)*sc;
454 			clen = 1;
455 			memset(&mbs, 0, sizeof(mbs));
456 		}
457 		if ((*dc++ = wc) == EOS) {
458 			too_long = 0;
459 			break;
460 		}
461 		sc += clen;
462 	}
463 	if (too_long)
464 		return (NULL);
465 
466 	dc = wbuf;
467 	for (b = patbuf; b < eb && *dc != EOS; *b++ = *dc++ | M_PROTECT)
468 		continue;
469 	if (*dc != EOS)
470 		return (NULL);
471 
472 	/* Append the rest of the pattern */
473 	if (*p != EOS) {
474 		too_long = 1;
475 		while (b <= eb) {
476 			if ((*b++ = *p++) == EOS) {
477 				too_long = 0;
478 				break;
479 			}
480 		}
481 		if (too_long)
482 			return (NULL);
483 	} else
484 		*b = EOS;
485 
486 	return (patbuf);
487 }
488 
489 
490 /*
491  * The main glob() routine: compiles the pattern (optionally processing
492  * quotes), calls glob1() to do the real pattern matching, and finally
493  * sorts the list (unless unsorted operation is requested).  Returns 0
494  * if things went well, nonzero if errors occurred.
495  */
496 static int
497 glob0(const Char *pattern, glob11_t *pglob, struct glob_limit *limit,
498     const char *origpat) {
499 	const Char *qpatnext;
500 	int err;
501 	size_t oldpathc;
502 	Char *bufnext, c, patbuf[MAXPATHLEN];
503 
504 	qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
505 	if (qpatnext == NULL) {
506 		errno = E2BIG;
507 		return (GLOB_NOSPACE);
508 	}
509 	oldpathc = pglob->gl_pathc;
510 	bufnext = patbuf;
511 
512 	/* We don't need to check for buffer overflow any more. */
513 	while ((c = *qpatnext++) != EOS) {
514 		switch (c) {
515 		case LBRACKET:
516 			c = *qpatnext;
517 			if (c == NOT)
518 				++qpatnext;
519 			if (*qpatnext == EOS ||
520 			    g_strchr(qpatnext+1, RBRACKET) == NULL) {
521 				*bufnext++ = LBRACKET;
522 				if (c == NOT)
523 					--qpatnext;
524 				break;
525 			}
526 			*bufnext++ = M_SET;
527 			if (c == NOT)
528 				*bufnext++ = M_NOT;
529 			c = *qpatnext++;
530 			do {
531 				*bufnext++ = CHAR(c);
532 				if (*qpatnext == RANGE &&
533 				    (c = qpatnext[1]) != RBRACKET) {
534 					*bufnext++ = M_RNG;
535 					*bufnext++ = CHAR(c);
536 					qpatnext += 2;
537 				}
538 			} while ((c = *qpatnext++) != RBRACKET);
539 			pglob->gl_flags |= GLOB_MAGCHAR;
540 			*bufnext++ = M_END;
541 			break;
542 		case QUESTION:
543 			pglob->gl_flags |= GLOB_MAGCHAR;
544 			*bufnext++ = M_ONE;
545 			break;
546 		case STAR:
547 			pglob->gl_flags |= GLOB_MAGCHAR;
548 			/* collapse adjacent stars to one,
549 			 * to avoid exponential behavior
550 			 */
551 			if (bufnext == patbuf || bufnext[-1] != M_ALL)
552 			    *bufnext++ = M_ALL;
553 			break;
554 		default:
555 			*bufnext++ = CHAR(c);
556 			break;
557 		}
558 	}
559 	*bufnext = EOS;
560 #ifdef DEBUG
561 	qprintf("glob0:", patbuf);
562 #endif
563 
564 	if ((err = glob1(patbuf, pglob, limit)) != 0)
565 		return(err);
566 
567 	if (origpat != NULL)
568 		return (globfinal(pglob, limit, oldpathc, origpat));
569 
570 	return (0);
571 }
572 
573 static int
574 globfinal(glob11_t *pglob, struct glob_limit *limit, size_t oldpathc,
575     const char *origpat) {
576 	if (pglob->gl_pathc == oldpathc)
577 		return (err_nomatch(pglob, limit, origpat));
578 
579 	if (!(pglob->gl_flags & GLOB_NOSORT))
580 		qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
581 		    pglob->gl_pathc - oldpathc, sizeof(char *), compare);
582 
583 	return (0);
584 }
585 
586 static int
587 compare(const void *p, const void *q)
588 {
589 	return (strcoll(*(char **)p, *(char **)q));
590 }
591 
592 static int
593 glob1(Char *pattern, glob11_t *pglob, struct glob_limit *limit)
594 {
595 	Char pathbuf[MAXPATHLEN];
596 
597 	/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
598 	if (*pattern == EOS)
599 		return (0);
600 	return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
601 	    pattern, pglob, limit));
602 }
603 
604 /*
605  * The functions glob2 and glob3 are mutually recursive; there is one level
606  * of recursion for each segment in the pattern that contains one or more
607  * meta characters.
608  */
609 static int
610 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
611       glob11_t *pglob, struct glob_limit *limit)
612 {
613 	struct freebsd11_stat sb;
614 	Char *p, *q;
615 	int anymeta;
616 
617 	/*
618 	 * Loop over pattern segments until end of pattern or until
619 	 * segment with meta character found.
620 	 */
621 	for (anymeta = 0;;) {
622 		if (*pattern == EOS) {		/* End of pattern? */
623 			*pathend = EOS;
624 			if (g_lstat(pathbuf, &sb, pglob))
625 				return (0);
626 
627 			if ((pglob->gl_flags & GLOB_LIMIT) &&
628 			    limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
629 				errno = E2BIG;
630 				return (GLOB_NOSPACE);
631 			}
632 			if ((pglob->gl_flags & GLOB_MARK) &&
633 			    UNPROT(pathend[-1]) != SEP &&
634 			    (S_ISDIR(sb.st_mode) ||
635 			    (S_ISLNK(sb.st_mode) &&
636 			    g_stat(pathbuf, &sb, pglob) == 0 &&
637 			    S_ISDIR(sb.st_mode)))) {
638 				if (pathend + 1 > pathend_last) {
639 					errno = E2BIG;
640 					return (GLOB_NOSPACE);
641 				}
642 				*pathend++ = SEP;
643 				*pathend = EOS;
644 			}
645 			++pglob->gl_matchc;
646 			return (globextend(pathbuf, pglob, limit, NULL));
647 		}
648 
649 		/* Find end of next segment, copy tentatively to pathend. */
650 		q = pathend;
651 		p = pattern;
652 		while (*p != EOS && UNPROT(*p) != SEP) {
653 			if (ismeta(*p))
654 				anymeta = 1;
655 			if (q + 1 > pathend_last) {
656 				errno = E2BIG;
657 				return (GLOB_NOSPACE);
658 			}
659 			*q++ = *p++;
660 		}
661 
662 		if (!anymeta) {		/* No expansion, do next segment. */
663 			pathend = q;
664 			pattern = p;
665 			while (UNPROT(*pattern) == SEP) {
666 				if (pathend + 1 > pathend_last) {
667 					errno = E2BIG;
668 					return (GLOB_NOSPACE);
669 				}
670 				*pathend++ = *pattern++;
671 			}
672 		} else			/* Need expansion, recurse. */
673 			return (glob3(pathbuf, pathend, pathend_last, pattern,
674 			    p, pglob, limit));
675 	}
676 	/* NOTREACHED */
677 }
678 
679 static int
680 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
681       Char *pattern, Char *restpattern,
682       glob11_t *pglob, struct glob_limit *limit)
683 {
684 	struct freebsd11_dirent *dp;
685 	DIR *dirp;
686 	int err, too_long, saverrno, saverrno2;
687 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
688 
689 	struct freebsd11_dirent *(*readdirfunc)(DIR *);
690 
691 	if (pathend > pathend_last) {
692 		errno = E2BIG;
693 		return (GLOB_NOSPACE);
694 	}
695 	*pathend = EOS;
696 	if (pglob->gl_errfunc != NULL &&
697 	    g_Ctoc(pathbuf, buf, sizeof(buf))) {
698 		errno = E2BIG;
699 		return (GLOB_NOSPACE);
700 	}
701 
702 	saverrno = errno;
703 	errno = 0;
704 	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
705 		if (errno == ENOENT || errno == ENOTDIR)
706 			return (0);
707 		err = err_aborted(pglob, errno, buf);
708 		if (errno == 0)
709 			errno = saverrno;
710 		return (err);
711 	}
712 
713 	err = 0;
714 
715 	/* pglob->gl_readdir takes a void *, fix this manually */
716 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
717 		readdirfunc =
718 		    (struct freebsd11_dirent *(*)(DIR *))pglob->gl_readdir;
719 	else
720 		readdirfunc = freebsd11_readdir;
721 
722 	errno = 0;
723 	/* Search directory for matching names. */
724 	while ((dp = (*readdirfunc)(dirp)) != NULL) {
725 		char *sc;
726 		Char *dc;
727 		wchar_t wc;
728 		size_t clen;
729 		mbstate_t mbs;
730 
731 		if ((pglob->gl_flags & GLOB_LIMIT) &&
732 		    limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
733 			errno = E2BIG;
734 			err = GLOB_NOSPACE;
735 			break;
736 		}
737 
738 		/* Initial DOT must be matched literally. */
739 		if (dp->d_name[0] == '.' && UNPROT(*pattern) != DOT) {
740 			errno = 0;
741 			continue;
742 		}
743 		memset(&mbs, 0, sizeof(mbs));
744 		dc = pathend;
745 		sc = dp->d_name;
746 		too_long = 1;
747 		while (dc <= pathend_last) {
748 			clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
749 			if (clen == (size_t)-1 || clen == (size_t)-2) {
750 				/* XXX See initial comment #2. */
751 				wc = (unsigned char)*sc;
752 				clen = 1;
753 				memset(&mbs, 0, sizeof(mbs));
754 			}
755 			if ((*dc++ = wc) == EOS) {
756 				too_long = 0;
757 				break;
758 			}
759 			sc += clen;
760 		}
761 		if (too_long && (err = err_aborted(pglob, ENAMETOOLONG,
762 		    buf))) {
763 			errno = ENAMETOOLONG;
764 			break;
765 		}
766 		if (too_long || !match(pathend, pattern, restpattern)) {
767 			*pathend = EOS;
768 			errno = 0;
769 			continue;
770 		}
771 		if (errno == 0)
772 			errno = saverrno;
773 		err = glob2(pathbuf, --dc, pathend_last, restpattern,
774 		    pglob, limit);
775 		if (err)
776 			break;
777 		errno = 0;
778 	}
779 
780 	saverrno2 = errno;
781 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
782 		(*pglob->gl_closedir)(dirp);
783 	else
784 		closedir(dirp);
785 	errno = saverrno2;
786 
787 	if (err)
788 		return (err);
789 
790 	if (dp == NULL && errno != 0 &&
791 	    (err = err_aborted(pglob, errno, buf)))
792 		return (err);
793 
794 	if (errno == 0)
795 		errno = saverrno;
796 	return (0);
797 }
798 
799 
800 /*
801  * Extend the gl_pathv member of a glob11_t structure to accommodate a new item,
802  * add the new item, and update gl_pathc.
803  *
804  * This assumes the BSD realloc, which only copies the block when its size
805  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
806  * behavior.
807  *
808  * Return 0 if new item added, error code if memory couldn't be allocated.
809  *
810  * Invariant of the glob11_t structure:
811  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
812  *	gl_pathv points to (gl_offs + gl_pathc + 1) items.
813  */
814 static int
815 globextend(const Char *path, glob11_t *pglob, struct glob_limit *limit,
816     const char *origpat)
817 {
818 	char **pathv;
819 	size_t i, newn, len;
820 	char *copy;
821 	const Char *p;
822 
823 	if ((pglob->gl_flags & GLOB_LIMIT) &&
824 	    pglob->gl_matchc > limit->l_path_lim) {
825 		errno = E2BIG;
826 		return (GLOB_NOSPACE);
827 	}
828 
829 	newn = 2 + pglob->gl_pathc + pglob->gl_offs;
830 	/* reallocarray(NULL, newn, size) is equivalent to malloc(newn*size). */
831 	pathv = reallocarray(pglob->gl_pathv, newn, sizeof(*pathv));
832 	if (pathv == NULL)
833 		return (GLOB_NOSPACE);
834 
835 	if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
836 		/* first time around -- clear initial gl_offs items */
837 		pathv += pglob->gl_offs;
838 		for (i = pglob->gl_offs + 1; --i > 0; )
839 			*--pathv = NULL;
840 	}
841 	pglob->gl_pathv = pathv;
842 
843 	if (origpat != NULL)
844 		copy = strdup(origpat);
845 	else {
846 		for (p = path; *p++ != EOS;)
847 			continue;
848 		len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */
849 		if ((copy = malloc(len)) != NULL) {
850 			if (g_Ctoc(path, copy, len)) {
851 				free(copy);
852 				errno = E2BIG;
853 				return (GLOB_NOSPACE);
854 			}
855 		}
856 	}
857 	if (copy != NULL) {
858 		limit->l_string_cnt += strlen(copy) + 1;
859 		if ((pglob->gl_flags & GLOB_LIMIT) &&
860 		    limit->l_string_cnt >= GLOB_LIMIT_STRING) {
861 			free(copy);
862 			errno = E2BIG;
863 			return (GLOB_NOSPACE);
864 		}
865 		pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
866 	}
867 	pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
868 	return (copy == NULL ? GLOB_NOSPACE : 0);
869 }
870 
871 /*
872  * pattern matching function for filenames.
873  */
874 static int
875 match(Char *name, Char *pat, Char *patend)
876 {
877 	int ok, negate_range;
878 	Char c, k, *nextp, *nextn;
879 	struct xlocale_collate *table =
880 		(struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
881 
882 	nextn = NULL;
883 	nextp = NULL;
884 
885 	while (1) {
886 		while (pat < patend) {
887 			c = *pat++;
888 			switch (c & M_MASK) {
889 			case M_ALL:
890 				if (pat == patend)
891 					return (1);
892 				if (*name == EOS)
893 					return (0);
894 				nextn = name + 1;
895 				nextp = pat - 1;
896 				break;
897 			case M_ONE:
898 				if (*name++ == EOS)
899 					goto fail;
900 				break;
901 			case M_SET:
902 				ok = 0;
903 				if ((k = *name++) == EOS)
904 					goto fail;
905 				negate_range = ((*pat & M_MASK) == M_NOT);
906 				if (negate_range != 0)
907 					++pat;
908 				while (((c = *pat++) & M_MASK) != M_END)
909 					if ((*pat & M_MASK) == M_RNG) {
910 						if (table->__collate_load_error ?
911 						    CHAR(c) <= CHAR(k) &&
912 						    CHAR(k) <= CHAR(pat[1]) :
913 						    __wcollate_range_cmp(CHAR(c),
914 						    CHAR(k)) <= 0 &&
915 						    __wcollate_range_cmp(CHAR(k),
916 						    CHAR(pat[1])) <= 0)
917 							ok = 1;
918 						pat += 2;
919 					} else if (c == k)
920 						ok = 1;
921 				if (ok == negate_range)
922 					goto fail;
923 				break;
924 			default:
925 				if (*name++ != c)
926 					goto fail;
927 				break;
928 			}
929 		}
930 		if (*name == EOS)
931 			return (1);
932 
933 	fail:
934 		if (nextn == NULL)
935 			break;
936 		pat = nextp;
937 		name = nextn;
938 	}
939 	return (0);
940 }
941 
942 /* Free allocated data belonging to a glob11_t structure. */
943 void
944 freebsd11_globfree(glob11_t *pglob)
945 {
946 	size_t i;
947 	char **pp;
948 
949 	if (pglob->gl_pathv != NULL) {
950 		pp = pglob->gl_pathv + pglob->gl_offs;
951 		for (i = pglob->gl_pathc; i--; ++pp)
952 			if (*pp)
953 				free(*pp);
954 		free(pglob->gl_pathv);
955 		pglob->gl_pathv = NULL;
956 	}
957 }
958 
959 static DIR *
960 g_opendir(Char *str, glob11_t *pglob)
961 {
962 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
963 
964 	if (*str == EOS)
965 		strcpy(buf, ".");
966 	else {
967 		if (g_Ctoc(str, buf, sizeof(buf))) {
968 			errno = ENAMETOOLONG;
969 			return (NULL);
970 		}
971 	}
972 
973 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
974 		return ((*pglob->gl_opendir)(buf));
975 
976 	return (opendir(buf));
977 }
978 
979 static int
980 g_lstat(Char *fn, struct freebsd11_stat *sb, glob11_t *pglob)
981 {
982 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
983 
984 	if (g_Ctoc(fn, buf, sizeof(buf))) {
985 		errno = ENAMETOOLONG;
986 		return (-1);
987 	}
988 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
989 		return((*pglob->gl_lstat)(buf, sb));
990 	return (freebsd11_lstat(buf, sb));
991 }
992 
993 static int
994 g_stat(Char *fn, struct freebsd11_stat *sb, glob11_t *pglob)
995 {
996 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
997 
998 	if (g_Ctoc(fn, buf, sizeof(buf))) {
999 		errno = ENAMETOOLONG;
1000 		return (-1);
1001 	}
1002 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1003 		return ((*pglob->gl_stat)(buf, sb));
1004 	return (freebsd11_stat(buf, sb));
1005 }
1006 
1007 static const Char *
1008 g_strchr(const Char *str, wchar_t ch)
1009 {
1010 
1011 	do {
1012 		if (*str == ch)
1013 			return (str);
1014 	} while (*str++);
1015 	return (NULL);
1016 }
1017 
1018 static int
1019 g_Ctoc(const Char *str, char *buf, size_t len)
1020 {
1021 	mbstate_t mbs;
1022 	size_t clen;
1023 
1024 	memset(&mbs, 0, sizeof(mbs));
1025 	while (len >= MB_CUR_MAX) {
1026 		clen = wcrtomb(buf, CHAR(*str), &mbs);
1027 		if (clen == (size_t)-1) {
1028 			/* XXX See initial comment #2. */
1029 			*buf = (char)CHAR(*str);
1030 			clen = 1;
1031 			memset(&mbs, 0, sizeof(mbs));
1032 		}
1033 		if (CHAR(*str) == EOS)
1034 			return (0);
1035 		str++;
1036 		buf += clen;
1037 		len -= clen;
1038 	}
1039 	return (1);
1040 }
1041 
1042 static int
1043 err_nomatch(glob11_t *pglob, struct glob_limit *limit, const char *origpat) {
1044 	/*
1045 	 * If there was no match we are going to append the origpat
1046 	 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
1047 	 * and the origpat did not contain any magic characters
1048 	 * GLOB_NOMAGIC is there just for compatibility with csh.
1049 	 */
1050 	if ((pglob->gl_flags & GLOB_NOCHECK) ||
1051 	    ((pglob->gl_flags & GLOB_NOMAGIC) &&
1052 	    !(pglob->gl_flags & GLOB_MAGCHAR)))
1053 		return (globextend(NULL, pglob, limit, origpat));
1054 	return (GLOB_NOMATCH);
1055 }
1056 
1057 static int
1058 err_aborted(glob11_t *pglob, int err, char *buf) {
1059 	if ((pglob->gl_errfunc != NULL && pglob->gl_errfunc(buf, err)) ||
1060 	    (pglob->gl_flags & GLOB_ERR))
1061 		return (GLOB_ABORTED);
1062 	return (0);
1063 }
1064 
1065 #ifdef DEBUG
1066 static void
1067 qprintf(const char *str, Char *s)
1068 {
1069 	Char *p;
1070 
1071 	(void)printf("%s\n", str);
1072 	if (s != NULL) {
1073 		for (p = s; *p != EOS; p++)
1074 			(void)printf("%c", (char)CHAR(*p));
1075 		(void)printf("\n");
1076 		for (p = s; *p != EOS; p++)
1077 			(void)printf("%c", (isprot(*p) ? '\\' : ' '));
1078 		(void)printf("\n");
1079 		for (p = s; *p != EOS; p++)
1080 			(void)printf("%c", (ismeta(*p) ? '_' : ' '));
1081 		(void)printf("\n");
1082 	}
1083 }
1084 #endif
1085 
1086 __sym_compat(glob, freebsd11_glob, FBSD_1.0);
1087 __sym_compat(globfree, freebsd11_globfree, FBSD_1.0);
1088