xref: /freebsd/lib/libc/gen/glob.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
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 value of the first byte 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 #define	DOLLAR		'$'
98 #define	DOT		'.'
99 #define	EOS		'\0'
100 #define	LBRACKET	'['
101 #define	NOT		'!'
102 #define	QUESTION	'?'
103 #define	QUOTE		'\\'
104 #define	RANGE		'-'
105 #define	RBRACKET	']'
106 #define	SEP		'/'
107 #define	STAR		'*'
108 #define	TILDE		'~'
109 #define	UNDERSCORE	'_'
110 #define	LBRACE		'{'
111 #define	RBRACE		'}'
112 #define	SLASH		'/'
113 #define	COMMA		','
114 
115 #ifndef DEBUG
116 
117 #define	M_QUOTE		0x8000000000ULL
118 #define	M_PROTECT	0x4000000000ULL
119 #define	M_MASK		0xffffffffffULL
120 #define	M_CHAR		0x00ffffffffULL
121 
122 typedef uint_fast64_t Char;
123 
124 #else
125 
126 #define	M_QUOTE		0x80
127 #define	M_PROTECT	0x40
128 #define	M_MASK		0xff
129 #define	M_CHAR		0x7f
130 
131 typedef char Char;
132 
133 #endif
134 
135 
136 #define	CHAR(c)		((Char)((c)&M_CHAR))
137 #define	META(c)		((Char)((c)|M_QUOTE))
138 #define	M_ALL		META('*')
139 #define	M_END		META(']')
140 #define	M_NOT		META('!')
141 #define	M_ONE		META('?')
142 #define	M_RNG		META('-')
143 #define	M_SET		META('[')
144 #define	ismeta(c)	(((c)&M_QUOTE) != 0)
145 
146 
147 static int	 compare(const void *, const void *);
148 static int	 g_Ctoc(const Char *, char *, size_t);
149 static int	 g_lstat(Char *, struct stat *, glob_t *);
150 static DIR	*g_opendir(Char *, glob_t *);
151 static const Char *g_strchr(const Char *, wchar_t);
152 #ifdef notdef
153 static Char	*g_strcat(Char *, const Char *);
154 #endif
155 static int	 g_stat(Char *, struct stat *, glob_t *);
156 static int	 glob0(const Char *, glob_t *, size_t *);
157 static int	 glob1(Char *, glob_t *, size_t *);
158 static int	 glob2(Char *, Char *, Char *, Char *, glob_t *, size_t *);
159 static int	 glob3(Char *, Char *, Char *, Char *, Char *, glob_t *, size_t *);
160 static int	 globextend(const Char *, glob_t *, size_t *);
161 static const Char *
162 		 globtilde(const Char *, Char *, size_t, glob_t *);
163 static int	 globexp1(const Char *, glob_t *, size_t *);
164 static int	 globexp2(const Char *, const Char *, glob_t *, int *, size_t *);
165 static int	 match(Char *, Char *, Char *);
166 #ifdef DEBUG
167 static void	 qprintf(const char *, Char *);
168 #endif
169 
170 int
171 glob(const char * __restrict pattern, int flags,
172 	 int (*errfunc)(const char *, int), glob_t * __restrict pglob)
173 {
174 	const char *patnext;
175 	size_t limit;
176 	Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
177 	mbstate_t mbs;
178 	wchar_t wc;
179 	size_t clen;
180 
181 	patnext = pattern;
182 	if (!(flags & GLOB_APPEND)) {
183 		pglob->gl_pathc = 0;
184 		pglob->gl_pathv = NULL;
185 		if (!(flags & GLOB_DOOFFS))
186 			pglob->gl_offs = 0;
187 	}
188 	if (flags & GLOB_LIMIT) {
189 		limit = pglob->gl_matchc;
190 		if (limit == 0)
191 			limit = ARG_MAX;
192 	} else
193 		limit = 0;
194 	pglob->gl_flags = flags & ~GLOB_MAGCHAR;
195 	pglob->gl_errfunc = errfunc;
196 	pglob->gl_matchc = 0;
197 
198 	bufnext = patbuf;
199 	bufend = bufnext + MAXPATHLEN - 1;
200 	if (flags & GLOB_NOESCAPE) {
201 		memset(&mbs, 0, sizeof(mbs));
202 		while (bufend - bufnext >= MB_CUR_MAX) {
203 			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
204 			if (clen == (size_t)-1 || clen == (size_t)-2)
205 				return (GLOB_NOMATCH);
206 			else if (clen == 0)
207 				break;
208 			*bufnext++ = wc;
209 			patnext += clen;
210 		}
211 	} else {
212 		/* Protect the quoted characters. */
213 		memset(&mbs, 0, sizeof(mbs));
214 		while (bufend - bufnext >= MB_CUR_MAX) {
215 			if (*patnext == QUOTE) {
216 				if (*++patnext == EOS) {
217 					*bufnext++ = QUOTE | M_PROTECT;
218 					continue;
219 				}
220 				prot = M_PROTECT;
221 			} else
222 				prot = 0;
223 			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
224 			if (clen == (size_t)-1 || clen == (size_t)-2)
225 				return (GLOB_NOMATCH);
226 			else if (clen == 0)
227 				break;
228 			*bufnext++ = wc | prot;
229 			patnext += clen;
230 		}
231 	}
232 	*bufnext = EOS;
233 
234 	if (flags & GLOB_BRACE)
235 	    return (globexp1(patbuf, pglob, &limit));
236 	else
237 	    return (glob0(patbuf, pglob, &limit));
238 }
239 
240 /*
241  * Expand recursively a glob {} pattern. When there is no more expansion
242  * invoke the standard globbing routine to glob the rest of the magic
243  * characters
244  */
245 static int
246 globexp1(const Char *pattern, glob_t *pglob, size_t *limit)
247 {
248 	const Char* ptr = pattern;
249 	int rv;
250 
251 	/* Protect a single {}, for find(1), like csh */
252 	if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
253 		return glob0(pattern, pglob, limit);
254 
255 	while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
256 		if (!globexp2(ptr, pattern, pglob, &rv, limit))
257 			return rv;
258 
259 	return glob0(pattern, pglob, limit);
260 }
261 
262 
263 /*
264  * Recursive brace globbing helper. Tries to expand a single brace.
265  * If it succeeds then it invokes globexp1 with the new pattern.
266  * If it fails then it tries to glob the rest of the pattern and returns.
267  */
268 static int
269 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv, size_t *limit)
270 {
271 	int     i;
272 	Char   *lm, *ls;
273 	const Char *pe, *pm, *pm1, *pl;
274 	Char    patbuf[MAXPATHLEN];
275 
276 	/* copy part up to the brace */
277 	for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
278 		continue;
279 	*lm = EOS;
280 	ls = lm;
281 
282 	/* Find the balanced brace */
283 	for (i = 0, pe = ++ptr; *pe; pe++)
284 		if (*pe == LBRACKET) {
285 			/* Ignore everything between [] */
286 			for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
287 				continue;
288 			if (*pe == EOS) {
289 				/*
290 				 * We could not find a matching RBRACKET.
291 				 * Ignore and just look for RBRACE
292 				 */
293 				pe = pm;
294 			}
295 		}
296 		else if (*pe == LBRACE)
297 			i++;
298 		else if (*pe == RBRACE) {
299 			if (i == 0)
300 				break;
301 			i--;
302 		}
303 
304 	/* Non matching braces; just glob the pattern */
305 	if (i != 0 || *pe == EOS) {
306 		*rv = glob0(patbuf, pglob, limit);
307 		return (0);
308 	}
309 
310 	for (i = 0, pl = pm = ptr; pm <= pe; pm++)
311 		switch (*pm) {
312 		case LBRACKET:
313 			/* Ignore everything between [] */
314 			for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
315 				continue;
316 			if (*pm == EOS) {
317 				/*
318 				 * We could not find a matching RBRACKET.
319 				 * Ignore and just look for RBRACE
320 				 */
321 				pm = pm1;
322 			}
323 			break;
324 
325 		case LBRACE:
326 			i++;
327 			break;
328 
329 		case RBRACE:
330 			if (i) {
331 			    i--;
332 			    break;
333 			}
334 			/* FALLTHROUGH */
335 		case COMMA:
336 			if (i && *pm == COMMA)
337 				break;
338 			else {
339 				/* Append the current string */
340 				for (lm = ls; (pl < pm); *lm++ = *pl++)
341 					continue;
342 				/*
343 				 * Append the rest of the pattern after the
344 				 * closing brace
345 				 */
346 				for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
347 					continue;
348 
349 				/* Expand the current pattern */
350 #ifdef DEBUG
351 				qprintf("globexp2:", patbuf);
352 #endif
353 				*rv = globexp1(patbuf, pglob, limit);
354 
355 				/* move after the comma, to the next string */
356 				pl = pm + 1;
357 			}
358 			break;
359 
360 		default:
361 			break;
362 		}
363 	*rv = 0;
364 	return (0);
365 }
366 
367 
368 
369 /*
370  * expand tilde from the passwd file.
371  */
372 static const Char *
373 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
374 {
375 	struct passwd *pwd;
376 	char *h;
377 	const Char *p;
378 	Char *b, *eb;
379 
380 	if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
381 		return (pattern);
382 
383 	/*
384 	 * Copy up to the end of the string or /
385 	 */
386 	eb = &patbuf[patbuf_len - 1];
387 	for (p = pattern + 1, h = (char *) patbuf;
388 	    h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
389 		continue;
390 
391 	*h = EOS;
392 
393 	if (((char *) patbuf)[0] == EOS) {
394 		/*
395 		 * handle a plain ~ or ~/ by expanding $HOME first (iff
396 		 * we're not running setuid or setgid) and then trying
397 		 * the password file
398 		 */
399 		if (issetugid() != 0 ||
400 		    (h = getenv("HOME")) == NULL) {
401 			if (((h = getlogin()) != NULL &&
402 			     (pwd = getpwnam(h)) != NULL) ||
403 			    (pwd = getpwuid(getuid())) != NULL)
404 				h = pwd->pw_dir;
405 			else
406 				return (pattern);
407 		}
408 	}
409 	else {
410 		/*
411 		 * Expand a ~user
412 		 */
413 		if ((pwd = getpwnam((char*) patbuf)) == NULL)
414 			return (pattern);
415 		else
416 			h = pwd->pw_dir;
417 	}
418 
419 	/* Copy the home directory */
420 	for (b = patbuf; b < eb && *h; *b++ = *h++)
421 		continue;
422 
423 	/* Append the rest of the pattern */
424 	while (b < eb && (*b++ = *p++) != EOS)
425 		continue;
426 	*b = EOS;
427 
428 	return (patbuf);
429 }
430 
431 
432 /*
433  * The main glob() routine: compiles the pattern (optionally processing
434  * quotes), calls glob1() to do the real pattern matching, and finally
435  * sorts the list (unless unsorted operation is requested).  Returns 0
436  * if things went well, nonzero if errors occurred.
437  */
438 static int
439 glob0(const Char *pattern, glob_t *pglob, size_t *limit)
440 {
441 	const Char *qpatnext;
442 	int err;
443 	size_t oldpathc;
444 	Char *bufnext, c, patbuf[MAXPATHLEN];
445 
446 	qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
447 	oldpathc = pglob->gl_pathc;
448 	bufnext = patbuf;
449 
450 	/* We don't need to check for buffer overflow any more. */
451 	while ((c = *qpatnext++) != EOS) {
452 		switch (c) {
453 		case LBRACKET:
454 			c = *qpatnext;
455 			if (c == NOT)
456 				++qpatnext;
457 			if (*qpatnext == EOS ||
458 			    g_strchr(qpatnext+1, RBRACKET) == NULL) {
459 				*bufnext++ = LBRACKET;
460 				if (c == NOT)
461 					--qpatnext;
462 				break;
463 			}
464 			*bufnext++ = M_SET;
465 			if (c == NOT)
466 				*bufnext++ = M_NOT;
467 			c = *qpatnext++;
468 			do {
469 				*bufnext++ = CHAR(c);
470 				if (*qpatnext == RANGE &&
471 				    (c = qpatnext[1]) != RBRACKET) {
472 					*bufnext++ = M_RNG;
473 					*bufnext++ = CHAR(c);
474 					qpatnext += 2;
475 				}
476 			} while ((c = *qpatnext++) != RBRACKET);
477 			pglob->gl_flags |= GLOB_MAGCHAR;
478 			*bufnext++ = M_END;
479 			break;
480 		case QUESTION:
481 			pglob->gl_flags |= GLOB_MAGCHAR;
482 			*bufnext++ = M_ONE;
483 			break;
484 		case STAR:
485 			pglob->gl_flags |= GLOB_MAGCHAR;
486 			/* collapse adjacent stars to one,
487 			 * to avoid exponential behavior
488 			 */
489 			if (bufnext == patbuf || bufnext[-1] != M_ALL)
490 			    *bufnext++ = M_ALL;
491 			break;
492 		default:
493 			*bufnext++ = CHAR(c);
494 			break;
495 		}
496 	}
497 	*bufnext = EOS;
498 #ifdef DEBUG
499 	qprintf("glob0:", patbuf);
500 #endif
501 
502 	if ((err = glob1(patbuf, pglob, limit)) != 0)
503 		return(err);
504 
505 	/*
506 	 * If there was no match we are going to append the pattern
507 	 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
508 	 * and the pattern did not contain any magic characters
509 	 * GLOB_NOMAGIC is there just for compatibility with csh.
510 	 */
511 	if (pglob->gl_pathc == oldpathc) {
512 		if (((pglob->gl_flags & GLOB_NOCHECK) ||
513 		    ((pglob->gl_flags & GLOB_NOMAGIC) &&
514 			!(pglob->gl_flags & GLOB_MAGCHAR))))
515 			return (globextend(pattern, pglob, limit));
516 		else
517 			return (GLOB_NOMATCH);
518 	}
519 	if (!(pglob->gl_flags & GLOB_NOSORT))
520 		qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
521 		    pglob->gl_pathc - oldpathc, sizeof(char *), compare);
522 	return (0);
523 }
524 
525 static int
526 compare(const void *p, const void *q)
527 {
528 	return (strcmp(*(char **)p, *(char **)q));
529 }
530 
531 static int
532 glob1(Char *pattern, glob_t *pglob, size_t *limit)
533 {
534 	Char pathbuf[MAXPATHLEN];
535 
536 	/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
537 	if (*pattern == EOS)
538 		return (0);
539 	return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
540 	    pattern, pglob, limit));
541 }
542 
543 /*
544  * The functions glob2 and glob3 are mutually recursive; there is one level
545  * of recursion for each segment in the pattern that contains one or more
546  * meta characters.
547  */
548 static int
549 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
550       glob_t *pglob, size_t *limit)
551 {
552 	struct stat sb;
553 	Char *p, *q;
554 	int anymeta;
555 
556 	/*
557 	 * Loop over pattern segments until end of pattern or until
558 	 * segment with meta character found.
559 	 */
560 	for (anymeta = 0;;) {
561 		if (*pattern == EOS) {		/* End of pattern? */
562 			*pathend = EOS;
563 			if (g_lstat(pathbuf, &sb, pglob))
564 				return (0);
565 
566 			if (((pglob->gl_flags & GLOB_MARK) &&
567 			    pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
568 			    || (S_ISLNK(sb.st_mode) &&
569 			    (g_stat(pathbuf, &sb, pglob) == 0) &&
570 			    S_ISDIR(sb.st_mode)))) {
571 				if (pathend + 1 > pathend_last)
572 					return (GLOB_ABORTED);
573 				*pathend++ = SEP;
574 				*pathend = EOS;
575 			}
576 			++pglob->gl_matchc;
577 			return (globextend(pathbuf, pglob, limit));
578 		}
579 
580 		/* Find end of next segment, copy tentatively to pathend. */
581 		q = pathend;
582 		p = pattern;
583 		while (*p != EOS && *p != SEP) {
584 			if (ismeta(*p))
585 				anymeta = 1;
586 			if (q + 1 > pathend_last)
587 				return (GLOB_ABORTED);
588 			*q++ = *p++;
589 		}
590 
591 		if (!anymeta) {		/* No expansion, do next segment. */
592 			pathend = q;
593 			pattern = p;
594 			while (*pattern == SEP) {
595 				if (pathend + 1 > pathend_last)
596 					return (GLOB_ABORTED);
597 				*pathend++ = *pattern++;
598 			}
599 		} else			/* Need expansion, recurse. */
600 			return (glob3(pathbuf, pathend, pathend_last, pattern,
601 			    p, pglob, limit));
602 	}
603 	/* NOTREACHED */
604 }
605 
606 static int
607 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
608       Char *pattern, Char *restpattern,
609       glob_t *pglob, size_t *limit)
610 {
611 	struct dirent *dp;
612 	DIR *dirp;
613 	int err;
614 	char buf[MAXPATHLEN];
615 
616 	/*
617 	 * The readdirfunc declaration can't be prototyped, because it is
618 	 * assigned, below, to two functions which are prototyped in glob.h
619 	 * and dirent.h as taking pointers to differently typed opaque
620 	 * structures.
621 	 */
622 	struct dirent *(*readdirfunc)();
623 
624 	if (pathend > pathend_last)
625 		return (GLOB_ABORTED);
626 	*pathend = EOS;
627 	errno = 0;
628 
629 	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
630 		/* TODO: don't call for ENOENT or ENOTDIR? */
631 		if (pglob->gl_errfunc) {
632 			if (g_Ctoc(pathbuf, buf, sizeof(buf)))
633 				return (GLOB_ABORTED);
634 			if (pglob->gl_errfunc(buf, errno) ||
635 			    pglob->gl_flags & GLOB_ERR)
636 				return (GLOB_ABORTED);
637 		}
638 		return (0);
639 	}
640 
641 	err = 0;
642 
643 	/* Search directory for matching names. */
644 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
645 		readdirfunc = pglob->gl_readdir;
646 	else
647 		readdirfunc = readdir;
648 	while ((dp = (*readdirfunc)(dirp))) {
649 		char *sc;
650 		Char *dc;
651 		wchar_t wc;
652 		size_t clen;
653 		mbstate_t mbs;
654 
655 		/* Initial DOT must be matched literally. */
656 		if (dp->d_name[0] == DOT && *pattern != DOT)
657 			continue;
658 		memset(&mbs, 0, sizeof(mbs));
659 		dc = pathend;
660 		sc = dp->d_name;
661 		while (dc < pathend_last) {
662 			clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
663 			if (clen == (size_t)-1 || clen == (size_t)-2) {
664 				wc = *sc;
665 				clen = 1;
666 				memset(&mbs, 0, sizeof(mbs));
667 			}
668 			if ((*dc++ = wc) == EOS)
669 				break;
670 			sc += clen;
671 		}
672 		if (!match(pathend, pattern, restpattern)) {
673 			*pathend = EOS;
674 			continue;
675 		}
676 		err = glob2(pathbuf, --dc, pathend_last, restpattern,
677 		    pglob, limit);
678 		if (err)
679 			break;
680 	}
681 
682 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
683 		(*pglob->gl_closedir)(dirp);
684 	else
685 		closedir(dirp);
686 	return (err);
687 }
688 
689 
690 /*
691  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
692  * add the new item, and update gl_pathc.
693  *
694  * This assumes the BSD realloc, which only copies the block when its size
695  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
696  * behavior.
697  *
698  * Return 0 if new item added, error code if memory couldn't be allocated.
699  *
700  * Invariant of the glob_t structure:
701  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
702  *	gl_pathv points to (gl_offs + gl_pathc + 1) items.
703  */
704 static int
705 globextend(const Char *path, glob_t *pglob, size_t *limit)
706 {
707 	char **pathv;
708 	size_t i, newsize, len;
709 	char *copy;
710 	const Char *p;
711 
712 	if (*limit && pglob->gl_pathc > *limit) {
713 		errno = 0;
714 		return (GLOB_NOSPACE);
715 	}
716 
717 	newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
718 	pathv = pglob->gl_pathv ?
719 		    realloc((char *)pglob->gl_pathv, newsize) :
720 		    malloc(newsize);
721 	if (pathv == NULL) {
722 		if (pglob->gl_pathv) {
723 			free(pglob->gl_pathv);
724 			pglob->gl_pathv = NULL;
725 		}
726 		return (GLOB_NOSPACE);
727 	}
728 
729 	if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
730 		/* first time around -- clear initial gl_offs items */
731 		pathv += pglob->gl_offs;
732 		for (i = pglob->gl_offs + 1; --i > 0; )
733 			*--pathv = NULL;
734 	}
735 	pglob->gl_pathv = pathv;
736 
737 	for (p = path; *p++;)
738 		continue;
739 	len = MB_CUR_MAX * (size_t)(p - path);	/* XXX overallocation */
740 	if ((copy = malloc(len)) != NULL) {
741 		if (g_Ctoc(path, copy, len)) {
742 			free(copy);
743 			return (GLOB_NOSPACE);
744 		}
745 		pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
746 	}
747 	pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
748 	return (copy == NULL ? GLOB_NOSPACE : 0);
749 }
750 
751 /*
752  * pattern matching function for filenames.  Each occurrence of the *
753  * pattern causes a recursion level.
754  */
755 static int
756 match(Char *name, Char *pat, Char *patend)
757 {
758 	int ok, negate_range;
759 	Char c, k;
760 	struct xlocale_collate *table =
761 		(struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
762 
763 	while (pat < patend) {
764 		c = *pat++;
765 		switch (c & M_MASK) {
766 		case M_ALL:
767 			if (pat == patend)
768 				return (1);
769 			do
770 			    if (match(name, pat, patend))
771 				    return (1);
772 			while (*name++ != EOS);
773 			return (0);
774 		case M_ONE:
775 			if (*name++ == EOS)
776 				return (0);
777 			break;
778 		case M_SET:
779 			ok = 0;
780 			if ((k = *name++) == EOS)
781 				return (0);
782 			if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
783 				++pat;
784 			while (((c = *pat++) & M_MASK) != M_END)
785 				if ((*pat & M_MASK) == M_RNG) {
786 					if (table->__collate_load_error ?
787 					    CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
788 					       __collate_range_cmp(table, CHAR(c), CHAR(k)) <= 0
789 					    && __collate_range_cmp(table, CHAR(k), CHAR(pat[1])) <= 0
790 					   )
791 						ok = 1;
792 					pat += 2;
793 				} else if (c == k)
794 					ok = 1;
795 			if (ok == negate_range)
796 				return (0);
797 			break;
798 		default:
799 			if (*name++ != c)
800 				return (0);
801 			break;
802 		}
803 	}
804 	return (*name == EOS);
805 }
806 
807 /* Free allocated data belonging to a glob_t structure. */
808 void
809 globfree(glob_t *pglob)
810 {
811 	size_t i;
812 	char **pp;
813 
814 	if (pglob->gl_pathv != NULL) {
815 		pp = pglob->gl_pathv + pglob->gl_offs;
816 		for (i = pglob->gl_pathc; i--; ++pp)
817 			if (*pp)
818 				free(*pp);
819 		free(pglob->gl_pathv);
820 		pglob->gl_pathv = NULL;
821 	}
822 }
823 
824 static DIR *
825 g_opendir(Char *str, glob_t *pglob)
826 {
827 	char buf[MAXPATHLEN];
828 
829 	if (!*str)
830 		strcpy(buf, ".");
831 	else {
832 		if (g_Ctoc(str, buf, sizeof(buf)))
833 			return (NULL);
834 	}
835 
836 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
837 		return ((*pglob->gl_opendir)(buf));
838 
839 	return (opendir(buf));
840 }
841 
842 static int
843 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
844 {
845 	char buf[MAXPATHLEN];
846 
847 	if (g_Ctoc(fn, buf, sizeof(buf))) {
848 		errno = ENAMETOOLONG;
849 		return (-1);
850 	}
851 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
852 		return((*pglob->gl_lstat)(buf, sb));
853 	return (lstat(buf, sb));
854 }
855 
856 static int
857 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
858 {
859 	char buf[MAXPATHLEN];
860 
861 	if (g_Ctoc(fn, buf, sizeof(buf))) {
862 		errno = ENAMETOOLONG;
863 		return (-1);
864 	}
865 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
866 		return ((*pglob->gl_stat)(buf, sb));
867 	return (stat(buf, sb));
868 }
869 
870 static const Char *
871 g_strchr(const Char *str, wchar_t ch)
872 {
873 
874 	do {
875 		if (*str == ch)
876 			return (str);
877 	} while (*str++);
878 	return (NULL);
879 }
880 
881 static int
882 g_Ctoc(const Char *str, char *buf, size_t len)
883 {
884 	mbstate_t mbs;
885 	size_t clen;
886 
887 	memset(&mbs, 0, sizeof(mbs));
888 	while (len >= MB_CUR_MAX) {
889 		clen = wcrtomb(buf, *str, &mbs);
890 		if (clen == (size_t)-1)
891 			return (1);
892 		if (*str == L'\0')
893 			return (0);
894 		str++;
895 		buf += clen;
896 		len -= clen;
897 	}
898 	return (1);
899 }
900 
901 #ifdef DEBUG
902 static void
903 qprintf(const char *str, Char *s)
904 {
905 	Char *p;
906 
907 	(void)printf("%s:\n", str);
908 	for (p = s; *p; p++)
909 		(void)printf("%c", CHAR(*p));
910 	(void)printf("\n");
911 	for (p = s; *p; p++)
912 		(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
913 	(void)printf("\n");
914 	for (p = s; *p; p++)
915 		(void)printf("%c", ismeta(*p) ? '_' : ' ');
916 	(void)printf("\n");
917 }
918 #endif
919