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 $
37 * $DragonFly: src/lib/libc/gen/glob.c,v 1.2 2003/06/17 04:26:42 dillon Exp $
39 * @(#)glob.c 8.3 (Berkeley) 10/13/93
40 * $FreeBSD: src/lib/libc/gen/glob.c,v 1.11.6.6 2002/09/18 14:13:31 mikeh Exp $
44 * glob(3) -- a superset of the one defined in POSIX 1003.2.
46 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
48 * Optional extra services, controlled by flags not defined by POSIX:
51 * Escaping convention: \ inhibits any special meaning the following
52 * character might have (except \ at end of string is retained).
54 * Set in gl_flags if pattern contained a globbing character.
56 * Same as GLOB_NOCHECK, but it will only append pattern if it did
57 * not contain any magic characters. [Used in csh style globbing]
59 * Use alternately specified directory access functions.
61 * expand ~user/foo to the /home/dir/of/user/foo
63 * expand {1,2}{a,b} to 1a 1b 2a 2b
65 * Number of matches in the current invocation of glob.
68 #include <sys/param.h>
95 #define UNDERSCORE '_'
103 #define M_QUOTE 0x8000
104 #define M_PROTECT 0x4000
105 #define M_MASK 0xffff
106 #define M_ASCII 0x00ff
108 typedef u_short Char;
113 #define M_PROTECT 0x40
122 #define CHAR(c) ((Char)((c)&M_ASCII))
123 #define META(c) ((Char)((c)|M_QUOTE))
124 #define M_ALL META('*')
125 #define M_END META(']')
126 #define M_NOT META('!')
127 #define M_ONE META('?')
128 #define M_RNG META('-')
129 #define M_SET META('[')
130 #define ismeta(c) (((c)&M_QUOTE) != 0)
133 static int compare(const void *, const void *);
134 static int g_Ctoc(const Char *, char *, u_int);
135 static int g_lstat(Char *, struct stat *, glob_t *);
136 static DIR *g_opendir(Char *, glob_t *);
137 static Char *g_strchr(Char *, int);
139 static Char *g_strcat(Char *, const Char *);
141 static int g_stat(Char *, struct stat *, glob_t *);
142 static int glob0(const Char *, glob_t *, int *);
143 static int glob1(Char *, glob_t *, int *);
144 static int glob2(Char *, Char *, Char *, Char *, glob_t *, int *);
145 static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *, int *);
146 static int globextend(const Char *, glob_t *, int *);
148 globtilde(const Char *, Char *, size_t, glob_t *);
149 static int globexp1(const Char *, glob_t *, int *);
150 static int globexp2(const Char *, const Char *, glob_t *, int *, int *);
151 static int match(Char *, Char *, Char *);
153 static void qprintf(const char *, Char *);
157 glob(pattern, flags, errfunc, pglob)
159 int flags, (*errfunc)(const char *, int);
162 const u_char *patnext;
164 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
166 patnext = (u_char *) pattern;
167 if (!(flags & GLOB_APPEND)) {
169 pglob->gl_pathv = NULL;
170 if (!(flags & GLOB_DOOFFS))
173 if (flags & GLOB_LIMIT) {
174 limit = pglob->gl_matchc;
179 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
180 pglob->gl_errfunc = errfunc;
181 pglob->gl_matchc = 0;
184 bufend = bufnext + MAXPATHLEN - 1;
185 if (flags & GLOB_NOESCAPE)
186 while (bufnext < bufend && (c = *patnext++) != EOS)
189 /* Protect the quoted characters. */
190 while (bufnext < bufend && (c = *patnext++) != EOS)
192 if ((c = *patnext++) == EOS) {
196 *bufnext++ = c | M_PROTECT;
203 if (flags & GLOB_BRACE)
204 return globexp1(patbuf, pglob, &limit);
206 return glob0(patbuf, pglob, &limit);
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
215 globexp1(pattern, pglob, limit)
220 const Char* ptr = pattern;
223 /* Protect a single {}, for find(1), like csh */
224 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
225 return glob0(pattern, pglob, limit);
227 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
228 if (!globexp2(ptr, pattern, pglob, &rv, limit))
231 return glob0(pattern, pglob, limit);
236 * Recursive brace globbing helper. Tries to expand a single brace.
237 * If it succeeds then it invokes globexp1 with the new pattern.
238 * If it fails then it tries to glob the rest of the pattern and returns.
241 globexp2(ptr, pattern, pglob, rv, limit)
242 const Char *ptr, *pattern;
248 const Char *pe, *pm, *pl;
249 Char patbuf[MAXPATHLEN];
251 /* copy part up to the brace */
252 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
257 /* Find the balanced brace */
258 for (i = 0, pe = ++ptr; *pe; pe++)
259 if (*pe == LBRACKET) {
260 /* Ignore everything between [] */
261 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
265 * We could not find a matching RBRACKET.
266 * Ignore and just look for RBRACE
271 else if (*pe == LBRACE)
273 else if (*pe == RBRACE) {
279 /* Non matching braces; just glob the pattern */
280 if (i != 0 || *pe == EOS) {
281 *rv = glob0(patbuf, pglob, limit);
285 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
288 /* Ignore everything between [] */
289 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
293 * We could not find a matching RBRACKET.
294 * Ignore and just look for RBRACE
311 if (i && *pm == COMMA)
314 /* Append the current string */
315 for (lm = ls; (pl < pm); *lm++ = *pl++)
318 * Append the rest of the pattern after the
321 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
324 /* Expand the current pattern */
326 qprintf("globexp2:", patbuf);
328 *rv = globexp1(patbuf, pglob, limit);
330 /* move after the comma, to the next string */
345 * expand tilde from the passwd file.
348 globtilde(pattern, patbuf, patbuf_len, pglob)
359 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
363 * Copy up to the end of the string or /
365 eb = &patbuf[patbuf_len - 1];
366 for (p = pattern + 1, h = (char *) patbuf;
367 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
372 if (((char *) patbuf)[0] == EOS) {
374 * handle a plain ~ or ~/ by expanding $HOME first (iff
375 * we're not running setuid or setgid) and then trying
379 #ifndef __NETBSD_SYSCALLS
382 (h = getenv("HOME")) == NULL) {
383 if (((h = getlogin()) != NULL &&
384 (pwd = getpwnam(h)) != NULL) ||
385 (pwd = getpwuid(getuid())) != NULL)
395 if ((pwd = getpwnam((char*) patbuf)) == NULL)
401 /* Copy the home directory */
402 for (b = patbuf; b < eb && *h; *b++ = *h++)
405 /* Append the rest of the pattern */
406 while (b < eb && (*b++ = *p++) != EOS)
415 * The main glob() routine: compiles the pattern (optionally processing
416 * quotes), calls glob1() to do the real pattern matching, and finally
417 * sorts the list (unless unsorted operation is requested). Returns 0
418 * if things went well, nonzero if errors occurred.
421 glob0(pattern, pglob, limit)
426 const Char *qpatnext;
427 int c, err, oldpathc;
428 Char *bufnext, patbuf[MAXPATHLEN];
430 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
431 oldpathc = pglob->gl_pathc;
434 /* We don't need to check for buffer overflow any more. */
435 while ((c = *qpatnext++) != EOS) {
441 if (*qpatnext == EOS ||
442 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
443 *bufnext++ = LBRACKET;
453 *bufnext++ = CHAR(c);
454 if (*qpatnext == RANGE &&
455 (c = qpatnext[1]) != RBRACKET) {
457 *bufnext++ = CHAR(c);
460 } while ((c = *qpatnext++) != RBRACKET);
461 pglob->gl_flags |= GLOB_MAGCHAR;
465 pglob->gl_flags |= GLOB_MAGCHAR;
469 pglob->gl_flags |= GLOB_MAGCHAR;
470 /* collapse adjacent stars to one,
471 * to avoid exponential behavior
473 if (bufnext == patbuf || bufnext[-1] != M_ALL)
477 *bufnext++ = CHAR(c);
483 qprintf("glob0:", patbuf);
486 if ((err = glob1(patbuf, pglob, limit)) != 0)
490 * If there was no match we are going to append the pattern
491 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
492 * and the pattern did not contain any magic characters
493 * GLOB_NOMAGIC is there just for compatibility with csh.
495 if (pglob->gl_pathc == oldpathc) {
496 if (((pglob->gl_flags & GLOB_NOCHECK) ||
497 ((pglob->gl_flags & GLOB_NOMAGIC) &&
498 !(pglob->gl_flags & GLOB_MAGCHAR))))
499 return(globextend(pattern, pglob, limit));
501 return(GLOB_NOMATCH);
503 if (!(pglob->gl_flags & GLOB_NOSORT))
504 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
505 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
513 return(strcmp(*(char **)p, *(char **)q));
517 glob1(pattern, pglob, limit)
522 Char pathbuf[MAXPATHLEN];
524 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
527 return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
528 pattern, pglob, limit));
532 * The functions glob2 and glob3 are mutually recursive; there is one level
533 * of recursion for each segment in the pattern that contains one or more
537 glob2(pathbuf, pathend, pathend_last, pattern, pglob, limit)
538 Char *pathbuf, *pathend, *pathend_last, *pattern;
547 * Loop over pattern segments until end of pattern or until
548 * segment with meta character found.
550 for (anymeta = 0;;) {
551 if (*pattern == EOS) { /* End of pattern? */
553 if (g_lstat(pathbuf, &sb, pglob))
556 if (((pglob->gl_flags & GLOB_MARK) &&
557 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
558 || (S_ISLNK(sb.st_mode) &&
559 (g_stat(pathbuf, &sb, pglob) == 0) &&
560 S_ISDIR(sb.st_mode)))) {
561 if (pathend + 1 > pathend_last)
562 return (GLOB_ABORTED);
567 return(globextend(pathbuf, pglob, limit));
570 /* Find end of next segment, copy tentatively to pathend. */
573 while (*p != EOS && *p != SEP) {
576 if (q + 1 > pathend_last)
577 return (GLOB_ABORTED);
581 if (!anymeta) { /* No expansion, do next segment. */
584 while (*pattern == SEP) {
585 if (pathend + 1 > pathend_last)
586 return (GLOB_ABORTED);
587 *pathend++ = *pattern++;
589 } else /* Need expansion, recurse. */
590 return(glob3(pathbuf, pathend, pathend_last, pattern, p,
597 glob3(pathbuf, pathend, pathend_last, pattern, restpattern, pglob, limit)
598 Char *pathbuf, *pathend, *pathend_last, *pattern, *restpattern;
605 char buf[MAXPATHLEN];
608 * The readdirfunc declaration can't be prototyped, because it is
609 * assigned, below, to two functions which are prototyped in glob.h
610 * and dirent.h as taking pointers to differently typed opaque
613 struct dirent *(*readdirfunc)();
615 if (pathend > pathend_last)
616 return (GLOB_ABORTED);
620 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
621 /* TODO: don't call for ENOENT or ENOTDIR? */
622 if (pglob->gl_errfunc) {
623 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
624 return (GLOB_ABORTED);
625 if (pglob->gl_errfunc(buf, errno) ||
626 pglob->gl_flags & GLOB_ERR)
627 return (GLOB_ABORTED);
634 /* Search directory for matching names. */
635 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
636 readdirfunc = pglob->gl_readdir;
638 readdirfunc = readdir;
639 while ((dp = (*readdirfunc)(dirp))) {
643 /* Initial DOT must be matched literally. */
644 if (dp->d_name[0] == DOT && *pattern != DOT)
647 sc = (u_char *) dp->d_name;
648 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
650 if (!match(pathend, pattern, restpattern)) {
654 err = glob2(pathbuf, --dc, pathend_last, restpattern,
660 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
661 (*pglob->gl_closedir)(dirp);
669 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
670 * add the new item, and update gl_pathc.
672 * This assumes the BSD realloc, which only copies the block when its size
673 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
676 * Return 0 if new item added, error code if memory couldn't be allocated.
678 * Invariant of the glob_t structure:
679 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
680 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
683 globextend(path, pglob, limit)
694 if (*limit && pglob->gl_pathc > *limit) {
696 return (GLOB_NOSPACE);
699 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
700 pathv = pglob->gl_pathv ?
701 realloc((char *)pglob->gl_pathv, newsize) :
704 if (pglob->gl_pathv) {
705 free(pglob->gl_pathv);
706 pglob->gl_pathv = NULL;
708 return(GLOB_NOSPACE);
711 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
712 /* first time around -- clear initial gl_offs items */
713 pathv += pglob->gl_offs;
714 for (i = pglob->gl_offs; --i >= 0; )
717 pglob->gl_pathv = pathv;
719 for (p = path; *p++;)
721 len = (size_t)(p - path);
722 if ((copy = malloc(len)) != NULL) {
723 if (g_Ctoc(path, copy, len)) {
725 return (GLOB_NOSPACE);
727 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
729 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
730 return(copy == NULL ? GLOB_NOSPACE : 0);
734 * pattern matching function for filenames. Each occurrence of the *
735 * pattern causes a recursion level.
738 match(name, pat, patend)
739 Char *name, *pat, *patend;
741 int ok, negate_range;
744 while (pat < patend) {
746 switch (c & M_MASK) {
751 if (match(name, pat, patend))
753 while (*name++ != EOS);
761 if ((k = *name++) == EOS)
763 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
765 while (((c = *pat++) & M_MASK) != M_END)
766 if ((*pat & M_MASK) == M_RNG) {
767 if (__collate_load_error ?
768 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
769 __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
770 && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
776 if (ok == negate_range)
785 return(*name == EOS);
788 /* Free allocated data belonging to a glob_t structure. */
796 if (pglob->gl_pathv != NULL) {
797 pp = pglob->gl_pathv + pglob->gl_offs;
798 for (i = pglob->gl_pathc; i--; ++pp)
801 free(pglob->gl_pathv);
802 pglob->gl_pathv = NULL;
807 g_opendir(str, pglob)
811 char buf[MAXPATHLEN];
816 if (g_Ctoc(str, buf, sizeof(buf)))
820 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
821 return((*pglob->gl_opendir)(buf));
823 return(opendir(buf));
827 g_lstat(fn, sb, pglob)
832 char buf[MAXPATHLEN];
834 if (g_Ctoc(fn, buf, sizeof(buf))) {
835 errno = ENAMETOOLONG;
838 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
839 return((*pglob->gl_lstat)(buf, sb));
840 return(lstat(buf, sb));
844 g_stat(fn, sb, pglob)
849 char buf[MAXPATHLEN];
851 if (g_Ctoc(fn, buf, sizeof(buf))) {
852 errno = ENAMETOOLONG;
855 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
856 return((*pglob->gl_stat)(buf, sb));
857 return(stat(buf, sb));
873 g_Ctoc(str, buf, len)
880 if ((*buf++ = *str++) == '\0')
894 (void)printf("%s:\n", str);
896 (void)printf("%c", CHAR(*p));
899 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
902 (void)printf("%c", ismeta(*p) ? '_' : ' ');