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