2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
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$");
40 * glob(3) -- a superset of the one defined in POSIX 1003.2.
42 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
44 * Optional extra services, controlled by flags not defined by POSIX:
47 * Escaping convention: \ inhibits any special meaning the following
48 * character might have (except \ at end of string is retained).
50 * Set in gl_flags if pattern contained a globbing character.
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]
55 * Use alternately specified directory access functions.
57 * expand ~user/foo to the /home/dir/of/user/foo
59 * expand {1,2}{a,b} to 1a 1b 2a 2b
61 * Number of matches in the current invocation of glob.
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
71 * 3. State-dependent encodings are not currently supported.
74 #include <sys/param.h>
93 * glob(3) expansion limits. Stop the expansion if any of these limits
94 * is reached. This caps the runtime in the face of DoS attacks. See
97 #define GLOB_LIMIT_BRACE 128 /* number of brace calls */
98 #define GLOB_LIMIT_PATH 65536 /* number of path elements */
99 #define GLOB_LIMIT_READDIR 16384 /* number of readdirs */
100 #define GLOB_LIMIT_STAT 1024 /* number of stat system calls */
101 #define GLOB_LIMIT_STRING ARG_MAX /* maximum total size for paths */
106 size_t l_readdir_cnt;
123 #define UNDERSCORE '_'
131 #define M_QUOTE 0x8000000000ULL
132 #define M_PROTECT 0x4000000000ULL
133 #define M_MASK 0xffffffffffULL
134 #define M_CHAR 0x00ffffffffULL
136 typedef uint_fast64_t Char;
141 #define M_PROTECT 0x40
150 #define CHAR(c) ((Char)((c)&M_CHAR))
151 #define META(c) ((Char)((c)|M_QUOTE))
152 #define M_ALL META('*')
153 #define M_END META(']')
154 #define M_NOT META('!')
155 #define M_ONE META('?')
156 #define M_RNG META('-')
157 #define M_SET META('[')
158 #define ismeta(c) (((c)&M_QUOTE) != 0)
161 static int compare(const void *, const void *);
162 static int g_Ctoc(const Char *, char *, size_t);
163 static int g_lstat(Char *, struct stat *, glob_t *);
164 static DIR *g_opendir(Char *, glob_t *);
165 static const Char *g_strchr(const Char *, wchar_t);
167 static Char *g_strcat(Char *, const Char *);
169 static int g_stat(Char *, struct stat *, glob_t *);
170 static int glob0(const Char *, glob_t *, struct glob_limit *);
171 static int glob1(Char *, glob_t *, struct glob_limit *);
172 static int glob2(Char *, Char *, Char *, Char *, glob_t *,
173 struct glob_limit *);
174 static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *,
175 struct glob_limit *);
176 static int globextend(const Char *, glob_t *, struct glob_limit *);
178 globtilde(const Char *, Char *, size_t, glob_t *);
179 static int globexp1(const Char *, glob_t *, struct glob_limit *);
180 static int globexp2(const Char *, const Char *, glob_t *, int *,
181 struct glob_limit *);
182 static int match(Char *, Char *, Char *);
184 static void qprintf(const char *, Char *);
188 glob(const char * __restrict pattern, int flags,
189 int (*errfunc)(const char *, int), glob_t * __restrict pglob)
191 struct glob_limit limit = { 0, 0, 0, 0, 0 };
193 Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
199 if (!(flags & GLOB_APPEND)) {
201 pglob->gl_pathv = NULL;
202 if (!(flags & GLOB_DOOFFS))
205 if (flags & GLOB_LIMIT) {
206 limit.l_path_lim = pglob->gl_matchc;
207 if (limit.l_path_lim == 0)
208 limit.l_path_lim = GLOB_LIMIT_PATH;
210 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
211 pglob->gl_errfunc = errfunc;
212 pglob->gl_matchc = 0;
215 bufend = bufnext + MAXPATHLEN - 1;
216 if (flags & GLOB_NOESCAPE) {
217 memset(&mbs, 0, sizeof(mbs));
218 while (bufend - bufnext >= MB_CUR_MAX) {
219 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
220 if (clen == (size_t)-1 || clen == (size_t)-2)
221 return (GLOB_NOMATCH);
228 /* Protect the quoted characters. */
229 memset(&mbs, 0, sizeof(mbs));
230 while (bufend - bufnext >= MB_CUR_MAX) {
231 if (*patnext == QUOTE) {
232 if (*++patnext == EOS) {
233 *bufnext++ = QUOTE | M_PROTECT;
239 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
240 if (clen == (size_t)-1 || clen == (size_t)-2)
241 return (GLOB_NOMATCH);
244 *bufnext++ = wc | prot;
250 if (flags & GLOB_BRACE)
251 return globexp1(patbuf, pglob, &limit);
253 return glob0(patbuf, pglob, &limit);
257 * Expand recursively a glob {} pattern. When there is no more expansion
258 * invoke the standard globbing routine to glob the rest of the magic
262 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
264 const Char* ptr = pattern;
267 if ((pglob->gl_flags & GLOB_LIMIT) &&
268 limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
270 return (GLOB_NOSPACE);
273 /* Protect a single {}, for find(1), like csh */
274 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
275 return glob0(pattern, pglob, limit);
277 while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
278 if (!globexp2(ptr, pattern, pglob, &rv, limit))
281 return glob0(pattern, pglob, limit);
286 * Recursive brace globbing helper. Tries to expand a single brace.
287 * If it succeeds then it invokes globexp1 with the new pattern.
288 * If it fails then it tries to glob the rest of the pattern and returns.
291 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
292 struct glob_limit *limit)
296 const Char *pe, *pm, *pm1, *pl;
297 Char patbuf[MAXPATHLEN];
299 /* copy part up to the brace */
300 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
305 /* Find the balanced brace */
306 for (i = 0, pe = ++ptr; *pe; pe++)
307 if (*pe == LBRACKET) {
308 /* Ignore everything between [] */
309 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
313 * We could not find a matching RBRACKET.
314 * Ignore and just look for RBRACE
319 else if (*pe == LBRACE)
321 else if (*pe == RBRACE) {
327 /* Non matching braces; just glob the pattern */
328 if (i != 0 || *pe == EOS) {
329 *rv = glob0(patbuf, pglob, limit);
333 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
336 /* Ignore everything between [] */
337 for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
341 * We could not find a matching RBRACKET.
342 * Ignore and just look for RBRACE
359 if (i && *pm == COMMA)
362 /* Append the current string */
363 for (lm = ls; (pl < pm); *lm++ = *pl++)
366 * Append the rest of the pattern after the
369 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
372 /* Expand the current pattern */
374 qprintf("globexp2:", patbuf);
376 *rv = globexp1(patbuf, pglob, limit);
378 /* move after the comma, to the next string */
393 * expand tilde from the passwd file.
396 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
403 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
407 * Copy up to the end of the string or /
409 eb = &patbuf[patbuf_len - 1];
410 for (p = pattern + 1, h = (char *) patbuf;
411 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
416 if (((char *) patbuf)[0] == EOS) {
418 * handle a plain ~ or ~/ by expanding $HOME first (iff
419 * we're not running setuid or setgid) and then trying
422 if (issetugid() != 0 ||
423 (h = getenv("HOME")) == NULL) {
424 if (((h = getlogin()) != NULL &&
425 (pwd = getpwnam(h)) != NULL) ||
426 (pwd = getpwuid(getuid())) != NULL)
436 if ((pwd = getpwnam((char*) patbuf)) == NULL)
442 /* Copy the home directory */
443 for (b = patbuf; b < eb && *h; *b++ = *h++)
446 /* Append the rest of the pattern */
447 while (b < eb && (*b++ = *p++) != EOS)
456 * The main glob() routine: compiles the pattern (optionally processing
457 * quotes), calls glob1() to do the real pattern matching, and finally
458 * sorts the list (unless unsorted operation is requested). Returns 0
459 * if things went well, nonzero if errors occurred.
462 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
464 const Char *qpatnext;
467 Char *bufnext, c, patbuf[MAXPATHLEN];
469 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
470 oldpathc = pglob->gl_pathc;
473 /* We don't need to check for buffer overflow any more. */
474 while ((c = *qpatnext++) != EOS) {
480 if (*qpatnext == EOS ||
481 g_strchr(qpatnext+1, RBRACKET) == NULL) {
482 *bufnext++ = LBRACKET;
492 *bufnext++ = CHAR(c);
493 if (*qpatnext == RANGE &&
494 (c = qpatnext[1]) != RBRACKET) {
496 *bufnext++ = CHAR(c);
499 } while ((c = *qpatnext++) != RBRACKET);
500 pglob->gl_flags |= GLOB_MAGCHAR;
504 pglob->gl_flags |= GLOB_MAGCHAR;
508 pglob->gl_flags |= GLOB_MAGCHAR;
509 /* collapse adjacent stars to one,
510 * to avoid exponential behavior
512 if (bufnext == patbuf || bufnext[-1] != M_ALL)
516 *bufnext++ = CHAR(c);
522 qprintf("glob0:", patbuf);
525 if ((err = glob1(patbuf, pglob, limit)) != 0)
529 * If there was no match we are going to append the pattern
530 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
531 * and the pattern did not contain any magic characters
532 * GLOB_NOMAGIC is there just for compatibility with csh.
534 if (pglob->gl_pathc == oldpathc) {
535 if (((pglob->gl_flags & GLOB_NOCHECK) ||
536 ((pglob->gl_flags & GLOB_NOMAGIC) &&
537 !(pglob->gl_flags & GLOB_MAGCHAR))))
538 return(globextend(pattern, pglob, limit));
540 return(GLOB_NOMATCH);
542 if (!(pglob->gl_flags & GLOB_NOSORT))
543 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
544 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
549 compare(const void *p, const void *q)
551 return(strcmp(*(char **)p, *(char **)q));
555 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
557 Char pathbuf[MAXPATHLEN];
559 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
562 return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
563 pattern, pglob, limit));
567 * The functions glob2 and glob3 are mutually recursive; there is one level
568 * of recursion for each segment in the pattern that contains one or more
572 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
573 glob_t *pglob, struct glob_limit *limit)
580 * Loop over pattern segments until end of pattern or until
581 * segment with meta character found.
583 for (anymeta = 0;;) {
584 if (*pattern == EOS) { /* End of pattern? */
586 if (g_lstat(pathbuf, &sb, pglob))
589 if ((pglob->gl_flags & GLOB_LIMIT) &&
590 limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
592 if (pathend + 1 > pathend_last)
593 return (GLOB_ABORTED);
596 return (GLOB_NOSPACE);
598 if (((pglob->gl_flags & GLOB_MARK) &&
599 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
600 || (S_ISLNK(sb.st_mode) &&
601 (g_stat(pathbuf, &sb, pglob) == 0) &&
602 S_ISDIR(sb.st_mode)))) {
603 if (pathend + 1 > pathend_last)
604 return (GLOB_ABORTED);
609 return(globextend(pathbuf, pglob, limit));
612 /* Find end of next segment, copy tentatively to pathend. */
615 while (*p != EOS && *p != SEP) {
618 if (q + 1 > pathend_last)
619 return (GLOB_ABORTED);
623 if (!anymeta) { /* No expansion, do next segment. */
626 while (*pattern == SEP) {
627 if (pathend + 1 > pathend_last)
628 return (GLOB_ABORTED);
629 *pathend++ = *pattern++;
631 } else /* Need expansion, recurse. */
632 return(glob3(pathbuf, pathend, pathend_last, pattern, p,
639 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
640 Char *pattern, Char *restpattern,
641 glob_t *pglob, struct glob_limit *limit)
646 char buf[MAXPATHLEN];
649 * The readdirfunc declaration can't be prototyped, because it is
650 * assigned, below, to two functions which are prototyped in glob.h
651 * and dirent.h as taking pointers to differently typed opaque
654 struct dirent *(*readdirfunc)();
656 if (pathend > pathend_last)
657 return (GLOB_ABORTED);
661 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
662 /* TODO: don't call for ENOENT or ENOTDIR? */
663 if (pglob->gl_errfunc) {
664 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
665 return (GLOB_ABORTED);
666 if (pglob->gl_errfunc(buf, errno) ||
667 pglob->gl_flags & GLOB_ERR)
668 return (GLOB_ABORTED);
675 /* Search directory for matching names. */
676 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
677 readdirfunc = pglob->gl_readdir;
679 readdirfunc = readdir;
680 while ((dp = (*readdirfunc)(dirp))) {
687 if ((pglob->gl_flags & GLOB_LIMIT) &&
688 limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
690 if (pathend + 1 > pathend_last)
700 /* Initial DOT must be matched literally. */
701 if (dp->d_name[0] == DOT && *pattern != DOT)
703 memset(&mbs, 0, sizeof(mbs));
706 while (dc < pathend_last) {
707 clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
708 if (clen == (size_t)-1 || clen == (size_t)-2) {
711 memset(&mbs, 0, sizeof(mbs));
713 if ((*dc++ = wc) == EOS)
717 if (!match(pathend, pattern, restpattern)) {
721 err = glob2(pathbuf, --dc, pathend_last, restpattern,
727 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
728 (*pglob->gl_closedir)(dirp);
736 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
737 * add the new item, and update gl_pathc.
739 * This assumes the BSD realloc, which only copies the block when its size
740 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
743 * Return 0 if new item added, error code if memory couldn't be allocated.
745 * Invariant of the glob_t structure:
746 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
747 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
750 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
753 size_t i, newsize, len;
757 if ((pglob->gl_flags & GLOB_LIMIT) &&
758 pglob->gl_matchc > limit->l_path_lim) {
760 return (GLOB_NOSPACE);
763 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
764 /* realloc(NULL, newsize) is equivalent to malloc(newsize). */
765 pathv = realloc((void *)pglob->gl_pathv, newsize);
767 return(GLOB_NOSPACE);
769 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
770 /* first time around -- clear initial gl_offs items */
771 pathv += pglob->gl_offs;
772 for (i = pglob->gl_offs + 1; --i > 0; )
775 pglob->gl_pathv = pathv;
777 for (p = path; *p++;)
779 len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */
780 limit->l_string_cnt += len;
781 if ((pglob->gl_flags & GLOB_LIMIT) &&
782 limit->l_string_cnt >= GLOB_LIMIT_STRING) {
784 return (GLOB_NOSPACE);
786 if ((copy = malloc(len)) != NULL) {
787 if (g_Ctoc(path, copy, len)) {
789 return (GLOB_NOSPACE);
791 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
793 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
794 return(copy == NULL ? GLOB_NOSPACE : 0);
798 * pattern matching function for filenames. Each occurrence of the *
799 * pattern causes a recursion level.
802 match(Char *name, Char *pat, Char *patend)
804 int ok, negate_range;
807 while (pat < patend) {
809 switch (c & M_MASK) {
814 if (match(name, pat, patend))
816 while (*name++ != EOS);
824 if ((k = *name++) == EOS)
826 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
828 while (((c = *pat++) & M_MASK) != M_END)
829 if ((*pat & M_MASK) == M_RNG) {
830 if (__collate_load_error ?
831 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
832 __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
833 && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
839 if (ok == negate_range)
848 return(*name == EOS);
851 /* Free allocated data belonging to a glob_t structure. */
853 globfree(glob_t *pglob)
858 if (pglob->gl_pathv != NULL) {
859 pp = pglob->gl_pathv + pglob->gl_offs;
860 for (i = pglob->gl_pathc; i--; ++pp)
863 free(pglob->gl_pathv);
864 pglob->gl_pathv = NULL;
869 g_opendir(Char *str, glob_t *pglob)
871 char buf[MAXPATHLEN];
876 if (g_Ctoc(str, buf, sizeof(buf)))
880 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
881 return((*pglob->gl_opendir)(buf));
883 return(opendir(buf));
887 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
889 char buf[MAXPATHLEN];
891 if (g_Ctoc(fn, buf, sizeof(buf))) {
892 errno = ENAMETOOLONG;
895 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
896 return((*pglob->gl_lstat)(buf, sb));
897 return(lstat(buf, sb));
901 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
903 char buf[MAXPATHLEN];
905 if (g_Ctoc(fn, buf, sizeof(buf))) {
906 errno = ENAMETOOLONG;
909 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
910 return((*pglob->gl_stat)(buf, sb));
911 return(stat(buf, sb));
915 g_strchr(const Char *str, wchar_t ch)
926 g_Ctoc(const Char *str, char *buf, size_t len)
931 memset(&mbs, 0, sizeof(mbs));
932 while (len >= MB_CUR_MAX) {
933 clen = wcrtomb(buf, *str, &mbs);
934 if (clen == (size_t)-1)
947 qprintf(const char *str, Char *s)
951 (void)printf("%s:\n", str);
953 (void)printf("%c", CHAR(*p));
956 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
959 (void)printf("%c", ismeta(*p) ? '_' : ' ');