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