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