1 /* $OpenBSD: glob.c,v 1.26 2005/11/28 17:50:12 deraadt 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>
49 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
50 !defined(GLOB_HAS_GL_MATCHC) || \
51 !defined(HAVE_DECL_GLOB_NOMATCH) || HAVE_DECL_GLOB_NOMATCH == 0 || \
59 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
60 return(sysconf(_SC_ARG_MAX));
62 return(256); /* XXX: arbitrary */
67 * glob(3) -- a superset of the one defined in POSIX 1003.2.
69 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
71 * Optional extra services, controlled by flags not defined by POSIX:
74 * Escaping convention: \ inhibits any special meaning the following
75 * character might have (except \ at end of string is retained).
77 * Set in gl_flags if pattern contained a globbing character.
79 * Same as GLOB_NOCHECK, but it will only append pattern if it did
80 * not contain any magic characters. [Used in csh style globbing]
82 * Use alternately specified directory access functions.
84 * expand ~user/foo to the /home/dir/of/user/foo
86 * expand {1,2}{a,b} to 1a 1b 2a 2b
88 * Number of matches in the current invocation of glob.
103 #undef TILDE /* Some platforms may already define it */
105 #define UNDERSCORE '_'
113 #define M_QUOTE 0x8000
114 #define M_PROTECT 0x4000
115 #define M_MASK 0xffff
116 #define M_ASCII 0x00ff
118 typedef u_short Char;
123 #define M_PROTECT 0x40
132 #define CHAR(c) ((Char)((c)&M_ASCII))
133 #define META(c) ((Char)((c)|M_QUOTE))
134 #define M_ALL META('*')
135 #define M_END META(']')
136 #define M_NOT META('!')
137 #define M_ONE META('?')
138 #define M_RNG META('-')
139 #define M_SET META('[')
140 #define ismeta(c) (((c)&M_QUOTE) != 0)
143 static int compare(const void *, const void *);
144 static int g_Ctoc(const Char *, char *, u_int);
145 static int g_lstat(Char *, struct stat *, glob_t *);
146 static DIR *g_opendir(Char *, glob_t *);
147 static Char *g_strchr(Char *, int);
148 static int g_stat(Char *, struct stat *, glob_t *);
149 static int glob0(const Char *, glob_t *);
150 static int glob1(Char *, Char *, glob_t *, size_t *);
151 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
153 static int glob3(Char *, Char *, Char *, Char *, Char *,
154 Char *, Char *, glob_t *, size_t *);
155 static int globextend(const Char *, glob_t *, size_t *);
157 globtilde(const Char *, Char *, size_t, glob_t *);
158 static int globexp1(const Char *, glob_t *);
159 static int globexp2(const Char *, const Char *, glob_t *, int *);
160 static int match(Char *, Char *, Char *);
162 static void qprintf(const char *, Char *);
166 glob(const char *pattern, int flags, int (*errfunc)(const char *, int),
169 const u_char *patnext;
171 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
173 patnext = (u_char *) pattern;
174 if (!(flags & GLOB_APPEND)) {
176 pglob->gl_pathv = NULL;
177 if (!(flags & GLOB_DOOFFS))
180 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
181 pglob->gl_errfunc = errfunc;
182 pglob->gl_matchc = 0;
185 bufend = bufnext + MAXPATHLEN - 1;
186 if (flags & GLOB_NOESCAPE)
187 while (bufnext < bufend && (c = *patnext++) != EOS)
190 /* Protect the quoted characters. */
191 while (bufnext < bufend && (c = *patnext++) != EOS)
193 if ((c = *patnext++) == EOS) {
197 *bufnext++ = c | M_PROTECT;
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
215 globexp1(const Char *pattern, glob_t *pglob)
217 const Char* ptr = pattern;
220 /* Protect a single {}, for find(1), like csh */
221 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
222 return glob0(pattern, pglob);
224 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
225 if (!globexp2(ptr, pattern, pglob, &rv))
228 return glob0(pattern, pglob);
233 * Recursive brace globbing helper. Tries to expand a single brace.
234 * If it succeeds then it invokes globexp1 with the new pattern.
235 * If it fails then it tries to glob the rest of the pattern and returns.
238 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv)
242 const Char *pe, *pm, *pl;
243 Char patbuf[MAXPATHLEN];
245 /* copy part up to the brace */
246 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
251 /* Find the balanced brace */
252 for (i = 0, pe = ++ptr; *pe; pe++)
253 if (*pe == LBRACKET) {
254 /* Ignore everything between [] */
255 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
259 * We could not find a matching RBRACKET.
260 * Ignore and just look for RBRACE
264 } else if (*pe == LBRACE)
266 else if (*pe == RBRACE) {
272 /* Non matching braces; just glob the pattern */
273 if (i != 0 || *pe == EOS) {
274 *rv = glob0(patbuf, pglob);
278 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
281 /* Ignore everything between [] */
282 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
286 * We could not find a matching RBRACKET.
287 * Ignore and just look for RBRACE
304 if (i && *pm == COMMA)
307 /* Append the current string */
308 for (lm = ls; (pl < pm); *lm++ = *pl++)
312 * Append the rest of the pattern after the
315 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
318 /* Expand the current pattern */
320 qprintf("globexp2:", patbuf);
322 *rv = globexp1(patbuf, pglob);
324 /* move after the comma, to the next string */
340 * expand tilde from the passwd file.
343 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
350 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
353 /* Copy up to the end of the string or / */
354 eb = &patbuf[patbuf_len - 1];
355 for (p = pattern + 1, h = (char *) patbuf;
356 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
366 if (((char *) patbuf)[0] == EOS) {
368 * handle a plain ~ or ~/ by expanding $HOME
369 * first and then trying the password file
372 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
374 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
375 if ((pwd = getpwuid(getuid())) == NULL)
384 if ((pwd = getpwnam((char*) patbuf)) == NULL)
390 /* Copy the home directory */
391 for (b = patbuf; b < eb && *h; *b++ = *h++)
394 /* Append the rest of the pattern */
395 while (b < eb && (*b++ = *p++) != EOS)
404 * The main glob() routine: compiles the pattern (optionally processing
405 * quotes), calls glob1() to do the real pattern matching, and finally
406 * sorts the list (unless unsorted operation is requested). Returns 0
407 * if things went well, nonzero if errors occurred. It is not an error
408 * to find no matches.
411 glob0(const Char *pattern, glob_t *pglob)
413 const Char *qpatnext;
414 int c, err, oldpathc;
415 Char *bufnext, patbuf[MAXPATHLEN];
418 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
419 oldpathc = pglob->gl_pathc;
422 /* We don't need to check for buffer overflow any more. */
423 while ((c = *qpatnext++) != EOS) {
429 if (*qpatnext == EOS ||
430 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
431 *bufnext++ = LBRACKET;
441 *bufnext++ = CHAR(c);
442 if (*qpatnext == RANGE &&
443 (c = qpatnext[1]) != RBRACKET) {
445 *bufnext++ = CHAR(c);
448 } while ((c = *qpatnext++) != RBRACKET);
449 pglob->gl_flags |= GLOB_MAGCHAR;
453 pglob->gl_flags |= GLOB_MAGCHAR;
457 pglob->gl_flags |= GLOB_MAGCHAR;
458 /* collapse adjacent stars to one,
459 * to avoid exponential behavior
461 if (bufnext == patbuf || bufnext[-1] != M_ALL)
465 *bufnext++ = CHAR(c);
471 qprintf("glob0:", patbuf);
474 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
478 * If there was no match we are going to append the pattern
479 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
480 * and the pattern did not contain any magic characters
481 * GLOB_NOMAGIC is there just for compatibility with csh.
483 if (pglob->gl_pathc == oldpathc) {
484 if ((pglob->gl_flags & GLOB_NOCHECK) ||
485 ((pglob->gl_flags & GLOB_NOMAGIC) &&
486 !(pglob->gl_flags & GLOB_MAGCHAR)))
487 return(globextend(pattern, pglob, &limit));
489 return(GLOB_NOMATCH);
491 if (!(pglob->gl_flags & GLOB_NOSORT))
492 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
493 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
498 compare(const void *p, const void *q)
500 return(strcmp(*(char **)p, *(char **)q));
504 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
506 Char pathbuf[MAXPATHLEN];
508 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
511 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
512 pathbuf, pathbuf+MAXPATHLEN-1,
513 pattern, pattern_last, pglob, limitp));
517 * The functions glob2 and glob3 are mutually recursive; there is one level
518 * of recursion for each segment in the pattern that contains one or more
522 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
523 Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
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? */
536 if (g_lstat(pathbuf, &sb, pglob))
539 if (((pglob->gl_flags & GLOB_MARK) &&
540 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
541 (S_ISLNK(sb.st_mode) &&
542 (g_stat(pathbuf, &sb, pglob) == 0) &&
543 S_ISDIR(sb.st_mode)))) {
544 if (pathend+1 > pathend_last)
550 return(globextend(pathbuf, pglob, limitp));
553 /* Find end of next segment, copy tentatively to pathend. */
556 while (*p != EOS && *p != SEP) {
559 if (q+1 > pathend_last)
564 if (!anymeta) { /* No expansion, do next segment. */
567 while (*pattern == SEP) {
568 if (pathend+1 > pathend_last)
570 *pathend++ = *pattern++;
573 /* Need expansion, recurse. */
574 return(glob3(pathbuf, pathbuf_last, pathend,
575 pathend_last, pattern, p, pattern_last,
582 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
583 Char *pattern, Char *restpattern, Char *restpattern_last, glob_t *pglob,
589 char buf[MAXPATHLEN];
592 * The readdirfunc declaration can't be prototyped, because it is
593 * assigned, below, to two functions which are prototyped in glob.h
594 * and dirent.h as taking pointers to differently typed opaque
597 struct dirent *(*readdirfunc)(void *);
599 if (pathend > pathend_last)
604 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
605 /* TODO: don't call for ENOENT or ENOTDIR? */
606 if (pglob->gl_errfunc) {
607 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
608 return(GLOB_ABORTED);
609 if (pglob->gl_errfunc(buf, errno) ||
610 pglob->gl_flags & GLOB_ERR)
611 return(GLOB_ABORTED);
618 /* Search directory for matching names. */
619 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
620 readdirfunc = pglob->gl_readdir;
622 readdirfunc = (struct dirent *(*)(void *))readdir;
623 while ((dp = (*readdirfunc)(dirp))) {
627 /* Initial DOT must be matched literally. */
628 if (dp->d_name[0] == DOT && *pattern != DOT)
631 sc = (u_char *) dp->d_name;
632 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
634 if (dc >= pathend_last) {
640 if (!match(pathend, pattern, restpattern)) {
644 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
645 restpattern, restpattern_last, pglob, limitp);
650 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
651 (*pglob->gl_closedir)(dirp);
659 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
660 * add the new item, and update gl_pathc.
662 * This assumes the BSD realloc, which only copies the block when its size
663 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
666 * Return 0 if new item added, error code if memory couldn't be allocated.
668 * Invariant of the glob_t structure:
669 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
670 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
673 globextend(const Char *path, glob_t *pglob, size_t *limitp)
681 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
682 pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
685 if (pglob->gl_pathv) {
686 free(pglob->gl_pathv);
687 pglob->gl_pathv = NULL;
689 return(GLOB_NOSPACE);
692 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
693 /* first time around -- clear initial gl_offs items */
694 pathv += pglob->gl_offs;
695 for (i = pglob->gl_offs; --i >= 0; )
698 pglob->gl_pathv = pathv;
700 for (p = path; *p++;)
702 len = (size_t)(p - path);
704 if ((copy = malloc(len)) != NULL) {
705 if (g_Ctoc(path, copy, len)) {
707 return(GLOB_NOSPACE);
709 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
711 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
713 if ((pglob->gl_flags & GLOB_LIMIT) &&
714 newsize + *limitp >= (u_int) get_arg_max()) {
716 return(GLOB_NOSPACE);
719 return(copy == NULL ? GLOB_NOSPACE : 0);
724 * pattern matching function for filenames. Each occurrence of the *
725 * pattern causes a recursion level.
728 match(Char *name, Char *pat, Char *patend)
730 int ok, negate_range;
733 while (pat < patend) {
735 switch (c & M_MASK) {
740 if (match(name, pat, patend))
742 } while (*name++ != EOS);
750 if ((k = *name++) == EOS)
752 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
754 while (((c = *pat++) & M_MASK) != M_END)
755 if ((*pat & M_MASK) == M_RNG) {
756 if (c <= k && k <= pat[1])
761 if (ok == negate_range)
770 return(*name == EOS);
773 /* Free allocated data belonging to a glob_t structure. */
775 globfree(glob_t *pglob)
780 if (pglob->gl_pathv != NULL) {
781 pp = pglob->gl_pathv + pglob->gl_offs;
782 for (i = pglob->gl_pathc; i--; ++pp)
785 free(pglob->gl_pathv);
786 pglob->gl_pathv = NULL;
791 g_opendir(Char *str, glob_t *pglob)
793 char buf[MAXPATHLEN];
796 strlcpy(buf, ".", sizeof buf);
798 if (g_Ctoc(str, buf, sizeof(buf)))
802 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
803 return((*pglob->gl_opendir)(buf));
805 return(opendir(buf));
809 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
811 char buf[MAXPATHLEN];
813 if (g_Ctoc(fn, buf, sizeof(buf)))
815 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
816 return((*pglob->gl_lstat)(buf, sb));
817 return(lstat(buf, sb));
821 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
823 char buf[MAXPATHLEN];
825 if (g_Ctoc(fn, buf, sizeof(buf)))
827 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
828 return((*pglob->gl_stat)(buf, sb));
829 return(stat(buf, sb));
833 g_strchr(Char *str, int ch)
843 g_Ctoc(const Char *str, char *buf, u_int len)
847 if ((*buf++ = *str++) == EOS)
855 qprintf(const char *str, Char *s)
859 (void)printf("%s:\n", str);
861 (void)printf("%c", CHAR(*p));
864 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
867 (void)printf("%c", ismeta(*p) ? '_' : ' ');
872 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
873 !defined(GLOB_HAS_GL_MATCHC) */