1 /* $OpenBSD: glob.c,v 1.23 2004/05/18 02:05:52 jfb Exp $ */
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)glob.c 8.3 (Berkeley) 10/13/93
38 * glob(3) -- a superset of the one defined in POSIX 1003.2.
40 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
42 * Optional extra services, controlled by flags not defined by POSIX:
45 * Set in gl_flags if pattern contained a globbing character.
47 * expand ~user/foo to the /home/dir/of/user/foo
49 * expand {1,2}{a,b} to 1a 1b 2a 2b
51 * Number of matches in the current invocation of glob.
56 #include <sys/param.h>
67 #endif /* STDC_HEADERS */
68 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
70 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
74 # ifdef HAVE_STRINGS_H
77 #endif /* HAVE_STRING_H */
80 #endif /* HAVE_UNISTD_H */
85 # define dirent direct
86 # ifdef HAVE_SYS_NDIR_H
87 # include <sys/ndir.h>
89 # ifdef HAVE_SYS_DIR_H
101 #include "emul/glob.h"
115 #define UNDERSCORE '_'
123 #define M_QUOTE 0x8000
124 #define M_PROTECT 0x4000
125 #define M_MASK 0xffff
126 #define M_ASCII 0x00ff
128 typedef unsigned short Char;
133 #define M_PROTECT 0x40
142 #define CHAR(c) ((Char)((c)&M_ASCII))
143 #define META(c) ((Char)((c)|M_QUOTE))
144 #define M_ALL META('*')
145 #define M_END META(']')
146 #define M_NOT META('!')
147 #define M_ONE META('?')
148 #define M_RNG META('-')
149 #define M_SET META('[')
150 #define ismeta(c) (((c)&M_QUOTE) != 0)
153 static int compare __P((const void *, const void *));
154 static int g_Ctoc __P((const Char *, char *, unsigned int));
155 static int g_lstat __P((Char *, struct stat *, glob_t *));
156 static DIR *g_opendir __P((Char *, glob_t *));
157 static Char *g_strchr __P((Char *, int));
158 static int g_stat __P((Char *, struct stat *, glob_t *));
159 static int glob0 __P((const Char *, glob_t *));
160 static int glob1 __P((Char *, Char *, glob_t *));
161 static int glob2 __P((Char *, Char *, Char *, Char *, Char *, Char *,
163 static int glob3 __P((Char *, Char *, Char *, Char *, Char *, Char *,
164 Char *, Char *, glob_t *));
165 static int globextend __P((const Char *, glob_t *));
167 globtilde __P((const Char *, Char *, size_t, glob_t *));
168 static int globexp1 __P((const Char *, glob_t *));
169 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
170 static int match __P((Char *, Char *, Char *));
172 static void qprintf __P((const char *, Char *));
176 glob(pattern, flags, errfunc, pglob)
178 int flags, (*errfunc) __P((const char *, int));
181 const unsigned char *patnext;
183 Char *bufnext, *bufend, patbuf[PATH_MAX];
185 patnext = (unsigned char *) pattern;
186 if (!(flags & GLOB_APPEND)) {
188 pglob->gl_pathv = NULL;
189 if (!(flags & GLOB_DOOFFS))
192 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
193 pglob->gl_errfunc = errfunc;
194 pglob->gl_matchc = 0;
197 bufend = bufnext + PATH_MAX - 1;
198 if (flags & GLOB_NOESCAPE)
199 while (bufnext < bufend && (c = *patnext++) != EOS)
202 /* Protect the quoted characters. */
203 while (bufnext < bufend && (c = *patnext++) != EOS)
205 if ((c = *patnext++) == EOS) {
209 *bufnext++ = c | M_PROTECT;
215 if (flags & GLOB_BRACE)
216 return globexp1(patbuf, pglob);
218 return glob0(patbuf, pglob);
222 * Expand recursively a glob {} pattern. When there is no more expansion
223 * invoke the standard globbing routine to glob the rest of the magic
227 globexp1(pattern, pglob)
231 const Char* ptr = pattern;
234 /* Protect a single {}, for find(1), like csh */
235 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
236 return glob0(pattern, pglob);
238 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
239 if (!globexp2(ptr, pattern, pglob, &rv))
242 return glob0(pattern, pglob);
247 * Recursive brace globbing helper. Tries to expand a single brace.
248 * If it succeeds then it invokes globexp1 with the new pattern.
249 * If it fails then it tries to glob the rest of the pattern and returns.
252 globexp2(ptr, pattern, pglob, rv)
253 const Char *ptr, *pattern;
259 const Char *pe, *pm, *pl;
260 Char patbuf[PATH_MAX];
262 /* copy part up to the brace */
263 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
268 /* Find the balanced brace */
269 for (i = 0, pe = ++ptr; *pe; pe++)
270 if (*pe == LBRACKET) {
271 /* Ignore everything between [] */
272 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
276 * We could not find a matching RBRACKET.
277 * Ignore and just look for RBRACE
281 } else if (*pe == LBRACE)
283 else if (*pe == RBRACE) {
289 /* Non matching braces; just glob the pattern */
290 if (i != 0 || *pe == EOS) {
291 *rv = glob0(patbuf, pglob);
295 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
298 /* Ignore everything between [] */
299 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
303 * We could not find a matching RBRACKET.
304 * Ignore and just look for RBRACE
321 if (i && *pm == COMMA)
324 /* Append the current string */
325 for (lm = ls; (pl < pm); *lm++ = *pl++)
329 * Append the rest of the pattern after the
332 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
335 /* Expand the current pattern */
337 qprintf("globexp2:", patbuf);
339 *rv = globexp1(patbuf, pglob);
341 /* move after the comma, to the next string */
357 * expand tilde from the passwd file.
360 globtilde(pattern, patbuf, patbuf_len, pglob)
371 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
374 /* Copy up to the end of the string or / */
375 eb = &patbuf[patbuf_len - 1];
376 for (p = pattern + 1, h = (char *) patbuf;
377 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
382 if (((char *) patbuf)[0] == EOS) {
384 * handle a plain ~ or ~/ by expanding $HOME
385 * first and then trying the password file
387 if ((h = getenv("HOME")) == NULL) {
388 if ((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. It is not an error
421 * to find no matches.
424 glob0(pattern, pglob)
428 const Char *qpatnext;
429 int c, err, oldpathc;
430 Char *bufnext, patbuf[PATH_MAX];
432 qpatnext = globtilde(pattern, patbuf, PATH_MAX, 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, patbuf + PATH_MAX - 1, pglob)) != 0)
492 * If there was no match we are going to append the pattern
493 * if GLOB_NOCHECK was specified.
495 if (pglob->gl_pathc == oldpathc) {
496 if (pglob->gl_flags & GLOB_NOCHECK)
497 return(globextend(pattern, pglob));
499 return(GLOB_NOMATCH);
501 if (!(pglob->gl_flags & GLOB_NOSORT))
502 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
503 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
511 return(strcmp(*(char **)p, *(char **)q));
515 glob1(pattern, pattern_last, pglob)
516 Char *pattern, *pattern_last;
519 Char pathbuf[PATH_MAX];
521 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
524 return(glob2(pathbuf, pathbuf + PATH_MAX - 1,
525 pathbuf, pathbuf + PATH_MAX - 1,
526 pattern, pattern_last, pglob));
530 * The functions glob2 and glob3 are mutually recursive; there is one level
531 * of recursion for each segment in the pattern that contains one or more
535 glob2(pathbuf, pathbuf_last, pathend, pathend_last, pattern, pattern_last, pglob)
536 Char *pathbuf, *pathbuf_last;
537 Char *pathend, *pathend_last;
538 Char *pattern, *pattern_last;
546 * Loop over pattern segments until end of pattern or until
547 * segment with meta character found.
549 for (anymeta = 0;;) {
550 if (*pattern == EOS) { /* End of pattern? */
552 if (g_lstat(pathbuf, &sb, pglob))
555 if (((pglob->gl_flags & GLOB_MARK) &&
556 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
557 (S_ISLNK(sb.st_mode) &&
558 (g_stat(pathbuf, &sb, pglob) == 0) &&
559 S_ISDIR(sb.st_mode)))) {
560 if (pathend+1 > pathend_last)
566 return(globextend(pathbuf, pglob));
569 /* Find end of next segment, copy tentatively to pathend. */
572 while (*p != EOS && *p != SEP) {
575 if (q+1 > pathend_last)
580 if (!anymeta) { /* No expansion, do next segment. */
583 while (*pattern == SEP) {
584 if (pathend+1 > pathend_last)
586 *pathend++ = *pattern++;
589 /* Need expansion, recurse. */
590 return(glob3(pathbuf, pathbuf_last, pathend,
591 pathend_last, pattern, pattern_last,
592 p, pattern_last, pglob));
598 glob3(pathbuf, pathbuf_last, pathend, pathend_last, pattern, pattern_last,
599 restpattern, restpattern_last, pglob)
600 Char *pathbuf, *pathbuf_last, *pathend, *pathend_last;
601 Char *pattern, *pattern_last, *restpattern, *restpattern_last;
609 if (pathend > pathend_last)
614 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
615 /* TODO: don't call for ENOENT or ENOTDIR? */
616 if (pglob->gl_errfunc) {
617 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
618 return(GLOB_ABORTED);
619 if (pglob->gl_errfunc(buf, errno) ||
620 pglob->gl_flags & GLOB_ERR)
621 return(GLOB_ABORTED);
628 /* Search directory for matching names. */
629 while ((dp = readdir(dirp))) {
633 /* Initial DOT must be matched literally. */
634 if (dp->d_name[0] == DOT && *pattern != DOT)
637 sc = (unsigned char *) dp->d_name;
638 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
640 if (dc >= pathend_last) {
646 if (!match(pathend, pattern, restpattern)) {
650 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
651 restpattern, restpattern_last, pglob);
661 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
662 * add the new item, and update gl_pathc.
664 * This assumes the BSD realloc, which only copies the block when its size
665 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
668 * Return 0 if new item added, error code if memory couldn't be allocated.
670 * Invariant of the glob_t structure:
671 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
672 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
675 globextend(path, pglob)
681 unsigned int newsize, len;
685 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
686 pathv = pglob->gl_pathv ?
687 (char **)realloc((char *)pglob->gl_pathv, newsize) :
688 (char **)malloc(newsize);
690 if (pglob->gl_pathv) {
691 free(pglob->gl_pathv);
692 pglob->gl_pathv = NULL;
694 return(GLOB_NOSPACE);
697 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
698 /* first time around -- clear initial gl_offs items */
699 pathv += pglob->gl_offs;
700 for (i = pglob->gl_offs; --i >= 0; )
703 pglob->gl_pathv = pathv;
705 for (p = path; *p++;)
707 len = (size_t)(p - path);
708 if ((copy = malloc(len)) != NULL) {
709 if (g_Ctoc(path, copy, len)) {
711 return(GLOB_NOSPACE);
713 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
715 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
717 return(copy == NULL ? GLOB_NOSPACE : 0);
721 * pattern matching function for filenames. Each occurrence of the *
722 * pattern causes a recursion level.
725 match(name, pat, patend)
726 Char *name, *pat, *patend;
728 int ok, negate_range;
731 while (pat < patend) {
733 switch (c & M_MASK) {
738 if (match(name, pat, patend))
740 } while (*name++ != EOS);
748 if ((k = *name++) == EOS)
750 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
752 while (((c = *pat++) & M_MASK) != M_END)
753 if ((*pat & M_MASK) == M_RNG) {
754 if (c <= k && k <= pat[1])
759 if (ok == negate_range)
768 return(*name == EOS);
771 /* Free allocated data belonging to a glob_t structure. */
779 if (pglob->gl_pathv != NULL) {
780 pp = pglob->gl_pathv + pglob->gl_offs;
781 for (i = pglob->gl_pathc; i--; ++pp)
784 free(pglob->gl_pathv);
785 pglob->gl_pathv = NULL;
790 g_opendir(str, pglob)
800 if (g_Ctoc(str, buf, sizeof(buf)))
803 return(opendir(buf));
807 g_lstat(fn, sb, pglob)
814 if (g_Ctoc(fn, buf, sizeof(buf)))
816 return(lstat(buf, sb));
820 g_stat(fn, sb, pglob)
827 if (g_Ctoc(fn, buf, sizeof(buf)))
829 return(stat(buf, sb));
845 g_Ctoc(str, buf, len)
852 if ((*buf++ = *str++) == EOS)
866 (void)printf("%s:\n", str);
868 (void)printf("%c", CHAR(*p));
871 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
874 (void)printf("%c", ismeta(*p) ? '_' : ' ');