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