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
40 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC)
42 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
46 static char rcsid[] = "$OpenBSD: glob.c,v 1.8 1998/08/14 21:39:30 deraadt Exp $";
48 #endif /* LIBC_SCCS and not lint */
51 * glob(3) -- a superset of the one defined in POSIX 1003.2.
53 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
55 * Optional extra services, controlled by flags not defined by POSIX:
58 * Escaping convention: \ inhibits any special meaning the following
59 * character might have (except \ at end of string is retained).
61 * Set in gl_flags if pattern contained a globbing character.
63 * Same as GLOB_NOCHECK, but it will only append pattern if it did
64 * not contain any magic characters. [Used in csh style globbing]
66 * Use alternately specified directory access functions.
68 * expand ~user/foo to the /home/dir/of/user/foo
70 * expand {1,2}{a,b} to 1a 1b 2a 2b
72 * Number of matches in the current invocation of glob.
88 #define UNDERSCORE '_'
96 #define M_QUOTE 0x8000
97 #define M_PROTECT 0x4000
99 #define M_ASCII 0x00ff
101 typedef u_short Char;
106 #define M_PROTECT 0x40
115 #define CHAR(c) ((Char)((c)&M_ASCII))
116 #define META(c) ((Char)((c)|M_QUOTE))
117 #define M_ALL META('*')
118 #define M_END META(']')
119 #define M_NOT META('!')
120 #define M_ONE META('?')
121 #define M_RNG META('-')
122 #define M_SET META('[')
123 #define ismeta(c) (((c)&M_QUOTE) != 0)
126 static int compare __P((const void *, const void *));
127 static void g_Ctoc __P((const Char *, char *));
128 static int g_lstat __P((Char *, struct stat *, glob_t *));
129 static DIR *g_opendir __P((Char *, glob_t *));
130 static Char *g_strchr __P((Char *, int));
132 static Char *g_strcat __P((Char *, const Char *));
134 static int g_stat __P((Char *, struct stat *, glob_t *));
135 static int glob0 __P((const Char *, glob_t *));
136 static int glob1 __P((Char *, glob_t *));
137 static int glob2 __P((Char *, Char *, Char *, glob_t *));
138 static int glob3 __P((Char *, Char *, Char *, Char *, glob_t *));
139 static int globextend __P((const Char *, glob_t *));
140 static const Char * globtilde __P((const Char *, Char *, size_t, glob_t *));
141 static int globexp1 __P((const Char *, glob_t *));
142 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
143 static int match __P((Char *, Char *, Char *));
145 static void qprintf __P((const char *, Char *));
149 glob(pattern, flags, errfunc, pglob)
151 int flags, (*errfunc) __P((const char *, int));
154 const u_char *patnext;
156 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
158 patnext = (u_char *) pattern;
159 if (!(flags & GLOB_APPEND)) {
161 pglob->gl_pathv = NULL;
162 if (!(flags & GLOB_DOOFFS))
165 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
166 pglob->gl_errfunc = errfunc;
167 pglob->gl_matchc = 0;
170 bufend = bufnext + MAXPATHLEN;
171 if (flags & GLOB_NOESCAPE)
172 while (bufnext < bufend && (c = *patnext++) != EOS)
175 /* Protect the quoted characters. */
176 while (bufnext < bufend && (c = *patnext++) != EOS)
178 if ((c = *patnext++) == EOS) {
182 *bufnext++ = c | M_PROTECT;
189 if (flags & GLOB_BRACE)
190 return globexp1(patbuf, pglob);
192 return glob0(patbuf, pglob);
196 * Expand recursively a glob {} pattern. When there is no more expansion
197 * invoke the standard globbing routine to glob the rest of the magic
200 static int globexp1(pattern, pglob)
204 const Char* ptr = pattern;
207 /* Protect a single {}, for find(1), like csh */
208 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
209 return glob0(pattern, pglob);
211 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
212 if (!globexp2(ptr, pattern, pglob, &rv))
215 return glob0(pattern, pglob);
220 * Recursive brace globbing helper. Tries to expand a single brace.
221 * If it succeeds then it invokes globexp1 with the new pattern.
222 * If it fails then it tries to glob the rest of the pattern and returns.
224 static int globexp2(ptr, pattern, pglob, rv)
225 const Char *ptr, *pattern;
231 const Char *pe, *pm, *pl;
232 Char patbuf[MAXPATHLEN + 1];
234 /* copy part up to the brace */
235 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
239 /* Find the balanced brace */
240 for (i = 0, pe = ++ptr; *pe; pe++)
241 if (*pe == LBRACKET) {
242 /* Ignore everything between [] */
243 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
247 * We could not find a matching RBRACKET.
248 * Ignore and just look for RBRACE
253 else if (*pe == LBRACE)
255 else if (*pe == RBRACE) {
261 /* Non matching braces; just glob the pattern */
262 if (i != 0 || *pe == EOS) {
263 *rv = glob0(patbuf, pglob);
267 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
270 /* Ignore everything between [] */
271 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
275 * We could not find a matching RBRACKET.
276 * Ignore and just look for RBRACE
293 if (i && *pm == COMMA)
296 /* Append the current string */
297 for (lm = ls; (pl < pm); *lm++ = *pl++)
300 * Append the rest of the pattern after the
303 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
306 /* Expand the current pattern */
308 qprintf("globexp2:", patbuf);
310 *rv = globexp1(patbuf, pglob);
312 /* move after the comma, to the next string */
327 * expand tilde from the passwd file.
330 globtilde(pattern, patbuf, patbuf_len, pglob)
341 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
344 /* Copy up to the end of the string or / */
345 eb = &patbuf[patbuf_len - 1];
346 for (p = pattern + 1, h = (char *) patbuf;
347 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
352 if (((char *) patbuf)[0] == EOS) {
354 * handle a plain ~ or ~/ by expanding $HOME
355 * first and then trying the password file
358 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
360 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
361 if ((pwd = getpwuid(getuid())) == NULL)
371 if ((pwd = getpwnam((char*) patbuf)) == NULL)
377 /* Copy the home directory */
378 for (b = patbuf; b < eb && *h; *b++ = *h++)
381 /* Append the rest of the pattern */
382 while (b < eb && (*b++ = *p++) != EOS)
391 * The main glob() routine: compiles the pattern (optionally processing
392 * quotes), calls glob1() to do the real pattern matching, and finally
393 * sorts the list (unless unsorted operation is requested). Returns 0
394 * if things went well, nonzero if errors occurred. It is not an error
395 * to find no matches.
398 glob0(pattern, pglob)
402 const Char *qpatnext;
403 int c, err, oldpathc;
404 Char *bufnext, patbuf[MAXPATHLEN+1];
406 qpatnext = globtilde(pattern, patbuf, sizeof(patbuf) / sizeof(Char),
408 oldpathc = pglob->gl_pathc;
411 /* We don't need to check for buffer overflow any more. */
412 while ((c = *qpatnext++) != EOS) {
418 if (*qpatnext == EOS ||
419 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
420 *bufnext++ = LBRACKET;
430 *bufnext++ = CHAR(c);
431 if (*qpatnext == RANGE &&
432 (c = qpatnext[1]) != RBRACKET) {
434 *bufnext++ = CHAR(c);
437 } while ((c = *qpatnext++) != RBRACKET);
438 pglob->gl_flags |= GLOB_MAGCHAR;
442 pglob->gl_flags |= GLOB_MAGCHAR;
446 pglob->gl_flags |= GLOB_MAGCHAR;
447 /* collapse adjacent stars to one,
448 * to avoid exponential behavior
450 if (bufnext == patbuf || bufnext[-1] != M_ALL)
454 *bufnext++ = CHAR(c);
460 qprintf("glob0:", patbuf);
463 if ((err = glob1(patbuf, pglob)) != 0)
467 * If there was no match we are going to append the pattern
468 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
469 * and the pattern did not contain any magic characters
470 * GLOB_NOMAGIC is there just for compatibility with csh.
472 if (pglob->gl_pathc == oldpathc) {
473 if ((pglob->gl_flags & GLOB_NOCHECK) ||
474 ((pglob->gl_flags & GLOB_NOMAGIC) &&
475 !(pglob->gl_flags & GLOB_MAGCHAR)))
476 return(globextend(pattern, pglob));
478 return(GLOB_NOMATCH);
480 if (!(pglob->gl_flags & GLOB_NOSORT))
481 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
482 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
490 return(strcmp(*(char **)p, *(char **)q));
494 glob1(pattern, pglob)
498 Char pathbuf[MAXPATHLEN+1];
500 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
503 return(glob2(pathbuf, pathbuf, pattern, pglob));
507 * The functions glob2 and glob3 are mutually recursive; there is one level
508 * of recursion for each segment in the pattern that contains one or more
512 glob2(pathbuf, pathend, pattern, pglob)
513 Char *pathbuf, *pathend, *pattern;
521 * Loop over pattern segments until end of pattern or until
522 * segment with meta character found.
524 for (anymeta = 0;;) {
525 if (*pattern == EOS) { /* End of pattern? */
527 if (g_lstat(pathbuf, &sb, pglob))
530 if (((pglob->gl_flags & GLOB_MARK) &&
531 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
532 || (S_ISLNK(sb.st_mode) &&
533 (g_stat(pathbuf, &sb, pglob) == 0) &&
534 S_ISDIR(sb.st_mode)))) {
539 return(globextend(pathbuf, pglob));
542 /* Find end of next segment, copy tentatively to pathend. */
545 while (*p != EOS && *p != SEP) {
551 if (!anymeta) { /* No expansion, do next segment. */
554 while (*pattern == SEP)
555 *pathend++ = *pattern++;
556 } else /* Need expansion, recurse. */
557 return(glob3(pathbuf, pathend, pattern, p, pglob));
563 glob3(pathbuf, pathend, pattern, restpattern, pglob)
564 Char *pathbuf, *pathend, *pattern, *restpattern;
567 register struct dirent *dp;
570 char buf[MAXPATHLEN];
573 * The readdirfunc declaration can't be prototyped, because it is
574 * assigned, below, to two functions which are prototyped in glob.h
575 * and dirent.h as taking pointers to differently typed opaque
578 struct dirent *(*readdirfunc)();
583 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
584 /* TODO: don't call for ENOENT or ENOTDIR? */
585 if (pglob->gl_errfunc) {
586 g_Ctoc(pathbuf, buf);
587 if (pglob->gl_errfunc(buf, errno) ||
588 pglob->gl_flags & GLOB_ERR)
589 return (GLOB_ABORTED);
596 /* Search directory for matching names. */
597 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
598 readdirfunc = pglob->gl_readdir;
600 readdirfunc = readdir;
601 while ((dp = (*readdirfunc)(dirp))) {
605 /* Initial DOT must be matched literally. */
606 if (dp->d_name[0] == DOT && *pattern != DOT)
608 for (sc = (u_char *) dp->d_name, dc = pathend;
609 (*dc++ = *sc++) != EOS;)
611 if (!match(pathend, pattern, restpattern)) {
615 err = glob2(pathbuf, --dc, restpattern, pglob);
620 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
621 (*pglob->gl_closedir)(dirp);
629 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
630 * add the new item, and update gl_pathc.
632 * This assumes the BSD realloc, which only copies the block when its size
633 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
636 * Return 0 if new item added, error code if memory couldn't be allocated.
638 * Invariant of the glob_t structure:
639 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
640 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
643 globextend(path, pglob)
647 register char **pathv;
653 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
654 pathv = pglob->gl_pathv ?
655 realloc((char *)pglob->gl_pathv, newsize) :
659 free(pglob->gl_pathv);
660 return(GLOB_NOSPACE);
663 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
664 /* first time around -- clear initial gl_offs items */
665 pathv += pglob->gl_offs;
666 for (i = pglob->gl_offs; --i >= 0; )
669 pglob->gl_pathv = pathv;
671 for (p = path; *p++;)
673 if ((copy = malloc(p - path)) != NULL) {
675 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
677 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
678 return(copy == NULL ? GLOB_NOSPACE : 0);
683 * pattern matching function for filenames. Each occurrence of the *
684 * pattern causes a recursion level.
687 match(name, pat, patend)
688 register Char *name, *pat, *patend;
690 int ok, negate_range;
693 while (pat < patend) {
695 switch (c & M_MASK) {
700 if (match(name, pat, patend))
702 while (*name++ != EOS);
710 if ((k = *name++) == EOS)
712 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
714 while (((c = *pat++) & M_MASK) != M_END)
715 if ((*pat & M_MASK) == M_RNG) {
716 if (c <= k && k <= pat[1])
721 if (ok == negate_range)
730 return(*name == EOS);
733 /* Free allocated data belonging to a glob_t structure. */
741 if (pglob->gl_pathv != NULL) {
742 pp = pglob->gl_pathv + pglob->gl_offs;
743 for (i = pglob->gl_pathc; i--; ++pp)
746 free(pglob->gl_pathv);
751 g_opendir(str, pglob)
755 char buf[MAXPATHLEN];
762 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
763 return((*pglob->gl_opendir)(buf));
765 return(opendir(buf));
769 g_lstat(fn, sb, pglob)
774 char buf[MAXPATHLEN];
777 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
778 return((*pglob->gl_lstat)(buf, sb));
779 return(lstat(buf, sb));
783 g_stat(fn, sb, pglob)
788 char buf[MAXPATHLEN];
791 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
792 return((*pglob->gl_stat)(buf, sb));
793 return(stat(buf, sb));
819 while((*dst++ = *src++) != EOS)
828 register const Char *str;
833 for (dc = buf; (*dc++ = *str++) != EOS;)
845 (void)printf("%s:\n", str);
847 (void)printf("%c", CHAR(*p));
850 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
853 (void)printf("%c", ismeta(*p) ? '_' : ' ');
858 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) */