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 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)glob.c 8.3 (Berkeley) 10/13/93
37 * $OpenBSD: glob.c,v 1.20 2002/06/14 21:34:58 todd Exp $
48 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
49 return(sysconf(_SC_ARG_MAX));
51 return(256); /* XXX: arbitrary */
55 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
56 !defined(GLOB_HAS_GL_MATCHC)
59 * glob(3) -- a superset of the one defined in POSIX 1003.2.
61 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
63 * Optional extra services, controlled by flags not defined by POSIX:
66 * Escaping convention: \ inhibits any special meaning the following
67 * character might have (except \ at end of string is retained).
69 * Set in gl_flags if pattern contained a globbing character.
71 * Same as GLOB_NOCHECK, but it will only append pattern if it did
72 * not contain any magic characters. [Used in csh style globbing]
74 * Use alternately specified directory access functions.
76 * expand ~user/foo to the /home/dir/of/user/foo
78 * expand {1,2}{a,b} to 1a 1b 2a 2b
80 * Number of matches in the current invocation of glob.
95 #undef TILDE /* Some platforms may already define it */
97 #define UNDERSCORE '_'
105 #define M_QUOTE 0x8000
106 #define M_PROTECT 0x4000
107 #define M_MASK 0xffff
108 #define M_ASCII 0x00ff
110 typedef u_short Char;
115 #define M_PROTECT 0x40
124 #define CHAR(c) ((Char)((c)&M_ASCII))
125 #define META(c) ((Char)((c)|M_QUOTE))
126 #define M_ALL META('*')
127 #define M_END META(']')
128 #define M_NOT META('!')
129 #define M_ONE META('?')
130 #define M_RNG META('-')
131 #define M_SET META('[')
132 #define ismeta(c) (((c)&M_QUOTE) != 0)
135 static int compare(const void *, const void *);
136 static int g_Ctoc(const Char *, char *, u_int);
137 static int g_lstat(Char *, struct stat *, glob_t *);
138 static DIR *g_opendir(Char *, glob_t *);
139 static Char *g_strchr(Char *, int);
140 static int g_stat(Char *, struct stat *, glob_t *);
141 static int glob0(const Char *, glob_t *);
142 static int glob1(Char *, Char *, glob_t *, size_t *);
143 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
145 static int glob3(Char *, Char *, Char *, Char *, Char *, Char *,
146 Char *, Char *, glob_t *, size_t *);
147 static int globextend(const Char *, glob_t *, size_t *);
149 globtilde(const Char *, Char *, size_t, glob_t *);
150 static int globexp1(const Char *, glob_t *);
151 static int globexp2(const Char *, const Char *, glob_t *, int *);
152 static int match(Char *, Char *, Char *);
154 static void qprintf(const char *, Char *);
158 glob(pattern, flags, errfunc, pglob)
160 int flags, (*errfunc)(const char *, int);
163 const u_char *patnext;
165 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
167 patnext = (u_char *) pattern;
168 if (!(flags & GLOB_APPEND)) {
170 pglob->gl_pathv = NULL;
171 if (!(flags & GLOB_DOOFFS))
174 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
175 pglob->gl_errfunc = errfunc;
176 pglob->gl_matchc = 0;
179 bufend = bufnext + MAXPATHLEN - 1;
180 if (flags & GLOB_NOESCAPE)
181 while (bufnext < bufend && (c = *patnext++) != EOS)
184 /* Protect the quoted characters. */
185 while (bufnext < bufend && (c = *patnext++) != EOS)
187 if ((c = *patnext++) == EOS) {
191 *bufnext++ = c | M_PROTECT;
197 if (flags & GLOB_BRACE)
198 return globexp1(patbuf, pglob);
200 return glob0(patbuf, pglob);
204 * Expand recursively a glob {} pattern. When there is no more expansion
205 * invoke the standard globbing routine to glob the rest of the magic
209 globexp1(pattern, pglob)
213 const Char* ptr = pattern;
216 /* Protect a single {}, for find(1), like csh */
217 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
218 return glob0(pattern, pglob);
220 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
221 if (!globexp2(ptr, pattern, pglob, &rv))
224 return glob0(pattern, pglob);
229 * Recursive brace globbing helper. Tries to expand a single brace.
230 * If it succeeds then it invokes globexp1 with the new pattern.
231 * If it fails then it tries to glob the rest of the pattern and returns.
234 globexp2(ptr, pattern, pglob, rv)
235 const Char *ptr, *pattern;
241 const Char *pe, *pm, *pl;
242 Char patbuf[MAXPATHLEN];
244 /* copy part up to the brace */
245 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
250 /* Find the balanced brace */
251 for (i = 0, pe = ++ptr; *pe; pe++)
252 if (*pe == LBRACKET) {
253 /* Ignore everything between [] */
254 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
258 * We could not find a matching RBRACKET.
259 * Ignore and just look for RBRACE
263 } else if (*pe == LBRACE)
265 else if (*pe == RBRACE) {
271 /* Non matching braces; just glob the pattern */
272 if (i != 0 || *pe == EOS) {
273 *rv = glob0(patbuf, pglob);
277 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
280 /* Ignore everything between [] */
281 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
285 * We could not find a matching RBRACKET.
286 * Ignore and just look for RBRACE
303 if (i && *pm == COMMA)
306 /* Append the current string */
307 for (lm = ls; (pl < pm); *lm++ = *pl++)
311 * Append the rest of the pattern after the
314 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
317 /* Expand the current pattern */
319 qprintf("globexp2:", patbuf);
321 *rv = globexp1(patbuf, pglob);
323 /* move after the comma, to the next string */
339 * expand tilde from the passwd file.
342 globtilde(pattern, patbuf, patbuf_len, pglob)
353 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
356 /* Copy up to the end of the string or / */
357 eb = &patbuf[patbuf_len - 1];
358 for (p = pattern + 1, h = (char *) patbuf;
359 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
369 if (((char *) patbuf)[0] == EOS) {
371 * handle a plain ~ or ~/ by expanding $HOME
372 * first and then trying the password file
375 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
377 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
378 if ((pwd = getpwuid(getuid())) == NULL)
387 if ((pwd = getpwnam((char*) patbuf)) == NULL)
393 /* Copy the home directory */
394 for (b = patbuf; b < eb && *h; *b++ = *h++)
397 /* Append the rest of the pattern */
398 while (b < eb && (*b++ = *p++) != EOS)
407 * The main glob() routine: compiles the pattern (optionally processing
408 * quotes), calls glob1() to do the real pattern matching, and finally
409 * sorts the list (unless unsorted operation is requested). Returns 0
410 * if things went well, nonzero if errors occurred. It is not an error
411 * to find no matches.
414 glob0(pattern, pglob)
418 const Char *qpatnext;
419 int c, err, oldpathc;
420 Char *bufnext, patbuf[MAXPATHLEN];
423 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
424 oldpathc = pglob->gl_pathc;
427 /* We don't need to check for buffer overflow any more. */
428 while ((c = *qpatnext++) != EOS) {
434 if (*qpatnext == EOS ||
435 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
436 *bufnext++ = LBRACKET;
446 *bufnext++ = CHAR(c);
447 if (*qpatnext == RANGE &&
448 (c = qpatnext[1]) != RBRACKET) {
450 *bufnext++ = CHAR(c);
453 } while ((c = *qpatnext++) != RBRACKET);
454 pglob->gl_flags |= GLOB_MAGCHAR;
458 pglob->gl_flags |= GLOB_MAGCHAR;
462 pglob->gl_flags |= GLOB_MAGCHAR;
463 /* collapse adjacent stars to one,
464 * to avoid exponential behavior
466 if (bufnext == patbuf || bufnext[-1] != M_ALL)
470 *bufnext++ = CHAR(c);
476 qprintf("glob0:", patbuf);
479 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
483 * If there was no match we are going to append the pattern
484 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
485 * and the pattern did not contain any magic characters
486 * GLOB_NOMAGIC is there just for compatibility with csh.
488 if (pglob->gl_pathc == oldpathc) {
489 if ((pglob->gl_flags & GLOB_NOCHECK) ||
490 ((pglob->gl_flags & GLOB_NOMAGIC) &&
491 !(pglob->gl_flags & GLOB_MAGCHAR)))
492 return(globextend(pattern, pglob, &limit));
494 return(GLOB_NOMATCH);
496 if (!(pglob->gl_flags & GLOB_NOSORT))
497 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
498 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
506 return(strcmp(*(char **)p, *(char **)q));
510 glob1(pattern, pattern_last, pglob, limitp)
511 Char *pattern, *pattern_last;
515 Char pathbuf[MAXPATHLEN];
517 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
520 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
521 pathbuf, pathbuf+MAXPATHLEN-1,
522 pattern, pattern_last, pglob, limitp));
526 * The functions glob2 and glob3 are mutually recursive; there is one level
527 * of recursion for each segment in the pattern that contains one or more
531 glob2(pathbuf, pathbuf_last, pathend, pathend_last, pattern,
532 pattern_last, pglob, limitp)
533 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
534 Char *pattern, *pattern_last;
543 * Loop over pattern segments until end of pattern or until
544 * segment with meta character found.
546 for (anymeta = 0;;) {
547 if (*pattern == EOS) { /* End of pattern? */
549 if (g_lstat(pathbuf, &sb, pglob))
552 if (((pglob->gl_flags & GLOB_MARK) &&
553 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
554 (S_ISLNK(sb.st_mode) &&
555 (g_stat(pathbuf, &sb, pglob) == 0) &&
556 S_ISDIR(sb.st_mode)))) {
557 if (pathend+1 > pathend_last)
563 return(globextend(pathbuf, pglob, limitp));
566 /* Find end of next segment, copy tentatively to pathend. */
569 while (*p != EOS && *p != SEP) {
572 if (q+1 > pathend_last)
577 if (!anymeta) { /* No expansion, do next segment. */
580 while (*pattern == SEP) {
581 if (pathend+1 > pathend_last)
583 *pathend++ = *pattern++;
586 /* Need expansion, recurse. */
587 return(glob3(pathbuf, pathbuf_last, pathend,
588 pathend_last, pattern, pattern_last,
589 p, pattern_last, pglob, limitp));
595 glob3(pathbuf, pathbuf_last, pathend, pathend_last, pattern, pattern_last,
596 restpattern, restpattern_last, pglob, limitp)
597 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
598 Char *pattern, *pattern_last, *restpattern, *restpattern_last;
602 register struct dirent *dp;
605 char buf[MAXPATHLEN];
608 * The readdirfunc declaration can't be prototyped, because it is
609 * assigned, below, to two functions which are prototyped in glob.h
610 * and dirent.h as taking pointers to differently typed opaque
613 struct dirent *(*readdirfunc)();
615 if (pathend > pathend_last)
620 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
621 /* TODO: don't call for ENOENT or ENOTDIR? */
622 if (pglob->gl_errfunc) {
623 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
624 return(GLOB_ABORTED);
625 if (pglob->gl_errfunc(buf, errno) ||
626 pglob->gl_flags & GLOB_ERR)
627 return(GLOB_ABORTED);
634 /* Search directory for matching names. */
635 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
636 readdirfunc = pglob->gl_readdir;
638 readdirfunc = readdir;
639 while ((dp = (*readdirfunc)(dirp))) {
643 /* Initial DOT must be matched literally. */
644 if (dp->d_name[0] == DOT && *pattern != DOT)
647 sc = (u_char *) dp->d_name;
648 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
650 if (dc >= pathend_last) {
656 if (!match(pathend, pattern, restpattern)) {
660 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
661 restpattern, restpattern_last, pglob, limitp);
666 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
667 (*pglob->gl_closedir)(dirp);
675 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
676 * add the new item, and update gl_pathc.
678 * This assumes the BSD realloc, which only copies the block when its size
679 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
682 * Return 0 if new item added, error code if memory couldn't be allocated.
684 * Invariant of the glob_t structure:
685 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
686 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
689 globextend(path, pglob, limitp)
694 register char **pathv;
700 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
701 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
704 if (pglob->gl_pathv) {
705 free(pglob->gl_pathv);
706 pglob->gl_pathv = NULL;
708 return(GLOB_NOSPACE);
711 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
712 /* first time around -- clear initial gl_offs items */
713 pathv += pglob->gl_offs;
714 for (i = pglob->gl_offs; --i >= 0; )
717 pglob->gl_pathv = pathv;
719 for (p = path; *p++;)
721 len = (size_t)(p - path);
723 if ((copy = malloc(len)) != NULL) {
724 if (g_Ctoc(path, copy, len)) {
726 return(GLOB_NOSPACE);
728 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
730 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
732 if ((pglob->gl_flags & GLOB_LIMIT) &&
733 newsize + *limitp >= (u_int) get_arg_max()) {
735 return(GLOB_NOSPACE);
738 return(copy == NULL ? GLOB_NOSPACE : 0);
743 * pattern matching function for filenames. Each occurrence of the *
744 * pattern causes a recursion level.
747 match(name, pat, patend)
748 register Char *name, *pat, *patend;
750 int ok, negate_range;
753 while (pat < patend) {
755 switch (c & M_MASK) {
760 if (match(name, pat, patend))
762 while (*name++ != EOS)
771 if ((k = *name++) == EOS)
773 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
775 while (((c = *pat++) & M_MASK) != M_END)
776 if ((*pat & M_MASK) == M_RNG) {
777 if (c <= k && k <= pat[1])
782 if (ok == negate_range)
791 return(*name == EOS);
794 /* Free allocated data belonging to a glob_t structure. */
802 if (pglob->gl_pathv != NULL) {
803 pp = pglob->gl_pathv + pglob->gl_offs;
804 for (i = pglob->gl_pathc; i--; ++pp)
807 free(pglob->gl_pathv);
808 pglob->gl_pathv = NULL;
813 g_opendir(str, pglob)
817 char buf[MAXPATHLEN];
820 strlcpy(buf, ".", sizeof buf);
822 if (g_Ctoc(str, buf, sizeof(buf)))
826 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
827 return((*pglob->gl_opendir)(buf));
829 return(opendir(buf));
833 g_lstat(fn, sb, pglob)
838 char buf[MAXPATHLEN];
840 if (g_Ctoc(fn, buf, sizeof(buf)))
842 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
843 return((*pglob->gl_lstat)(buf, sb));
844 return(lstat(buf, sb));
848 g_stat(fn, sb, pglob)
853 char buf[MAXPATHLEN];
855 if (g_Ctoc(fn, buf, sizeof(buf)))
857 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
858 return((*pglob->gl_stat)(buf, sb));
859 return(stat(buf, sb));
875 g_Ctoc(str, buf, len)
876 register const Char *str;
882 if ((*buf++ = *str++) == EOS)
896 (void)printf("%s:\n", str);
898 (void)printf("%c", CHAR(*p));
901 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
904 (void)printf("%c", ismeta(*p) ? '_' : ' ');
909 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
910 !defined(GLOB_HAS_GL_MATCHC) */