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 * Copyright (c) 2011 The FreeBSD Foundation
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)glob.c 8.3 (Berkeley) 10/13/93
38 * $FreeBSD: head/lib/libc/gen/glob.c 249381 2013-04-11 20:15:37Z emaste $
42 * glob(3) -- a superset of the one defined in POSIX 1003.2.
44 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
46 * Optional extra services, controlled by flags not defined by POSIX:
49 * Escaping convention: \ inhibits any special meaning the following
50 * character might have (except \ at end of string is retained).
52 * Set in gl_flags if pattern contained a globbing character.
54 * Same as GLOB_NOCHECK, but it will only append pattern if it did
55 * not contain any magic characters. [Used in csh style globbing]
57 * Use alternately specified directory access functions.
59 * expand ~user/foo to the /home/dir/of/user/foo
61 * expand {1,2}{a,b} to 1a 1b 2a 2b
63 * Number of matches in the current invocation of glob.
67 * Some notes on multibyte character support:
68 * 1. Patterns with illegal byte sequences match nothing - even if
69 * GLOB_NOCHECK is specified.
70 * 2. Illegal byte sequences in filenames are handled by treating them as
71 * single-byte characters with a value of the first byte of the sequence
73 * 3. State-dependent encodings are not currently supported.
76 #include "namespace.h"
77 #include <sys/param.h>
94 #include "un-namespace.h"
97 * glob(3) expansion limits. Stop the expansion if any of these limits
98 * is reached. This caps the runtime in the face of DoS attacks. See
101 #define GLOB_LIMIT_BRACE 128 /* number of brace calls */
102 #define GLOB_LIMIT_PATH 65536 /* number of path elements */
103 #define GLOB_LIMIT_READDIR 16384 /* number of readdirs */
104 #define GLOB_LIMIT_STAT 1024 /* number of stat system calls */
105 #define GLOB_LIMIT_STRING ARG_MAX /* maximum total size for paths */
110 size_t l_readdir_cnt;
127 #define UNDERSCORE '_'
135 #define M_QUOTE 0x8000000000ULL
136 #define M_PROTECT 0x4000000000ULL
137 #define M_MASK 0xffffffffffULL
138 #define M_CHAR 0x00ffffffffULL
140 typedef uint_fast64_t Char;
145 #define M_PROTECT 0x40
154 #define CHAR(c) ((Char)((c)&M_CHAR))
155 #define META(c) ((Char)((c)|M_QUOTE))
156 #define M_ALL META('*')
157 #define M_END META(']')
158 #define M_NOT META('!')
159 #define M_ONE META('?')
160 #define M_RNG META('-')
161 #define M_SET META('[')
162 #define ismeta(c) (((c)&M_QUOTE) != 0)
165 static int compare(const void *, const void *);
166 static int g_Ctoc(const Char *, char *, size_t);
167 static int g_lstat(Char *, struct stat *, glob_t *);
168 static DIR *g_opendir(Char *, glob_t *);
169 static const Char *g_strchr(const Char *, wchar_t);
171 static Char *g_strcat(Char *, const Char *);
173 static int g_stat(Char *, struct stat *, glob_t *);
174 static int glob0(const Char *, glob_t *, struct glob_limit *);
175 static int glob1(Char *, glob_t *, struct glob_limit *);
176 static int glob2(Char *, Char *, Char *, Char *, glob_t *,
177 struct glob_limit *);
178 static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *,
179 struct glob_limit *);
180 static int globextend(const Char *, glob_t *, struct glob_limit *);
182 globtilde(const Char *, Char *, size_t, glob_t *);
183 static int globexp1(const Char *, glob_t *, struct glob_limit *);
184 static int globexp2(const Char *, const Char *, glob_t *, int *,
185 struct glob_limit *);
186 static int match(Char *, Char *, Char *);
188 static void qprintf(const char *, Char *);
192 glob(const char * __restrict pattern, int flags,
193 int (*errfunc)(const char *, int), glob_t * __restrict pglob)
195 struct glob_limit limit = { 0, 0, 0, 0, 0 };
197 Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
203 if (!(flags & GLOB_APPEND)) {
205 pglob->gl_pathv = NULL;
206 if (!(flags & GLOB_DOOFFS))
209 if (flags & GLOB_LIMIT) {
210 limit.l_path_lim = pglob->gl_matchc;
211 if (limit.l_path_lim == 0)
212 limit.l_path_lim = GLOB_LIMIT_PATH;
214 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
215 pglob->gl_errfunc = errfunc;
216 pglob->gl_matchc = 0;
219 bufend = bufnext + MAXPATHLEN - 1;
220 if (flags & GLOB_NOESCAPE) {
221 memset(&mbs, 0, sizeof(mbs));
222 while (bufend - bufnext >= MB_CUR_MAX) {
223 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
224 if (clen == (size_t)-1 || clen == (size_t)-2)
225 return (GLOB_NOMATCH);
232 /* Protect the quoted characters. */
233 memset(&mbs, 0, sizeof(mbs));
234 while (bufend - bufnext >= MB_CUR_MAX) {
235 if (*patnext == QUOTE) {
236 if (*++patnext == EOS) {
237 *bufnext++ = QUOTE | M_PROTECT;
243 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
244 if (clen == (size_t)-1 || clen == (size_t)-2)
245 return (GLOB_NOMATCH);
248 *bufnext++ = wc | prot;
254 if (flags & GLOB_BRACE)
255 return (globexp1(patbuf, pglob, &limit));
257 return (glob0(patbuf, pglob, &limit));
261 * Expand recursively a glob {} pattern. When there is no more expansion
262 * invoke the standard globbing routine to glob the rest of the magic
266 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
268 const Char* ptr = pattern;
271 if ((pglob->gl_flags & GLOB_LIMIT) &&
272 limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
274 return (GLOB_NOSPACE);
277 /* Protect a single {}, for find(1), like csh */
278 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
279 return glob0(pattern, pglob, limit);
281 while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
282 if (!globexp2(ptr, pattern, pglob, &rv, limit))
285 return glob0(pattern, pglob, limit);
290 * Recursive brace globbing helper. Tries to expand a single brace.
291 * If it succeeds then it invokes globexp1 with the new pattern.
292 * If it fails then it tries to glob the rest of the pattern and returns.
295 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
296 struct glob_limit *limit)
300 const Char *pe, *pm, *pm1, *pl;
301 Char patbuf[MAXPATHLEN];
303 /* copy part up to the brace */
304 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
309 /* Find the balanced brace */
310 for (i = 0, pe = ++ptr; *pe; pe++)
311 if (*pe == LBRACKET) {
312 /* Ignore everything between [] */
313 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
317 * We could not find a matching RBRACKET.
318 * Ignore and just look for RBRACE
323 else if (*pe == LBRACE)
325 else if (*pe == RBRACE) {
331 /* Non matching braces; just glob the pattern */
332 if (i != 0 || *pe == EOS) {
333 *rv = glob0(patbuf, pglob, limit);
337 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
340 /* Ignore everything between [] */
341 for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
345 * We could not find a matching RBRACKET.
346 * Ignore and just look for RBRACE
363 if (i && *pm == COMMA)
366 /* Append the current string */
367 for (lm = ls; (pl < pm); *lm++ = *pl++)
370 * Append the rest of the pattern after the
373 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
376 /* Expand the current pattern */
378 qprintf("globexp2:", patbuf);
380 *rv = globexp1(patbuf, pglob, limit);
382 /* move after the comma, to the next string */
397 * expand tilde from the passwd file.
400 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
407 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
411 * Copy up to the end of the string or /
413 eb = &patbuf[patbuf_len - 1];
414 for (p = pattern + 1, h = (char *) patbuf;
415 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
420 if (((char *) patbuf)[0] == EOS) {
422 * handle a plain ~ or ~/ by expanding $HOME first (iff
423 * we're not running setuid or setgid) and then trying
426 if (issetugid() != 0 ||
427 (h = getenv("HOME")) == NULL) {
428 if (((h = _getlogin()) != NULL &&
429 (pwd = getpwnam(h)) != NULL) ||
430 (pwd = getpwuid(getuid())) != NULL)
440 if ((pwd = getpwnam((char*) patbuf)) == NULL)
446 /* Copy the home directory */
447 for (b = patbuf; b < eb && *h; *b++ = *h++)
450 /* Append the rest of the pattern */
451 while (b < eb && (*b++ = *p++) != EOS)
460 * The main glob() routine: compiles the pattern (optionally processing
461 * quotes), calls glob1() to do the real pattern matching, and finally
462 * sorts the list (unless unsorted operation is requested). Returns 0
463 * if things went well, nonzero if errors occurred.
466 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
468 const Char *qpatnext;
471 Char *bufnext, c, patbuf[MAXPATHLEN];
473 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
474 oldpathc = pglob->gl_pathc;
477 /* We don't need to check for buffer overflow any more. */
478 while ((c = *qpatnext++) != EOS) {
484 if (*qpatnext == EOS ||
485 g_strchr(qpatnext+1, RBRACKET) == NULL) {
486 *bufnext++ = LBRACKET;
496 *bufnext++ = CHAR(c);
497 if (*qpatnext == RANGE &&
498 (c = qpatnext[1]) != RBRACKET) {
500 *bufnext++ = CHAR(c);
503 } while ((c = *qpatnext++) != RBRACKET);
504 pglob->gl_flags |= GLOB_MAGCHAR;
508 pglob->gl_flags |= GLOB_MAGCHAR;
512 pglob->gl_flags |= GLOB_MAGCHAR;
513 /* collapse adjacent stars to one,
514 * to avoid exponential behavior
516 if (bufnext == patbuf || bufnext[-1] != M_ALL)
520 *bufnext++ = CHAR(c);
526 qprintf("glob0:", patbuf);
529 if ((err = glob1(patbuf, pglob, limit)) != 0)
533 * If there was no match we are going to append the pattern
534 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
535 * and the pattern did not contain any magic characters
536 * GLOB_NOMAGIC is there just for compatibility with csh.
538 if (pglob->gl_pathc == oldpathc) {
539 if (((pglob->gl_flags & GLOB_NOCHECK) ||
540 ((pglob->gl_flags & GLOB_NOMAGIC) &&
541 !(pglob->gl_flags & GLOB_MAGCHAR))))
542 return (globextend(pattern, pglob, limit));
544 return (GLOB_NOMATCH);
546 if (!(pglob->gl_flags & GLOB_NOSORT))
547 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
548 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
553 compare(const void *p, const void *q)
555 return (strcmp(*(char **)p, *(char **)q));
559 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
561 Char pathbuf[MAXPATHLEN];
563 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
566 return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
567 pattern, pglob, limit));
571 * The functions glob2 and glob3 are mutually recursive; there is one level
572 * of recursion for each segment in the pattern that contains one or more
576 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
577 glob_t *pglob, struct glob_limit *limit)
584 * Loop over pattern segments until end of pattern or until
585 * segment with meta character found.
587 for (anymeta = 0;;) {
588 if (*pattern == EOS) { /* End of pattern? */
590 if (g_lstat(pathbuf, &sb, pglob))
593 if ((pglob->gl_flags & GLOB_LIMIT) &&
594 limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
596 if (pathend + 1 > pathend_last)
597 return (GLOB_ABORTED);
600 return (GLOB_NOSPACE);
602 if (((pglob->gl_flags & GLOB_MARK) &&
603 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
604 || (S_ISLNK(sb.st_mode) &&
605 (g_stat(pathbuf, &sb, pglob) == 0) &&
606 S_ISDIR(sb.st_mode)))) {
607 if (pathend + 1 > pathend_last)
608 return (GLOB_ABORTED);
613 return (globextend(pathbuf, pglob, limit));
616 /* Find end of next segment, copy tentatively to pathend. */
619 while (*p != EOS && *p != SEP) {
622 if (q + 1 > pathend_last)
623 return (GLOB_ABORTED);
627 if (!anymeta) { /* No expansion, do next segment. */
630 while (*pattern == SEP) {
631 if (pathend + 1 > pathend_last)
632 return (GLOB_ABORTED);
633 *pathend++ = *pattern++;
635 } else /* Need expansion, recurse. */
636 return (glob3(pathbuf, pathend, pathend_last, pattern,
643 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
644 Char *pattern, Char *restpattern,
645 glob_t *pglob, struct glob_limit *limit)
650 char buf[MAXPATHLEN];
652 struct dirent *(*readdirfunc)(DIR *);
654 if (pathend > pathend_last)
655 return (GLOB_ABORTED);
659 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
660 /* TODO: don't call for ENOENT or ENOTDIR? */
661 if (pglob->gl_errfunc) {
662 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
663 return (GLOB_ABORTED);
664 if (pglob->gl_errfunc(buf, errno) ||
665 pglob->gl_flags & GLOB_ERR)
666 return (GLOB_ABORTED);
673 /* pglob->gl_readdir takes a void *, fix this manually */
674 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
675 readdirfunc = (struct dirent *(*)(DIR *))pglob->gl_readdir;
677 readdirfunc = readdir;
679 /* Search directory for matching names. */
680 while ((dp = (*readdirfunc)(dirp)) != NULL) {
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 accommodate 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;
806 struct xlocale_collate *table =
807 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
809 while (pat < patend) {
811 switch (c & M_MASK) {
816 if (match(name, pat, patend))
818 while (*name++ != EOS);
826 if ((k = *name++) == EOS)
828 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
830 while (((c = *pat++) & M_MASK) != M_END)
831 if ((*pat & M_MASK) == M_RNG) {
832 if (table->__collate_load_error ?
833 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
834 __wcollate_range_cmp(CHAR(c), CHAR(k)) <= 0 &&
835 __wcollate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
841 if (ok == negate_range)
850 return (*name == EOS);
853 /* Free allocated data belonging to a glob_t structure. */
855 globfree(glob_t *pglob)
860 if (pglob->gl_pathv != NULL) {
861 pp = pglob->gl_pathv + pglob->gl_offs;
862 for (i = pglob->gl_pathc; i--; ++pp)
865 free(pglob->gl_pathv);
866 pglob->gl_pathv = NULL;
871 g_opendir(Char *str, glob_t *pglob)
873 char buf[MAXPATHLEN];
878 if (g_Ctoc(str, buf, sizeof(buf)))
882 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
883 return ((*pglob->gl_opendir)(buf));
885 return (opendir(buf));
889 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
891 char buf[MAXPATHLEN];
893 if (g_Ctoc(fn, buf, sizeof(buf))) {
894 errno = ENAMETOOLONG;
897 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
898 return((*pglob->gl_lstat)(buf, sb));
899 return (lstat(buf, sb));
903 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
905 char buf[MAXPATHLEN];
907 if (g_Ctoc(fn, buf, sizeof(buf))) {
908 errno = ENAMETOOLONG;
911 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
912 return ((*pglob->gl_stat)(buf, sb));
913 return (stat(buf, sb));
917 g_strchr(const Char *str, wchar_t ch)
928 g_Ctoc(const Char *str, char *buf, size_t len)
933 memset(&mbs, 0, sizeof(mbs));
934 while (len >= MB_CUR_MAX) {
935 clen = wcrtomb(buf, *str, &mbs);
936 if (clen == (size_t)-1)
949 qprintf(const char *str, Char *s)
953 (void)printf("%s:\n", str);
955 (void)printf("%c", CHAR(*p));
958 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
961 (void)printf("%c", ismeta(*p) ? '_' : ' ');