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.13 2001/03/28 08:00:00 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 *, 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 *, glob_t *, size_t *));
147 static int glob2 __P((Char *, Char *, Char *, glob_t *, size_t *));
148 static int glob3 __P((Char *, Char *, Char *, Char *, glob_t *,
150 static int globextend __P((const Char *, glob_t *, size_t *));
152 globtilde __P((const Char *, Char *, size_t, glob_t *));
153 static int globexp1 __P((const Char *, glob_t *));
154 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
155 static int match __P((Char *, Char *, Char *));
157 static void qprintf __P((const char *, Char *));
161 glob(pattern, flags, errfunc, pglob)
163 int flags, (*errfunc) __P((const char *, int));
166 const u_char *patnext;
168 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
170 patnext = (u_char *) pattern;
171 if (!(flags & GLOB_APPEND)) {
173 pglob->gl_pathv = NULL;
174 if (!(flags & GLOB_DOOFFS))
177 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
178 pglob->gl_errfunc = errfunc;
179 pglob->gl_matchc = 0;
182 bufend = bufnext + MAXPATHLEN;
183 if (flags & GLOB_NOESCAPE)
184 while (bufnext < bufend && (c = *patnext++) != EOS)
187 /* Protect the quoted characters. */
188 while (bufnext < bufend && (c = *patnext++) != EOS)
190 if ((c = *patnext++) == EOS) {
194 *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
212 static int globexp1(pattern, pglob)
216 const Char* ptr = pattern;
219 /* Protect a single {}, for find(1), like csh */
220 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
221 return glob0(pattern, pglob);
223 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
224 if (!globexp2(ptr, pattern, pglob, &rv))
227 return glob0(pattern, pglob);
232 * Recursive brace globbing helper. Tries to expand a single brace.
233 * If it succeeds then it invokes globexp1 with the new pattern.
234 * If it fails then it tries to glob the rest of the pattern and returns.
236 static int globexp2(ptr, pattern, pglob, rv)
237 const Char *ptr, *pattern;
243 const Char *pe, *pm, *pl;
244 Char patbuf[MAXPATHLEN + 1];
246 /* copy part up to the brace */
247 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
265 else if (*pe == LBRACE)
267 else if (*pe == RBRACE) {
273 /* Non matching braces; just glob the pattern */
274 if (i != 0 || *pe == EOS) {
275 *rv = glob0(patbuf, pglob);
279 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
282 /* Ignore everything between [] */
283 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
287 * We could not find a matching RBRACKET.
288 * Ignore and just look for RBRACE
305 if (i && *pm == COMMA)
308 /* Append the current string */
309 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++)
365 if (((char *) patbuf)[0] == EOS) {
367 * handle a plain ~ or ~/ by expanding $HOME
368 * first and then trying the password file
371 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
373 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
374 if ((pwd = getpwuid(getuid())) == NULL)
384 if ((pwd = getpwnam((char*) patbuf)) == NULL)
390 /* Copy the home directory */
391 for (b = patbuf; b < eb && *h; *b++ = *h++)
394 /* Append the rest of the pattern */
395 while (b < eb && (*b++ = *p++) != EOS)
404 * The main glob() routine: compiles the pattern (optionally processing
405 * quotes), calls glob1() to do the real pattern matching, and finally
406 * sorts the list (unless unsorted operation is requested). Returns 0
407 * if things went well, nonzero if errors occurred. It is not an error
408 * to find no matches.
411 glob0(pattern, pglob)
415 const Char *qpatnext;
416 int c, err, oldpathc;
417 Char *bufnext, patbuf[MAXPATHLEN+1];
420 qpatnext = globtilde(pattern, patbuf, sizeof(patbuf) / sizeof(Char),
422 oldpathc = pglob->gl_pathc;
425 /* We don't need to check for buffer overflow any more. */
426 while ((c = *qpatnext++) != EOS) {
432 if (*qpatnext == EOS ||
433 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
434 *bufnext++ = LBRACKET;
444 *bufnext++ = CHAR(c);
445 if (*qpatnext == RANGE &&
446 (c = qpatnext[1]) != RBRACKET) {
448 *bufnext++ = CHAR(c);
451 } while ((c = *qpatnext++) != RBRACKET);
452 pglob->gl_flags |= GLOB_MAGCHAR;
456 pglob->gl_flags |= GLOB_MAGCHAR;
460 pglob->gl_flags |= GLOB_MAGCHAR;
461 /* collapse adjacent stars to one,
462 * to avoid exponential behavior
464 if (bufnext == patbuf || bufnext[-1] != M_ALL)
468 *bufnext++ = CHAR(c);
474 qprintf("glob0:", patbuf);
477 if ((err = glob1(patbuf, pglob, &limit)) != 0)
481 * If there was no match we are going to append the pattern
482 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
483 * and the pattern did not contain any magic characters
484 * GLOB_NOMAGIC is there just for compatibility with csh.
486 if (pglob->gl_pathc == oldpathc) {
487 if ((pglob->gl_flags & GLOB_NOCHECK) ||
488 ((pglob->gl_flags & GLOB_NOMAGIC) &&
489 !(pglob->gl_flags & GLOB_MAGCHAR)))
490 return(globextend(pattern, pglob, &limit));
492 return(GLOB_NOMATCH);
494 if (!(pglob->gl_flags & GLOB_NOSORT))
495 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
496 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
504 return(strcmp(*(char **)p, *(char **)q));
508 glob1(pattern, pglob, limitp)
513 Char pathbuf[MAXPATHLEN+1];
515 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
518 return(glob2(pathbuf, pathbuf, pattern, pglob, limitp));
522 * The functions glob2 and glob3 are mutually recursive; there is one level
523 * of recursion for each segment in the pattern that contains one or more
527 glob2(pathbuf, pathend, pattern, pglob, limitp)
528 Char *pathbuf, *pathend, *pattern;
537 * Loop over pattern segments until end of pattern or until
538 * segment with meta character found.
540 for (anymeta = 0;;) {
541 if (*pattern == EOS) { /* End of pattern? */
543 if (g_lstat(pathbuf, &sb, pglob))
546 if (((pglob->gl_flags & GLOB_MARK) &&
547 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
548 (S_ISLNK(sb.st_mode) &&
549 (g_stat(pathbuf, &sb, pglob) == 0) &&
550 S_ISDIR(sb.st_mode)))) {
555 return(globextend(pathbuf, pglob, limitp));
558 /* Find end of next segment, copy tentatively to pathend. */
561 while (*p != EOS && *p != SEP) {
567 if (!anymeta) { /* No expansion, do next segment. */
570 while (*pattern == SEP)
571 *pathend++ = *pattern++;
573 /* Need expansion, recurse. */
574 return(glob3(pathbuf, pathend, pattern, p, pglob,
581 glob3(pathbuf, pathend, pattern, restpattern, pglob, limitp)
582 Char *pathbuf, *pathend, *pattern, *restpattern;
586 register struct dirent *dp;
589 char buf[MAXPATHLEN];
592 * The readdirfunc declaration can't be prototyped, because it is
593 * assigned, below, to two functions which are prototyped in glob.h
594 * and dirent.h as taking pointers to differently typed opaque
597 struct dirent *(*readdirfunc)();
602 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
603 /* TODO: don't call for ENOENT or ENOTDIR? */
604 if (pglob->gl_errfunc) {
605 if (g_Ctoc(pathbuf, buf, buf+sizeof(buf)))
606 return(GLOB_ABORTED);
607 if (pglob->gl_errfunc(buf, errno) ||
608 pglob->gl_flags & GLOB_ERR)
609 return(GLOB_ABORTED);
616 /* Search directory for matching names. */
617 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
618 readdirfunc = pglob->gl_readdir;
620 readdirfunc = readdir;
621 while ((dp = (*readdirfunc)(dirp))) {
625 /* Initial DOT must be matched literally. */
626 if (dp->d_name[0] == DOT && *pattern != DOT)
628 for (sc = (u_char *) dp->d_name, dc = pathend;
629 (*dc++ = *sc++) != EOS;)
631 if (!match(pathend, pattern, restpattern)) {
635 err = glob2(pathbuf, --dc, restpattern, pglob, limitp);
640 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
641 (*pglob->gl_closedir)(dirp);
649 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
650 * add the new item, and update gl_pathc.
652 * This assumes the BSD realloc, which only copies the block when its size
653 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
656 * Return 0 if new item added, error code if memory couldn't be allocated.
658 * Invariant of the glob_t structure:
659 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
660 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
663 globextend(path, pglob, limitp)
668 register char **pathv;
674 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
675 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
678 if (pglob->gl_pathv) {
679 free(pglob->gl_pathv);
680 pglob->gl_pathv = NULL;
682 return(GLOB_NOSPACE);
685 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
686 /* first time around -- clear initial gl_offs items */
687 pathv += pglob->gl_offs;
688 for (i = pglob->gl_offs; --i >= 0; )
691 pglob->gl_pathv = pathv;
693 for (p = path; *p++;)
695 len = (size_t)(p - path);
697 if ((copy = malloc(len)) != NULL) {
698 if (g_Ctoc(path, copy, copy+len+1)) {
700 return(GLOB_NOSPACE);
702 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
704 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
706 if ((pglob->gl_flags & GLOB_LIMIT) &&
707 newsize + *limitp >= (u_int) get_arg_max()) {
709 return(GLOB_NOSPACE);
712 return(copy == NULL ? GLOB_NOSPACE : 0);
717 * pattern matching function for filenames. Each occurrence of the *
718 * pattern causes a recursion level.
721 match(name, pat, patend)
722 register Char *name, *pat, *patend;
724 int ok, negate_range;
727 while (pat < patend) {
729 switch (c & M_MASK) {
734 if (match(name, pat, patend))
736 while (*name++ != EOS)
745 if ((k = *name++) == EOS)
747 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
749 while (((c = *pat++) & M_MASK) != M_END)
750 if ((*pat & M_MASK) == M_RNG) {
751 if (c <= k && k <= pat[1])
756 if (ok == negate_range)
765 return(*name == EOS);
768 /* Free allocated data belonging to a glob_t structure. */
776 if (pglob->gl_pathv != NULL) {
777 pp = pglob->gl_pathv + pglob->gl_offs;
778 for (i = pglob->gl_pathc; i--; ++pp)
781 free(pglob->gl_pathv);
782 pglob->gl_pathv = NULL;
787 g_opendir(str, pglob)
791 char buf[MAXPATHLEN];
796 if (g_Ctoc(str, buf, buf+sizeof(buf)))
800 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
801 return((*pglob->gl_opendir)(buf));
803 return(opendir(buf));
807 g_lstat(fn, sb, pglob)
812 char buf[MAXPATHLEN];
814 if (g_Ctoc(fn, buf, buf+sizeof(buf)))
816 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
817 return((*pglob->gl_lstat)(buf, sb));
818 return(lstat(buf, sb));
822 g_stat(fn, sb, pglob)
827 char buf[MAXPATHLEN];
829 if (g_Ctoc(fn, buf, buf+sizeof(buf)))
831 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
832 return((*pglob->gl_stat)(buf, sb));
833 return(stat(buf, sb));
849 g_Ctoc(str, buf, ebuf)
850 register const Char *str;
855 for (dc = buf; dc < ebuf && (*dc++ = *str++) != EOS;)
870 (void)printf("%s:\n", str);
872 (void)printf("%c", CHAR(*p));
875 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
878 (void)printf("%c", ismeta(*p) ? '_' : ' ');
883 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
884 !defined(GLOB_HAS_GL_MATCHC) */