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 *pattern, int flags, int (*errfunc)(const char *, int), glob_t *pglob)
190 struct glob_limit limit = { 0, 0, 0, 0, 0 };
192 Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
198 if (!(flags & GLOB_APPEND)) {
200 pglob->gl_pathv = NULL;
201 if (!(flags & GLOB_DOOFFS))
204 if (flags & GLOB_LIMIT) {
205 limit.l_path_lim = pglob->gl_matchc;
206 if (limit.l_path_lim == 0)
207 limit.l_path_lim = GLOB_LIMIT_PATH;
209 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
210 pglob->gl_errfunc = errfunc;
211 pglob->gl_matchc = 0;
214 bufend = bufnext + MAXPATHLEN - 1;
215 if (flags & GLOB_NOESCAPE) {
216 memset(&mbs, 0, sizeof(mbs));
217 while (bufend - bufnext >= MB_CUR_MAX) {
218 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
219 if (clen == (size_t)-1 || clen == (size_t)-2)
220 return (GLOB_NOMATCH);
227 /* Protect the quoted characters. */
228 memset(&mbs, 0, sizeof(mbs));
229 while (bufend - bufnext >= MB_CUR_MAX) {
230 if (*patnext == QUOTE) {
231 if (*++patnext == EOS) {
232 *bufnext++ = QUOTE | M_PROTECT;
238 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
239 if (clen == (size_t)-1 || clen == (size_t)-2)
240 return (GLOB_NOMATCH);
243 *bufnext++ = wc | prot;
249 if (flags & GLOB_BRACE)
250 return globexp1(patbuf, pglob, &limit);
252 return glob0(patbuf, pglob, &limit);
256 * Expand recursively a glob {} pattern. When there is no more expansion
257 * invoke the standard globbing routine to glob the rest of the magic
261 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
263 const Char* ptr = pattern;
266 if ((pglob->gl_flags & GLOB_LIMIT) &&
267 limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
269 return (GLOB_NOSPACE);
272 /* Protect a single {}, for find(1), like csh */
273 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
274 return glob0(pattern, pglob, limit);
276 while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
277 if (!globexp2(ptr, pattern, pglob, &rv, limit))
280 return glob0(pattern, pglob, limit);
285 * Recursive brace globbing helper. Tries to expand a single brace.
286 * If it succeeds then it invokes globexp1 with the new pattern.
287 * If it fails then it tries to glob the rest of the pattern and returns.
290 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
291 struct glob_limit *limit)
295 const Char *pe, *pm, *pm1, *pl;
296 Char patbuf[MAXPATHLEN];
298 /* copy part up to the brace */
299 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
304 /* Find the balanced brace */
305 for (i = 0, pe = ++ptr; *pe; pe++)
306 if (*pe == LBRACKET) {
307 /* Ignore everything between [] */
308 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
312 * We could not find a matching RBRACKET.
313 * Ignore and just look for RBRACE
318 else if (*pe == LBRACE)
320 else if (*pe == RBRACE) {
326 /* Non matching braces; just glob the pattern */
327 if (i != 0 || *pe == EOS) {
328 *rv = glob0(patbuf, pglob, limit);
332 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
335 /* Ignore everything between [] */
336 for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
340 * We could not find a matching RBRACKET.
341 * Ignore and just look for RBRACE
358 if (i && *pm == COMMA)
361 /* Append the current string */
362 for (lm = ls; (pl < pm); *lm++ = *pl++)
365 * Append the rest of the pattern after the
368 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
371 /* Expand the current pattern */
373 qprintf("globexp2:", patbuf);
375 *rv = globexp1(patbuf, pglob, limit);
377 /* move after the comma, to the next string */
392 * expand tilde from the passwd file.
395 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
402 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
406 * Copy up to the end of the string or /
408 eb = &patbuf[patbuf_len - 1];
409 for (p = pattern + 1, h = (char *) patbuf;
410 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
415 if (((char *) patbuf)[0] == EOS) {
417 * handle a plain ~ or ~/ by expanding $HOME first (iff
418 * we're not running setuid or setgid) and then trying
421 if (issetugid() != 0 ||
422 (h = getenv("HOME")) == NULL) {
423 if (((h = getlogin()) != NULL &&
424 (pwd = getpwnam(h)) != NULL) ||
425 (pwd = getpwuid(getuid())) != NULL)
435 if ((pwd = getpwnam((char*) patbuf)) == NULL)
441 /* Copy the home directory */
442 for (b = patbuf; b < eb && *h; *b++ = *h++)
445 /* Append the rest of the pattern */
446 while (b < eb && (*b++ = *p++) != EOS)
455 * The main glob() routine: compiles the pattern (optionally processing
456 * quotes), calls glob1() to do the real pattern matching, and finally
457 * sorts the list (unless unsorted operation is requested). Returns 0
458 * if things went well, nonzero if errors occurred.
461 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
463 const Char *qpatnext;
466 Char *bufnext, c, patbuf[MAXPATHLEN];
468 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
469 oldpathc = pglob->gl_pathc;
472 /* We don't need to check for buffer overflow any more. */
473 while ((c = *qpatnext++) != EOS) {
479 if (*qpatnext == EOS ||
480 g_strchr(qpatnext+1, RBRACKET) == NULL) {
481 *bufnext++ = LBRACKET;
491 *bufnext++ = CHAR(c);
492 if (*qpatnext == RANGE &&
493 (c = qpatnext[1]) != RBRACKET) {
495 *bufnext++ = CHAR(c);
498 } while ((c = *qpatnext++) != RBRACKET);
499 pglob->gl_flags |= GLOB_MAGCHAR;
503 pglob->gl_flags |= GLOB_MAGCHAR;
507 pglob->gl_flags |= GLOB_MAGCHAR;
508 /* collapse adjacent stars to one,
509 * to avoid exponential behavior
511 if (bufnext == patbuf || bufnext[-1] != M_ALL)
515 *bufnext++ = CHAR(c);
521 qprintf("glob0:", patbuf);
524 if ((err = glob1(patbuf, pglob, limit)) != 0)
528 * If there was no match we are going to append the pattern
529 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
530 * and the pattern did not contain any magic characters
531 * GLOB_NOMAGIC is there just for compatibility with csh.
533 if (pglob->gl_pathc == oldpathc) {
534 if (((pglob->gl_flags & GLOB_NOCHECK) ||
535 ((pglob->gl_flags & GLOB_NOMAGIC) &&
536 !(pglob->gl_flags & GLOB_MAGCHAR))))
537 return(globextend(pattern, pglob, limit));
539 return(GLOB_NOMATCH);
541 if (!(pglob->gl_flags & GLOB_NOSORT))
542 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
543 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
548 compare(const void *p, const void *q)
550 return(strcmp(*(char **)p, *(char **)q));
554 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
556 Char pathbuf[MAXPATHLEN];
558 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
561 return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
562 pattern, pglob, limit));
566 * The functions glob2 and glob3 are mutually recursive; there is one level
567 * of recursion for each segment in the pattern that contains one or more
571 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
572 glob_t *pglob, struct glob_limit *limit)
579 * Loop over pattern segments until end of pattern or until
580 * segment with meta character found.
582 for (anymeta = 0;;) {
583 if (*pattern == EOS) { /* End of pattern? */
585 if (g_lstat(pathbuf, &sb, pglob))
588 if ((pglob->gl_flags & GLOB_LIMIT) &&
589 limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
591 if (pathend + 1 > pathend_last)
592 return (GLOB_ABORTED);
595 return (GLOB_NOSPACE);
597 if (((pglob->gl_flags & GLOB_MARK) &&
598 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
599 || (S_ISLNK(sb.st_mode) &&
600 (g_stat(pathbuf, &sb, pglob) == 0) &&
601 S_ISDIR(sb.st_mode)))) {
602 if (pathend + 1 > pathend_last)
603 return (GLOB_ABORTED);
608 return(globextend(pathbuf, pglob, limit));
611 /* Find end of next segment, copy tentatively to pathend. */
614 while (*p != EOS && *p != SEP) {
617 if (q + 1 > pathend_last)
618 return (GLOB_ABORTED);
622 if (!anymeta) { /* No expansion, do next segment. */
625 while (*pattern == SEP) {
626 if (pathend + 1 > pathend_last)
627 return (GLOB_ABORTED);
628 *pathend++ = *pattern++;
630 } else /* Need expansion, recurse. */
631 return(glob3(pathbuf, pathend, pathend_last, pattern, p,
638 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
639 Char *pattern, Char *restpattern,
640 glob_t *pglob, struct glob_limit *limit)
645 char buf[MAXPATHLEN];
648 * The readdirfunc declaration can't be prototyped, because it is
649 * assigned, below, to two functions which are prototyped in glob.h
650 * and dirent.h as taking pointers to differently typed opaque
653 struct dirent *(*readdirfunc)();
655 if (pathend > pathend_last)
656 return (GLOB_ABORTED);
660 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
661 /* TODO: don't call for ENOENT or ENOTDIR? */
662 if (pglob->gl_errfunc) {
663 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
664 return (GLOB_ABORTED);
665 if (pglob->gl_errfunc(buf, errno) ||
666 pglob->gl_flags & GLOB_ERR)
667 return (GLOB_ABORTED);
674 /* Search directory for matching names. */
675 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
676 readdirfunc = pglob->gl_readdir;
678 readdirfunc = readdir;
679 while ((dp = (*readdirfunc)(dirp))) {
686 if ((pglob->gl_flags & GLOB_LIMIT) &&
687 limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
689 if (pathend + 1 > pathend_last)
699 /* Initial DOT must be matched literally. */
700 if (dp->d_name[0] == DOT && *pattern != DOT)
702 memset(&mbs, 0, sizeof(mbs));
705 while (dc < pathend_last) {
706 clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
707 if (clen == (size_t)-1 || clen == (size_t)-2) {
710 memset(&mbs, 0, sizeof(mbs));
712 if ((*dc++ = wc) == EOS)
716 if (!match(pathend, pattern, restpattern)) {
720 err = glob2(pathbuf, --dc, pathend_last, restpattern,
726 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
727 (*pglob->gl_closedir)(dirp);
735 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
736 * add the new item, and update gl_pathc.
738 * This assumes the BSD realloc, which only copies the block when its size
739 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
742 * Return 0 if new item added, error code if memory couldn't be allocated.
744 * Invariant of the glob_t structure:
745 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
746 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
749 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
752 size_t i, newsize, len;
756 if ((pglob->gl_flags & GLOB_LIMIT) &&
757 pglob->gl_matchc > limit->l_path_lim) {
759 return (GLOB_NOSPACE);
762 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
763 pathv = pglob->gl_pathv ?
764 realloc((char *)pglob->gl_pathv, newsize) :
767 if (pglob->gl_pathv) {
768 free(pglob->gl_pathv);
769 pglob->gl_pathv = NULL;
771 return(GLOB_NOSPACE);
774 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
775 /* first time around -- clear initial gl_offs items */
776 pathv += pglob->gl_offs;
777 for (i = pglob->gl_offs + 1; --i > 0; )
780 pglob->gl_pathv = pathv;
782 for (p = path; *p++;)
784 len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */
785 limit->l_string_cnt += len;
786 if ((pglob->gl_flags & GLOB_LIMIT) &&
787 limit->l_string_cnt >= GLOB_LIMIT_STRING) {
789 return (GLOB_NOSPACE);
791 if ((copy = malloc(len)) != NULL) {
792 if (g_Ctoc(path, copy, len)) {
794 return (GLOB_NOSPACE);
796 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
798 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
799 return(copy == NULL ? GLOB_NOSPACE : 0);
803 * pattern matching function for filenames. Each occurrence of the *
804 * pattern causes a recursion level.
807 match(Char *name, Char *pat, Char *patend)
809 int ok, negate_range;
812 while (pat < patend) {
814 switch (c & M_MASK) {
819 if (match(name, pat, patend))
821 while (*name++ != EOS);
829 if ((k = *name++) == EOS)
831 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
833 while (((c = *pat++) & M_MASK) != M_END)
834 if ((*pat & M_MASK) == M_RNG) {
835 if (__collate_load_error ?
836 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
837 __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
838 && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
844 if (ok == negate_range)
853 return(*name == EOS);
856 /* Free allocated data belonging to a glob_t structure. */
858 globfree(glob_t *pglob)
863 if (pglob->gl_pathv != NULL) {
864 pp = pglob->gl_pathv + pglob->gl_offs;
865 for (i = pglob->gl_pathc; i--; ++pp)
868 free(pglob->gl_pathv);
869 pglob->gl_pathv = NULL;
874 g_opendir(Char *str, glob_t *pglob)
876 char buf[MAXPATHLEN];
881 if (g_Ctoc(str, buf, sizeof(buf)))
885 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
886 return((*pglob->gl_opendir)(buf));
888 return(opendir(buf));
892 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
894 char buf[MAXPATHLEN];
896 if (g_Ctoc(fn, buf, sizeof(buf))) {
897 errno = ENAMETOOLONG;
900 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
901 return((*pglob->gl_lstat)(buf, sb));
902 return(lstat(buf, sb));
906 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
908 char buf[MAXPATHLEN];
910 if (g_Ctoc(fn, buf, sizeof(buf))) {
911 errno = ENAMETOOLONG;
914 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
915 return((*pglob->gl_stat)(buf, sb));
916 return(stat(buf, sb));
920 g_strchr(const Char *str, wchar_t ch)
931 g_Ctoc(const Char *str, char *buf, size_t len)
936 memset(&mbs, 0, sizeof(mbs));
937 while (len >= MB_CUR_MAX) {
938 clen = wcrtomb(buf, *str, &mbs);
939 if (clen == (size_t)-1)
952 qprintf(const char *str, Char *s)
956 (void)printf("%s:\n", str);
958 (void)printf("%c", CHAR(*p));
961 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
964 (void)printf("%c", ismeta(*p) ? '_' : ' ');