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