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