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