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