2 * Copyright (c) 2008-2010 Todd C. Miller <Todd.Miller@courtesan.com>
3 * Copyright (c) 1989, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)glob.c 8.3 (Berkeley) 10/13/93
37 * glob(3) -- a superset of the one defined in POSIX 1003.2.
39 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
41 * Optional extra services, controlled by flags not defined by POSIX:
44 * Set in gl_flags if pattern contained a globbing character.
46 * expand ~user/foo to the /home/dir/of/user/foo
48 * expand {1,2}{a,b} to 1a 1b 2a 2b
50 * Number of matches in the current invocation of glob.
57 #include <sys/types.h>
68 #endif /* STDC_HEADERS */
69 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
71 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
74 #endif /* HAVE_STRING_H */
77 #endif /* HAVE_STRINGS_H */
80 #endif /* HAVE_UNISTD_H */
85 # define dirent direct
86 # ifdef HAVE_SYS_NDIR_H
87 # include <sys/ndir.h>
89 # ifdef HAVE_SYS_DIR_H
101 #include "compat/glob.h"
102 #include "compat/charclass.h"
116 #define UNDERSCORE '_'
124 #define M_QUOTE 0x8000
125 #define M_PROTECT 0x4000
126 #define M_MASK 0xffff
127 #define M_ASCII 0x00ff
129 typedef unsigned short Char;
134 #define M_PROTECT 0x40
143 #define CHAR(c) ((Char)((c)&M_ASCII))
144 #define META(c) ((Char)((c)|M_QUOTE))
145 #define M_ALL META('*')
146 #define M_END META(']')
147 #define M_NOT META('!')
148 #define M_ONE META('?')
149 #define M_RNG META('-')
150 #define M_SET META('[')
151 #define M_CLASS META(':')
152 #define ismeta(c) (((c)&M_QUOTE) != 0)
155 static int compare(const void *, const void *);
156 static int g_Ctoc(const Char *, char *, unsigned int);
157 static int g_lstat(Char *, struct stat *, glob_t *);
158 static DIR *g_opendir(Char *, glob_t *);
159 static Char *g_strchr(const Char *, int);
160 static int g_strncmp(const Char *, const char *, size_t);
161 static int g_stat(Char *, struct stat *, glob_t *);
162 static int glob0(const Char *, glob_t *);
163 static int glob1(Char *, Char *, glob_t *);
164 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
166 static int glob3(Char *, Char *, Char *, Char *, Char *, Char *,
167 Char *, Char *, glob_t *);
168 static int globextend(const Char *, glob_t *);
170 globtilde(const Char *, Char *, size_t, glob_t *);
171 static int globexp1(const Char *, glob_t *);
172 static int globexp2(const Char *, const Char *, glob_t *, int *);
173 static int match(Char *, Char *, Char *);
175 static void qprintf(const char *, Char *);
179 rpl_glob(const char *pattern, int flags, int (*errfunc)(const char *, int),
182 const unsigned char *patnext;
184 Char *bufnext, *bufend, patbuf[PATH_MAX];
186 patnext = (unsigned char *) pattern;
187 if (!(flags & GLOB_APPEND)) {
189 pglob->gl_pathv = NULL;
190 if (!(flags & GLOB_DOOFFS))
193 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
194 pglob->gl_errfunc = errfunc;
195 pglob->gl_matchc = 0;
198 bufend = bufnext + PATH_MAX - 1;
199 if (flags & GLOB_NOESCAPE)
200 while (bufnext < bufend && (c = *patnext++) != EOS)
203 /* Protect the quoted characters. */
204 while (bufnext < bufend && (c = *patnext++) != EOS)
206 if ((c = *patnext++) == EOS) {
210 *bufnext++ = c | M_PROTECT;
216 if (flags & GLOB_BRACE)
217 return globexp1(patbuf, pglob);
219 return glob0(patbuf, pglob);
223 * Expand recursively a glob {} pattern. When there is no more expansion
224 * invoke the standard globbing routine to glob the rest of the magic
228 globexp1(const Char *pattern, glob_t *pglob)
230 const Char* ptr = pattern;
233 /* Protect a single {}, for find(1), like csh */
234 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
235 return glob0(pattern, pglob);
237 while ((ptr = (const Char *) g_strchr(ptr, LBRACE)) != NULL)
238 if (!globexp2(ptr, pattern, pglob, &rv))
241 return glob0(pattern, pglob);
246 * Recursive brace globbing helper. Tries to expand a single brace.
247 * If it succeeds then it invokes globexp1 with the new pattern.
248 * If it fails then it tries to glob the rest of the pattern and returns.
251 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv)
255 const Char *pe, *pm, *pl;
256 Char patbuf[PATH_MAX];
258 /* copy part up to the brace */
259 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
264 /* Find the balanced brace */
265 for (i = 0, pe = ++ptr; *pe; pe++)
266 if (*pe == LBRACKET) {
267 /* Ignore everything between [] */
268 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
272 * We could not find a matching RBRACKET.
273 * Ignore and just look for RBRACE
277 } else if (*pe == LBRACE)
279 else if (*pe == RBRACE) {
285 /* Non matching braces; just glob the pattern */
286 if (i != 0 || *pe == EOS) {
287 *rv = glob0(patbuf, pglob);
291 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
294 /* Ignore everything between [] */
295 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
299 * We could not find a matching RBRACKET.
300 * Ignore and just look for RBRACE
317 if (i && *pm == COMMA)
320 /* Append the current string */
321 for (lm = ls; (pl < pm); *lm++ = *pl++)
325 * Append the rest of the pattern after the
328 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
331 /* Expand the current pattern */
333 qprintf("globexp2:", patbuf);
335 *rv = globexp1(patbuf, pglob);
337 /* move after the comma, to the next string */
353 * expand tilde from the passwd file.
356 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
363 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
366 /* Copy up to the end of the string or / */
367 eb = &patbuf[patbuf_len - 1];
368 for (p = pattern + 1, h = (char *) patbuf;
369 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
374 if (((char *) patbuf)[0] == EOS) {
376 * handle a plain ~ or ~/ by expanding $HOME
377 * first and then trying the password file
379 if ((h = getenv("HOME")) == NULL) {
380 if ((pwd = getpwuid(getuid())) == NULL)
389 if ((pwd = getpwnam((char*) patbuf)) == NULL)
395 /* Copy the home directory */
396 for (b = patbuf; b < eb && *h; *b++ = *h++)
399 /* Append the rest of the pattern */
400 while (b < eb && (*b++ = *p++) != EOS)
408 g_strncmp(const Char *s1, const char *s2, size_t n)
413 rv = *(Char *)s1 - *(const unsigned char *)s2++;
423 g_charclass(const Char **patternp, Char **bufnextp)
425 const Char *pattern = *patternp + 1;
426 Char *bufnext = *bufnextp;
431 if ((colon = g_strchr(pattern, ':')) == NULL || colon[1] != ']')
432 return 1; /* not a character class */
434 len = (size_t)(colon - pattern);
435 for (cc = cclasses; cc->name != NULL; cc++) {
436 if (!g_strncmp(pattern, cc->name, len) && cc->name[len] == '\0')
439 if (cc->name == NULL)
440 return -1; /* invalid character class */
441 *bufnext++ = M_CLASS;
442 *bufnext++ = (Char)(cc - &cclasses[0]);
444 *patternp += len + 3;
450 * The main glob() routine: compiles the pattern (optionally processing
451 * quotes), calls glob1() to do the real pattern matching, and finally
452 * sorts the list (unless unsorted operation is requested). Returns 0
453 * if things went well, nonzero if errors occurred. It is not an error
454 * to find no matches.
457 glob0(const Char *pattern, glob_t *pglob)
459 const Char *qpatnext;
460 int c, err, oldpathc;
461 Char *bufnext, patbuf[PATH_MAX];
463 qpatnext = globtilde(pattern, patbuf, PATH_MAX, pglob);
464 oldpathc = pglob->gl_pathc;
467 /* We don't need to check for buffer overflow any more. */
468 while ((c = *qpatnext++) != EOS) {
474 if (*qpatnext == EOS ||
475 g_strchr(qpatnext+1, RBRACKET) == NULL) {
476 *bufnext++ = LBRACKET;
486 if (c == LBRACKET && *qpatnext == ':') {
488 err = g_charclass(&qpatnext,
493 } while (c == LBRACKET && *qpatnext == ':');
495 !(pglob->gl_flags & GLOB_NOCHECK))
500 *bufnext++ = CHAR(c);
501 if (*qpatnext == RANGE &&
502 (c = qpatnext[1]) != RBRACKET) {
504 *bufnext++ = CHAR(c);
507 } while ((c = *qpatnext++) != RBRACKET);
508 pglob->gl_flags |= GLOB_MAGCHAR;
512 pglob->gl_flags |= GLOB_MAGCHAR;
516 pglob->gl_flags |= GLOB_MAGCHAR;
517 /* collapse adjacent stars to one,
518 * to avoid exponential behavior
520 if (bufnext == patbuf || bufnext[-1] != M_ALL)
524 *bufnext++ = CHAR(c);
530 qprintf("glob0:", patbuf);
533 if ((err = glob1(patbuf, patbuf + PATH_MAX - 1, pglob)) != 0)
537 * If there was no match we are going to append the pattern
538 * if GLOB_NOCHECK was specified.
540 if (pglob->gl_pathc == oldpathc) {
541 if (pglob->gl_flags & GLOB_NOCHECK)
542 return globextend(pattern, pglob);
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, Char *pattern_last, glob_t *pglob)
561 Char pathbuf[PATH_MAX];
563 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
566 return glob2(pathbuf, pathbuf + PATH_MAX - 1,
567 pathbuf, pathbuf + PATH_MAX - 1,
568 pattern, pattern_last, pglob);
572 * The functions glob2 and glob3 are mutually recursive; there is one level
573 * of recursion for each segment in the pattern that contains one or more
577 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
578 Char *pattern, Char *pattern_last, glob_t *pglob)
585 * Loop over pattern segments until end of pattern or until
586 * segment with meta character found.
588 for (anymeta = 0;;) {
589 if (*pattern == EOS) { /* End of pattern? */
591 if (g_lstat(pathbuf, &sb, pglob))
594 if (((pglob->gl_flags & GLOB_MARK) &&
595 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
596 (S_ISLNK(sb.st_mode) &&
597 (g_stat(pathbuf, &sb, pglob) == 0) &&
598 S_ISDIR(sb.st_mode)))) {
599 if (pathend+1 > pathend_last)
605 return globextend(pathbuf, pglob);
608 /* Find end of next segment, copy tentatively to pathend. */
611 while (*p != EOS && *p != SEP) {
614 if (q+1 > pathend_last)
619 if (!anymeta) { /* No expansion, do next segment. */
622 while (*pattern == SEP) {
623 if (pathend+1 > pathend_last)
625 *pathend++ = *pattern++;
628 /* Need expansion, recurse. */
629 return glob3(pathbuf, pathbuf_last, pathend,
630 pathend_last, pattern, pattern_last,
631 p, pattern_last, pglob);
637 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
638 Char *pattern, Char *pattern_last, Char *restpattern,
639 Char *restpattern_last, glob_t *pglob)
646 if (pathend > pathend_last)
651 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
652 /* TODO: don't call for ENOENT or ENOTDIR? */
653 if (pglob->gl_errfunc) {
654 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
656 if (pglob->gl_errfunc(buf, errno) ||
657 pglob->gl_flags & GLOB_ERR)
665 /* Search directory for matching names. */
666 while ((dp = readdir(dirp))) {
670 /* Initial DOT must be matched literally. */
671 if (dp->d_name[0] == DOT && *pattern != DOT)
674 sc = (unsigned char *) dp->d_name;
675 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
677 if (dc >= pathend_last) {
683 if (!match(pathend, pattern, restpattern)) {
687 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
688 restpattern, restpattern_last, pglob);
698 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
699 * add the new item, and update gl_pathc.
701 * This assumes the BSD realloc, which only copies the block when its size
702 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
705 * Return 0 if new item added, error code if memory couldn't be allocated.
707 * Invariant of the glob_t structure:
708 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
709 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
712 globextend(const Char *path, glob_t *pglob)
716 unsigned int newsize, len;
720 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
721 pathv = pglob->gl_pathv ?
722 (char **)realloc((char *)pglob->gl_pathv, newsize) :
723 (char **)malloc(newsize);
725 if (pglob->gl_pathv) {
726 free(pglob->gl_pathv);
727 pglob->gl_pathv = NULL;
732 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
733 /* first time around -- clear initial gl_offs items */
734 pathv += pglob->gl_offs;
735 for (i = pglob->gl_offs; --i >= 0; )
738 pglob->gl_pathv = pathv;
740 for (p = path; *p++;)
742 len = (size_t)(p - path);
743 if ((copy = malloc(len)) != NULL) {
744 if (g_Ctoc(path, copy, len)) {
748 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
750 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
752 return copy == NULL ? GLOB_NOSPACE : 0;
756 * pattern matching function for filenames. Each occurrence of the *
757 * pattern causes a recursion level.
760 match(Char *name, Char *pat, Char *patend)
762 int ok, negate_range;
765 while (pat < patend) {
767 switch (c & M_MASK) {
772 if (match(name, pat, patend))
774 } while (*name++ != EOS);
782 if ((k = *name++) == EOS)
784 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
786 while (((c = *pat++) & M_MASK) != M_END) {
787 if ((c & M_MASK) == M_CLASS) {
788 int idx = *pat & M_MASK;
789 if (idx < NCCLASSES &&
790 cclasses[idx].isctype(k))
794 if ((*pat & M_MASK) == M_RNG) {
795 if (c <= k && k <= pat[1])
801 if (ok == negate_range)
813 /* Free allocated data belonging to a glob_t structure. */
815 rpl_globfree(glob_t *pglob)
820 if (pglob->gl_pathv != NULL) {
821 pp = pglob->gl_pathv + pglob->gl_offs;
822 for (i = pglob->gl_pathc; i--; ++pp)
825 free(pglob->gl_pathv);
826 pglob->gl_pathv = NULL;
831 g_opendir(Char *str, glob_t *pglob)
839 if (g_Ctoc(str, buf, sizeof(buf)))
846 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
850 if (g_Ctoc(fn, buf, sizeof(buf)))
852 return lstat(buf, sb);
856 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
860 if (g_Ctoc(fn, buf, sizeof(buf)))
862 return stat(buf, sb);
866 g_strchr(const Char *str, int ch)
876 g_Ctoc(const Char *str, char *buf, unsigned int len)
880 if ((*buf++ = *str++) == EOS)
888 qprintf(const char *str, Char *s)
892 (void)printf("%s:\n", str);
894 (void)printf("%c", CHAR(*p));
897 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
900 (void)printf("%c", ismeta(*p) ? '_' : ' ');
904 #endif /* HAVE_GLOB */