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