1 /* $OpenBSD: glob.c,v 1.25 2005/08/08 08:05:34 espie Exp $ */
3 * Copyright (c) 1989, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 /* OPENBSD ORIGINAL: lib/libc/gen/glob.c */
38 #include <sys/types.h>
50 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
51 return(sysconf(_SC_ARG_MAX));
53 return(256); /* XXX: arbitrary */
57 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
58 !defined(GLOB_HAS_GL_MATCHC)
61 * glob(3) -- a superset of the one defined in POSIX 1003.2.
63 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
65 * Optional extra services, controlled by flags not defined by POSIX:
68 * Escaping convention: \ inhibits any special meaning the following
69 * character might have (except \ at end of string is retained).
71 * Set in gl_flags if pattern contained a globbing character.
73 * Same as GLOB_NOCHECK, but it will only append pattern if it did
74 * not contain any magic characters. [Used in csh style globbing]
76 * Use alternately specified directory access functions.
78 * expand ~user/foo to the /home/dir/of/user/foo
80 * expand {1,2}{a,b} to 1a 1b 2a 2b
82 * Number of matches in the current invocation of glob.
97 #undef TILDE /* Some platforms may already define it */
99 #define UNDERSCORE '_'
107 #define M_QUOTE 0x8000
108 #define M_PROTECT 0x4000
109 #define M_MASK 0xffff
110 #define M_ASCII 0x00ff
112 typedef u_short Char;
117 #define M_PROTECT 0x40
126 #define CHAR(c) ((Char)((c)&M_ASCII))
127 #define META(c) ((Char)((c)|M_QUOTE))
128 #define M_ALL META('*')
129 #define M_END META(']')
130 #define M_NOT META('!')
131 #define M_ONE META('?')
132 #define M_RNG META('-')
133 #define M_SET META('[')
134 #define ismeta(c) (((c)&M_QUOTE) != 0)
137 static int compare(const void *, const void *);
138 static int g_Ctoc(const Char *, char *, u_int);
139 static int g_lstat(Char *, struct stat *, glob_t *);
140 static DIR *g_opendir(Char *, glob_t *);
141 static Char *g_strchr(Char *, int);
142 static int g_stat(Char *, struct stat *, glob_t *);
143 static int glob0(const Char *, glob_t *);
144 static int glob1(Char *, Char *, glob_t *, size_t *);
145 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
147 static int glob3(Char *, Char *, Char *, Char *, Char *, Char *,
148 Char *, Char *, glob_t *, size_t *);
149 static int globextend(const Char *, glob_t *, size_t *);
151 globtilde(const Char *, Char *, size_t, glob_t *);
152 static int globexp1(const Char *, glob_t *);
153 static int globexp2(const Char *, const Char *, glob_t *, int *);
154 static int match(Char *, Char *, Char *);
156 static void qprintf(const char *, Char *);
160 glob(const char *pattern, int flags, int (*errfunc)(const char *, int),
163 const u_char *patnext;
165 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
167 patnext = (u_char *) pattern;
168 if (!(flags & GLOB_APPEND)) {
170 pglob->gl_pathv = NULL;
171 if (!(flags & GLOB_DOOFFS))
174 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
175 pglob->gl_errfunc = errfunc;
176 pglob->gl_matchc = 0;
179 bufend = bufnext + MAXPATHLEN - 1;
180 if (flags & GLOB_NOESCAPE)
181 while (bufnext < bufend && (c = *patnext++) != EOS)
184 /* Protect the quoted characters. */
185 while (bufnext < bufend && (c = *patnext++) != EOS)
187 if ((c = *patnext++) == EOS) {
191 *bufnext++ = c | M_PROTECT;
197 if (flags & GLOB_BRACE)
198 return globexp1(patbuf, pglob);
200 return glob0(patbuf, pglob);
204 * Expand recursively a glob {} pattern. When there is no more expansion
205 * invoke the standard globbing routine to glob the rest of the magic
209 globexp1(const Char *pattern, glob_t *pglob)
211 const Char* ptr = pattern;
214 /* Protect a single {}, for find(1), like csh */
215 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
216 return glob0(pattern, pglob);
218 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
219 if (!globexp2(ptr, pattern, pglob, &rv))
222 return glob0(pattern, pglob);
227 * Recursive brace globbing helper. Tries to expand a single brace.
228 * If it succeeds then it invokes globexp1 with the new pattern.
229 * If it fails then it tries to glob the rest of the pattern and returns.
232 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv)
236 const Char *pe, *pm, *pl;
237 Char patbuf[MAXPATHLEN];
239 /* copy part up to the brace */
240 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
245 /* Find the balanced brace */
246 for (i = 0, pe = ++ptr; *pe; pe++)
247 if (*pe == LBRACKET) {
248 /* Ignore everything between [] */
249 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
253 * We could not find a matching RBRACKET.
254 * Ignore and just look for RBRACE
258 } else if (*pe == LBRACE)
260 else if (*pe == RBRACE) {
266 /* Non matching braces; just glob the pattern */
267 if (i != 0 || *pe == EOS) {
268 *rv = glob0(patbuf, pglob);
272 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
275 /* Ignore everything between [] */
276 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
280 * We could not find a matching RBRACKET.
281 * Ignore and just look for RBRACE
298 if (i && *pm == COMMA)
301 /* Append the current string */
302 for (lm = ls; (pl < pm); *lm++ = *pl++)
306 * Append the rest of the pattern after the
309 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
312 /* Expand the current pattern */
314 qprintf("globexp2:", patbuf);
316 *rv = globexp1(patbuf, pglob);
318 /* move after the comma, to the next string */
334 * expand tilde from the passwd file.
337 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *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++)
360 if (((char *) patbuf)[0] == EOS) {
362 * handle a plain ~ or ~/ by expanding $HOME
363 * first and then trying the password file
366 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
368 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
369 if ((pwd = getpwuid(getuid())) == NULL)
378 if ((pwd = getpwnam((char*) patbuf)) == NULL)
384 /* Copy the home directory */
385 for (b = patbuf; b < eb && *h; *b++ = *h++)
388 /* Append the rest of the pattern */
389 while (b < eb && (*b++ = *p++) != EOS)
398 * The main glob() routine: compiles the pattern (optionally processing
399 * quotes), calls glob1() to do the real pattern matching, and finally
400 * sorts the list (unless unsorted operation is requested). Returns 0
401 * if things went well, nonzero if errors occurred. It is not an error
402 * to find no matches.
405 glob0(const Char *pattern, glob_t *pglob)
407 const Char *qpatnext;
408 int c, err, oldpathc;
409 Char *bufnext, patbuf[MAXPATHLEN];
412 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
413 oldpathc = pglob->gl_pathc;
416 /* We don't need to check for buffer overflow any more. */
417 while ((c = *qpatnext++) != EOS) {
423 if (*qpatnext == EOS ||
424 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
425 *bufnext++ = LBRACKET;
435 *bufnext++ = CHAR(c);
436 if (*qpatnext == RANGE &&
437 (c = qpatnext[1]) != RBRACKET) {
439 *bufnext++ = CHAR(c);
442 } while ((c = *qpatnext++) != RBRACKET);
443 pglob->gl_flags |= GLOB_MAGCHAR;
447 pglob->gl_flags |= GLOB_MAGCHAR;
451 pglob->gl_flags |= GLOB_MAGCHAR;
452 /* collapse adjacent stars to one,
453 * to avoid exponential behavior
455 if (bufnext == patbuf || bufnext[-1] != M_ALL)
459 *bufnext++ = CHAR(c);
465 qprintf("glob0:", patbuf);
468 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
472 * If there was no match we are going to append the pattern
473 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
474 * and the pattern did not contain any magic characters
475 * GLOB_NOMAGIC is there just for compatibility with csh.
477 if (pglob->gl_pathc == oldpathc) {
478 if ((pglob->gl_flags & GLOB_NOCHECK) ||
479 ((pglob->gl_flags & GLOB_NOMAGIC) &&
480 !(pglob->gl_flags & GLOB_MAGCHAR)))
481 return(globextend(pattern, pglob, &limit));
483 return(GLOB_NOMATCH);
485 if (!(pglob->gl_flags & GLOB_NOSORT))
486 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
487 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
492 compare(const void *p, const void *q)
494 return(strcmp(*(char **)p, *(char **)q));
498 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
500 Char pathbuf[MAXPATHLEN];
502 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
505 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
506 pathbuf, pathbuf+MAXPATHLEN-1,
507 pattern, pattern_last, pglob, limitp));
511 * The functions glob2 and glob3 are mutually recursive; there is one level
512 * of recursion for each segment in the pattern that contains one or more
516 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
517 Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
524 * Loop over pattern segments until end of pattern or until
525 * segment with meta character found.
527 for (anymeta = 0;;) {
528 if (*pattern == EOS) { /* End of pattern? */
530 if (g_lstat(pathbuf, &sb, pglob))
533 if (((pglob->gl_flags & GLOB_MARK) &&
534 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
535 (S_ISLNK(sb.st_mode) &&
536 (g_stat(pathbuf, &sb, pglob) == 0) &&
537 S_ISDIR(sb.st_mode)))) {
538 if (pathend+1 > pathend_last)
544 return(globextend(pathbuf, pglob, limitp));
547 /* Find end of next segment, copy tentatively to pathend. */
550 while (*p != EOS && *p != SEP) {
553 if (q+1 > pathend_last)
558 if (!anymeta) { /* No expansion, do next segment. */
561 while (*pattern == SEP) {
562 if (pathend+1 > pathend_last)
564 *pathend++ = *pattern++;
567 /* Need expansion, recurse. */
568 return(glob3(pathbuf, pathbuf_last, pathend,
569 pathend_last, pattern, pattern_last,
570 p, pattern_last, pglob, limitp));
576 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
577 Char *pattern, Char *pattern_last, Char *restpattern,
578 Char *restpattern_last, glob_t *pglob, size_t *limitp)
583 char buf[MAXPATHLEN];
586 * The readdirfunc declaration can't be prototyped, because it is
587 * assigned, below, to two functions which are prototyped in glob.h
588 * and dirent.h as taking pointers to differently typed opaque
591 struct dirent *(*readdirfunc)(void *);
593 if (pathend > pathend_last)
598 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
599 /* TODO: don't call for ENOENT or ENOTDIR? */
600 if (pglob->gl_errfunc) {
601 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
602 return(GLOB_ABORTED);
603 if (pglob->gl_errfunc(buf, errno) ||
604 pglob->gl_flags & GLOB_ERR)
605 return(GLOB_ABORTED);
612 /* Search directory for matching names. */
613 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
614 readdirfunc = pglob->gl_readdir;
616 readdirfunc = (struct dirent *(*)(void *))readdir;
617 while ((dp = (*readdirfunc)(dirp))) {
621 /* Initial DOT must be matched literally. */
622 if (dp->d_name[0] == DOT && *pattern != DOT)
625 sc = (u_char *) dp->d_name;
626 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
628 if (dc >= pathend_last) {
634 if (!match(pathend, pattern, restpattern)) {
638 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
639 restpattern, restpattern_last, pglob, limitp);
644 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
645 (*pglob->gl_closedir)(dirp);
653 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
654 * add the new item, and update gl_pathc.
656 * This assumes the BSD realloc, which only copies the block when its size
657 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
660 * Return 0 if new item added, error code if memory couldn't be allocated.
662 * Invariant of the glob_t structure:
663 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
664 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
667 globextend(const Char *path, glob_t *pglob, size_t *limitp)
675 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
676 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
679 if (pglob->gl_pathv) {
680 free(pglob->gl_pathv);
681 pglob->gl_pathv = NULL;
683 return(GLOB_NOSPACE);
686 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
687 /* first time around -- clear initial gl_offs items */
688 pathv += pglob->gl_offs;
689 for (i = pglob->gl_offs; --i >= 0; )
692 pglob->gl_pathv = pathv;
694 for (p = path; *p++;)
696 len = (size_t)(p - path);
698 if ((copy = malloc(len)) != NULL) {
699 if (g_Ctoc(path, copy, len)) {
701 return(GLOB_NOSPACE);
703 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
705 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
707 if ((pglob->gl_flags & GLOB_LIMIT) &&
708 newsize + *limitp >= (u_int) get_arg_max()) {
710 return(GLOB_NOSPACE);
713 return(copy == NULL ? GLOB_NOSPACE : 0);
718 * pattern matching function for filenames. Each occurrence of the *
719 * pattern causes a recursion level.
722 match(Char *name, Char *pat, Char *patend)
724 int ok, negate_range;
727 while (pat < patend) {
729 switch (c & M_MASK) {
734 if (match(name, pat, patend))
736 } while (*name++ != EOS);
744 if ((k = *name++) == EOS)
746 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
748 while (((c = *pat++) & M_MASK) != M_END)
749 if ((*pat & M_MASK) == M_RNG) {
750 if (c <= k && k <= pat[1])
755 if (ok == negate_range)
764 return(*name == EOS);
767 /* Free allocated data belonging to a glob_t structure. */
769 globfree(glob_t *pglob)
774 if (pglob->gl_pathv != NULL) {
775 pp = pglob->gl_pathv + pglob->gl_offs;
776 for (i = pglob->gl_pathc; i--; ++pp)
779 free(pglob->gl_pathv);
780 pglob->gl_pathv = NULL;
785 g_opendir(Char *str, glob_t *pglob)
787 char buf[MAXPATHLEN];
790 strlcpy(buf, ".", sizeof buf);
792 if (g_Ctoc(str, buf, sizeof(buf)))
796 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
797 return((*pglob->gl_opendir)(buf));
799 return(opendir(buf));
803 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
805 char buf[MAXPATHLEN];
807 if (g_Ctoc(fn, buf, sizeof(buf)))
809 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
810 return((*pglob->gl_lstat)(buf, sb));
811 return(lstat(buf, sb));
815 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
817 char buf[MAXPATHLEN];
819 if (g_Ctoc(fn, buf, sizeof(buf)))
821 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
822 return((*pglob->gl_stat)(buf, sb));
823 return(stat(buf, sb));
827 g_strchr(Char *str, int ch)
837 g_Ctoc(const Char *str, char *buf, u_int len)
841 if ((*buf++ = *str++) == EOS)
849 qprintf(const char *str, Char *s)
853 (void)printf("%s:\n", str);
855 (void)printf("%c", CHAR(*p));
858 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
861 (void)printf("%c", ismeta(*p) ? '_' : ' ');
866 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
867 !defined(GLOB_HAS_GL_MATCHC) */