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