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