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) || \
41 !defined(GLOB_HAS_GL_MATCHC)
43 #if defined(LIBC_SCCS) && !defined(lint)
45 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
47 static char rcsid[] = "$OpenBSD: glob.c,v 1.10 2001/03/19 13:45:30 millert Exp $";
49 #endif /* LIBC_SCCS and not lint */
52 * glob(3) -- a superset of the one defined in POSIX 1003.2.
54 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
56 * Optional extra services, controlled by flags not defined by POSIX:
59 * Escaping convention: \ inhibits any special meaning the following
60 * character might have (except \ at end of string is retained).
62 * Set in gl_flags if pattern contained a globbing character.
64 * Same as GLOB_NOCHECK, but it will only append pattern if it did
65 * not contain any magic characters. [Used in csh style globbing]
67 * Use alternately specified directory access functions.
69 * expand ~user/foo to the /home/dir/of/user/foo
71 * expand {1,2}{a,b} to 1a 1b 2a 2b
73 * Number of matches in the current invocation of glob.
89 #define UNDERSCORE '_'
97 #define M_QUOTE 0x8000
98 #define M_PROTECT 0x4000
100 #define M_ASCII 0x00ff
102 typedef u_short Char;
107 #define M_PROTECT 0x40
116 #define CHAR(c) ((Char)((c)&M_ASCII))
117 #define META(c) ((Char)((c)|M_QUOTE))
118 #define M_ALL META('*')
119 #define M_END META(']')
120 #define M_NOT META('!')
121 #define M_ONE META('?')
122 #define M_RNG META('-')
123 #define M_SET META('[')
124 #define ismeta(c) (((c)&M_QUOTE) != 0)
127 static int compare __P((const void *, const void *));
128 static void g_Ctoc __P((const Char *, char *));
129 static int g_lstat __P((Char *, struct stat *, glob_t *));
130 static DIR *g_opendir __P((Char *, glob_t *));
131 static Char *g_strchr __P((Char *, int));
133 static Char *g_strcat __P((Char *, const Char *));
135 static int g_stat __P((Char *, struct stat *, glob_t *));
136 static int glob0 __P((const Char *, glob_t *));
137 static int glob1 __P((Char *, glob_t *, size_t *));
138 static int glob2 __P((Char *, Char *, Char *, glob_t *, size_t *));
139 static int glob3 __P((Char *, Char *, Char *, Char *, glob_t *,
141 static int globextend __P((const Char *, glob_t *, size_t *));
143 globtilde __P((const Char *, Char *, size_t, glob_t *));
144 static int globexp1 __P((const Char *, glob_t *));
145 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
146 static int match __P((Char *, Char *, Char *));
148 static void qprintf __P((const char *, Char *));
152 glob(pattern, flags, errfunc, pglob)
154 int flags, (*errfunc) __P((const char *, int));
157 const u_char *patnext;
159 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
161 patnext = (u_char *) pattern;
162 if (!(flags & GLOB_APPEND)) {
164 pglob->gl_pathv = NULL;
165 if (!(flags & GLOB_DOOFFS))
168 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
169 pglob->gl_errfunc = errfunc;
170 pglob->gl_matchc = 0;
173 bufend = bufnext + MAXPATHLEN;
174 if (flags & GLOB_NOESCAPE)
175 while (bufnext < bufend && (c = *patnext++) != EOS)
178 /* Protect the quoted characters. */
179 while (bufnext < bufend && (c = *patnext++) != EOS)
181 if ((c = *patnext++) == EOS) {
185 *bufnext++ = c | M_PROTECT;
192 if (flags & GLOB_BRACE)
193 return globexp1(patbuf, pglob);
195 return glob0(patbuf, pglob);
199 * Expand recursively a glob {} pattern. When there is no more expansion
200 * invoke the standard globbing routine to glob the rest of the magic
203 static int globexp1(pattern, pglob)
207 const Char* ptr = pattern;
210 /* Protect a single {}, for find(1), like csh */
211 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
212 return glob0(pattern, pglob);
214 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
215 if (!globexp2(ptr, pattern, pglob, &rv))
218 return glob0(pattern, pglob);
223 * Recursive brace globbing helper. Tries to expand a single brace.
224 * If it succeeds then it invokes globexp1 with the new pattern.
225 * If it fails then it tries to glob the rest of the pattern and returns.
227 static int globexp2(ptr, pattern, pglob, rv)
228 const Char *ptr, *pattern;
234 const Char *pe, *pm, *pl;
235 Char patbuf[MAXPATHLEN + 1];
237 /* copy part up to the brace */
238 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
242 /* Find the balanced brace */
243 for (i = 0, pe = ++ptr; *pe; pe++)
244 if (*pe == LBRACKET) {
245 /* Ignore everything between [] */
246 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
250 * We could not find a matching RBRACKET.
251 * Ignore and just look for RBRACE
256 else if (*pe == LBRACE)
258 else if (*pe == RBRACE) {
264 /* Non matching braces; just glob the pattern */
265 if (i != 0 || *pe == EOS) {
266 *rv = glob0(patbuf, pglob);
270 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
273 /* Ignore everything between [] */
274 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
278 * We could not find a matching RBRACKET.
279 * Ignore and just look for RBRACE
296 if (i && *pm == COMMA)
299 /* Append the current string */
300 for (lm = ls; (pl < pm); *lm++ = *pl++)
303 * Append the rest of the pattern after the
306 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
309 /* Expand the current pattern */
311 qprintf("globexp2:", patbuf);
313 *rv = globexp1(patbuf, pglob);
315 /* move after the comma, to the next string */
330 * expand tilde from the passwd file.
333 globtilde(pattern, patbuf, patbuf_len, pglob)
344 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
347 /* Copy up to the end of the string or / */
348 eb = &patbuf[patbuf_len - 1];
349 for (p = pattern + 1, h = (char *) patbuf;
350 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
355 if (((char *) patbuf)[0] == EOS) {
357 * handle a plain ~ or ~/ by expanding $HOME
358 * first and then trying the password file
361 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
363 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
364 if ((pwd = getpwuid(getuid())) == NULL)
374 if ((pwd = getpwnam((char*) patbuf)) == NULL)
380 /* Copy the home directory */
381 for (b = patbuf; b < eb && *h; *b++ = *h++)
384 /* Append the rest of the pattern */
385 while (b < eb && (*b++ = *p++) != EOS)
394 * The main glob() routine: compiles the pattern (optionally processing
395 * quotes), calls glob1() to do the real pattern matching, and finally
396 * sorts the list (unless unsorted operation is requested). Returns 0
397 * if things went well, nonzero if errors occurred. It is not an error
398 * to find no matches.
401 glob0(pattern, pglob)
405 const Char *qpatnext;
406 int c, err, oldpathc;
407 Char *bufnext, patbuf[MAXPATHLEN+1];
410 qpatnext = globtilde(pattern, patbuf, sizeof(patbuf) / sizeof(Char),
412 oldpathc = pglob->gl_pathc;
415 /* We don't need to check for buffer overflow any more. */
416 while ((c = *qpatnext++) != EOS) {
422 if (*qpatnext == EOS ||
423 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
424 *bufnext++ = LBRACKET;
434 *bufnext++ = CHAR(c);
435 if (*qpatnext == RANGE &&
436 (c = qpatnext[1]) != RBRACKET) {
438 *bufnext++ = CHAR(c);
441 } while ((c = *qpatnext++) != RBRACKET);
442 pglob->gl_flags |= GLOB_MAGCHAR;
446 pglob->gl_flags |= GLOB_MAGCHAR;
450 pglob->gl_flags |= GLOB_MAGCHAR;
451 /* collapse adjacent stars to one,
452 * to avoid exponential behavior
454 if (bufnext == patbuf || bufnext[-1] != M_ALL)
458 *bufnext++ = CHAR(c);
464 qprintf("glob0:", patbuf);
467 if ((err = glob1(patbuf, pglob, &limit)) != 0)
471 * If there was no match we are going to append the pattern
472 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
473 * and the pattern did not contain any magic characters
474 * GLOB_NOMAGIC is there just for compatibility with csh.
476 if (pglob->gl_pathc == oldpathc) {
477 if ((pglob->gl_flags & GLOB_NOCHECK) ||
478 ((pglob->gl_flags & GLOB_NOMAGIC) &&
479 !(pglob->gl_flags & GLOB_MAGCHAR)))
480 return(globextend(pattern, pglob, &limit));
482 return(GLOB_NOMATCH);
484 if (!(pglob->gl_flags & GLOB_NOSORT))
485 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
486 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
494 return(strcmp(*(char **)p, *(char **)q));
498 glob1(pattern, pglob, limitp)
503 Char pathbuf[MAXPATHLEN+1];
505 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
508 return(glob2(pathbuf, pathbuf, pattern, pglob, limitp));
512 * The functions glob2 and glob3 are mutually recursive; there is one level
513 * of recursion for each segment in the pattern that contains one or more
517 glob2(pathbuf, pathend, pattern, pglob, limitp)
518 Char *pathbuf, *pathend, *pattern;
527 * Loop over pattern segments until end of pattern or until
528 * segment with meta character found.
530 for (anymeta = 0;;) {
531 if (*pattern == EOS) { /* End of pattern? */
533 if (g_lstat(pathbuf, &sb, pglob))
536 if (((pglob->gl_flags & GLOB_MARK) &&
537 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
538 || (S_ISLNK(sb.st_mode) &&
539 (g_stat(pathbuf, &sb, pglob) == 0) &&
540 S_ISDIR(sb.st_mode)))) {
545 return(globextend(pathbuf, pglob, limitp));
548 /* Find end of next segment, copy tentatively to pathend. */
551 while (*p != EOS && *p != SEP) {
557 if (!anymeta) { /* No expansion, do next segment. */
560 while (*pattern == SEP)
561 *pathend++ = *pattern++;
562 } else /* Need expansion, recurse. */
563 return(glob3(pathbuf, pathend, pattern, p, pglob,
570 glob3(pathbuf, pathend, pattern, restpattern, pglob, limitp)
571 Char *pathbuf, *pathend, *pattern, *restpattern;
575 register struct dirent *dp;
578 char buf[MAXPATHLEN];
581 * The readdirfunc declaration can't be prototyped, because it is
582 * assigned, below, to two functions which are prototyped in glob.h
583 * and dirent.h as taking pointers to differently typed opaque
586 struct dirent *(*readdirfunc)();
591 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
592 /* TODO: don't call for ENOENT or ENOTDIR? */
593 if (pglob->gl_errfunc) {
594 g_Ctoc(pathbuf, buf);
595 if (pglob->gl_errfunc(buf, errno) ||
596 pglob->gl_flags & GLOB_ERR)
597 return (GLOB_ABORTED);
604 /* Search directory for matching names. */
605 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
606 readdirfunc = pglob->gl_readdir;
608 readdirfunc = readdir;
609 while ((dp = (*readdirfunc)(dirp))) {
613 /* Initial DOT must be matched literally. */
614 if (dp->d_name[0] == DOT && *pattern != DOT)
616 for (sc = (u_char *) dp->d_name, dc = pathend;
617 (*dc++ = *sc++) != EOS;)
619 if (!match(pathend, pattern, restpattern)) {
623 err = glob2(pathbuf, --dc, restpattern, pglob, limitp);
628 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
629 (*pglob->gl_closedir)(dirp);
637 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
638 * add the new item, and update gl_pathc.
640 * This assumes the BSD realloc, which only copies the block when its size
641 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
644 * Return 0 if new item added, error code if memory couldn't be allocated.
646 * Invariant of the glob_t structure:
647 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
648 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
651 globextend(path, pglob, limitp)
656 register char **pathv;
662 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
663 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
666 if (pglob->gl_pathv) {
667 free(pglob->gl_pathv);
668 pglob->gl_pathv = NULL;
670 return(GLOB_NOSPACE);
673 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
674 /* first time around -- clear initial gl_offs items */
675 pathv += pglob->gl_offs;
676 for (i = pglob->gl_offs; --i >= 0; )
679 pglob->gl_pathv = pathv;
681 for (p = path; *p++;)
683 len = (size_t)(p - path);
685 if ((copy = malloc(len)) != NULL) {
687 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
689 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
691 if ((pglob->gl_flags & GLOB_LIMIT) &&
692 newsize + *limitp >= ARG_MAX) {
694 return(GLOB_NOSPACE);
697 return(copy == NULL ? GLOB_NOSPACE : 0);
702 * pattern matching function for filenames. Each occurrence of the *
703 * pattern causes a recursion level.
706 match(name, pat, patend)
707 register Char *name, *pat, *patend;
709 int ok, negate_range;
712 while (pat < patend) {
714 switch (c & M_MASK) {
719 if (match(name, pat, patend))
721 while (*name++ != EOS);
729 if ((k = *name++) == EOS)
731 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
733 while (((c = *pat++) & M_MASK) != M_END)
734 if ((*pat & M_MASK) == M_RNG) {
735 if (c <= k && k <= pat[1])
740 if (ok == negate_range)
749 return(*name == EOS);
752 /* Free allocated data belonging to a glob_t structure. */
760 if (pglob->gl_pathv != NULL) {
761 pp = pglob->gl_pathv + pglob->gl_offs;
762 for (i = pglob->gl_pathc; i--; ++pp)
765 free(pglob->gl_pathv);
766 pglob->gl_pathv = NULL;
771 g_opendir(str, pglob)
775 char buf[MAXPATHLEN];
782 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
783 return((*pglob->gl_opendir)(buf));
785 return(opendir(buf));
789 g_lstat(fn, sb, pglob)
794 char buf[MAXPATHLEN];
797 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
798 return((*pglob->gl_lstat)(buf, sb));
799 return(lstat(buf, sb));
803 g_stat(fn, sb, pglob)
808 char buf[MAXPATHLEN];
811 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
812 return((*pglob->gl_stat)(buf, sb));
813 return(stat(buf, sb));
839 while((*dst++ = *src++) != EOS)
848 register const Char *str;
853 for (dc = buf; (*dc++ = *str++) != EOS;)
865 (void)printf("%s:\n", str);
867 (void)printf("%c", CHAR(*p));
870 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
873 (void)printf("%c", ismeta(*p) ? '_' : ' ');
878 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
879 !defined(GLOB_HAS_GL_MATCHC) */