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