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. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
42 return(sysconf(_SC_ARG_MAX));
44 return(256); /* XXX: arbitrary */
48 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
49 !defined(GLOB_HAS_GL_MATCHC)
51 #if defined(LIBC_SCCS) && !defined(lint)
53 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
55 static char rcsid[] = "$OpenBSD: glob.c,v 1.22 2003/06/25 21:16:47 deraadt Exp $";
57 #endif /* LIBC_SCCS and not lint */
60 * glob(3) -- a superset of the one defined in POSIX 1003.2.
62 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
64 * Optional extra services, controlled by flags not defined by POSIX:
67 * Escaping convention: \ inhibits any special meaning the following
68 * character might have (except \ at end of string is retained).
70 * Set in gl_flags if pattern contained a globbing character.
72 * Same as GLOB_NOCHECK, but it will only append pattern if it did
73 * not contain any magic characters. [Used in csh style globbing]
75 * Use alternately specified directory access functions.
77 * expand ~user/foo to the /home/dir/of/user/foo
79 * expand {1,2}{a,b} to 1a 1b 2a 2b
81 * Number of matches in the current invocation of glob.
96 #undef TILDE /* Some platforms may already define it */
98 #define UNDERSCORE '_'
106 #define M_QUOTE 0x8000
107 #define M_PROTECT 0x4000
108 #define M_MASK 0xffff
109 #define M_ASCII 0x00ff
111 typedef u_short Char;
116 #define M_PROTECT 0x40
125 #define CHAR(c) ((Char)((c)&M_ASCII))
126 #define META(c) ((Char)((c)|M_QUOTE))
127 #define M_ALL META('*')
128 #define M_END META(']')
129 #define M_NOT META('!')
130 #define M_ONE META('?')
131 #define M_RNG META('-')
132 #define M_SET META('[')
133 #define ismeta(c) (((c)&M_QUOTE) != 0)
136 static int compare(const void *, const void *);
137 static int g_Ctoc(const Char *, char *, u_int);
138 static int g_lstat(Char *, struct stat *, glob_t *);
139 static DIR *g_opendir(Char *, glob_t *);
140 static Char *g_strchr(Char *, int);
141 static int g_stat(Char *, struct stat *, glob_t *);
142 static int glob0(const Char *, glob_t *);
143 static int glob1(Char *, Char *, glob_t *, size_t *);
144 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
146 static int glob3(Char *, Char *, Char *, Char *, Char *, Char *,
147 Char *, Char *, glob_t *, size_t *);
148 static int globextend(const Char *, glob_t *, size_t *);
150 globtilde(const Char *, Char *, size_t, glob_t *);
151 static int globexp1(const Char *, glob_t *);
152 static int globexp2(const Char *, const Char *, glob_t *, int *);
153 static int match(Char *, Char *, Char *);
155 static void qprintf(const char *, Char *);
159 glob(pattern, flags, errfunc, pglob)
161 int flags, (*errfunc)(const char *, int);
164 const u_char *patnext;
166 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
168 patnext = (u_char *) pattern;
169 if (!(flags & GLOB_APPEND)) {
171 pglob->gl_pathv = NULL;
172 if (!(flags & GLOB_DOOFFS))
175 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
176 pglob->gl_errfunc = errfunc;
177 pglob->gl_matchc = 0;
180 bufend = bufnext + MAXPATHLEN - 1;
181 if (flags & GLOB_NOESCAPE)
182 while (bufnext < bufend && (c = *patnext++) != EOS)
185 /* Protect the quoted characters. */
186 while (bufnext < bufend && (c = *patnext++) != EOS)
188 if ((c = *patnext++) == EOS) {
192 *bufnext++ = c | M_PROTECT;
198 if (flags & GLOB_BRACE)
199 return globexp1(patbuf, pglob);
201 return glob0(patbuf, pglob);
205 * Expand recursively a glob {} pattern. When there is no more expansion
206 * invoke the standard globbing routine to glob the rest of the magic
210 globexp1(pattern, pglob)
214 const Char* ptr = pattern;
217 /* Protect a single {}, for find(1), like csh */
218 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
219 return glob0(pattern, pglob);
221 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
222 if (!globexp2(ptr, pattern, pglob, &rv))
225 return glob0(pattern, pglob);
230 * Recursive brace globbing helper. Tries to expand a single brace.
231 * If it succeeds then it invokes globexp1 with the new pattern.
232 * If it fails then it tries to glob the rest of the pattern and returns.
235 globexp2(ptr, pattern, pglob, rv)
236 const Char *ptr, *pattern;
242 const Char *pe, *pm, *pl;
243 Char patbuf[MAXPATHLEN];
245 /* copy part up to the brace */
246 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
251 /* Find the balanced brace */
252 for (i = 0, pe = ++ptr; *pe; pe++)
253 if (*pe == LBRACKET) {
254 /* Ignore everything between [] */
255 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
259 * We could not find a matching RBRACKET.
260 * Ignore and just look for RBRACE
264 } else if (*pe == LBRACE)
266 else if (*pe == RBRACE) {
272 /* Non matching braces; just glob the pattern */
273 if (i != 0 || *pe == EOS) {
274 *rv = glob0(patbuf, pglob);
278 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
281 /* Ignore everything between [] */
282 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
286 * We could not find a matching RBRACKET.
287 * Ignore and just look for RBRACE
304 if (i && *pm == COMMA)
307 /* Append the current string */
308 for (lm = ls; (pl < pm); *lm++ = *pl++)
312 * Append the rest of the pattern after the
315 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
318 /* Expand the current pattern */
320 qprintf("globexp2:", patbuf);
322 *rv = globexp1(patbuf, pglob);
324 /* move after the comma, to the next string */
340 * expand tilde from the passwd file.
343 globtilde(pattern, patbuf, patbuf_len, pglob)
354 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
357 /* Copy up to the end of the string or / */
358 eb = &patbuf[patbuf_len - 1];
359 for (p = pattern + 1, h = (char *) patbuf;
360 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
370 if (((char *) patbuf)[0] == EOS) {
372 * handle a plain ~ or ~/ by expanding $HOME
373 * first and then trying the password file
376 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
378 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
379 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)(void *);
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, 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 = (struct dirent *(*)(void *))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 accommodate 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, len)) {
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];
821 strlcpy(buf, ".", sizeof buf);
823 if (g_Ctoc(str, 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, 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, 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, len)
877 register const Char *str;
883 if ((*buf++ = *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) */