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