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.16 2001/04/05 18:36:12 deraadt 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 *, u_int));
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;
201 if (flags & GLOB_BRACE)
202 return globexp1(patbuf, pglob);
204 return glob0(patbuf, pglob);
208 * Expand recursively a glob {} pattern. When there is no more expansion
209 * invoke the standard globbing routine to glob the rest of the magic
213 globexp1(pattern, pglob)
217 const Char* ptr = pattern;
220 /* Protect a single {}, for find(1), like csh */
221 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
222 return glob0(pattern, pglob);
224 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
225 if (!globexp2(ptr, pattern, pglob, &rv))
228 return glob0(pattern, pglob);
233 * Recursive brace globbing helper. Tries to expand a single brace.
234 * If it succeeds then it invokes globexp1 with the new pattern.
235 * If it fails then it tries to glob the rest of the pattern and returns.
238 globexp2(ptr, pattern, pglob, rv)
239 const Char *ptr, *pattern;
245 const Char *pe, *pm, *pl;
246 Char patbuf[MAXPATHLEN];
248 /* copy part up to the brace */
249 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
254 /* Find the balanced brace */
255 for (i = 0, pe = ++ptr; *pe; pe++)
256 if (*pe == LBRACKET) {
257 /* Ignore everything between [] */
258 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
262 * We could not find a matching RBRACKET.
263 * Ignore and just look for RBRACE
267 } else if (*pe == LBRACE)
269 else if (*pe == RBRACE) {
275 /* Non matching braces; just glob the pattern */
276 if (i != 0 || *pe == EOS) {
277 *rv = glob0(patbuf, pglob);
281 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
284 /* Ignore everything between [] */
285 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
289 * We could not find a matching RBRACKET.
290 * Ignore and just look for RBRACE
307 if (i && *pm == COMMA)
310 /* Append the current string */
311 for (lm = ls; (pl < pm); *lm++ = *pl++)
315 * Append the rest of the pattern after the
318 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
321 /* Expand the current pattern */
323 qprintf("globexp2:", patbuf);
325 *rv = globexp1(patbuf, pglob);
327 /* move after the comma, to the next string */
343 * expand tilde from the passwd file.
346 globtilde(pattern, patbuf, patbuf_len, pglob)
357 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
360 /* Copy up to the end of the string or / */
361 eb = &patbuf[patbuf_len - 1];
362 for (p = pattern + 1, h = (char *) patbuf;
363 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
373 if (((char *) patbuf)[0] == EOS) {
375 * handle a plain ~ or ~/ by expanding $HOME
376 * first and then trying the password file
379 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
381 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
382 if ((pwd = getpwuid(getuid())) == NULL)
391 if ((pwd = getpwnam((char*) patbuf)) == NULL)
397 /* Copy the home directory */
398 for (b = patbuf; b < eb && *h; *b++ = *h++)
401 /* Append the rest of the pattern */
402 while (b < eb && (*b++ = *p++) != EOS)
411 * The main glob() routine: compiles the pattern (optionally processing
412 * quotes), calls glob1() to do the real pattern matching, and finally
413 * sorts the list (unless unsorted operation is requested). Returns 0
414 * if things went well, nonzero if errors occurred. It is not an error
415 * to find no matches.
418 glob0(pattern, pglob)
422 const Char *qpatnext;
423 int c, err, oldpathc;
424 Char *bufnext, patbuf[MAXPATHLEN];
427 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
428 oldpathc = pglob->gl_pathc;
431 /* We don't need to check for buffer overflow any more. */
432 while ((c = *qpatnext++) != EOS) {
438 if (*qpatnext == EOS ||
439 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
440 *bufnext++ = LBRACKET;
450 *bufnext++ = CHAR(c);
451 if (*qpatnext == RANGE &&
452 (c = qpatnext[1]) != RBRACKET) {
454 *bufnext++ = CHAR(c);
457 } while ((c = *qpatnext++) != RBRACKET);
458 pglob->gl_flags |= GLOB_MAGCHAR;
462 pglob->gl_flags |= GLOB_MAGCHAR;
466 pglob->gl_flags |= GLOB_MAGCHAR;
467 /* collapse adjacent stars to one,
468 * to avoid exponential behavior
470 if (bufnext == patbuf || bufnext[-1] != M_ALL)
474 *bufnext++ = CHAR(c);
480 qprintf("glob0:", patbuf);
483 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
487 * If there was no match we are going to append the pattern
488 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
489 * and the pattern did not contain any magic characters
490 * GLOB_NOMAGIC is there just for compatibility with csh.
492 if (pglob->gl_pathc == oldpathc) {
493 if ((pglob->gl_flags & GLOB_NOCHECK) ||
494 ((pglob->gl_flags & GLOB_NOMAGIC) &&
495 !(pglob->gl_flags & GLOB_MAGCHAR)))
496 return(globextend(pattern, pglob, &limit));
498 return(GLOB_NOMATCH);
500 if (!(pglob->gl_flags & GLOB_NOSORT))
501 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
502 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
510 return(strcmp(*(char **)p, *(char **)q));
514 glob1(pattern, pattern_last, pglob, limitp)
515 Char *pattern, *pattern_last;
519 Char pathbuf[MAXPATHLEN];
521 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
524 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
525 pathbuf, pathbuf+MAXPATHLEN-1,
526 pattern, pattern_last, pglob, limitp));
530 * The functions glob2 and glob3 are mutually recursive; there is one level
531 * of recursion for each segment in the pattern that contains one or more
535 glob2(pathbuf, pathbuf_last, pathend, pathend_last, pattern,
536 pattern_last, pglob, limitp)
537 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
538 Char *pattern, *pattern_last;
547 * Loop over pattern segments until end of pattern or until
548 * segment with meta character found.
550 for (anymeta = 0;;) {
551 if (*pattern == EOS) { /* End of pattern? */
553 if (g_lstat(pathbuf, &sb, pglob))
556 if (((pglob->gl_flags & GLOB_MARK) &&
557 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
558 (S_ISLNK(sb.st_mode) &&
559 (g_stat(pathbuf, &sb, pglob) == 0) &&
560 S_ISDIR(sb.st_mode)))) {
561 if (pathend+1 > pathend_last)
567 return(globextend(pathbuf, pglob, limitp));
570 /* Find end of next segment, copy tentatively to pathend. */
573 while (*p != EOS && *p != SEP) {
576 if (q+1 > pathend_last)
581 if (!anymeta) { /* No expansion, do next segment. */
584 while (*pattern == SEP) {
585 if (pathend+1 > pathend_last)
587 *pathend++ = *pattern++;
590 /* Need expansion, recurse. */
591 return(glob3(pathbuf, pathbuf_last, pathend,
592 pathend_last, pattern, pattern_last,
593 p, pattern_last, pglob, limitp));
599 glob3(pathbuf, pathbuf_last, pathend, pathend_last, pattern, pattern_last,
600 restpattern, restpattern_last, pglob, limitp)
601 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
602 Char *pattern, *pattern_last, *restpattern, *restpattern_last;
606 register struct dirent *dp;
609 char buf[MAXPATHLEN];
612 * The readdirfunc declaration can't be prototyped, because it is
613 * assigned, below, to two functions which are prototyped in glob.h
614 * and dirent.h as taking pointers to differently typed opaque
617 struct dirent *(*readdirfunc)();
619 if (pathend > pathend_last)
624 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
625 /* TODO: don't call for ENOENT or ENOTDIR? */
626 if (pglob->gl_errfunc) {
627 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
628 return(GLOB_ABORTED);
629 if (pglob->gl_errfunc(buf, errno) ||
630 pglob->gl_flags & GLOB_ERR)
631 return(GLOB_ABORTED);
638 /* Search directory for matching names. */
639 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
640 readdirfunc = pglob->gl_readdir;
642 readdirfunc = readdir;
643 while ((dp = (*readdirfunc)(dirp))) {
647 /* Initial DOT must be matched literally. */
648 if (dp->d_name[0] == DOT && *pattern != DOT)
651 sc = (u_char *) dp->d_name;
652 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
654 if (dc >= pathend_last) {
660 if (!match(pathend, pattern, restpattern)) {
664 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
665 restpattern, restpattern_last, pglob, limitp);
670 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
671 (*pglob->gl_closedir)(dirp);
679 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
680 * add the new item, and update gl_pathc.
682 * This assumes the BSD realloc, which only copies the block when its size
683 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
686 * Return 0 if new item added, error code if memory couldn't be allocated.
688 * Invariant of the glob_t structure:
689 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
690 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
693 globextend(path, pglob, limitp)
698 register char **pathv;
704 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
705 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
708 if (pglob->gl_pathv) {
709 free(pglob->gl_pathv);
710 pglob->gl_pathv = NULL;
712 return(GLOB_NOSPACE);
715 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
716 /* first time around -- clear initial gl_offs items */
717 pathv += pglob->gl_offs;
718 for (i = pglob->gl_offs; --i >= 0; )
721 pglob->gl_pathv = pathv;
723 for (p = path; *p++;)
725 len = (size_t)(p - path);
727 if ((copy = malloc(len)) != NULL) {
728 if (g_Ctoc(path, copy, len)) {
730 return(GLOB_NOSPACE);
732 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
734 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
736 if ((pglob->gl_flags & GLOB_LIMIT) &&
737 newsize + *limitp >= (u_int) get_arg_max()) {
739 return(GLOB_NOSPACE);
742 return(copy == NULL ? GLOB_NOSPACE : 0);
747 * pattern matching function for filenames. Each occurrence of the *
748 * pattern causes a recursion level.
751 match(name, pat, patend)
752 register Char *name, *pat, *patend;
754 int ok, negate_range;
757 while (pat < patend) {
759 switch (c & M_MASK) {
764 if (match(name, pat, patend))
766 while (*name++ != EOS)
775 if ((k = *name++) == EOS)
777 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
779 while (((c = *pat++) & M_MASK) != M_END)
780 if ((*pat & M_MASK) == M_RNG) {
781 if (c <= k && k <= pat[1])
786 if (ok == negate_range)
795 return(*name == EOS);
798 /* Free allocated data belonging to a glob_t structure. */
806 if (pglob->gl_pathv != NULL) {
807 pp = pglob->gl_pathv + pglob->gl_offs;
808 for (i = pglob->gl_pathc; i--; ++pp)
811 free(pglob->gl_pathv);
812 pglob->gl_pathv = NULL;
817 g_opendir(str, pglob)
821 char buf[MAXPATHLEN];
826 if (g_Ctoc(str, buf, sizeof(buf)))
830 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
831 return((*pglob->gl_opendir)(buf));
833 return(opendir(buf));
837 g_lstat(fn, sb, pglob)
842 char buf[MAXPATHLEN];
844 if (g_Ctoc(fn, buf, sizeof(buf)))
846 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
847 return((*pglob->gl_lstat)(buf, sb));
848 return(lstat(buf, sb));
852 g_stat(fn, sb, pglob)
857 char buf[MAXPATHLEN];
859 if (g_Ctoc(fn, buf, sizeof(buf)))
861 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
862 return((*pglob->gl_stat)(buf, sb));
863 return(stat(buf, sb));
879 g_Ctoc(str, buf, len)
880 register const Char *str;
886 if ((*buf++ = *str++) == EOS)
900 (void)printf("%s:\n", str);
902 (void)printf("%c", CHAR(*p));
905 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
908 (void)printf("%c", ismeta(*p) ? '_' : ' ');
913 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
914 !defined(GLOB_HAS_GL_MATCHC) */