xref: /openbsd/lib/libc/gen/glob.c (revision cca36db2)
1 /*	$OpenBSD: glob.c,v 1.39 2012/01/20 07:09:42 tedu 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/param.h>
60 #include <sys/stat.h>
61 
62 #include <ctype.h>
63 #include <dirent.h>
64 #include <errno.h>
65 #include <glob.h>
66 #include <limits.h>
67 #include <pwd.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[MAXPATHLEN];
176 	struct glob_lim limit = { 0, 0, 0 };
177 
178 	if (strnlen(pattern, PATH_MAX) == PATH_MAX)
179 		return(GLOB_NOMATCH);
180 
181 	patnext = (u_char *) pattern;
182 	if (!(flags & GLOB_APPEND)) {
183 		pglob->gl_pathc = 0;
184 		pglob->gl_pathv = NULL;
185 		pglob->gl_statv = NULL;
186 		if (!(flags & GLOB_DOOFFS))
187 			pglob->gl_offs = 0;
188 	}
189 	pglob->gl_flags = flags & ~GLOB_MAGCHAR;
190 	pglob->gl_errfunc = errfunc;
191 	pglob->gl_matchc = 0;
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 + MAXPATHLEN - 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[MAXPATHLEN];
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 *pwd;
358 	char *h;
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 			if ((pwd = getpwuid(getuid())) == NULL)
385 				return pattern;
386 			else
387 				h = pwd->pw_dir;
388 		}
389 	} else {
390 		/*
391 		 * Expand a ~user
392 		 */
393 		if ((pwd = getpwnam((char*) patbuf)) == NULL)
394 			return pattern;
395 		else
396 			h = pwd->pw_dir;
397 	}
398 
399 	/* Copy the home directory */
400 	for (b = patbuf; b < eb && *h; *b++ = *h++)
401 		;
402 
403 	/* Append the rest of the pattern */
404 	while (b < eb && (*b++ = *p++) != EOS)
405 		;
406 	*b = EOS;
407 
408 	return patbuf;
409 }
410 
411 static int
412 g_strncmp(const Char *s1, const char *s2, size_t n)
413 {
414 	int rv = 0;
415 
416 	while (n--) {
417 		rv = *(Char *)s1 - *(const unsigned char *)s2++;
418 		if (rv)
419 			break;
420 		if (*s1++ == '\0')
421 			break;
422 	}
423 	return rv;
424 }
425 
426 static int
427 g_charclass(const Char **patternp, Char **bufnextp)
428 {
429 	const Char *pattern = *patternp + 1;
430 	Char *bufnext = *bufnextp;
431 	const Char *colon;
432 	struct cclass *cc;
433 	size_t len;
434 
435 	if ((colon = g_strchr(pattern, ':')) == NULL || colon[1] != ']')
436 		return 1;	/* not a character class */
437 
438 	len = (size_t)(colon - pattern);
439 	for (cc = cclasses; cc->name != NULL; cc++) {
440 		if (!g_strncmp(pattern, cc->name, len) && cc->name[len] == '\0')
441 			break;
442 	}
443 	if (cc->name == NULL)
444 		return -1;	/* invalid character class */
445 	*bufnext++ = M_CLASS;
446 	*bufnext++ = (Char)(cc - &cclasses[0]);
447 	*bufnextp = bufnext;
448 	*patternp += len + 3;
449 
450 	return 0;
451 }
452 
453 /*
454  * The main glob() routine: compiles the pattern (optionally processing
455  * quotes), calls glob1() to do the real pattern matching, and finally
456  * sorts the list (unless unsorted operation is requested).  Returns 0
457  * if things went well, nonzero if errors occurred.  It is not an error
458  * to find no matches.
459  */
460 static int
461 glob0(const Char *pattern, glob_t *pglob, struct glob_lim *limitp)
462 {
463 	const Char *qpatnext;
464 	int c, err, oldpathc;
465 	Char *bufnext, patbuf[MAXPATHLEN];
466 
467 	qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
468 	oldpathc = pglob->gl_pathc;
469 	bufnext = patbuf;
470 
471 	/* We don't need to check for buffer overflow any more. */
472 	while ((c = *qpatnext++) != EOS) {
473 		switch (c) {
474 		case LBRACKET:
475 			c = *qpatnext;
476 			if (c == NOT)
477 				++qpatnext;
478 			if (*qpatnext == EOS ||
479 			    g_strchr(qpatnext+1, RBRACKET) == NULL) {
480 				*bufnext++ = LBRACKET;
481 				if (c == NOT)
482 					--qpatnext;
483 				break;
484 			}
485 			*bufnext++ = M_SET;
486 			if (c == NOT)
487 				*bufnext++ = M_NOT;
488 			c = *qpatnext++;
489 			do {
490 				if (c == LBRACKET && *qpatnext == ':') {
491 					do {
492 						err = g_charclass(&qpatnext,
493 						    &bufnext);
494 						if (err)
495 							break;
496 						c = *qpatnext++;
497 					} while (c == LBRACKET && *qpatnext == ':');
498 					if (err == -1 &&
499 					    !(pglob->gl_flags & GLOB_NOCHECK))
500 						return GLOB_NOMATCH;
501 					if (c == RBRACKET)
502 						break;
503 				}
504 				*bufnext++ = CHAR(c);
505 				if (*qpatnext == RANGE &&
506 				    (c = qpatnext[1]) != RBRACKET) {
507 					*bufnext++ = M_RNG;
508 					*bufnext++ = CHAR(c);
509 					qpatnext += 2;
510 				}
511 			} while ((c = *qpatnext++) != RBRACKET);
512 			pglob->gl_flags |= GLOB_MAGCHAR;
513 			*bufnext++ = M_END;
514 			break;
515 		case QUESTION:
516 			pglob->gl_flags |= GLOB_MAGCHAR;
517 			*bufnext++ = M_ONE;
518 			break;
519 		case STAR:
520 			pglob->gl_flags |= GLOB_MAGCHAR;
521 			/* collapse adjacent stars to one,
522 			 * to avoid exponential behavior
523 			 */
524 			if (bufnext == patbuf || bufnext[-1] != M_ALL)
525 				*bufnext++ = M_ALL;
526 			break;
527 		default:
528 			*bufnext++ = CHAR(c);
529 			break;
530 		}
531 	}
532 	*bufnext = EOS;
533 #ifdef DEBUG
534 	qprintf("glob0:", patbuf);
535 #endif
536 
537 	if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, limitp)) != 0)
538 		return(err);
539 
540 	/*
541 	 * If there was no match we are going to append the pattern
542 	 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
543 	 * and the pattern did not contain any magic characters
544 	 * GLOB_NOMAGIC is there just for compatibility with csh.
545 	 */
546 	if (pglob->gl_pathc == oldpathc) {
547 		if ((pglob->gl_flags & GLOB_NOCHECK) ||
548 		    ((pglob->gl_flags & GLOB_NOMAGIC) &&
549 		    !(pglob->gl_flags & GLOB_MAGCHAR)))
550 			return(globextend(pattern, pglob, limitp, NULL));
551 		else
552 			return(GLOB_NOMATCH);
553 	}
554 	if (!(pglob->gl_flags & GLOB_NOSORT)) {
555 		if ((pglob->gl_flags & GLOB_KEEPSTAT)) {
556 			/* Keep the paths and stat info synced during sort */
557 			struct glob_path_stat *path_stat;
558 			int i;
559 			int n = pglob->gl_pathc - oldpathc;
560 			int o = pglob->gl_offs + oldpathc;
561 
562 			if ((path_stat = calloc(n, sizeof(*path_stat))) == NULL)
563 				return GLOB_NOSPACE;
564 			for (i = 0; i < n; i++) {
565 				path_stat[i].gps_path = pglob->gl_pathv[o + i];
566 				path_stat[i].gps_stat = pglob->gl_statv[o + i];
567 			}
568 			qsort(path_stat, n, sizeof(*path_stat), compare_gps);
569 			for (i = 0; i < n; i++) {
570 				pglob->gl_pathv[o + i] = path_stat[i].gps_path;
571 				pglob->gl_statv[o + i] = path_stat[i].gps_stat;
572 			}
573 			free(path_stat);
574 		} else {
575 			qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
576 			    pglob->gl_pathc - oldpathc, sizeof(char *),
577 			    compare);
578 		}
579 	}
580 	return(0);
581 }
582 
583 static int
584 compare(const void *p, const void *q)
585 {
586 	return(strcmp(*(char **)p, *(char **)q));
587 }
588 
589 static int
590 compare_gps(const void *_p, const void *_q)
591 {
592 	const struct glob_path_stat *p = (const struct glob_path_stat *)_p;
593 	const struct glob_path_stat *q = (const struct glob_path_stat *)_q;
594 
595 	return(strcmp(p->gps_path, q->gps_path));
596 }
597 
598 static int
599 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, struct glob_lim *limitp)
600 {
601 	Char pathbuf[MAXPATHLEN];
602 
603 	/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
604 	if (*pattern == EOS)
605 		return(0);
606 	return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
607 	    pathbuf, pathbuf+MAXPATHLEN-1,
608 	    pattern, pattern_last, pglob, limitp));
609 }
610 
611 /*
612  * The functions glob2 and glob3 are mutually recursive; there is one level
613  * of recursion for each segment in the pattern that contains one or more
614  * meta characters.
615  */
616 static int
617 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
618     Char *pattern, Char *pattern_last, glob_t *pglob, struct glob_lim *limitp)
619 {
620 	struct stat sb;
621 	Char *p, *q;
622 	int anymeta;
623 
624 	/*
625 	 * Loop over pattern segments until end of pattern or until
626 	 * segment with meta character found.
627 	 */
628 	for (anymeta = 0;;) {
629 		if (*pattern == EOS) {		/* End of pattern? */
630 			*pathend = EOS;
631 
632 			if ((pglob->gl_flags & GLOB_LIMIT) &&
633 			    limitp->glim_stat++ >= GLOB_LIMIT_STAT) {
634 				errno = 0;
635 				*pathend++ = SEP;
636 				*pathend = EOS;
637 				return(GLOB_NOSPACE);
638 			}
639 			if (g_lstat(pathbuf, &sb, pglob))
640 				return(0);
641 
642 			if (((pglob->gl_flags & GLOB_MARK) &&
643 			    pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
644 			    (S_ISLNK(sb.st_mode) &&
645 			    (g_stat(pathbuf, &sb, pglob) == 0) &&
646 			    S_ISDIR(sb.st_mode)))) {
647 				if (pathend+1 > pathend_last)
648 					return (1);
649 				*pathend++ = SEP;
650 				*pathend = EOS;
651 			}
652 			++pglob->gl_matchc;
653 			return(globextend(pathbuf, pglob, limitp, &sb));
654 		}
655 
656 		/* Find end of next segment, copy tentatively to pathend. */
657 		q = pathend;
658 		p = pattern;
659 		while (*p != EOS && *p != SEP) {
660 			if (ismeta(*p))
661 				anymeta = 1;
662 			if (q+1 > pathend_last)
663 				return (1);
664 			*q++ = *p++;
665 		}
666 
667 		if (!anymeta) {		/* No expansion, do next segment. */
668 			pathend = q;
669 			pattern = p;
670 			while (*pattern == SEP) {
671 				if (pathend+1 > pathend_last)
672 					return (1);
673 				*pathend++ = *pattern++;
674 			}
675 		} else
676 			/* Need expansion, recurse. */
677 			return(glob3(pathbuf, pathbuf_last, pathend,
678 			    pathend_last, pattern, p, pattern_last,
679 			    pglob, limitp));
680 	}
681 	/* NOTREACHED */
682 }
683 
684 static int
685 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
686     Char *pattern, Char *restpattern, Char *restpattern_last, glob_t *pglob,
687     struct glob_lim *limitp)
688 {
689 	struct dirent *dp;
690 	DIR *dirp;
691 	int err;
692 	char buf[MAXPATHLEN];
693 
694 	/*
695 	 * The readdirfunc declaration can't be prototyped, because it is
696 	 * assigned, below, to two functions which are prototyped in glob.h
697 	 * and dirent.h as taking pointers to differently typed opaque
698 	 * structures.
699 	 */
700 	struct dirent *(*readdirfunc)(void *);
701 
702 	if (pathend > pathend_last)
703 		return (1);
704 	*pathend = EOS;
705 	errno = 0;
706 
707 	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
708 		/* TODO: don't call for ENOENT or ENOTDIR? */
709 		if (pglob->gl_errfunc) {
710 			if (g_Ctoc(pathbuf, buf, sizeof(buf)))
711 				return(GLOB_ABORTED);
712 			if (pglob->gl_errfunc(buf, errno) ||
713 			    pglob->gl_flags & GLOB_ERR)
714 				return(GLOB_ABORTED);
715 		}
716 		return(0);
717 	}
718 
719 	err = 0;
720 
721 	/* Search directory for matching names. */
722 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
723 		readdirfunc = pglob->gl_readdir;
724 	else
725 		readdirfunc = (struct dirent *(*)(void *))readdir;
726 	while ((dp = (*readdirfunc)(dirp))) {
727 		u_char *sc;
728 		Char *dc;
729 
730 		if ((pglob->gl_flags & GLOB_LIMIT) &&
731 		    limitp->glim_readdir++ >= GLOB_LIMIT_READDIR) {
732 			errno = 0;
733 			*pathend++ = SEP;
734 			*pathend = EOS;
735 			err = GLOB_NOSPACE;
736 			break;
737 		}
738 
739 		/* Initial DOT must be matched literally. */
740 		if (dp->d_name[0] == DOT && *pattern != DOT)
741 			continue;
742 		dc = pathend;
743 		sc = (u_char *) dp->d_name;
744 		while (dc < pathend_last && (*dc++ = *sc++) != EOS)
745 			;
746 		if (dc >= pathend_last) {
747 			*dc = EOS;
748 			err = 1;
749 			break;
750 		}
751 
752 		if (!match(pathend, pattern, restpattern, GLOB_LIMIT_RECUR)) {
753 			*pathend = EOS;
754 			continue;
755 		}
756 		err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
757 		    restpattern, restpattern_last, pglob, limitp);
758 		if (err)
759 			break;
760 	}
761 
762 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
763 		(*pglob->gl_closedir)(dirp);
764 	else
765 		closedir(dirp);
766 	return(err);
767 }
768 
769 
770 /*
771  * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
772  * add the new item, and update gl_pathc.
773  *
774  * This assumes the BSD realloc, which only copies the block when its size
775  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
776  * behavior.
777  *
778  * Return 0 if new item added, error code if memory couldn't be allocated.
779  *
780  * Invariant of the glob_t structure:
781  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
782  *	gl_pathv points to (gl_offs + gl_pathc + 1) items.
783  */
784 static int
785 globextend(const Char *path, glob_t *pglob, struct glob_lim *limitp,
786     struct stat *sb)
787 {
788 	char **pathv;
789 	ssize_t i;
790 	size_t newn, len;
791 	char *copy = NULL;
792 	const Char *p;
793 	struct stat **statv;
794 
795 	newn = 2 + pglob->gl_pathc + pglob->gl_offs;
796 	if (pglob->gl_offs >= INT_MAX ||
797 	    pglob->gl_pathc >= INT_MAX ||
798 	    newn >= INT_MAX ||
799 	    SIZE_MAX / sizeof(*pathv) <= newn ||
800 	    SIZE_MAX / sizeof(*statv) <= newn) {
801  nospace:
802 		for (i = pglob->gl_offs; i < (ssize_t)(newn - 2); i++) {
803 			if (pglob->gl_pathv && pglob->gl_pathv[i])
804 				free(pglob->gl_pathv[i]);
805 			if ((pglob->gl_flags & GLOB_KEEPSTAT) != 0 &&
806 			    pglob->gl_pathv && pglob->gl_pathv[i])
807 				free(pglob->gl_statv[i]);
808 		}
809 		if (pglob->gl_pathv) {
810 			free(pglob->gl_pathv);
811 			pglob->gl_pathv = NULL;
812 		}
813 		if (pglob->gl_statv) {
814 			free(pglob->gl_statv);
815 			pglob->gl_statv = NULL;
816 		}
817 		return(GLOB_NOSPACE);
818 	}
819 
820 	pathv = realloc(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 = realloc(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 			if (*pp)
958 				free(*pp);
959 		free(pglob->gl_pathv);
960 		pglob->gl_pathv = NULL;
961 	}
962 	if (pglob->gl_statv != NULL) {
963 		for (i = 0; i < pglob->gl_pathc; i++) {
964 			if (pglob->gl_statv[i] != NULL)
965 				free(pglob->gl_statv[i]);
966 		}
967 		free(pglob->gl_statv);
968 		pglob->gl_statv = NULL;
969 	}
970 }
971 
972 static DIR *
973 g_opendir(Char *str, glob_t *pglob)
974 {
975 	char buf[MAXPATHLEN];
976 
977 	if (!*str)
978 		strlcpy(buf, ".", sizeof buf);
979 	else {
980 		if (g_Ctoc(str, buf, sizeof(buf)))
981 			return(NULL);
982 	}
983 
984 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
985 		return((*pglob->gl_opendir)(buf));
986 
987 	return(opendir(buf));
988 }
989 
990 static int
991 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
992 {
993 	char buf[MAXPATHLEN];
994 
995 	if (g_Ctoc(fn, buf, sizeof(buf)))
996 		return(-1);
997 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
998 		return((*pglob->gl_lstat)(buf, sb));
999 	return(lstat(buf, sb));
1000 }
1001 
1002 static int
1003 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
1004 {
1005 	char buf[MAXPATHLEN];
1006 
1007 	if (g_Ctoc(fn, buf, sizeof(buf)))
1008 		return(-1);
1009 	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1010 		return((*pglob->gl_stat)(buf, sb));
1011 	return(stat(buf, sb));
1012 }
1013 
1014 static Char *
1015 g_strchr(const Char *str, int ch)
1016 {
1017 	do {
1018 		if (*str == ch)
1019 			return ((Char *)str);
1020 	} while (*str++);
1021 	return (NULL);
1022 }
1023 
1024 static int
1025 g_Ctoc(const Char *str, char *buf, u_int len)
1026 {
1027 
1028 	while (len--) {
1029 		if ((*buf++ = *str++) == EOS)
1030 			return (0);
1031 	}
1032 	return (1);
1033 }
1034 
1035 #ifdef DEBUG
1036 static void
1037 qprintf(const char *str, Char *s)
1038 {
1039 	Char *p;
1040 
1041 	(void)printf("%s:\n", str);
1042 	for (p = s; *p; p++)
1043 		(void)printf("%c", CHAR(*p));
1044 	(void)printf("\n");
1045 	for (p = s; *p; p++)
1046 		(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
1047 	(void)printf("\n");
1048 	for (p = s; *p; p++)
1049 		(void)printf("%c", ismeta(*p) ? '_' : ' ');
1050 	(void)printf("\n");
1051 }
1052 #endif
1053