xref: /freebsd/lib/libc/gen/glob.c (revision 3f2a60a1371a69d7e9caac43bf457b6f89cdfd48)
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  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)glob.c	8.3 (Berkeley) 10/13/93";
40 #endif /* LIBC_SCCS and not lint */
41 #include <sys/cdefs.h>
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	SLASH		L'/'
130 #define	COMMA		L','
131 
132 #ifndef DEBUG
133 
134 #define	M_QUOTE		0x8000000000ULL
135 #define	M_PROTECT	0x4000000000ULL
136 #define	M_MASK		0xffffffffffULL
137 #define	M_CHAR		0x00ffffffffULL
138 
139 typedef uint_fast64_t Char;
140 
141 #else
142 
143 #define	M_QUOTE		0x80
144 #define	M_PROTECT	0x40
145 #define	M_MASK		0xff
146 #define	M_CHAR		0x7f
147 
148 typedef char Char;
149 
150 #endif
151 
152 
153 #define	CHAR(c)		((Char)((c)&M_CHAR))
154 #define	META(c)		((Char)((c)|M_QUOTE))
155 #define	M_ALL		META(L'*')
156 #define	M_END		META(L']')
157 #define	M_NOT		META(L'!')
158 #define	M_ONE		META(L'?')
159 #define	M_RNG		META(L'-')
160 #define	M_SET		META(L'[')
161 #define	ismeta(c)	(((c)&M_QUOTE) != 0)
162 
163 
164 static int	 compare(const void *, const void *);
165 static int	 g_Ctoc(const Char *, char *, size_t);
166 static int	 g_lstat(Char *, struct stat *, glob_t *);
167 static DIR	*g_opendir(Char *, glob_t *);
168 static const Char *g_strchr(const Char *, wchar_t);
169 #ifdef notdef
170 static Char	*g_strcat(Char *, const Char *);
171 #endif
172 static int	 g_stat(Char *, struct stat *, glob_t *);
173 static int	 glob0(const Char *, glob_t *, struct glob_limit *);
174 static int	 glob1(Char *, glob_t *, struct glob_limit *);
175 static int	 glob2(Char *, Char *, Char *, Char *, glob_t *,
176     struct glob_limit *);
177 static int	 glob3(Char *, Char *, Char *, Char *, Char *, glob_t *,
178     struct glob_limit *);
179 static int	 globextend(const Char *, glob_t *, struct glob_limit *);
180 static const Char *
181 		 globtilde(const Char *, Char *, size_t, glob_t *);
182 static int	 globexp1(const Char *, glob_t *, struct glob_limit *);
183 static int	 globexp2(const Char *, const Char *, glob_t *, int *,
184     struct glob_limit *);
185 static int	 match(Char *, Char *, Char *);
186 #ifdef DEBUG
187 static void	 qprintf(const char *, Char *);
188 #endif
189 
190 int
191 glob(const char * __restrict pattern, int flags,
192 	 int (*errfunc)(const char *, int), glob_t * __restrict pglob)
193 {
194 	struct glob_limit limit = { 0, 0, 0, 0, 0 };
195 	const char *patnext;
196 	Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
197 	mbstate_t mbs;
198 	wchar_t wc;
199 	size_t clen;
200 
201 	patnext = pattern;
202 	if (!(flags & GLOB_APPEND)) {
203 		pglob->gl_pathc = 0;
204 		pglob->gl_pathv = NULL;
205 		if (!(flags & GLOB_DOOFFS))
206 			pglob->gl_offs = 0;
207 	}
208 	if (flags & GLOB_LIMIT) {
209 		limit.l_path_lim = pglob->gl_matchc;
210 		if (limit.l_path_lim == 0)
211 			limit.l_path_lim = GLOB_LIMIT_PATH;
212 	}
213 	pglob->gl_flags = flags & ~GLOB_MAGCHAR;
214 	pglob->gl_errfunc = errfunc;
215 	pglob->gl_matchc = 0;
216 
217 	bufnext = patbuf;
218 	bufend = bufnext + MAXPATHLEN - 1;
219 	if (flags & GLOB_NOESCAPE) {
220 		memset(&mbs, 0, sizeof(mbs));
221 		while (bufend - bufnext >= MB_CUR_MAX) {
222 			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
223 			if (clen == (size_t)-1 || clen == (size_t)-2)
224 				return (GLOB_NOMATCH);
225 			else if (clen == 0)
226 				break;
227 			*bufnext++ = wc;
228 			patnext += clen;
229 		}
230 	} else {
231 		/* Protect the quoted characters. */
232 		memset(&mbs, 0, sizeof(mbs));
233 		while (bufend - bufnext >= MB_CUR_MAX) {
234 			if (*patnext == '\\') {
235 				if (*++patnext == '\0') {
236 					*bufnext++ = QUOTE | M_PROTECT;
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 (GLOB_NOMATCH);
245 			else if (clen == 0)
246 				break;
247 			*bufnext++ = wc | ((wc != DOT && wc != SEP) ?
248 			    prot : 0);
249 			patnext += clen;
250 		}
251 	}
252 	*bufnext = EOS;
253 
254 	if (flags & GLOB_BRACE)
255 	    return (globexp1(patbuf, pglob, &limit));
256 	else
257 	    return (glob0(patbuf, pglob, &limit));
258 }
259 
260 /*
261  * Expand recursively a glob {} pattern. When there is no more expansion
262  * invoke the standard globbing routine to glob the rest of the magic
263  * characters
264  */
265 static int
266 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
267 {
268 	const Char* ptr = pattern;
269 	int rv;
270 
271 	if ((pglob->gl_flags & GLOB_LIMIT) &&
272 	    limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
273 		errno = 0;
274 		return (GLOB_NOSPACE);
275 	}
276 
277 	/* Protect a single {}, for find(1), like csh */
278 	if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
279 		return glob0(pattern, pglob, limit);
280 
281 	while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
282 		if (!globexp2(ptr, pattern, pglob, &rv, limit))
283 			return rv;
284 
285 	return glob0(pattern, pglob, limit);
286 }
287 
288 
289 /*
290  * Recursive brace globbing helper. Tries to expand a single brace.
291  * If it succeeds then it invokes globexp1 with the new pattern.
292  * If it fails then it tries to glob the rest of the pattern and returns.
293  */
294 static int
295 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
296     struct glob_limit *limit)
297 {
298 	int     i;
299 	Char   *lm, *ls;
300 	const Char *pe, *pm, *pm1, *pl;
301 	Char    patbuf[MAXPATHLEN];
302 
303 	/* copy part up to the brace */
304 	for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
305 		continue;
306 	*lm = EOS;
307 	ls = lm;
308 
309 	/* Find the balanced brace */
310 	for (i = 0, pe = ++ptr; *pe; pe++)
311 		if (*pe == LBRACKET) {
312 			/* Ignore everything between [] */
313 			for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
314 				continue;
315 			if (*pe == EOS) {
316 				/*
317 				 * We could not find a matching RBRACKET.
318 				 * Ignore and just look for RBRACE
319 				 */
320 				pe = pm;
321 			}
322 		}
323 		else if (*pe == LBRACE)
324 			i++;
325 		else if (*pe == RBRACE) {
326 			if (i == 0)
327 				break;
328 			i--;
329 		}
330 
331 	/* Non matching braces; just glob the pattern */
332 	if (i != 0 || *pe == EOS) {
333 		*rv = glob0(patbuf, pglob, limit);
334 		return (0);
335 	}
336 
337 	for (i = 0, pl = pm = ptr; pm <= pe; pm++)
338 		switch (*pm) {
339 		case LBRACKET:
340 			/* Ignore everything between [] */
341 			for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
342 				continue;
343 			if (*pm == EOS) {
344 				/*
345 				 * We could not find a matching RBRACKET.
346 				 * Ignore and just look for RBRACE
347 				 */
348 				pm = pm1;
349 			}
350 			break;
351 
352 		case LBRACE:
353 			i++;
354 			break;
355 
356 		case RBRACE:
357 			if (i) {
358 			    i--;
359 			    break;
360 			}
361 			/* FALLTHROUGH */
362 		case COMMA:
363 			if (i && *pm == COMMA)
364 				break;
365 			else {
366 				/* Append the current string */
367 				for (lm = ls; (pl < pm); *lm++ = *pl++)
368 					continue;
369 				/*
370 				 * Append the rest of the pattern after the
371 				 * closing brace
372 				 */
373 				for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
374 					continue;
375 
376 				/* Expand the current pattern */
377 #ifdef DEBUG
378 				qprintf("globexp2:", patbuf);
379 #endif
380 				*rv = globexp1(patbuf, pglob, limit);
381 
382 				/* move after the comma, to the next string */
383 				pl = pm + 1;
384 			}
385 			break;
386 
387 		default:
388 			break;
389 		}
390 	*rv = 0;
391 	return (0);
392 }
393 
394 
395 
396 /*
397  * expand tilde from the passwd file.
398  */
399 static const Char *
400 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
401 {
402 	struct passwd *pwd;
403 	char *h, *sc;
404 	const Char *p;
405 	Char *b, *eb;
406 	wchar_t wc;
407 	wchar_t wbuf[MAXPATHLEN];
408 	wchar_t *wbufend, *dc;
409 	size_t clen;
410 	mbstate_t mbs;
411 	int too_long;
412 
413 	if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
414 		return (pattern);
415 
416 	/*
417 	 * Copy up to the end of the string or /
418 	 */
419 	eb = &patbuf[patbuf_len - 1];
420 	for (p = pattern + 1, b = patbuf;
421 	    b < eb && *p != EOS && *p != SLASH; *b++ = *p++)
422 		continue;
423 
424 	if (*p != EOS && *p != SLASH)
425 		return (NULL);
426 
427 	*b = EOS;
428 	h = NULL;
429 
430 	if (patbuf[0] == EOS) {
431 		/*
432 		 * handle a plain ~ or ~/ by expanding $HOME first (iff
433 		 * we're not running setuid or setgid) and then trying
434 		 * the password file
435 		 */
436 		if (issetugid() != 0 ||
437 		    (h = getenv("HOME")) == NULL) {
438 			if (((h = getlogin()) != NULL &&
439 			     (pwd = getpwnam(h)) != NULL) ||
440 			    (pwd = getpwuid(getuid())) != NULL)
441 				h = pwd->pw_dir;
442 			else
443 				return (pattern);
444 		}
445 	}
446 	else {
447 		/*
448 		 * Expand a ~user
449 		 */
450 		if (g_Ctoc(patbuf, (char *)wbuf, sizeof(wbuf)))
451 			return (NULL);
452 		if ((pwd = getpwnam((char *)wbuf)) == NULL)
453 			return (pattern);
454 		else
455 			h = pwd->pw_dir;
456 	}
457 
458 	/* Copy the home directory */
459 	dc = wbuf;
460 	sc = h;
461 	wbufend = wbuf + MAXPATHLEN - 1;
462 	too_long = 1;
463 	memset(&mbs, 0, sizeof(mbs));
464 	while (dc <= wbufend) {
465 		clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
466 		if (clen == (size_t)-1 || clen == (size_t)-2) {
467 			/* XXX See initial comment #2. */
468 			wc = (unsigned char)*sc;
469 			clen = 1;
470 			memset(&mbs, 0, sizeof(mbs));
471 		}
472 		if ((*dc++ = wc) == EOS) {
473 			too_long = 0;
474 			break;
475 		}
476 		sc += clen;
477 	}
478 	if (too_long)
479 		return (NULL);
480 
481 	dc = wbuf;
482 	for (b = patbuf; b < eb && *dc != EOS; b++, dc++)
483 		*b = *dc | ((*dc != DOT && *dc != SEP) ? M_PROTECT : 0);
484 	if (*dc != EOS)
485 		return (NULL);
486 
487 	/* Append the rest of the pattern */
488 	if (*p != EOS) {
489 		too_long = 1;
490 		while (b <= eb) {
491 			if ((*b++ = *p++) == EOS) {
492 				too_long = 0;
493 				break;
494 			}
495 		}
496 		if (too_long)
497 			return (NULL);
498 	} else
499 		*b = EOS;
500 
501 	return (patbuf);
502 }
503 
504 
505 /*
506  * The main glob() routine: compiles the pattern (optionally processing
507  * quotes), calls glob1() to do the real pattern matching, and finally
508  * sorts the list (unless unsorted operation is requested).  Returns 0
509  * if things went well, nonzero if errors occurred.
510  */
511 static int
512 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
513 {
514 	const Char *qpatnext;
515 	int err;
516 	size_t oldpathc;
517 	Char *bufnext, c, patbuf[MAXPATHLEN];
518 
519 	qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
520 	if (qpatnext == NULL) {
521 		errno = 0;
522 		return (GLOB_NOSPACE);
523 	}
524 	oldpathc = pglob->gl_pathc;
525 	bufnext = patbuf;
526 
527 	/* We don't need to check for buffer overflow any more. */
528 	while ((c = *qpatnext++) != EOS) {
529 		switch (c) {
530 		case LBRACKET:
531 			c = *qpatnext;
532 			if (c == NOT)
533 				++qpatnext;
534 			if (*qpatnext == EOS ||
535 			    g_strchr(qpatnext+1, RBRACKET) == NULL) {
536 				*bufnext++ = LBRACKET;
537 				if (c == NOT)
538 					--qpatnext;
539 				break;
540 			}
541 			*bufnext++ = M_SET;
542 			if (c == NOT)
543 				*bufnext++ = M_NOT;
544 			c = *qpatnext++;
545 			do {
546 				*bufnext++ = CHAR(c);
547 				if (*qpatnext == RANGE &&
548 				    (c = qpatnext[1]) != RBRACKET) {
549 					*bufnext++ = M_RNG;
550 					*bufnext++ = CHAR(c);
551 					qpatnext += 2;
552 				}
553 			} while ((c = *qpatnext++) != RBRACKET);
554 			pglob->gl_flags |= GLOB_MAGCHAR;
555 			*bufnext++ = M_END;
556 			break;
557 		case QUESTION:
558 			pglob->gl_flags |= GLOB_MAGCHAR;
559 			*bufnext++ = M_ONE;
560 			break;
561 		case STAR:
562 			pglob->gl_flags |= GLOB_MAGCHAR;
563 			/* collapse adjacent stars to one,
564 			 * to avoid exponential behavior
565 			 */
566 			if (bufnext == patbuf || bufnext[-1] != M_ALL)
567 			    *bufnext++ = M_ALL;
568 			break;
569 		default:
570 			*bufnext++ = CHAR(c);
571 			break;
572 		}
573 	}
574 	*bufnext = EOS;
575 #ifdef DEBUG
576 	qprintf("glob0:", patbuf);
577 #endif
578 
579 	if ((err = glob1(patbuf, pglob, limit)) != 0)
580 		return(err);
581 
582 	/*
583 	 * If there was no match we are going to append the pattern
584 	 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
585 	 * and the pattern did not contain any magic characters
586 	 * GLOB_NOMAGIC is there just for compatibility with csh.
587 	 */
588 	if (pglob->gl_pathc == oldpathc) {
589 		if (((pglob->gl_flags & GLOB_NOCHECK) ||
590 		    ((pglob->gl_flags & GLOB_NOMAGIC) &&
591 			!(pglob->gl_flags & GLOB_MAGCHAR))))
592 			return (globextend(pattern, pglob, limit));
593 		else
594 			return (GLOB_NOMATCH);
595 	}
596 	if (!(pglob->gl_flags & GLOB_NOSORT))
597 		qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
598 		    pglob->gl_pathc - oldpathc, sizeof(char *), compare);
599 	return (0);
600 }
601 
602 static int
603 compare(const void *p, const void *q)
604 {
605 	return (strcoll(*(char **)p, *(char **)q));
606 }
607 
608 static int
609 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
610 {
611 	Char pathbuf[MAXPATHLEN];
612 
613 	/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
614 	if (*pattern == EOS)
615 		return (0);
616 	return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
617 	    pattern, pglob, limit));
618 }
619 
620 /*
621  * The functions glob2 and glob3 are mutually recursive; there is one level
622  * of recursion for each segment in the pattern that contains one or more
623  * meta characters.
624  */
625 static int
626 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
627       glob_t *pglob, struct glob_limit *limit)
628 {
629 	struct stat sb;
630 	Char *p, *q;
631 	int anymeta;
632 
633 	/*
634 	 * Loop over pattern segments until end of pattern or until
635 	 * segment with meta character found.
636 	 */
637 	for (anymeta = 0;;) {
638 		if (*pattern == EOS) {		/* End of pattern? */
639 			*pathend = EOS;
640 			if (g_lstat(pathbuf, &sb, pglob))
641 				return (0);
642 
643 			if ((pglob->gl_flags & GLOB_LIMIT) &&
644 			    limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
645 				errno = 0;
646 				return (GLOB_NOSPACE);
647 			}
648 			if (((pglob->gl_flags & GLOB_MARK) &&
649 			    pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
650 			    || (S_ISLNK(sb.st_mode) &&
651 			    (g_stat(pathbuf, &sb, pglob) == 0) &&
652 			    S_ISDIR(sb.st_mode)))) {
653 				if (pathend + 1 > pathend_last) {
654 					errno = 0;
655 					return (GLOB_NOSPACE);
656 				}
657 				*pathend++ = SEP;
658 				*pathend = EOS;
659 			}
660 			++pglob->gl_matchc;
661 			return (globextend(pathbuf, pglob, limit));
662 		}
663 
664 		/* Find end of next segment, copy tentatively to pathend. */
665 		q = pathend;
666 		p = pattern;
667 		while (*p != EOS && *p != SEP) {
668 			if (ismeta(*p))
669 				anymeta = 1;
670 			if (q + 1 > pathend_last) {
671 				errno = 0;
672 				return (GLOB_NOSPACE);
673 			}
674 			*q++ = *p++;
675 		}
676 
677 		if (!anymeta) {		/* No expansion, do next segment. */
678 			pathend = q;
679 			pattern = p;
680 			while (*pattern == SEP) {
681 				if (pathend + 1 > pathend_last) {
682 					errno = 0;
683 					return (GLOB_NOSPACE);
684 				}
685 				*pathend++ = *pattern++;
686 			}
687 		} else			/* Need expansion, recurse. */
688 			return (glob3(pathbuf, pathend, pathend_last, pattern,
689 			    p, pglob, limit));
690 	}
691 	/* NOTREACHED */
692 }
693 
694 static int
695 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
696       Char *pattern, Char *restpattern,
697       glob_t *pglob, struct glob_limit *limit)
698 {
699 	struct dirent *dp;
700 	DIR *dirp;
701 	int err;
702 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
703 
704 	struct dirent *(*readdirfunc)(DIR *);
705 
706 	errno = 0;
707 	if (pathend > pathend_last)
708 		return (GLOB_NOSPACE);
709 	*pathend = EOS;
710 
711 	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
712 		if (errno == ENOENT || errno == ENOTDIR)
713 			return (0);
714 		if (pglob->gl_errfunc != NULL) {
715 			if (g_Ctoc(pathbuf, buf, sizeof(buf))) {
716 				errno = 0;
717 				return (GLOB_NOSPACE);
718 			}
719 			if (pglob->gl_errfunc(buf, errno))
720 				return (GLOB_ABORTED);
721 		}
722 		if (pglob->gl_flags & GLOB_ERR)
723 			return (GLOB_ABORTED);
724 		return (0);
725 	}
726 
727 	err = 0;
728 
729 	/* pglob->gl_readdir takes a void *, fix this manually */
730 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
731 		readdirfunc = (struct dirent *(*)(DIR *))pglob->gl_readdir;
732 	else
733 		readdirfunc = readdir;
734 
735 	/* Search directory for matching names. */
736 	while ((dp = (*readdirfunc)(dirp)) != NULL) {
737 		char *sc;
738 		Char *dc;
739 		wchar_t wc;
740 		size_t clen;
741 		mbstate_t mbs;
742 
743 		if ((pglob->gl_flags & GLOB_LIMIT) &&
744 		    limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
745 			errno = 0;
746 			if (pathend + 1 > pathend_last)
747 				err = GLOB_NOSPACE;
748 			else {
749 				*pathend++ = SEP;
750 				*pathend = EOS;
751 				err = GLOB_NOSPACE;
752 			}
753 			break;
754 		}
755 
756 		/* Initial DOT must be matched literally. */
757 		if (dp->d_name[0] == '.' && *pattern != DOT)
758 			continue;
759 		memset(&mbs, 0, sizeof(mbs));
760 		dc = pathend;
761 		sc = dp->d_name;
762 		while (dc < pathend_last) {
763 			clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
764 			if (clen == (size_t)-1 || clen == (size_t)-2) {
765 				/* XXX See initial comment #2. */
766 				wc = (unsigned char)*sc;
767 				clen = 1;
768 				memset(&mbs, 0, sizeof(mbs));
769 			}
770 			if ((*dc++ = wc) == EOS)
771 				break;
772 			sc += clen;
773 		}
774 		if (!match(pathend, pattern, restpattern)) {
775 			*pathend = EOS;
776 			continue;
777 		}
778 		err = glob2(pathbuf, --dc, pathend_last, restpattern,
779 		    pglob, limit);
780 		if (err)
781 			break;
782 	}
783 
784 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
785 		(*pglob->gl_closedir)(dirp);
786 	else
787 		closedir(dirp);
788 	return (err);
789 }
790 
791 
792 /*
793  * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
794  * add the new item, and update gl_pathc.
795  *
796  * This assumes the BSD realloc, which only copies the block when its size
797  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
798  * behavior.
799  *
800  * Return 0 if new item added, error code if memory couldn't be allocated.
801  *
802  * Invariant of the glob_t structure:
803  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
804  *	gl_pathv points to (gl_offs + gl_pathc + 1) items.
805  */
806 static int
807 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
808 {
809 	char **pathv;
810 	size_t i, newsize, len;
811 	char *copy;
812 	const Char *p;
813 
814 	if ((pglob->gl_flags & GLOB_LIMIT) &&
815 	    pglob->gl_matchc > limit->l_path_lim) {
816 		errno = 0;
817 		return (GLOB_NOSPACE);
818 	}
819 
820 	newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
821 	/* realloc(NULL, newsize) is equivalent to malloc(newsize). */
822 	pathv = realloc((void *)pglob->gl_pathv, newsize);
823 	if (pathv == NULL)
824 		return (GLOB_NOSPACE);
825 
826 	if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
827 		/* first time around -- clear initial gl_offs items */
828 		pathv += pglob->gl_offs;
829 		for (i = pglob->gl_offs + 1; --i > 0; )
830 			*--pathv = NULL;
831 	}
832 	pglob->gl_pathv = pathv;
833 
834 	for (p = path; *p++;)
835 		continue;
836 	len = MB_CUR_MAX * (size_t)(p - path);	/* XXX overallocation */
837 	limit->l_string_cnt += len;
838 	if ((pglob->gl_flags & GLOB_LIMIT) &&
839 	    limit->l_string_cnt >= GLOB_LIMIT_STRING) {
840 		errno = 0;
841 		return (GLOB_NOSPACE);
842 	}
843 	if ((copy = malloc(len)) != NULL) {
844 		if (g_Ctoc(path, copy, len)) {
845 			free(copy);
846 			errno = 0;
847 			return (GLOB_NOSPACE);
848 		}
849 		pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
850 	}
851 	pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
852 	return (copy == NULL ? GLOB_NOSPACE : 0);
853 }
854 
855 /*
856  * pattern matching function for filenames.  Each occurrence of the *
857  * pattern causes a recursion level.
858  */
859 static int
860 match(Char *name, Char *pat, Char *patend)
861 {
862 	int ok, negate_range;
863 	Char c, k;
864 	struct xlocale_collate *table =
865 		(struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
866 
867 	while (pat < patend) {
868 		c = *pat++;
869 		switch (c & M_MASK) {
870 		case M_ALL:
871 			if (pat == patend)
872 				return (1);
873 			do
874 			    if (match(name, pat, patend))
875 				    return (1);
876 			while (*name++ != EOS);
877 			return (0);
878 		case M_ONE:
879 			if (*name++ == EOS)
880 				return (0);
881 			break;
882 		case M_SET:
883 			ok = 0;
884 			if ((k = *name++) == EOS)
885 				return (0);
886 			if ((negate_range = ((*pat & M_MASK) == M_NOT)) != 0)
887 				++pat;
888 			while (((c = *pat++) & M_MASK) != M_END)
889 				if ((*pat & M_MASK) == M_RNG) {
890 					if (table->__collate_load_error ?
891 					    CHAR(c) <= CHAR(k) &&
892 					    CHAR(k) <= CHAR(pat[1]) :
893 					    __wcollate_range_cmp(CHAR(c),
894 					    CHAR(k)) <= 0 &&
895 					    __wcollate_range_cmp(CHAR(k),
896 					    CHAR(pat[1])) <= 0)
897 						ok = 1;
898 					pat += 2;
899 				} else if (c == k)
900 					ok = 1;
901 			if (ok == negate_range)
902 				return (0);
903 			break;
904 		default:
905 			if (*name++ != c)
906 				return (0);
907 			break;
908 		}
909 	}
910 	return (*name == EOS);
911 }
912 
913 /* Free allocated data belonging to a glob_t structure. */
914 void
915 globfree(glob_t *pglob)
916 {
917 	size_t i;
918 	char **pp;
919 
920 	if (pglob->gl_pathv != NULL) {
921 		pp = pglob->gl_pathv + pglob->gl_offs;
922 		for (i = pglob->gl_pathc; i--; ++pp)
923 			if (*pp)
924 				free(*pp);
925 		free(pglob->gl_pathv);
926 		pglob->gl_pathv = NULL;
927 	}
928 }
929 
930 static DIR *
931 g_opendir(Char *str, glob_t *pglob)
932 {
933 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
934 
935 	if (*str == EOS)
936 		strcpy(buf, ".");
937 	else {
938 		if (g_Ctoc(str, buf, sizeof(buf))) {
939 			errno = ENAMETOOLONG;
940 			return (NULL);
941 		}
942 	}
943 
944 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
945 		return ((*pglob->gl_opendir)(buf));
946 
947 	return (opendir(buf));
948 }
949 
950 static int
951 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
952 {
953 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
954 
955 	if (g_Ctoc(fn, buf, sizeof(buf))) {
956 		errno = ENAMETOOLONG;
957 		return (-1);
958 	}
959 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
960 		return((*pglob->gl_lstat)(buf, sb));
961 	return (lstat(buf, sb));
962 }
963 
964 static int
965 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
966 {
967 	char buf[MAXPATHLEN + MB_LEN_MAX - 1];
968 
969 	if (g_Ctoc(fn, buf, sizeof(buf))) {
970 		errno = ENAMETOOLONG;
971 		return (-1);
972 	}
973 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
974 		return ((*pglob->gl_stat)(buf, sb));
975 	return (stat(buf, sb));
976 }
977 
978 static const Char *
979 g_strchr(const Char *str, wchar_t ch)
980 {
981 
982 	do {
983 		if (*str == ch)
984 			return (str);
985 	} while (*str++);
986 	return (NULL);
987 }
988 
989 static int
990 g_Ctoc(const Char *str, char *buf, size_t len)
991 {
992 	mbstate_t mbs;
993 	size_t clen;
994 
995 	memset(&mbs, 0, sizeof(mbs));
996 	while (len >= MB_CUR_MAX) {
997 		clen = wcrtomb(buf, CHAR(*str), &mbs);
998 		if (clen == (size_t)-1) {
999 			/* XXX See initial comment #2. */
1000 			*buf = (char)CHAR(*str);
1001 			clen = 1;
1002 			memset(&mbs, 0, sizeof(mbs));
1003 		}
1004 		if (CHAR(*str) == EOS)
1005 			return (0);
1006 		str++;
1007 		buf += clen;
1008 		len -= clen;
1009 	}
1010 	return (1);
1011 }
1012 
1013 #ifdef DEBUG
1014 static void
1015 qprintf(const char *str, Char *s)
1016 {
1017 	Char *p;
1018 
1019 	(void)printf("%s:\n", str);
1020 	for (p = s; *p; p++)
1021 		(void)printf("%c", CHAR(*p));
1022 	(void)printf("\n");
1023 	for (p = s; *p; p++)
1024 		(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
1025 	(void)printf("\n");
1026 	for (p = s; *p; p++)
1027 		(void)printf("%c", ismeta(*p) ? '_' : ' ');
1028 	(void)printf("\n");
1029 }
1030 #endif
1031