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
36 * $FreeBSD: src/lib/libc/gen/glob.c,v 1.11.6.6 2002/09/18 14:13:31 mikeh Exp $
39 #if defined(LIBC_SCCS) && !defined(lint)
40 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
41 #endif /* LIBC_SCCS and not lint */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD: src/lib/libc/gen/glob.c,v 1.11.6.6 2002/09/18 14:13:31 mikeh Exp $");
46 * glob(3) -- a superset of the one defined in POSIX 1003.2.
48 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
50 * Optional extra services, controlled by flags not defined by POSIX:
53 * Escaping convention: \ inhibits any special meaning the following
54 * character might have (except \ at end of string is retained).
56 * Set in gl_flags if pattern contained a globbing character.
58 * Same as GLOB_NOCHECK, but it will only append pattern if it did
59 * not contain any magic characters. [Used in csh style globbing]
61 * Use alternately specified directory access functions.
63 * expand ~user/foo to the /home/dir/of/user/foo
65 * expand {1,2}{a,b} to 1a 1b 2a 2b
67 * Number of matches in the current invocation of glob.
70 #include <sys/param.h>
97 #define UNDERSCORE '_'
105 #define M_QUOTE 0x8000
106 #define M_PROTECT 0x4000
107 #define M_MASK 0xffff
108 #define M_ASCII 0x00ff
110 typedef u_short Char;
115 #define M_PROTECT 0x40
124 #define CHAR(c) ((Char)((c)&M_ASCII))
125 #define META(c) ((Char)((c)|M_QUOTE))
126 #define M_ALL META('*')
127 #define M_END META(']')
128 #define M_NOT META('!')
129 #define M_ONE META('?')
130 #define M_RNG META('-')
131 #define M_SET META('[')
132 #define ismeta(c) (((c)&M_QUOTE) != 0)
135 static int compare(const void *, const void *);
136 static int g_Ctoc(const Char *, char *, u_int);
137 static int g_lstat(Char *, struct stat *, glob_t *);
138 static DIR *g_opendir(Char *, glob_t *);
139 static Char *g_strchr(Char *, int);
141 static Char *g_strcat(Char *, const Char *);
143 static int g_stat(Char *, struct stat *, glob_t *);
144 static int glob0(const Char *, glob_t *, int *);
145 static int glob1(Char *, glob_t *, int *);
146 static int glob2(Char *, Char *, Char *, Char *, glob_t *, int *);
147 static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *, int *);
148 static int globextend(const Char *, glob_t *, int *);
150 globtilde(const Char *, Char *, size_t, glob_t *);
151 static int globexp1(const Char *, glob_t *, int *);
152 static int globexp2(const Char *, const Char *, glob_t *, int *, 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 if (flags & GLOB_LIMIT) {
176 limit = pglob->gl_matchc;
181 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
182 pglob->gl_errfunc = errfunc;
183 pglob->gl_matchc = 0;
186 bufend = bufnext + MAXPATHLEN - 1;
187 if (flags & GLOB_NOESCAPE)
188 while (bufnext < bufend && (c = *patnext++) != EOS)
191 /* Protect the quoted characters. */
192 while (bufnext < bufend && (c = *patnext++) != EOS)
194 if ((c = *patnext++) == EOS) {
198 *bufnext++ = c | M_PROTECT;
205 if (flags & GLOB_BRACE)
206 return globexp1(patbuf, pglob, &limit);
208 return glob0(patbuf, pglob, &limit);
212 * Expand recursively a glob {} pattern. When there is no more expansion
213 * invoke the standard globbing routine to glob the rest of the magic
217 globexp1(pattern, pglob, limit)
222 const Char* ptr = pattern;
225 /* Protect a single {}, for find(1), like csh */
226 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
227 return glob0(pattern, pglob, limit);
229 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
230 if (!globexp2(ptr, pattern, pglob, &rv, limit))
233 return glob0(pattern, pglob, limit);
238 * Recursive brace globbing helper. Tries to expand a single brace.
239 * If it succeeds then it invokes globexp1 with the new pattern.
240 * If it fails then it tries to glob the rest of the pattern and returns.
243 globexp2(ptr, pattern, pglob, rv, limit)
244 const Char *ptr, *pattern;
250 const Char *pe, *pm, *pl;
251 Char patbuf[MAXPATHLEN];
253 /* copy part up to the brace */
254 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
259 /* Find the balanced brace */
260 for (i = 0, pe = ++ptr; *pe; pe++)
261 if (*pe == LBRACKET) {
262 /* Ignore everything between [] */
263 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
267 * We could not find a matching RBRACKET.
268 * Ignore and just look for RBRACE
273 else if (*pe == LBRACE)
275 else if (*pe == RBRACE) {
281 /* Non matching braces; just glob the pattern */
282 if (i != 0 || *pe == EOS) {
283 *rv = glob0(patbuf, pglob, limit);
287 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
290 /* Ignore everything between [] */
291 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
295 * We could not find a matching RBRACKET.
296 * Ignore and just look for RBRACE
313 if (i && *pm == COMMA)
316 /* Append the current string */
317 for (lm = ls; (pl < pm); *lm++ = *pl++)
320 * Append the rest of the pattern after the
323 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
326 /* Expand the current pattern */
328 qprintf("globexp2:", patbuf);
330 *rv = globexp1(patbuf, pglob, limit);
332 /* move after the comma, to the next string */
347 * expand tilde from the passwd file.
350 globtilde(pattern, patbuf, patbuf_len, pglob)
361 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
365 * Copy up to the end of the string or /
367 eb = &patbuf[patbuf_len - 1];
368 for (p = pattern + 1, h = (char *) patbuf;
369 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
374 if (((char *) patbuf)[0] == EOS) {
376 * handle a plain ~ or ~/ by expanding $HOME first (iff
377 * we're not running setuid or setgid) and then trying
381 #ifndef __NETBSD_SYSCALLS
384 (h = getenv("HOME")) == NULL) {
385 if (((h = getlogin()) != NULL &&
386 (pwd = getpwnam(h)) != NULL) ||
387 (pwd = getpwuid(getuid())) != NULL)
397 if ((pwd = getpwnam((char*) patbuf)) == NULL)
403 /* Copy the home directory */
404 for (b = patbuf; b < eb && *h; *b++ = *h++)
407 /* Append the rest of the pattern */
408 while (b < eb && (*b++ = *p++) != EOS)
417 * The main glob() routine: compiles the pattern (optionally processing
418 * quotes), calls glob1() to do the real pattern matching, and finally
419 * sorts the list (unless unsorted operation is requested). Returns 0
420 * if things went well, nonzero if errors occurred.
423 glob0(pattern, pglob, limit)
428 const Char *qpatnext;
429 int c, err, oldpathc;
430 Char *bufnext, patbuf[MAXPATHLEN];
432 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
433 oldpathc = pglob->gl_pathc;
436 /* We don't need to check for buffer overflow any more. */
437 while ((c = *qpatnext++) != EOS) {
443 if (*qpatnext == EOS ||
444 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
445 *bufnext++ = LBRACKET;
455 *bufnext++ = CHAR(c);
456 if (*qpatnext == RANGE &&
457 (c = qpatnext[1]) != RBRACKET) {
459 *bufnext++ = CHAR(c);
462 } while ((c = *qpatnext++) != RBRACKET);
463 pglob->gl_flags |= GLOB_MAGCHAR;
467 pglob->gl_flags |= GLOB_MAGCHAR;
471 pglob->gl_flags |= GLOB_MAGCHAR;
472 /* collapse adjacent stars to one,
473 * to avoid exponential behavior
475 if (bufnext == patbuf || bufnext[-1] != M_ALL)
479 *bufnext++ = CHAR(c);
485 qprintf("glob0:", patbuf);
488 if ((err = glob1(patbuf, pglob, limit)) != 0)
492 * If there was no match we are going to append the pattern
493 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
494 * and the pattern did not contain any magic characters
495 * GLOB_NOMAGIC is there just for compatibility with csh.
497 if (pglob->gl_pathc == oldpathc) {
498 if (((pglob->gl_flags & GLOB_NOCHECK) ||
499 ((pglob->gl_flags & GLOB_NOMAGIC) &&
500 !(pglob->gl_flags & GLOB_MAGCHAR))))
501 return(globextend(pattern, pglob, limit));
503 return(GLOB_NOMATCH);
505 if (!(pglob->gl_flags & GLOB_NOSORT))
506 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
507 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
515 return(strcmp(*(char **)p, *(char **)q));
519 glob1(pattern, pglob, limit)
524 Char pathbuf[MAXPATHLEN];
526 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
529 return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
530 pattern, pglob, limit));
534 * The functions glob2 and glob3 are mutually recursive; there is one level
535 * of recursion for each segment in the pattern that contains one or more
539 glob2(pathbuf, pathend, pathend_last, pattern, pglob, limit)
540 Char *pathbuf, *pathend, *pathend_last, *pattern;
549 * Loop over pattern segments until end of pattern or until
550 * segment with meta character found.
552 for (anymeta = 0;;) {
553 if (*pattern == EOS) { /* End of pattern? */
555 if (g_lstat(pathbuf, &sb, pglob))
558 if (((pglob->gl_flags & GLOB_MARK) &&
559 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
560 || (S_ISLNK(sb.st_mode) &&
561 (g_stat(pathbuf, &sb, pglob) == 0) &&
562 S_ISDIR(sb.st_mode)))) {
563 if (pathend + 1 > pathend_last)
564 return (GLOB_ABORTED);
569 return(globextend(pathbuf, pglob, limit));
572 /* Find end of next segment, copy tentatively to pathend. */
575 while (*p != EOS && *p != SEP) {
578 if (q + 1 > pathend_last)
579 return (GLOB_ABORTED);
583 if (!anymeta) { /* No expansion, do next segment. */
586 while (*pattern == SEP) {
587 if (pathend + 1 > pathend_last)
588 return (GLOB_ABORTED);
589 *pathend++ = *pattern++;
591 } else /* Need expansion, recurse. */
592 return(glob3(pathbuf, pathend, pathend_last, pattern, p,
599 glob3(pathbuf, pathend, pathend_last, pattern, restpattern, pglob, limit)
600 Char *pathbuf, *pathend, *pathend_last, *pattern, *restpattern;
607 char buf[MAXPATHLEN];
610 * The readdirfunc declaration can't be prototyped, because it is
611 * assigned, below, to two functions which are prototyped in glob.h
612 * and dirent.h as taking pointers to differently typed opaque
615 struct dirent *(*readdirfunc)();
617 if (pathend > pathend_last)
618 return (GLOB_ABORTED);
622 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
623 /* TODO: don't call for ENOENT or ENOTDIR? */
624 if (pglob->gl_errfunc) {
625 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
626 return (GLOB_ABORTED);
627 if (pglob->gl_errfunc(buf, errno) ||
628 pglob->gl_flags & GLOB_ERR)
629 return (GLOB_ABORTED);
636 /* Search directory for matching names. */
637 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
638 readdirfunc = pglob->gl_readdir;
640 readdirfunc = readdir;
641 while ((dp = (*readdirfunc)(dirp))) {
645 /* Initial DOT must be matched literally. */
646 if (dp->d_name[0] == DOT && *pattern != DOT)
649 sc = (u_char *) dp->d_name;
650 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
652 if (!match(pathend, pattern, restpattern)) {
656 err = glob2(pathbuf, --dc, pathend_last, restpattern,
662 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
663 (*pglob->gl_closedir)(dirp);
671 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
672 * add the new item, and update gl_pathc.
674 * This assumes the BSD realloc, which only copies the block when its size
675 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
678 * Return 0 if new item added, error code if memory couldn't be allocated.
680 * Invariant of the glob_t structure:
681 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
682 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
685 globextend(path, pglob, limit)
696 if (*limit && pglob->gl_pathc > *limit) {
698 return (GLOB_NOSPACE);
701 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
702 pathv = pglob->gl_pathv ?
703 realloc((char *)pglob->gl_pathv, newsize) :
706 if (pglob->gl_pathv) {
707 free(pglob->gl_pathv);
708 pglob->gl_pathv = NULL;
710 return(GLOB_NOSPACE);
713 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
714 /* first time around -- clear initial gl_offs items */
715 pathv += pglob->gl_offs;
716 for (i = pglob->gl_offs; --i >= 0; )
719 pglob->gl_pathv = pathv;
721 for (p = path; *p++;)
723 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;
732 return(copy == NULL ? GLOB_NOSPACE : 0);
736 * pattern matching function for filenames. Each occurrence of the *
737 * pattern causes a recursion level.
740 match(name, pat, patend)
741 Char *name, *pat, *patend;
743 int ok, negate_range;
746 while (pat < patend) {
748 switch (c & M_MASK) {
753 if (match(name, pat, patend))
755 while (*name++ != EOS);
763 if ((k = *name++) == EOS)
765 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
767 while (((c = *pat++) & M_MASK) != M_END)
768 if ((*pat & M_MASK) == M_RNG) {
769 if (__collate_load_error ?
770 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
771 __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
772 && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
778 if (ok == negate_range)
787 return(*name == EOS);
790 /* Free allocated data belonging to a glob_t structure. */
798 if (pglob->gl_pathv != NULL) {
799 pp = pglob->gl_pathv + pglob->gl_offs;
800 for (i = pglob->gl_pathc; i--; ++pp)
803 free(pglob->gl_pathv);
804 pglob->gl_pathv = NULL;
809 g_opendir(str, pglob)
813 char buf[MAXPATHLEN];
818 if (g_Ctoc(str, buf, sizeof(buf)))
822 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
823 return((*pglob->gl_opendir)(buf));
825 return(opendir(buf));
829 g_lstat(fn, sb, pglob)
834 char buf[MAXPATHLEN];
836 if (g_Ctoc(fn, buf, sizeof(buf))) {
837 errno = ENAMETOOLONG;
840 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
841 return((*pglob->gl_lstat)(buf, sb));
842 return(lstat(buf, sb));
846 g_stat(fn, sb, pglob)
851 char buf[MAXPATHLEN];
853 if (g_Ctoc(fn, buf, sizeof(buf))) {
854 errno = ENAMETOOLONG;
857 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
858 return((*pglob->gl_stat)(buf, sb));
859 return(stat(buf, sb));
875 g_Ctoc(str, buf, len)
882 if ((*buf++ = *str++) == '\0')
896 (void)printf("%s:\n", str);
898 (void)printf("%c", CHAR(*p));
901 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
904 (void)printf("%c", ismeta(*p) ? '_' : ' ');