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