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