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