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 <sys/param.h>
95 * glob(3) expansion limits. Stop the expansion if any of these limits
96 * is reached. This caps the runtime in the face of DoS attacks. See
99 #define GLOB_LIMIT_BRACE 128 /* number of brace calls */
100 #define GLOB_LIMIT_PATH 65536 /* number of path elements */
101 #define GLOB_LIMIT_READDIR 16384 /* number of readdirs */
102 #define GLOB_LIMIT_STAT 1024 /* number of stat system calls */
103 #define GLOB_LIMIT_STRING ARG_MAX /* maximum total size for paths */
108 size_t l_readdir_cnt;
125 #define UNDERSCORE '_'
133 #define M_QUOTE 0x8000000000ULL
134 #define M_PROTECT 0x4000000000ULL
135 #define M_MASK 0xffffffffffULL
136 #define M_CHAR 0x00ffffffffULL
138 typedef uint_fast64_t Char;
143 #define M_PROTECT 0x40
152 #define CHAR(c) ((Char)((c)&M_CHAR))
153 #define META(c) ((Char)((c)|M_QUOTE))
154 #define M_ALL META('*')
155 #define M_END META(']')
156 #define M_NOT META('!')
157 #define M_ONE META('?')
158 #define M_RNG META('-')
159 #define M_SET META('[')
160 #define ismeta(c) (((c)&M_QUOTE) != 0)
163 static int compare(const void *, const void *);
164 static int g_Ctoc(const Char *, char *, size_t);
165 static int g_lstat(Char *, struct stat *, glob_t *);
166 static DIR *g_opendir(Char *, glob_t *);
167 static const Char *g_strchr(const Char *, wchar_t);
169 static Char *g_strcat(Char *, const Char *);
171 static int g_stat(Char *, struct stat *, glob_t *);
172 static int glob0(const Char *, glob_t *, struct glob_limit *);
173 static int glob1(Char *, glob_t *, struct glob_limit *);
174 static int glob2(Char *, Char *, Char *, Char *, glob_t *,
175 struct glob_limit *);
176 static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *,
177 struct glob_limit *);
178 static int globextend(const Char *, glob_t *, struct glob_limit *);
180 globtilde(const Char *, Char *, size_t, glob_t *);
181 static int globexp1(const Char *, glob_t *, struct glob_limit *);
182 static int globexp2(const Char *, const Char *, glob_t *, int *,
183 struct glob_limit *);
184 static int match(Char *, Char *, Char *);
186 static void qprintf(const char *, Char *);
190 glob(const char * __restrict pattern, int flags,
191 int (*errfunc)(const char *, int), glob_t * __restrict pglob)
193 struct glob_limit limit = { 0, 0, 0, 0, 0 };
195 Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
201 if (!(flags & GLOB_APPEND)) {
203 pglob->gl_pathv = NULL;
204 if (!(flags & GLOB_DOOFFS))
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;
212 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
213 pglob->gl_errfunc = errfunc;
214 pglob->gl_matchc = 0;
217 bufend = bufnext + MAXPATHLEN - 1;
218 if (flags & GLOB_NOESCAPE) {
219 memset(&mbs, 0, sizeof(mbs));
220 while (bufend - bufnext >= MB_CUR_MAX) {
221 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
222 if (clen == (size_t)-1 || clen == (size_t)-2)
223 return (GLOB_NOMATCH);
230 /* Protect the quoted characters. */
231 memset(&mbs, 0, sizeof(mbs));
232 while (bufend - bufnext >= MB_CUR_MAX) {
233 if (*patnext == QUOTE) {
234 if (*++patnext == EOS) {
235 *bufnext++ = QUOTE | M_PROTECT;
241 clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
242 if (clen == (size_t)-1 || clen == (size_t)-2)
243 return (GLOB_NOMATCH);
246 *bufnext++ = wc | prot;
252 if (flags & GLOB_BRACE)
253 return (globexp1(patbuf, pglob, &limit));
255 return (glob0(patbuf, pglob, &limit));
259 * Expand recursively a glob {} pattern. When there is no more expansion
260 * invoke the standard globbing routine to glob the rest of the magic
264 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
266 const Char* ptr = pattern;
269 if ((pglob->gl_flags & GLOB_LIMIT) &&
270 limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
272 return (GLOB_NOSPACE);
275 /* Protect a single {}, for find(1), like csh */
276 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
277 return glob0(pattern, pglob, limit);
279 while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
280 if (!globexp2(ptr, pattern, pglob, &rv, limit))
283 return glob0(pattern, pglob, limit);
288 * Recursive brace globbing helper. Tries to expand a single brace.
289 * If it succeeds then it invokes globexp1 with the new pattern.
290 * If it fails then it tries to glob the rest of the pattern and returns.
293 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
294 struct glob_limit *limit)
298 const Char *pe, *pm, *pm1, *pl;
299 Char patbuf[MAXPATHLEN];
301 /* copy part up to the brace */
302 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
307 /* Find the balanced brace */
308 for (i = 0, pe = ++ptr; *pe; pe++)
309 if (*pe == LBRACKET) {
310 /* Ignore everything between [] */
311 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
315 * We could not find a matching RBRACKET.
316 * Ignore and just look for RBRACE
321 else if (*pe == LBRACE)
323 else if (*pe == RBRACE) {
329 /* Non matching braces; just glob the pattern */
330 if (i != 0 || *pe == EOS) {
331 *rv = glob0(patbuf, pglob, limit);
335 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
338 /* Ignore everything between [] */
339 for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
343 * We could not find a matching RBRACKET.
344 * Ignore and just look for RBRACE
361 if (i && *pm == COMMA)
364 /* Append the current string */
365 for (lm = ls; (pl < pm); *lm++ = *pl++)
368 * Append the rest of the pattern after the
371 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
374 /* Expand the current pattern */
376 qprintf("globexp2:", patbuf);
378 *rv = globexp1(patbuf, pglob, limit);
380 /* move after the comma, to the next string */
395 * expand tilde from the passwd file.
398 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
405 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
409 * Copy up to the end of the string or /
411 eb = &patbuf[patbuf_len - 1];
412 for (p = pattern + 1, h = (char *) patbuf;
413 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
418 if (((char *) patbuf)[0] == EOS) {
420 * handle a plain ~ or ~/ by expanding $HOME first (iff
421 * we're not running setuid or setgid) and then trying
424 if (issetugid() != 0 ||
425 (h = getenv("HOME")) == NULL) {
426 if (((h = getlogin()) != NULL &&
427 (pwd = getpwnam(h)) != NULL) ||
428 (pwd = getpwuid(getuid())) != NULL)
438 if ((pwd = getpwnam((char*) patbuf)) == NULL)
444 /* Copy the home directory */
445 for (b = patbuf; b < eb && *h; *b++ = *h++)
448 /* Append the rest of the pattern */
449 while (b < eb && (*b++ = *p++) != EOS)
458 * The main glob() routine: compiles the pattern (optionally processing
459 * quotes), calls glob1() to do the real pattern matching, and finally
460 * sorts the list (unless unsorted operation is requested). Returns 0
461 * if things went well, nonzero if errors occurred.
464 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
466 const Char *qpatnext;
469 Char *bufnext, c, patbuf[MAXPATHLEN];
471 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
472 oldpathc = pglob->gl_pathc;
475 /* We don't need to check for buffer overflow any more. */
476 while ((c = *qpatnext++) != EOS) {
482 if (*qpatnext == EOS ||
483 g_strchr(qpatnext+1, RBRACKET) == NULL) {
484 *bufnext++ = LBRACKET;
494 *bufnext++ = CHAR(c);
495 if (*qpatnext == RANGE &&
496 (c = qpatnext[1]) != RBRACKET) {
498 *bufnext++ = CHAR(c);
501 } while ((c = *qpatnext++) != RBRACKET);
502 pglob->gl_flags |= GLOB_MAGCHAR;
506 pglob->gl_flags |= GLOB_MAGCHAR;
510 pglob->gl_flags |= GLOB_MAGCHAR;
511 /* collapse adjacent stars to one,
512 * to avoid exponential behavior
514 if (bufnext == patbuf || bufnext[-1] != M_ALL)
518 *bufnext++ = CHAR(c);
524 qprintf("glob0:", patbuf);
527 if ((err = glob1(patbuf, pglob, limit)) != 0)
531 * If there was no match we are going to append the pattern
532 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
533 * and the pattern did not contain any magic characters
534 * GLOB_NOMAGIC is there just for compatibility with csh.
536 if (pglob->gl_pathc == oldpathc) {
537 if (((pglob->gl_flags & GLOB_NOCHECK) ||
538 ((pglob->gl_flags & GLOB_NOMAGIC) &&
539 !(pglob->gl_flags & GLOB_MAGCHAR))))
540 return (globextend(pattern, pglob, limit));
542 return (GLOB_NOMATCH);
544 if (!(pglob->gl_flags & GLOB_NOSORT))
545 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
546 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
551 compare(const void *p, const void *q)
553 return (strcmp(*(char **)p, *(char **)q));
557 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
559 Char pathbuf[MAXPATHLEN];
561 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
564 return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
565 pattern, pglob, limit));
569 * The functions glob2 and glob3 are mutually recursive; there is one level
570 * of recursion for each segment in the pattern that contains one or more
574 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
575 glob_t *pglob, struct glob_limit *limit)
582 * Loop over pattern segments until end of pattern or until
583 * segment with meta character found.
585 for (anymeta = 0;;) {
586 if (*pattern == EOS) { /* End of pattern? */
588 if (g_lstat(pathbuf, &sb, pglob))
591 if ((pglob->gl_flags & GLOB_LIMIT) &&
592 limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
594 if (pathend + 1 > pathend_last)
595 return (GLOB_ABORTED);
598 return (GLOB_NOSPACE);
600 if (((pglob->gl_flags & GLOB_MARK) &&
601 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
602 || (S_ISLNK(sb.st_mode) &&
603 (g_stat(pathbuf, &sb, pglob) == 0) &&
604 S_ISDIR(sb.st_mode)))) {
605 if (pathend + 1 > pathend_last)
606 return (GLOB_ABORTED);
611 return (globextend(pathbuf, pglob, limit));
614 /* Find end of next segment, copy tentatively to pathend. */
617 while (*p != EOS && *p != SEP) {
620 if (q + 1 > pathend_last)
621 return (GLOB_ABORTED);
625 if (!anymeta) { /* No expansion, do next segment. */
628 while (*pattern == SEP) {
629 if (pathend + 1 > pathend_last)
630 return (GLOB_ABORTED);
631 *pathend++ = *pattern++;
633 } else /* Need expansion, recurse. */
634 return (glob3(pathbuf, pathend, pathend_last, pattern,
641 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
642 Char *pattern, Char *restpattern,
643 glob_t *pglob, struct glob_limit *limit)
648 char buf[MAXPATHLEN];
651 * The readdirfunc declaration can't be prototyped, because it is
652 * assigned, below, to two functions which are prototyped in glob.h
653 * and dirent.h as taking pointers to differently typed opaque
656 struct dirent *(*readdirfunc)();
658 if (pathend > pathend_last)
659 return (GLOB_ABORTED);
663 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
664 /* TODO: don't call for ENOENT or ENOTDIR? */
665 if (pglob->gl_errfunc) {
666 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
667 return (GLOB_ABORTED);
668 if (pglob->gl_errfunc(buf, errno) ||
669 pglob->gl_flags & GLOB_ERR)
670 return (GLOB_ABORTED);
677 /* Search directory for matching names. */
678 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
679 readdirfunc = pglob->gl_readdir;
681 readdirfunc = readdir;
682 while ((dp = (*readdirfunc)(dirp))) {
689 if ((pglob->gl_flags & GLOB_LIMIT) &&
690 limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
692 if (pathend + 1 > pathend_last)
702 /* Initial DOT must be matched literally. */
703 if (dp->d_name[0] == DOT && *pattern != DOT)
705 memset(&mbs, 0, sizeof(mbs));
708 while (dc < pathend_last) {
709 clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
710 if (clen == (size_t)-1 || clen == (size_t)-2) {
713 memset(&mbs, 0, sizeof(mbs));
715 if ((*dc++ = wc) == EOS)
719 if (!match(pathend, pattern, restpattern)) {
723 err = glob2(pathbuf, --dc, pathend_last, restpattern,
729 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
730 (*pglob->gl_closedir)(dirp);
738 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
739 * add the new item, and update gl_pathc.
741 * This assumes the BSD realloc, which only copies the block when its size
742 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
745 * Return 0 if new item added, error code if memory couldn't be allocated.
747 * Invariant of the glob_t structure:
748 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
749 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
752 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
755 size_t i, newsize, len;
759 if ((pglob->gl_flags & GLOB_LIMIT) &&
760 pglob->gl_matchc > limit->l_path_lim) {
762 return (GLOB_NOSPACE);
765 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
766 /* realloc(NULL, newsize) is equivalent to malloc(newsize). */
767 pathv = realloc((void *)pglob->gl_pathv, newsize);
769 return (GLOB_NOSPACE);
771 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
772 /* first time around -- clear initial gl_offs items */
773 pathv += pglob->gl_offs;
774 for (i = pglob->gl_offs + 1; --i > 0; )
777 pglob->gl_pathv = pathv;
779 for (p = path; *p++;)
781 len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */
782 limit->l_string_cnt += len;
783 if ((pglob->gl_flags & GLOB_LIMIT) &&
784 limit->l_string_cnt >= GLOB_LIMIT_STRING) {
786 return (GLOB_NOSPACE);
788 if ((copy = malloc(len)) != NULL) {
789 if (g_Ctoc(path, copy, len)) {
791 return (GLOB_NOSPACE);
793 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
795 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
796 return (copy == NULL ? GLOB_NOSPACE : 0);
800 * pattern matching function for filenames. Each occurrence of the *
801 * pattern causes a recursion level.
804 match(Char *name, Char *pat, Char *patend)
806 int ok, negate_range;
808 struct xlocale_collate *table =
809 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
811 while (pat < patend) {
813 switch (c & M_MASK) {
818 if (match(name, pat, patend))
820 while (*name++ != EOS);
828 if ((k = *name++) == EOS)
830 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
832 while (((c = *pat++) & M_MASK) != M_END)
833 if ((*pat & M_MASK) == M_RNG) {
834 if (table->__collate_load_error ?
835 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
836 __collate_range_cmp(table, CHAR(c), CHAR(k)) <= 0
837 && __collate_range_cmp(table, CHAR(k), CHAR(pat[1])) <= 0
843 if (ok == negate_range)
852 return (*name == EOS);
855 /* Free allocated data belonging to a glob_t structure. */
857 globfree(glob_t *pglob)
862 if (pglob->gl_pathv != NULL) {
863 pp = pglob->gl_pathv + pglob->gl_offs;
864 for (i = pglob->gl_pathc; i--; ++pp)
867 free(pglob->gl_pathv);
868 pglob->gl_pathv = NULL;
873 g_opendir(Char *str, glob_t *pglob)
875 char buf[MAXPATHLEN];
880 if (g_Ctoc(str, buf, sizeof(buf)))
884 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
885 return ((*pglob->gl_opendir)(buf));
887 return (opendir(buf));
891 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
893 char buf[MAXPATHLEN];
895 if (g_Ctoc(fn, buf, sizeof(buf))) {
896 errno = ENAMETOOLONG;
899 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
900 return((*pglob->gl_lstat)(buf, sb));
901 return (lstat(buf, sb));
905 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
907 char buf[MAXPATHLEN];
909 if (g_Ctoc(fn, buf, sizeof(buf))) {
910 errno = ENAMETOOLONG;
913 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
914 return ((*pglob->gl_stat)(buf, sb));
915 return (stat(buf, sb));
919 g_strchr(const Char *str, wchar_t ch)
930 g_Ctoc(const Char *str, char *buf, size_t len)
935 memset(&mbs, 0, sizeof(mbs));
936 while (len >= MB_CUR_MAX) {
937 clen = wcrtomb(buf, *str, &mbs);
938 if (clen == (size_t)-1)
951 qprintf(const char *str, Char *s)
955 (void)printf("%s:\n", str);
957 (void)printf("%c", CHAR(*p));
960 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
963 (void)printf("%c", ismeta(*p) ? '_' : ' ');