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