xref: /netbsd-src/lib/libc/gen/glob.c (revision 00f5cbb6dce52e8e676c44c053a30aaf50e10cee)
1 /*	$NetBSD: glob.c,v 1.20 2008/01/18 16:20:00 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.20 2008/01/18 16:20:00 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                 /*
629 		 * No expansion, or path ends in dot-slash or dot-dot-slash,
630 		 * do next segment.
631 		 */
632                  if ((!anymeta) ||
633 		     (((pathend-pathbuf) > 1) &&
634 		      (((*(pathend-1) == SEP) && (*(pathend-2) == DOT)) &&
635 		        ((((pathend-pathbuf) < 3) || (*(pathend-3) == SEP)) ||
636 		         (((pathend-pathbuf) < 4) ||
637 		         ((*(pathend-3) == DOT) && (*(pathend-4) == SEP))))))) {
638 			pathend = q;
639 			pattern = p;
640 			while (*pattern == SEP) {
641 				if (pathend >= pathlim)
642 					return GLOB_ABORTED;
643 				*pathend++ = *pattern++;
644 			}
645 		} else			/* Need expansion, recurse. */
646 			return glob3(pathbuf, pathend, pathlim, pattern, p,
647 			    pglob, limit);
648 	}
649 	/* NOTREACHED */
650 }
651 
652 static int
653 glob3(Char *pathbuf, Char *pathend, Char *pathlim, Char *pattern,
654     Char *restpattern, glob_t *pglob, size_t *limit)
655 {
656 	struct dirent *dp;
657 	DIR *dirp;
658 	int error;
659 	char buf[MAXPATHLEN];
660 
661 	/*
662 	 * The readdirfunc declaration can't be prototyped, because it is
663 	 * assigned, below, to two functions which are prototyped in glob.h
664 	 * and dirent.h as taking pointers to differently typed opaque
665 	 * structures.
666 	 */
667 	struct dirent *(*readdirfunc)(void *);
668 
669 	_DIAGASSERT(pathbuf != NULL);
670 	_DIAGASSERT(pathend != NULL);
671 	_DIAGASSERT(pattern != NULL);
672 	_DIAGASSERT(restpattern != NULL);
673 	_DIAGASSERT(pglob != NULL);
674 
675 	*pathend = EOS;
676 	errno = 0;
677 
678 	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
679 		if (pglob->gl_errfunc) {
680 			if (g_Ctoc(pathbuf, buf, sizeof(buf)))
681 				return GLOB_ABORTED;
682 			if (pglob->gl_errfunc(buf, errno) ||
683 			    pglob->gl_flags & GLOB_ERR)
684 				return GLOB_ABORTED;
685 		}
686 		/*
687 		 * Posix/XOpen: glob should return when it encounters a
688 		 * directory that it cannot open or read
689 		 * XXX: Should we ignore ENOTDIR and ENOENT though?
690 		 * I think that Posix had in mind EPERM...
691 		 */
692 		if (pglob->gl_flags & GLOB_ERR)
693 			return GLOB_ABORTED;
694 
695 		return 0;
696 	}
697 
698 	error = 0;
699 
700 	/* Search directory for matching names. */
701 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
702 		readdirfunc = pglob->gl_readdir;
703 	else
704 		readdirfunc = (struct dirent *(*)__P((void *))) readdir;
705 	while ((dp = (*readdirfunc)(dirp)) != NULL) {
706 		u_char *sc;
707 		Char *dc;
708 
709 		/*
710 		 * Initial DOT must be matched literally, unless we have
711 		 * GLOB_PERIOD set.
712 		 */
713 		if ((pglob->gl_flags & GLOB_PERIOD) == 0)
714 			if (dp->d_name[0] == DOT && *pattern != DOT)
715 				continue;
716 		/*
717 		 * The resulting string contains EOS, so we can
718 		 * use the pathlim character, if it is the nul
719 		 */
720 		for (sc = (u_char *) dp->d_name, dc = pathend;
721 		     dc <= pathlim && (*dc++ = *sc++) != EOS;)
722 			continue;
723 
724 		/*
725 		 * Have we filled the buffer without seeing EOS?
726 		 */
727 		if (dc > pathlim && *pathlim != EOS) {
728 			/*
729 			 * Abort when requested by caller, otherwise
730 			 * reset pathend back to last SEP and continue
731 			 * with next dir entry.
732 			 */
733 			if (pglob->gl_flags & GLOB_ERR) {
734 				error = GLOB_ABORTED;
735 				break;
736 			}
737 			else {
738 				*pathend = EOS;
739 				continue;
740 			}
741 		}
742 
743 		if (!match(pathend, pattern, restpattern)) {
744 			*pathend = EOS;
745 			continue;
746 		}
747 		error = glob2(pathbuf, --dc, pathlim, restpattern, pglob, limit);
748 		if (error)
749 			break;
750 	}
751 
752 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
753 		(*pglob->gl_closedir)(dirp);
754 	else
755 		closedir(dirp);
756 
757 	/*
758 	 * Again Posix X/Open issue with regards to error handling.
759 	 */
760 	if ((error || errno) && (pglob->gl_flags & GLOB_ERR))
761 		return GLOB_ABORTED;
762 
763 	return error;
764 }
765 
766 
767 /*
768  * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
769  * add the new item, and update gl_pathc.
770  *
771  * This assumes the BSD realloc, which only copies the block when its size
772  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
773  * behavior.
774  *
775  * Return 0 if new item added, error code if memory couldn't be allocated.
776  *
777  * Invariant of the glob_t structure:
778  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
779  *	gl_pathv points to (gl_offs + gl_pathc + 1) items.
780  */
781 static int
782 globextend(const Char *path, glob_t *pglob, size_t *limit)
783 {
784 	char **pathv;
785 	size_t i, newsize, len;
786 	char *copy;
787 	const Char *p;
788 
789 	_DIAGASSERT(path != NULL);
790 	_DIAGASSERT(pglob != NULL);
791 
792 	newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
793 	pathv = pglob->gl_pathv ? realloc(pglob->gl_pathv, newsize) :
794 	    malloc(newsize);
795 	if (pathv == NULL)
796 		return GLOB_NOSPACE;
797 
798 	if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
799 		/* first time around -- clear initial gl_offs items */
800 		pathv += pglob->gl_offs;
801 		for (i = pglob->gl_offs + 1; --i > 0; )
802 			*--pathv = NULL;
803 	}
804 	pglob->gl_pathv = pathv;
805 
806 	for (p = path; *p++;)
807 		continue;
808 	len = (size_t)(p - path);
809 	*limit += len;
810 	if ((copy = malloc(len)) != NULL) {
811 		if (g_Ctoc(path, copy, len)) {
812 			free(copy);
813 			return GLOB_ABORTED;
814 		}
815 		pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
816 	}
817 	pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
818 
819 	if ((pglob->gl_flags & GLOB_LIMIT) && (newsize + *limit) >= ARG_MAX) {
820 		errno = 0;
821 		return GLOB_NOSPACE;
822 	}
823 
824 	return copy == NULL ? GLOB_NOSPACE : 0;
825 }
826 
827 
828 /*
829  * pattern matching function for filenames.  Each occurrence of the *
830  * pattern causes a recursion level.
831  */
832 static int
833 match(Char *name, Char *pat, Char *patend)
834 {
835 	int ok, negate_range;
836 	Char c, k;
837 
838 	_DIAGASSERT(name != NULL);
839 	_DIAGASSERT(pat != NULL);
840 	_DIAGASSERT(patend != NULL);
841 
842 	while (pat < patend) {
843 		c = *pat++;
844 		switch (c & M_MASK) {
845 		case M_ALL:
846 			if (pat == patend)
847 				return 1;
848 			do
849 			    if (match(name, pat, patend))
850 				    return 1;
851 			while (*name++ != EOS);
852 			return 0;
853 		case M_ONE:
854 			if (*name++ == EOS)
855 				return 0;
856 			break;
857 		case M_SET:
858 			ok = 0;
859 			if ((k = *name++) == EOS)
860 				return 0;
861 			if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
862 				++pat;
863 			while (((c = *pat++) & M_MASK) != M_END)
864 				if ((*pat & M_MASK) == M_RNG) {
865 					if (c <= k && k <= pat[1])
866 						ok = 1;
867 					pat += 2;
868 				} else if (c == k)
869 					ok = 1;
870 			if (ok == negate_range)
871 				return 0;
872 			break;
873 		default:
874 			if (*name++ != c)
875 				return 0;
876 			break;
877 		}
878 	}
879 	return *name == EOS;
880 }
881 
882 /* Free allocated data belonging to a glob_t structure. */
883 void
884 globfree(glob_t *pglob)
885 {
886 	size_t i;
887 	char **pp;
888 
889 	_DIAGASSERT(pglob != NULL);
890 
891 	if (pglob->gl_pathv != NULL) {
892 		pp = pglob->gl_pathv + pglob->gl_offs;
893 		for (i = pglob->gl_pathc; i--; ++pp)
894 			if (*pp)
895 				free(*pp);
896 		free(pglob->gl_pathv);
897 		pglob->gl_pathv = NULL;
898 		pglob->gl_pathc = 0;
899 	}
900 }
901 
902 static DIR *
903 g_opendir(Char *str, glob_t *pglob)
904 {
905 	char buf[MAXPATHLEN];
906 
907 	_DIAGASSERT(str != NULL);
908 	_DIAGASSERT(pglob != NULL);
909 
910 	if (!*str)
911 		(void)strlcpy(buf, ".", sizeof(buf));
912 	else {
913 		if (g_Ctoc(str, buf, sizeof(buf)))
914 			return NULL;
915 	}
916 
917 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
918 		return (*pglob->gl_opendir)(buf);
919 
920 	return opendir(buf);
921 }
922 
923 static int
924 g_lstat(Char *fn, __gl_stat_t *sb, glob_t *pglob)
925 {
926 	char buf[MAXPATHLEN];
927 
928 	_DIAGASSERT(fn != NULL);
929 	_DIAGASSERT(sb != NULL);
930 	_DIAGASSERT(pglob != NULL);
931 
932 	if (g_Ctoc(fn, buf, sizeof(buf)))
933 		return -1;
934 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
935 		return (*pglob->gl_lstat)(buf, sb);
936 	return lstat(buf, sb);
937 }
938 
939 static int
940 g_stat(Char *fn, __gl_stat_t *sb, glob_t *pglob)
941 {
942 	char buf[MAXPATHLEN];
943 
944 	_DIAGASSERT(fn != NULL);
945 	_DIAGASSERT(sb != NULL);
946 	_DIAGASSERT(pglob != NULL);
947 
948 	if (g_Ctoc(fn, buf, sizeof(buf)))
949 		return -1;
950 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
951 		return (*pglob->gl_stat)(buf, sb);
952 	return stat(buf, sb);
953 }
954 
955 static Char *
956 g_strchr(const Char *str, int ch)
957 {
958 
959 	_DIAGASSERT(str != NULL);
960 
961 	do {
962 		if (*str == ch)
963 			return __UNCONST(str);
964 	} while (*str++);
965 	return NULL;
966 }
967 
968 static int
969 g_Ctoc(const Char *str, char *buf, size_t len)
970 {
971 	char *dc;
972 
973 	_DIAGASSERT(str != NULL);
974 	_DIAGASSERT(buf != NULL);
975 
976 	if (len == 0)
977 		return 1;
978 
979 	for (dc = buf; len && (*dc++ = *str++) != EOS; len--)
980 		continue;
981 
982 	return len == 0;
983 }
984 
985 #ifdef DEBUG
986 static void
987 qprintf(const char *str, Char *s)
988 {
989 	Char *p;
990 
991 	_DIAGASSERT(str != NULL);
992 	_DIAGASSERT(s != NULL);
993 
994 	(void)printf("%s:\n", str);
995 	for (p = s; *p; p++)
996 		(void)printf("%c", CHAR(*p));
997 	(void)printf("\n");
998 	for (p = s; *p; p++)
999 		(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
1000 	(void)printf("\n");
1001 	for (p = s; *p; p++)
1002 		(void)printf("%c", ismeta(*p) ? '_' : ' ');
1003 	(void)printf("\n");
1004 }
1005 #endif
1006