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
45 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
46 return(sysconf(_SC_ARG_MAX));
48 return(256); /* XXX: arbitrary */
52 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
53 !defined(GLOB_HAS_GL_MATCHC)
55 #if defined(LIBC_SCCS) && !defined(lint)
57 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
59 static char rcsid[] = "$OpenBSD: glob.c,v 1.14 2001/03/28 20:54:19 millert Exp $";
61 #endif /* LIBC_SCCS and not lint */
64 * glob(3) -- a superset of the one defined in POSIX 1003.2.
66 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
68 * Optional extra services, controlled by flags not defined by POSIX:
71 * Escaping convention: \ inhibits any special meaning the following
72 * character might have (except \ at end of string is retained).
74 * Set in gl_flags if pattern contained a globbing character.
76 * Same as GLOB_NOCHECK, but it will only append pattern if it did
77 * not contain any magic characters. [Used in csh style globbing]
79 * Use alternately specified directory access functions.
81 * expand ~user/foo to the /home/dir/of/user/foo
83 * expand {1,2}{a,b} to 1a 1b 2a 2b
85 * Number of matches in the current invocation of glob.
101 #define UNDERSCORE '_'
109 #define M_QUOTE 0x8000
110 #define M_PROTECT 0x4000
111 #define M_MASK 0xffff
112 #define M_ASCII 0x00ff
114 typedef u_short Char;
119 #define M_PROTECT 0x40
128 #define CHAR(c) ((Char)((c)&M_ASCII))
129 #define META(c) ((Char)((c)|M_QUOTE))
130 #define M_ALL META('*')
131 #define M_END META(']')
132 #define M_NOT META('!')
133 #define M_ONE META('?')
134 #define M_RNG META('-')
135 #define M_SET META('[')
136 #define ismeta(c) (((c)&M_QUOTE) != 0)
139 static int compare __P((const void *, const void *));
140 static int g_Ctoc __P((const Char *, char *, char *));
141 static int g_lstat __P((Char *, struct stat *, glob_t *));
142 static DIR *g_opendir __P((Char *, glob_t *));
143 static Char *g_strchr __P((Char *, int));
144 static int g_stat __P((Char *, struct stat *, glob_t *));
145 static int glob0 __P((const Char *, glob_t *));
146 static int glob1 __P((Char *, Char *, glob_t *, size_t *));
147 static int glob2 __P((Char *, Char *, Char *, Char *, Char *, Char *,
148 glob_t *, size_t *));
149 static int glob3 __P((Char *, Char *, Char *, Char *, Char *, Char *,
150 Char *, Char *, glob_t *, size_t *));
151 static int globextend __P((const Char *, glob_t *, size_t *));
153 globtilde __P((const Char *, Char *, size_t, glob_t *));
154 static int globexp1 __P((const Char *, glob_t *));
155 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
156 static int match __P((Char *, Char *, Char *));
158 static void qprintf __P((const char *, Char *));
162 glob(pattern, flags, errfunc, pglob)
164 int flags, (*errfunc) __P((const char *, int));
167 const u_char *patnext;
169 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
171 patnext = (u_char *) pattern;
172 if (!(flags & GLOB_APPEND)) {
174 pglob->gl_pathv = NULL;
175 if (!(flags & GLOB_DOOFFS))
178 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
179 pglob->gl_errfunc = errfunc;
180 pglob->gl_matchc = 0;
183 bufend = bufnext + MAXPATHLEN - 1;
184 if (flags & GLOB_NOESCAPE)
185 while (bufnext < bufend && (c = *patnext++) != EOS)
188 /* Protect the quoted characters. */
189 while (bufnext < bufend && (c = *patnext++) != EOS)
191 if ((c = *patnext++) == EOS) {
195 *bufnext++ = c | M_PROTECT;
202 if (flags & GLOB_BRACE)
203 return globexp1(patbuf, pglob);
205 return glob0(patbuf, pglob);
209 * Expand recursively a glob {} pattern. When there is no more expansion
210 * invoke the standard globbing routine to glob the rest of the magic
214 globexp1(pattern, pglob)
218 const Char* ptr = pattern;
221 /* Protect a single {}, for find(1), like csh */
222 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
223 return glob0(pattern, pglob);
225 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
226 if (!globexp2(ptr, pattern, pglob, &rv))
229 return glob0(pattern, pglob);
234 * Recursive brace globbing helper. Tries to expand a single brace.
235 * If it succeeds then it invokes globexp1 with the new pattern.
236 * If it fails then it tries to glob the rest of the pattern and returns.
239 globexp2(ptr, pattern, pglob, rv)
240 const Char *ptr, *pattern;
246 const Char *pe, *pm, *pl;
247 Char patbuf[MAXPATHLEN];
249 /* copy part up to the brace */
250 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
255 /* Find the balanced brace */
256 for (i = 0, pe = ++ptr; *pe; pe++)
257 if (*pe == LBRACKET) {
258 /* Ignore everything between [] */
259 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
263 * We could not find a matching RBRACKET.
264 * Ignore and just look for RBRACE
269 else if (*pe == LBRACE)
271 else if (*pe == RBRACE) {
277 /* Non matching braces; just glob the pattern */
278 if (i != 0 || *pe == EOS) {
279 *rv = glob0(patbuf, pglob);
283 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
286 /* Ignore everything between [] */
287 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
291 * We could not find a matching RBRACKET.
292 * Ignore and just look for RBRACE
309 if (i && *pm == COMMA)
312 /* Append the current string */
313 for (lm = ls; (pl < pm); *lm++ = *pl++)
316 * Append the rest of the pattern after the
319 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
322 /* Expand the current pattern */
324 qprintf("globexp2:", patbuf);
326 *rv = globexp1(patbuf, pglob);
328 /* move after the comma, to the next string */
344 * expand tilde from the passwd file.
347 globtilde(pattern, patbuf, patbuf_len, pglob)
358 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
361 /* Copy up to the end of the string or / */
362 eb = &patbuf[patbuf_len - 1];
363 for (p = pattern + 1, h = (char *) patbuf;
364 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)
388 if ((pwd = getpwnam((char*) patbuf)) == NULL)
394 /* Copy the home directory */
395 for (b = patbuf; b < eb && *h; *b++ = *h++)
398 /* Append the rest of the pattern */
399 while (b < eb && (*b++ = *p++) != EOS)
408 * The main glob() routine: compiles the pattern (optionally processing
409 * quotes), calls glob1() to do the real pattern matching, and finally
410 * sorts the list (unless unsorted operation is requested). Returns 0
411 * if things went well, nonzero if errors occurred. It is not an error
412 * to find no matches.
415 glob0(pattern, pglob)
419 const Char *qpatnext;
420 int c, err, oldpathc;
421 Char *bufnext, patbuf[MAXPATHLEN];
424 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
425 oldpathc = pglob->gl_pathc;
428 /* We don't need to check for buffer overflow any more. */
429 while ((c = *qpatnext++) != EOS) {
435 if (*qpatnext == EOS ||
436 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
437 *bufnext++ = LBRACKET;
447 *bufnext++ = CHAR(c);
448 if (*qpatnext == RANGE &&
449 (c = qpatnext[1]) != RBRACKET) {
451 *bufnext++ = CHAR(c);
454 } while ((c = *qpatnext++) != RBRACKET);
455 pglob->gl_flags |= GLOB_MAGCHAR;
459 pglob->gl_flags |= GLOB_MAGCHAR;
463 pglob->gl_flags |= GLOB_MAGCHAR;
464 /* collapse adjacent stars to one,
465 * to avoid exponential behavior
467 if (bufnext == patbuf || bufnext[-1] != M_ALL)
471 *bufnext++ = CHAR(c);
477 qprintf("glob0:", patbuf);
480 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
484 * If there was no match we are going to append the pattern
485 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
486 * and the pattern did not contain any magic characters
487 * GLOB_NOMAGIC is there just for compatibility with csh.
489 if (pglob->gl_pathc == oldpathc) {
490 if ((pglob->gl_flags & GLOB_NOCHECK) ||
491 ((pglob->gl_flags & GLOB_NOMAGIC) &&
492 !(pglob->gl_flags & GLOB_MAGCHAR)))
493 return(globextend(pattern, pglob, &limit));
495 return(GLOB_NOMATCH);
497 if (!(pglob->gl_flags & GLOB_NOSORT))
498 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
499 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
507 return(strcmp(*(char **)p, *(char **)q));
511 glob1(pattern, pattern_last, pglob, limitp)
512 Char *pattern, *pattern_last;
516 Char pathbuf[MAXPATHLEN];
518 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
521 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
522 pathbuf, pathbuf+MAXPATHLEN-1,
523 pattern, pattern_last, pglob, limitp));
527 * The functions glob2 and glob3 are mutually recursive; there is one level
528 * of recursion for each segment in the pattern that contains one or more
532 glob2(pathbuf, pathbuf_last, pathend, pathend_last, pattern,
533 pattern_last, pglob, limitp)
534 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
535 Char *pattern, *pattern_last;
544 * Loop over pattern segments until end of pattern or until
545 * segment with meta character found.
547 for (anymeta = 0;;) {
548 if (*pattern == EOS) { /* End of pattern? */
550 if (g_lstat(pathbuf, &sb, pglob))
553 if (((pglob->gl_flags & GLOB_MARK) &&
554 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
555 (S_ISLNK(sb.st_mode) &&
556 (g_stat(pathbuf, &sb, pglob) == 0) &&
557 S_ISDIR(sb.st_mode)))) {
558 if (pathend+1 > pathend_last)
564 return(globextend(pathbuf, pglob, limitp));
567 /* Find end of next segment, copy tentatively to pathend. */
570 while (*p != EOS && *p != SEP) {
573 if (q+1 > pathend_last)
578 if (!anymeta) { /* No expansion, do next segment. */
581 while (*pattern == SEP) {
582 if (pathend+1 > pathend_last)
584 *pathend++ = *pattern++;
587 /* Need expansion, recurse. */
588 return(glob3(pathbuf, pathbuf_last, pathend,
589 pathend_last, pattern, pattern_last,
590 p, pattern_last, pglob, limitp));
596 glob3(pathbuf, pathbuf_last, pathend, pathend_last, pattern, pattern_last,
597 restpattern, restpattern_last, pglob, limitp)
598 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
599 Char *pattern, *pattern_last, *restpattern, *restpattern_last;
603 register struct dirent *dp;
606 char buf[MAXPATHLEN];
609 * The readdirfunc declaration can't be prototyped, because it is
610 * assigned, below, to two functions which are prototyped in glob.h
611 * and dirent.h as taking pointers to differently typed opaque
614 struct dirent *(*readdirfunc)();
616 if (pathend > pathend_last)
621 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
622 /* TODO: don't call for ENOENT or ENOTDIR? */
623 if (pglob->gl_errfunc) {
624 if (g_Ctoc(pathbuf, buf, buf+sizeof(buf)))
625 return(GLOB_ABORTED);
626 if (pglob->gl_errfunc(buf, errno) ||
627 pglob->gl_flags & GLOB_ERR)
628 return(GLOB_ABORTED);
635 /* Search directory for matching names. */
636 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
637 readdirfunc = pglob->gl_readdir;
639 readdirfunc = readdir;
640 while ((dp = (*readdirfunc)(dirp))) {
644 /* Initial DOT must be matched literally. */
645 if (dp->d_name[0] == DOT && *pattern != DOT)
648 sc = (u_char *) dp->d_name;
649 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
651 if (dc >= pathend_last) {
657 if (!match(pathend, pattern, restpattern)) {
661 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
662 restpattern, restpattern_last, pglob, limitp);
667 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
668 (*pglob->gl_closedir)(dirp);
676 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
677 * add the new item, and update gl_pathc.
679 * This assumes the BSD realloc, which only copies the block when its size
680 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
683 * Return 0 if new item added, error code if memory couldn't be allocated.
685 * Invariant of the glob_t structure:
686 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
687 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
690 globextend(path, pglob, limitp)
695 register char **pathv;
701 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
702 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
705 if (pglob->gl_pathv) {
706 free(pglob->gl_pathv);
707 pglob->gl_pathv = NULL;
709 return(GLOB_NOSPACE);
712 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
713 /* first time around -- clear initial gl_offs items */
714 pathv += pglob->gl_offs;
715 for (i = pglob->gl_offs; --i >= 0; )
718 pglob->gl_pathv = pathv;
720 for (p = path; *p++;)
722 len = (size_t)(p - path);
724 if ((copy = malloc(len)) != NULL) {
725 if (g_Ctoc(path, copy, copy+len+1)) {
727 return(GLOB_NOSPACE);
729 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
731 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
733 if ((pglob->gl_flags & GLOB_LIMIT) &&
734 newsize + *limitp >= (u_int) get_arg_max()) {
736 return(GLOB_NOSPACE);
739 return(copy == NULL ? GLOB_NOSPACE : 0);
744 * pattern matching function for filenames. Each occurrence of the *
745 * pattern causes a recursion level.
748 match(name, pat, patend)
749 register Char *name, *pat, *patend;
751 int ok, negate_range;
754 while (pat < patend) {
756 switch (c & M_MASK) {
761 if (match(name, pat, patend))
763 while (*name++ != EOS)
772 if ((k = *name++) == EOS)
774 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
776 while (((c = *pat++) & M_MASK) != M_END)
777 if ((*pat & M_MASK) == M_RNG) {
778 if (c <= k && k <= pat[1])
783 if (ok == negate_range)
792 return(*name == EOS);
795 /* Free allocated data belonging to a glob_t structure. */
803 if (pglob->gl_pathv != NULL) {
804 pp = pglob->gl_pathv + pglob->gl_offs;
805 for (i = pglob->gl_pathc; i--; ++pp)
808 free(pglob->gl_pathv);
809 pglob->gl_pathv = NULL;
814 g_opendir(str, pglob)
818 char buf[MAXPATHLEN];
823 if (g_Ctoc(str, buf, buf+sizeof(buf)))
827 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
828 return((*pglob->gl_opendir)(buf));
830 return(opendir(buf));
834 g_lstat(fn, sb, pglob)
839 char buf[MAXPATHLEN];
841 if (g_Ctoc(fn, buf, buf+sizeof(buf)))
843 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
844 return((*pglob->gl_lstat)(buf, sb));
845 return(lstat(buf, sb));
849 g_stat(fn, sb, pglob)
854 char buf[MAXPATHLEN];
856 if (g_Ctoc(fn, buf, buf+sizeof(buf)))
858 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
859 return((*pglob->gl_stat)(buf, sb));
860 return(stat(buf, sb));
876 g_Ctoc(str, buf, ebuf)
877 register const Char *str;
882 for (dc = buf; dc < ebuf && (*dc++ = *str++) != EOS;)
897 (void)printf("%s:\n", str);
899 (void)printf("%c", CHAR(*p));
902 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
905 (void)printf("%c", ismeta(*p) ? '_' : ' ');
910 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
911 !defined(GLOB_HAS_GL_MATCHC) */