2 * Ported to Linux's Second Extended File System as part of the
3 * dump and restore backup suit
4 * Remy Card <card@Linux.EU.Org>, 1994-1997
5 * Stelian Pop <pop@cybercable.fr>, 1999
10 * Copyright (c) 1989, 1993
11 * The Regents of the University of California. All rights reserved.
13 * This code is derived from software contributed to Berkeley by
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. All advertising materials mentioning features or use of this software
25 * must display the following acknowledgement:
26 * This product includes software developed by the University of
27 * California, Berkeley and its contributors.
28 * 4. Neither the name of the University nor the names of its contributors
29 * may be used to endorse or promote products derived from this software
30 * without specific prior written permission.
32 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 #if defined(LIBC_SCCS) && !defined(lint)
46 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
47 #endif /* LIBC_SCCS and not lint */
50 * glob(3) -- a superset of the one defined in POSIX 1003.2.
52 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
54 * Optional extra services, controlled by flags not defined by POSIX:
57 * Escaping convention: \ inhibits any special meaning the following
58 * character might have (except \ at end of string is retained).
60 * Set in gl_flags if pattern contained a globbing character.
62 * Same as GLOB_NOCHECK, but it will only append pattern if it did
63 * not contain any magic characters. [Used in csh style globbing]
65 * Use alternately specified directory access functions.
67 * expand ~user/foo to the /home/dir/of/user/foo
69 * expand {1,2}{a,b} to 1a 1b 2a 2b
71 * Number of matches in the current invocation of glob.
74 #include <sys/param.h>
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 __P((const void *, const void *));
138 static void g_Ctoc __P((const Char *, char *));
139 static int g_lstat __P((Char *, struct stat *, glob_t *));
140 static DIR *g_opendir __P((Char *, glob_t *));
141 static Char *g_strchr __P((Char *, int));
143 static Char *g_strcat __P((Char *, const Char *));
145 static int g_stat __P((Char *, struct stat *, glob_t *));
146 static int glob0 __P((const Char *, glob_t *));
147 static int glob1 __P((Char *, glob_t *));
148 static int glob2 __P((Char *, Char *, Char *, glob_t *));
149 static int glob3 __P((Char *, Char *, Char *, Char *, glob_t *));
150 static int globextend __P((const Char *, glob_t *));
151 static const Char * globtilde __P((const Char *, Char *, size_t, glob_t *));
152 static int globexp1 __P((const Char *, glob_t *));
153 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
154 static int match __P((Char *, Char *, Char *));
156 static void qprintf __P((const char *, Char *));
160 glob(pattern, flags, errfunc, pglob)
162 int flags, (*errfunc) __P((const char *, int));
165 const u_char *patnext;
167 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
169 patnext = (u_char *) pattern;
170 if (!(flags & GLOB_APPEND)) {
172 pglob->gl_pathv = NULL;
173 if (!(flags & GLOB_DOOFFS))
176 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
177 pglob->gl_errfunc = errfunc;
178 pglob->gl_matchc = 0;
181 bufend = bufnext + MAXPATHLEN;
182 if (flags & GLOB_QUOTE) {
183 /* Protect the quoted characters. */
184 while (bufnext < bufend && (c = *patnext++) != EOS)
186 if ((c = *patnext++) == EOS) {
190 *bufnext++ = c | M_PROTECT;
196 while (bufnext < bufend && (c = *patnext++) != EOS)
200 if (flags & GLOB_BRACE)
201 return globexp1(patbuf, pglob);
203 return glob0(patbuf, pglob);
207 * Expand recursively a glob {} pattern. When there is no more expansion
208 * invoke the standard globbing routine to glob the rest of the magic
211 static int globexp1(pattern, pglob)
215 const Char* ptr = pattern;
218 /* Protect a single {}, for find(1), like csh */
219 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
220 return glob0(pattern, pglob);
222 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
223 if (!globexp2(ptr, pattern, pglob, &rv))
226 return glob0(pattern, pglob);
231 * Recursive brace globbing helper. Tries to expand a single brace.
232 * If it succeeds then it invokes globexp1 with the new pattern.
233 * If it fails then it tries to glob the rest of the pattern and returns.
235 static int globexp2(ptr, pattern, pglob, rv)
236 const Char *ptr, *pattern;
242 const Char *pe, *pm, *pl;
243 Char patbuf[MAXPATHLEN + 1];
245 /* copy part up to the brace */
246 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
250 /* Find the balanced brace */
251 for (i = 0, pe = ++ptr; *pe; pe++)
252 if (*pe == LBRACKET) {
253 /* Ignore everything between [] */
254 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
258 * We could not find a matching RBRACKET.
259 * 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++)
311 * Append the rest of the pattern after the
314 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
317 /* Expand the current pattern */
319 qprintf("globexp2:", patbuf);
321 *rv = globexp1(patbuf, pglob);
323 /* move after the comma, to the next string */
338 * expand tilde from the passwd file.
341 globtilde(pattern, patbuf, patbuf_len, pglob)
352 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
356 * Copy up to the end of the string or /
358 eb = &patbuf[patbuf_len - 1];
359 for (p = pattern + 1, h = (char *) patbuf;
360 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
365 if (((char *) patbuf)[0] == EOS) {
367 * handle a plain ~ or ~/ by expanding $HOME first if
368 * we're not running setuid or setgid) and then trying
373 #ifndef __NETBSD_SYSCALLS
377 (h = getenv("HOME")) == NULL) {
378 if (((h = getlogin()) != NULL &&
379 (pwd = getpwnam(h)) != NULL) ||
380 (pwd = getpwuid(getuid())) != NULL)
390 if ((pwd = getpwnam((char*) patbuf)) == NULL)
396 /* Copy the home directory */
397 for (b = patbuf; b < eb && *h; *b++ = *h++)
400 /* Append the rest of the pattern */
401 while (b < eb && (*b++ = *p++) != EOS)
410 * The main glob() routine: compiles the pattern (optionally processing
411 * quotes), calls glob1() to do the real pattern matching, and finally
412 * sorts the list (unless unsorted operation is requested). Returns 0
413 * if things went well, nonzero if errors occurred. It is not an error
414 * to find no matches.
417 glob0(pattern, pglob)
421 const Char *qpatnext;
422 int c, err, oldpathc;
423 Char *bufnext, patbuf[MAXPATHLEN+1];
425 qpatnext = globtilde(pattern, patbuf, sizeof(patbuf) / sizeof(Char),
427 oldpathc = pglob->gl_pathc;
430 /* We don't need to check for buffer overflow any more. */
431 while ((c = *qpatnext++) != EOS) {
437 if (*qpatnext == EOS ||
438 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
439 *bufnext++ = LBRACKET;
449 *bufnext++ = CHAR(c);
450 if (*qpatnext == RANGE &&
451 (c = qpatnext[1]) != RBRACKET) {
453 *bufnext++ = CHAR(c);
456 } while ((c = *qpatnext++) != RBRACKET);
457 pglob->gl_flags |= GLOB_MAGCHAR;
461 pglob->gl_flags |= GLOB_MAGCHAR;
465 pglob->gl_flags |= GLOB_MAGCHAR;
466 /* collapse adjacent stars to one,
467 * to avoid exponential behavior
469 if (bufnext == patbuf || bufnext[-1] != M_ALL)
473 *bufnext++ = CHAR(c);
479 qprintf("glob0:", patbuf);
482 if ((err = glob1(patbuf, pglob)) != 0)
486 * If there was no match we are going to append the pattern
487 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
488 * and the pattern did not contain any magic characters
489 * GLOB_NOMAGIC is there just for compatibility with csh.
491 if (pglob->gl_pathc == oldpathc &&
492 ((pglob->gl_flags & GLOB_NOCHECK) ||
493 ((pglob->gl_flags & GLOB_NOMAGIC) &&
494 !(pglob->gl_flags & GLOB_MAGCHAR))))
495 return(globextend(pattern, pglob));
496 else if (!(pglob->gl_flags & GLOB_NOSORT))
497 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
498 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
506 return(strcmp(*(char **)p, *(char **)q));
510 glob1(pattern, pglob)
514 Char pathbuf[MAXPATHLEN+1];
516 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
519 return(glob2(pathbuf, pathbuf, pattern, pglob));
523 * The functions glob2 and glob3 are mutually recursive; there is one level
524 * of recursion for each segment in the pattern that contains one or more
528 glob2(pathbuf, pathend, pattern, pglob)
529 Char *pathbuf, *pathend, *pattern;
537 * Loop over pattern segments until end of pattern or until
538 * segment with meta character found.
540 for (anymeta = 0;;) {
541 if (*pattern == EOS) { /* End of pattern? */
543 if (g_lstat(pathbuf, &sb, pglob))
546 if (((pglob->gl_flags & GLOB_MARK) &&
547 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
548 || (S_ISLNK(sb.st_mode) &&
549 (g_stat(pathbuf, &sb, pglob) == 0) &&
550 S_ISDIR(sb.st_mode)))) {
555 return(globextend(pathbuf, pglob));
558 /* Find end of next segment, copy tentatively to pathend. */
561 while (*p != EOS && *p != SEP) {
567 if (!anymeta) { /* No expansion, do next segment. */
570 while (*pattern == SEP)
571 *pathend++ = *pattern++;
572 } else /* Need expansion, recurse. */
573 return(glob3(pathbuf, pathend, pattern, p, pglob));
579 glob3(pathbuf, pathend, pattern, restpattern, pglob)
580 Char *pathbuf, *pathend, *pattern, *restpattern;
583 register struct dirent *dp;
586 char buf[MAXPATHLEN];
589 * The readdirfunc declaration can't be prototyped, because it is
590 * assigned, below, to two functions which are prototyped in glob.h
591 * and dirent.h as taking pointers to differently typed opaque
594 struct dirent *(*readdirfunc)();
599 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
600 /* TODO: don't call for ENOENT or ENOTDIR? */
601 if (pglob->gl_errfunc) {
602 g_Ctoc(pathbuf, buf);
603 if (pglob->gl_errfunc(buf, errno) ||
604 pglob->gl_flags & GLOB_ERR)
612 /* Search directory for matching names. */
613 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
614 readdirfunc = pglob->gl_readdir;
616 readdirfunc = readdir;
617 while ((dp = (*readdirfunc)(dirp))) {
621 /* Initial DOT must be matched literally. */
622 if (dp->d_name[0] == DOT && *pattern != DOT)
624 for (sc = (u_char *) dp->d_name, dc = pathend;
625 (*dc++ = *sc++) != EOS;)
627 if (!match(pathend, pattern, restpattern)) {
631 err = glob2(pathbuf, --dc, restpattern, pglob);
636 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
637 (*pglob->gl_closedir)(dirp);
645 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
646 * add the new item, and update gl_pathc.
648 * This assumes the BSD realloc, which only copies the block when its size
649 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
652 * Return 0 if new item added, error code if memory couldn't be allocated.
654 * Invariant of the glob_t structure:
655 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
656 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
659 globextend(path, pglob)
663 register char **pathv;
669 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
670 pathv = pglob->gl_pathv ?
671 realloc((char *)pglob->gl_pathv, newsize) :
674 return(GLOB_NOSPACE);
676 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
677 /* first time around -- clear initial gl_offs items */
678 pathv += pglob->gl_offs;
679 for (i = pglob->gl_offs; --i >= 0; )
682 pglob->gl_pathv = pathv;
684 for (p = path; *p++;)
686 if ((copy = malloc(p - path)) != NULL) {
688 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
690 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
691 return(copy == NULL ? GLOB_NOSPACE : 0);
695 * pattern matching function for filenames. Each occurrence of the *
696 * pattern causes a recursion level.
699 match(name, pat, patend)
700 register Char *name, *pat, *patend;
702 int ok, negate_range;
705 while (pat < patend) {
707 switch (c & M_MASK) {
712 if (match(name, pat, patend))
714 while (*name++ != EOS);
722 if ((k = *name++) == EOS)
724 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
726 while (((c = *pat++) & M_MASK) != M_END)
727 if ((*pat & M_MASK) == M_RNG) {
728 if (c <= k && k <= pat[1])
733 if (ok == negate_range)
742 return(*name == EOS);
745 /* Free allocated data belonging to a glob_t structure. */
753 if (pglob->gl_pathv != NULL) {
754 pp = pglob->gl_pathv + pglob->gl_offs;
755 for (i = pglob->gl_pathc; i--; ++pp)
758 free(pglob->gl_pathv);
763 g_opendir(str, pglob)
767 char buf[MAXPATHLEN];
774 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
775 return((*pglob->gl_opendir)(buf));
777 return(opendir(buf));
781 g_lstat(fn, sb, pglob)
786 char buf[MAXPATHLEN];
789 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
790 return((*pglob->gl_lstat)(buf, sb));
791 return(lstat(buf, sb));
795 g_stat(fn, sb, pglob)
800 char buf[MAXPATHLEN];
803 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
804 return((*pglob->gl_stat)(buf, sb));
805 return(stat(buf, sb));
831 while((*dst++ = *src++) != EOS)
840 register const Char *str;
845 for (dc = buf; (*dc++ = *str++) != EOS;)
857 (void)printf("%s:\n", str);
859 (void)printf("%c", CHAR(*p));
862 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
865 (void)printf("%c", ismeta(*p) ? '_' : ' ');