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 <stelian@popies.net>, 1999-2000
6 * Stelian Pop <stelian@popies.net> - AlcĂ´ve <www.alcove.com>, 2000-2002
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. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * glob(3) -- a superset of the one defined in POSIX 1003.2.
44 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
46 * Optional extra services, controlled by flags not defined by POSIX:
49 * Escaping convention: \ inhibits any special meaning the following
50 * character might have (except \ at end of string is retained).
52 * Set in gl_flags if pattern contained a globbing character.
54 * Same as GLOB_NOCHECK, but it will only append pattern if it did
55 * not contain any magic characters. [Used in csh style globbing]
57 * Use alternately specified directory access functions.
59 * expand ~user/foo to the /home/dir/of/user/foo
61 * expand {1,2}{a,b} to 1a 1b 2a 2b
63 * Number of matches in the current invocation of glob.
67 static const char rcsid[] =
68 "$Id: compatglob.c,v 1.10 2003/10/26 16:05:46 stelian Exp $";
72 #include <sys/types.h>
76 #include <sys/param.h>
82 #include <compatglob.h>
101 #define UNDERSCORE '_'
109 #define M_QUOTE 0x8000
110 #define M_PROTECT 0x4000
111 #define M_MASK 0xffff
112 #define M_ASCII 0x00ff
114 typedef u_short Char;
119 #define M_PROTECT 0x40
128 #define CHAR(c) ((Char)((c)&M_ASCII))
129 #define META(c) ((Char)((c)|M_QUOTE))
130 #define M_ALL META('*')
131 #define M_END META(']')
132 #define M_NOT META('!')
133 #define M_ONE META('?')
134 #define M_RNG META('-')
135 #define M_SET META('[')
136 #define ismeta(c) (((c)&M_QUOTE) != 0)
139 static int compare __P((const void *, const void *));
140 static void g_Ctoc __P((const Char *, char *));
141 static int g_lstat __P((Char *, struct stat *, glob_t *));
142 static DIR *g_opendir __P((Char *, glob_t *));
143 static Char *g_strchr __P((Char *, int));
145 static Char *g_strcat __P((Char *, const Char *));
147 static int g_stat __P((Char *, struct stat *, glob_t *));
148 static int glob0 __P((const Char *, glob_t *));
149 static int glob1 __P((Char *, glob_t *));
150 static int glob2 __P((Char *, Char *, Char *, glob_t *));
151 static int glob3 __P((Char *, Char *, Char *, Char *, glob_t *));
152 static int globextend __P((const Char *, glob_t *));
153 static const Char * globtilde __P((const Char *, Char *, size_t, glob_t *));
154 static int globexp1 __P((const Char *, glob_t *));
155 static int globexp2 __P((const Char *, const Char *, glob_t *, int *));
156 static int match __P((Char *, Char *, Char *));
158 static void qprintf __P((const char *, Char *));
162 glob(const char *pattern, int flags, int (*errfunc) __P((const char *, int)), glob_t *pglob)
164 const u_char *patnext;
166 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
168 patnext = (u_char *) pattern;
169 if (!(flags & GLOB_APPEND)) {
171 pglob->gl_pathv = NULL;
172 if (!(flags & GLOB_DOOFFS))
175 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
176 pglob->gl_errfunc = errfunc;
177 pglob->gl_matchc = 0;
180 bufend = bufnext + MAXPATHLEN;
181 if (flags & GLOB_QUOTE) {
182 /* Protect the quoted characters. */
183 while (bufnext < bufend && (c = *patnext++) != EOS)
185 if ((c = *patnext++) == EOS) {
189 *bufnext++ = c | M_PROTECT;
195 while (bufnext < bufend && (c = *patnext++) != EOS)
199 if (flags & GLOB_BRACE)
200 return globexp1(patbuf, pglob);
202 return glob0(patbuf, pglob);
206 * Expand recursively a glob {} pattern. When there is no more expansion
207 * invoke the standard globbing routine to glob the rest of the magic
210 static int globexp1(const Char *pattern, glob_t *pglob)
212 const Char* ptr = pattern;
215 /* Protect a single {}, for find(1), like csh */
216 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
217 return glob0(pattern, pglob);
219 while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
220 if (!globexp2(ptr, pattern, pglob, &rv))
223 return glob0(pattern, pglob);
228 * Recursive brace globbing helper. Tries to expand a single brace.
229 * If it succeeds then it invokes globexp1 with the new pattern.
230 * If it fails then it tries to glob the rest of the pattern and returns.
232 static int globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv)
236 const Char *pe, *pm, *pl;
237 Char patbuf[MAXPATHLEN + 1];
239 /* copy part up to the brace */
240 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
244 /* Find the balanced brace */
245 for (i = 0, pe = ++ptr; *pe; pe++)
246 if (*pe == LBRACKET) {
247 /* Ignore everything between [] */
248 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
252 * We could not find a matching RBRACKET.
253 * 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++)
305 * Append the rest of the pattern after the
308 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
311 /* Expand the current pattern */
313 qprintf("globexp2:", patbuf);
315 *rv = globexp1(patbuf, pglob);
317 /* move after the comma, to the next string */
332 * expand tilde from the passwd file.
335 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
342 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
346 * 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++)
355 if (((char *) patbuf)[0] == EOS) {
357 * handle a plain ~ or ~/ by expanding $HOME first if
358 * we're not running setuid or setgid) and then trying
362 #if !defined(__linux__) && !defined(sunos)
363 #ifndef __NETBSD_SYSCALLS
367 (h = getenv("HOME")) == NULL) {
368 if (((h = getlogin()) != NULL &&
369 (pwd = getpwnam(h)) != NULL) ||
370 (pwd = getpwuid(getuid())) != NULL)
380 if ((pwd = getpwnam((char*) patbuf)) == NULL)
386 /* Copy the home directory */
387 for (b = patbuf; b < eb && *h; *b++ = *h++)
390 /* Append the rest of the pattern */
391 while (b < eb && (*b++ = *p++) != EOS)
400 * The main glob() routine: compiles the pattern (optionally processing
401 * quotes), calls glob1() to do the real pattern matching, and finally
402 * sorts the list (unless unsorted operation is requested). Returns 0
403 * if things went well, nonzero if errors occurred. It is not an error
404 * to find no matches.
407 glob0(const Char *pattern, glob_t *pglob)
409 const Char *qpatnext;
410 int c, err, oldpathc;
411 Char *bufnext, patbuf[MAXPATHLEN+1];
413 qpatnext = globtilde(pattern, patbuf, sizeof(patbuf) / sizeof(Char),
415 oldpathc = pglob->gl_pathc;
418 /* We don't need to check for buffer overflow any more. */
419 while ((c = *qpatnext++) != EOS) {
425 if (*qpatnext == EOS ||
426 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
427 *bufnext++ = LBRACKET;
437 *bufnext++ = CHAR(c);
438 if (*qpatnext == RANGE &&
439 (c = qpatnext[1]) != RBRACKET) {
441 *bufnext++ = CHAR(c);
444 } while ((c = *qpatnext++) != RBRACKET);
445 pglob->gl_flags |= GLOB_MAGCHAR;
449 pglob->gl_flags |= GLOB_MAGCHAR;
453 pglob->gl_flags |= GLOB_MAGCHAR;
454 /* collapse adjacent stars to one,
455 * to avoid exponential behavior
457 if (bufnext == patbuf || bufnext[-1] != M_ALL)
461 *bufnext++ = CHAR(c);
467 qprintf("glob0:", patbuf);
470 if ((err = glob1(patbuf, pglob)) != 0)
474 * If there was no match we are going to append the pattern
475 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
476 * and the pattern did not contain any magic characters
477 * GLOB_NOMAGIC is there just for compatibility with csh.
479 if (pglob->gl_pathc == oldpathc &&
480 ((pglob->gl_flags & GLOB_NOCHECK) ||
481 ((pglob->gl_flags & GLOB_NOMAGIC) &&
482 !(pglob->gl_flags & GLOB_MAGCHAR))))
483 return(globextend(pattern, pglob));
484 else if (!(pglob->gl_flags & GLOB_NOSORT))
485 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
486 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
491 compare(const void *p, const void *q)
493 return(strcmp(*(char **)p, *(char **)q));
497 glob1(Char *pattern, glob_t *pglob)
499 Char pathbuf[MAXPATHLEN+1];
501 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
504 return(glob2(pathbuf, pathbuf, pattern, pglob));
508 * The functions glob2 and glob3 are mutually recursive; there is one level
509 * of recursion for each segment in the pattern that contains one or more
513 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
520 * Loop over pattern segments until end of pattern or until
521 * segment with meta character found.
523 for (anymeta = 0;;) {
524 if (*pattern == EOS) { /* End of pattern? */
526 if (g_lstat(pathbuf, &sb, pglob))
529 if (((pglob->gl_flags & GLOB_MARK) &&
530 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
531 || (S_ISLNK(sb.st_mode) &&
532 (g_stat(pathbuf, &sb, pglob) == 0) &&
533 S_ISDIR(sb.st_mode)))) {
538 return(globextend(pathbuf, pglob));
541 /* Find end of next segment, copy tentatively to pathend. */
544 while (*p != EOS && *p != SEP) {
550 if (!anymeta) { /* No expansion, do next segment. */
553 while (*pattern == SEP)
554 *pathend++ = *pattern++;
555 } else /* Need expansion, recurse. */
556 return(glob3(pathbuf, pathend, pattern, p, pglob));
562 glob3(Char *pathbuf, Char *pathend, Char *pattern, Char *restpattern, glob_t *pglob)
567 char buf[MAXPATHLEN];
570 * The readdirfunc declaration can't be prototyped, because it is
571 * assigned, below, to two functions which are prototyped in glob.h
572 * and dirent.h as taking pointers to differently typed opaque
575 struct dirent *(*readdirfunc)();
580 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
581 /* TODO: don't call for ENOENT or ENOTDIR? */
582 if (pglob->gl_errfunc) {
583 g_Ctoc(pathbuf, buf);
584 if (pglob->gl_errfunc(buf, errno) ||
585 pglob->gl_flags & GLOB_ERR)
593 /* Search directory for matching names. */
594 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
595 readdirfunc = pglob->gl_readdir;
597 readdirfunc = readdir;
598 while ((dp = (*readdirfunc)(dirp))) {
602 /* Initial DOT must be matched literally. */
603 if (dp->d_name[0] == DOT && *pattern != DOT)
605 for (sc = (u_char *) dp->d_name, dc = pathend;
606 (*dc++ = *sc++) != EOS;)
608 if (!match(pathend, pattern, restpattern)) {
612 err = glob2(pathbuf, --dc, restpattern, pglob);
617 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
618 (*pglob->gl_closedir)(dirp);
626 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
627 * add the new item, and update gl_pathc.
629 * This assumes the BSD realloc, which only copies the block when its size
630 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
633 * Return 0 if new item added, error code if memory couldn't be allocated.
635 * Invariant of the glob_t structure:
636 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
637 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
640 globextend(const Char *path, glob_t *pglob)
648 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
649 pathv = pglob->gl_pathv ?
650 realloc((char *)pglob->gl_pathv, newsize) :
653 return(GLOB_NOSPACE);
655 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
656 /* first time around -- clear initial gl_offs items */
657 pathv += pglob->gl_offs;
658 for (i = pglob->gl_offs; --i >= 0; )
661 pglob->gl_pathv = pathv;
663 for (p = path; *p++;)
665 if ((copy = malloc(p - path)) != NULL) {
667 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
669 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
670 return(copy == NULL ? GLOB_NOSPACE : 0);
674 * pattern matching function for filenames. Each occurrence of the *
675 * pattern causes a recursion level.
678 match(Char *name, Char *pat, Char *patend)
680 int ok, negate_range;
683 while (pat < patend) {
685 switch (c & M_MASK) {
690 if (match(name, pat, patend))
692 while (*name++ != EOS);
700 if ((k = *name++) == EOS)
702 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
704 while (((c = *pat++) & M_MASK) != M_END)
705 if ((*pat & M_MASK) == M_RNG) {
706 if (c <= k && k <= pat[1])
711 if (ok == negate_range)
720 return(*name == EOS);
723 /* Free allocated data belonging to a glob_t structure. */
725 globfree(glob_t *pglob)
730 if (pglob->gl_pathv != NULL) {
731 pp = pglob->gl_pathv + pglob->gl_offs;
732 for (i = pglob->gl_pathc; i--; ++pp)
735 free(pglob->gl_pathv);
740 g_opendir(Char *str, glob_t *pglob)
742 char buf[MAXPATHLEN];
749 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
750 return((*pglob->gl_opendir)(buf));
752 return(opendir(buf));
756 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
758 char buf[MAXPATHLEN];
761 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
762 return((*pglob->gl_lstat)(buf, sb));
763 return(lstat(buf, sb));
767 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
769 char buf[MAXPATHLEN];
772 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
773 return((*pglob->gl_stat)(buf, sb));
774 return(stat(buf, sb));
778 g_strchr(Char *str, int ch)
789 g_strcat(Char *dst, const Char *src)
796 while((*dst++ = *src++) != EOS)
804 g_Ctoc(const Char *str, char *buf)
808 for (dc = buf; (*dc++ = *str++) != EOS;)
814 qprintf(const char *str, Char *s)
818 (void)printf("%s:\n", str);
820 (void)printf("%c", CHAR(*p));
823 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
826 (void)printf("%c", ismeta(*p) ? '_' : ' ');
831 #endif /* ! HAVE_GLOB */