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
38 * Clause 3 above should be considered "deleted in its entirety".
39 * For the actual notice of withdrawal, see:
40 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
43 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
45 #endif /* LIBC_SCCS and not lint */
48 * glob(3) -- a superset of the one defined in POSIX 1003.2.
50 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
52 * Optional extra services, controlled by flags not defined by POSIX:
55 * Escaping convention: \ inhibits any special meaning the following
56 * character might have (except \ at end of string is retained).
58 * Set in gl_flags if pattern contained a globbing character.
60 * Same as GLOB_NOCHECK, but it will only append pattern if it did
61 * not contain any magic characters. [Used in csh style globbing]
63 * Use alternately specified directory access functions.
65 * expand ~user/foo to the /home/dir/of/user/foo
67 * expand {1,2}{a,b} to 1a 1b 2a 2b
69 * Number of matches in the current invocation of glob.
79 struct passwd *getpwnam(char *);
80 struct passwd *getpwuid(Uid_t);
86 # define MAXPATHLEN PATH_MAX
88 # define MAXPATHLEN 1024
104 #define UNDERSCORE '_'
112 #define M_QUOTE 0x8000
113 #define M_PROTECT 0x4000
114 #define M_MASK 0xffff
115 #define M_ASCII 0x00ff
122 #define M_PROTECT 0x40
128 #endif /* !GLOB_DEBUG */
131 #define CHAR(c) ((Char)((c)&M_ASCII))
132 #define META(c) ((Char)((c)|M_QUOTE))
133 #define M_ALL META('*')
134 #define M_END META(']')
135 #define M_NOT META('!')
136 #define M_ONE META('?')
137 #define M_RNG META('-')
138 #define M_SET META('[')
139 #define ismeta(c) (((c)&M_QUOTE) != 0)
142 static int compare(const void *, const void *);
143 static void g_Ctoc(const Char *, char *);
144 static int g_lstat(Char *, Stat_t *, glob_t *);
145 static DIR *g_opendir(Char *, glob_t *);
146 static Char *g_strchr(Char *, int);
148 static Char *g_strcat(Char *, const Char *);
150 static int g_stat(Char *, Stat_t *, glob_t *);
151 static int glob0(const Char *, glob_t *);
152 static int glob1(Char *, glob_t *);
153 static int glob2(Char *, Char *, Char *, glob_t *);
154 static int glob3(Char *, Char *, Char *, Char *, glob_t *);
155 static int globextend(const Char *, glob_t *);
156 static const Char * globtilde(const Char *, Char *, glob_t *);
157 static int globexp1(const Char *, glob_t *);
158 static int globexp2(const Char *, const Char *, glob_t *, int *);
159 static int match(Char *, Char *, Char *);
161 static void qprintf(const char *, Char *);
162 #endif /* GLOB_DEBUG */
165 bsd_glob(const char *pattern, int flags,
166 int (*errfunc)(const char *, int), glob_t *pglob)
170 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
172 patnext = (U8 *) pattern;
173 if (!(flags & GLOB_APPEND)) {
175 pglob->gl_pathv = NULL;
176 if (!(flags & GLOB_DOOFFS))
179 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
180 pglob->gl_errfunc = errfunc;
181 pglob->gl_matchc = 0;
184 bufend = bufnext + MAXPATHLEN;
185 if (flags & GLOB_QUOTE) {
186 /* Protect the quoted characters. */
187 while (bufnext < bufend && (c = *patnext++) != EOS)
189 if ((c = *patnext++) == EOS) {
193 *bufnext++ = c | M_PROTECT;
199 while (bufnext < bufend && (c = *patnext++) != EOS)
203 if (flags & GLOB_BRACE)
204 return globexp1(patbuf, pglob);
206 return glob0(patbuf, pglob);
210 * Expand recursively a glob {} pattern. When there is no more expansion
211 * invoke the standard globbing routine to glob the rest of the magic
214 static int globexp1(const Char *pattern, glob_t *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(const Char *ptr, const Char *pattern,
237 glob_t *pglob, int *rv)
241 const Char *pe, *pm, *pl;
242 Char patbuf[MAXPATHLEN + 1];
244 /* copy part up to the brace */
245 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
249 /* Find the balanced brace */
250 for (i = 0, pe = ++ptr; *pe; pe++)
251 if (*pe == LBRACKET) {
252 /* Ignore everything between [] */
253 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
257 * We could not find a matching RBRACKET.
258 * Ignore and just look for RBRACE
263 else if (*pe == LBRACE)
265 else if (*pe == RBRACE) {
271 /* Non matching braces; just glob the pattern */
272 if (i != 0 || *pe == EOS) {
273 *rv = glob0(patbuf, pglob);
277 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
280 /* Ignore everything between [] */
281 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
285 * We could not find a matching RBRACKET.
286 * Ignore and just look for RBRACE
303 if (i && *pm == COMMA)
306 /* Append the current string */
307 for (lm = ls; (pl < pm); *lm++ = *pl++)
310 * Append the rest of the pattern after the
313 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
316 /* Expand the current pattern */
318 qprintf("globexp2:", patbuf);
319 #endif /* GLOB_DEBUG */
320 *rv = globexp1(patbuf, pglob);
322 /* move after the comma, to the next string */
337 * expand tilde from the passwd file.
340 globtilde(const Char *pattern, Char *patbuf, glob_t *pglob)
347 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
350 /* Copy up to the end of the string or / */
351 for (p = pattern + 1, h = (char *) patbuf; *p && *p != SLASH;
357 if (((char *) patbuf)[0] == EOS) {
359 * handle a plain ~ or ~/ by expanding $HOME
360 * first and then trying the password file
362 if ((h = getenv("HOME")) == NULL) {
364 if ((pwd = getpwuid(getuid())) == NULL)
378 if ((pwd = getpwnam((char*) patbuf)) == NULL)
387 /* Copy the home directory */
388 for (b = patbuf; *h; *b++ = *h++)
391 /* Append the rest of the pattern */
392 while ((*b++ = *p++) != EOS)
400 * The main glob() routine: compiles the pattern (optionally processing
401 * quotes), calls glob1() to do the real pattern matching, and finally
402 * sorts the list (unless unsorted operation is requested). Returns 0
403 * if things went well, nonzero if errors occurred. It is not an error
404 * to find no matches.
407 glob0(const Char *pattern, glob_t *pglob)
409 const Char *qpat, *qpatnext;
410 int c, err, oldflags, oldpathc;
411 Char *bufnext, patbuf[MAXPATHLEN+1];
413 qpat = globtilde(pattern, patbuf, pglob);
415 oldflags = pglob->gl_flags;
416 oldpathc = pglob->gl_pathc;
419 /* We don't need to check for buffer overflow any more. */
420 while ((c = *qpatnext++) != EOS) {
426 if (*qpatnext == EOS ||
427 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
428 *bufnext++ = LBRACKET;
438 *bufnext++ = CHAR(c);
439 if (*qpatnext == RANGE &&
440 (c = qpatnext[1]) != RBRACKET) {
442 *bufnext++ = CHAR(c);
445 } while ((c = *qpatnext++) != RBRACKET);
446 pglob->gl_flags |= GLOB_MAGCHAR;
450 pglob->gl_flags |= GLOB_MAGCHAR;
454 pglob->gl_flags |= GLOB_MAGCHAR;
455 /* collapse adjacent stars to one,
456 * to avoid exponential behavior
458 if (bufnext == patbuf || bufnext[-1] != M_ALL)
462 *bufnext++ = CHAR(c);
468 qprintf("glob0:", patbuf);
469 #endif /* GLOB_DEBUG */
471 if ((err = glob1(patbuf, pglob)) != 0) {
472 pglob->gl_flags = oldflags;
477 * If there was no match we are going to append the pattern
478 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
479 * and the pattern did not contain any magic characters
480 * GLOB_NOMAGIC is there just for compatibility with csh.
482 if (pglob->gl_pathc == oldpathc &&
483 ((pglob->gl_flags & GLOB_NOCHECK) ||
484 ((pglob->gl_flags & GLOB_NOMAGIC) &&
485 !(pglob->gl_flags & GLOB_MAGCHAR))))
488 printf("calling globextend from glob0\n");
489 #endif /* GLOB_DEBUG */
490 pglob->gl_flags = oldflags;
491 return(globextend(qpat, pglob));
493 else if (!(pglob->gl_flags & GLOB_NOSORT))
494 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
495 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
496 pglob->gl_flags = oldflags;
501 compare(const void *p, const void *q)
503 return(strcmp(*(char **)p, *(char **)q));
507 glob1(Char *pattern, glob_t *pglob)
509 Char pathbuf[MAXPATHLEN+1];
511 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
514 return(glob2(pathbuf, pathbuf, pattern, pglob));
518 * The functions glob2 and glob3 are mutually recursive; there is one level
519 * of recursion for each segment in the pattern that contains one or more
523 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
530 * Loop over pattern segments until end of pattern or until
531 * segment with meta character found.
533 for (anymeta = 0;;) {
534 if (*pattern == EOS) { /* End of pattern? */
538 if (g_lstat(pathbuf, &sb, pglob))
540 #endif /* HAS_LSTAT */
542 if (((pglob->gl_flags & GLOB_MARK) &&
543 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
544 || (S_ISLNK(sb.st_mode) &&
545 (g_stat(pathbuf, &sb, pglob) == 0) &&
546 S_ISDIR(sb.st_mode)))) {
552 printf("calling globextend from glob2\n");
553 #endif /* GLOB_DEBUG */
554 return(globextend(pathbuf, pglob));
557 /* Find end of next segment, copy tentatively to pathend. */
560 while (*p != EOS && *p != SEP) {
566 if (!anymeta) { /* No expansion, do next segment. */
569 while (*pattern == SEP)
570 *pathend++ = *pattern++;
571 } else /* Need expansion, recurse. */
572 return(glob3(pathbuf, pathend, pattern, p, pglob));
578 glob3(Char *pathbuf, Char *pathend, Char *pattern,
579 Char *restpattern, glob_t *pglob)
581 register Direntry_t *dp;
584 char buf[MAXPATHLEN];
587 * The readdirfunc declaration can't be prototyped, because it is
588 * assigned, below, to two functions which are prototyped in glob.h
589 * and dirent.h as taking pointers to differently typed opaque
592 Direntry_t *(*readdirfunc)();
597 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
598 /* TODO: don't call for ENOENT or ENOTDIR? */
599 if (pglob->gl_errfunc) {
600 g_Ctoc(pathbuf, buf);
601 if (pglob->gl_errfunc(buf, errno) ||
602 (pglob->gl_flags & GLOB_ERR))
610 /* Search directory for matching names. */
611 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
612 readdirfunc = pglob->gl_readdir;
614 readdirfunc = readdir;
615 while ((dp = (*readdirfunc)(dirp))) {
619 /* Initial DOT must be matched literally. */
620 if (dp->d_name[0] == DOT && *pattern != DOT)
622 for (sc = (U8 *) dp->d_name, dc = pathend;
623 (*dc++ = *sc++) != EOS;)
625 if (!match(pathend, pattern, restpattern)) {
629 err = glob2(pathbuf, --dc, restpattern, pglob);
634 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
635 (*pglob->gl_closedir)(dirp);
643 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
644 * add the new item, and update gl_pathc.
646 * This assumes the BSD realloc, which only copies the block when its size
647 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
650 * Return 0 if new item added, error code if memory couldn't be allocated.
652 * Invariant of the glob_t structure:
653 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
654 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
657 globextend(const Char *path, glob_t *pglob)
659 register char **pathv;
667 for (p = path; *p; p++)
668 (void)printf("%c", CHAR(*p));
672 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
673 pathv = pglob->gl_pathv ?
674 realloc((char *)pglob->gl_pathv, newsize) :
677 return(GLOB_NOSPACE);
679 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
680 /* first time around -- clear initial gl_offs items */
681 pathv += pglob->gl_offs;
682 for (i = pglob->gl_offs; --i >= 0; )
685 pglob->gl_pathv = pathv;
687 for (p = path; *p++;)
689 if ((copy = malloc(p - path)) != NULL) {
691 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
693 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
694 return(copy == NULL ? GLOB_NOSPACE : 0);
699 * pattern matching function for filenames. Each occurrence of the *
700 * pattern causes a recursion level.
703 match(register Char *name, register Char *pat, register Char *patend)
705 int ok, negate_range;
708 while (pat < patend) {
710 switch (c & M_MASK) {
715 if (match(name, pat, patend))
717 while (*name++ != EOS);
725 if ((k = *name++) == EOS)
727 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
729 while (((c = *pat++) & M_MASK) != M_END)
730 if ((*pat & M_MASK) == M_RNG) {
731 if (c <= k && k <= pat[1])
736 if (ok == negate_range)
745 return(*name == EOS);
748 /* Free allocated data belonging to a glob_t structure. */
750 bsd_globfree(glob_t *pglob)
755 if (pglob->gl_pathv != NULL) {
756 pp = pglob->gl_pathv + pglob->gl_offs;
757 for (i = pglob->gl_pathc; i--; ++pp)
760 free(pglob->gl_pathv);
765 g_opendir(register Char *str, glob_t *pglob)
767 char buf[MAXPATHLEN];
774 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
775 return((*pglob->gl_opendir)(buf));
777 return(opendir(buf));
782 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
784 char buf[MAXPATHLEN];
787 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
788 return((*pglob->gl_lstat)(buf, sb));
789 return(lstat(buf, sb));
791 #endif /* HAS_LSTAT */
794 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
796 char buf[MAXPATHLEN];
799 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
800 return((*pglob->gl_stat)(buf, sb));
801 return(stat(buf, sb));
805 g_strchr(Char *str, int ch)
816 g_strcat(Char *dst, const Char *src)
823 while((*dst++ = *src++) != EOS)
831 g_Ctoc(register const Char *str, char *buf)
835 for (dc = buf; (*dc++ = *str++) != EOS;)
841 qprintf(const char *str, register Char *s)
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) ? '_' : ' ');
856 #endif /* GLOB_DEBUG */