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