2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * Clause 3 above should be considered "deleted in its entirety".
39 * For the actual notice of withdrawal, see:
40 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
43 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
45 #endif /* LIBC_SCCS and not lint */
48 * glob(3) -- a superset of the one defined in POSIX 1003.2.
50 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
52 * Optional extra services, controlled by flags not defined by POSIX:
55 * Escaping convention: \ inhibits any special meaning the following
56 * character might have (except \ at end of string is retained).
58 * Set in gl_flags if pattern contained a globbing character.
60 * Same as GLOB_NOCHECK, but it will only append pattern if it did
61 * not contain any magic characters. [Used in csh style globbing]
63 * Use alternately specified directory access functions.
65 * expand ~user/foo to the /home/dir/of/user/foo
67 * expand {1,2}{a,b} to 1a 1b 2a 2b
69 * Number of matches in the current invocation of glob.
81 struct passwd *getpwnam(char *);
82 struct passwd *getpwuid(Uid_t);
88 # define MAXPATHLEN PATH_MAX
90 # define MAXPATHLEN 1024
97 #define BG_LBRACKET '['
99 #define BG_QUESTION '?'
100 #define BG_QUOTE '\\'
102 #define BG_RBRACKET ']'
106 #define BG_UNDERSCORE '_'
107 #define BG_LBRACE '{'
108 #define BG_RBRACE '}'
114 #define M_QUOTE 0x8000
115 #define M_PROTECT 0x4000
116 #define M_MASK 0xffff
117 #define M_ASCII 0x00ff
124 #define M_PROTECT 0x40
130 #endif /* !GLOB_DEBUG */
133 #define CHAR(c) ((Char)((c)&M_ASCII))
134 #define META(c) ((Char)((c)|M_QUOTE))
135 #define M_ALL META('*')
136 #define M_END META(']')
137 #define M_NOT META('!')
138 #define M_ONE META('?')
139 #define M_RNG META('-')
140 #define M_SET META('[')
141 #define ismeta(c) (((c)&M_QUOTE) != 0)
144 static int compare(const void *, const void *);
145 static void g_Ctoc(const Char *, char *);
146 static int g_lstat(Char *, Stat_t *, glob_t *);
147 static DIR *g_opendir(Char *, glob_t *);
148 static Char *g_strchr(Char *, int);
150 static Char *g_strcat(Char *, const Char *);
152 static int g_stat(Char *, Stat_t *, glob_t *);
153 static int glob0(const Char *, glob_t *);
154 static int glob1(Char *, glob_t *);
155 static int glob2(Char *, Char *, Char *, glob_t *);
156 static int glob3(Char *, Char *, Char *, Char *, glob_t *);
157 static int globextend(const Char *, glob_t *);
158 static const Char * globtilde(const Char *, Char *, glob_t *);
159 static int globexp1(const Char *, glob_t *);
160 static int globexp2(const Char *, const Char *, glob_t *, int *);
161 static int match(Char *, Char *, Char *);
163 static void qprintf(const char *, Char *);
164 #endif /* GLOB_DEBUG */
166 #ifdef PERL_IMPLICIT_CONTEXT
167 static Direntry_t * my_readdir(DIR*);
172 return PerlDir_read(d);
175 #define my_readdir readdir
179 bsd_glob(const char *pattern, int flags,
180 int (*errfunc)(const char *, int), glob_t *pglob)
184 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
186 patnext = (U8 *) pattern;
187 if (!(flags & GLOB_APPEND)) {
189 pglob->gl_pathv = NULL;
190 if (!(flags & GLOB_DOOFFS))
193 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
194 pglob->gl_errfunc = errfunc;
195 pglob->gl_matchc = 0;
198 bufend = bufnext + MAXPATHLEN;
199 if (flags & GLOB_QUOTE) {
200 /* Protect the quoted characters. */
201 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
203 if ((c = *patnext++) == BG_EOS) {
207 *bufnext++ = c | M_PROTECT;
213 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
217 if (flags & GLOB_BRACE)
218 return globexp1(patbuf, pglob);
220 return glob0(patbuf, pglob);
224 * Expand recursively a glob {} pattern. When there is no more expansion
225 * invoke the standard globbing routine to glob the rest of the magic
228 static int globexp1(const Char *pattern, glob_t *pglob)
230 const Char* ptr = pattern;
233 /* Protect a single {}, for find(1), like csh */
234 if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
235 return glob0(pattern, pglob);
237 while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
238 if (!globexp2(ptr, pattern, pglob, &rv))
241 return glob0(pattern, pglob);
246 * Recursive brace globbing helper. Tries to expand a single brace.
247 * If it succeeds then it invokes globexp1 with the new pattern.
248 * If it fails then it tries to glob the rest of the pattern and returns.
250 static int globexp2(const Char *ptr, const Char *pattern,
251 glob_t *pglob, int *rv)
255 const Char *pe, *pm, *pl;
256 Char patbuf[MAXPATHLEN + 1];
258 /* copy part up to the brace */
259 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
263 /* Find the balanced brace */
264 for (i = 0, pe = ++ptr; *pe; pe++)
265 if (*pe == BG_LBRACKET) {
266 /* Ignore everything between [] */
267 for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
271 * We could not find a matching BG_RBRACKET.
272 * Ignore and just look for BG_RBRACE
277 else if (*pe == BG_LBRACE)
279 else if (*pe == BG_RBRACE) {
285 /* Non matching braces; just glob the pattern */
286 if (i != 0 || *pe == BG_EOS) {
287 *rv = glob0(patbuf, pglob);
291 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
294 /* Ignore everything between [] */
295 for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
299 * We could not find a matching BG_RBRACKET.
300 * Ignore and just look for BG_RBRACE
317 if (i && *pm == BG_COMMA)
320 /* Append the current string */
321 for (lm = ls; (pl < pm); *lm++ = *pl++)
324 * Append the rest of the pattern after the
327 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS;)
330 /* Expand the current pattern */
332 qprintf("globexp2:", patbuf);
333 #endif /* GLOB_DEBUG */
334 *rv = globexp1(patbuf, pglob);
336 /* move after the comma, to the next string */
351 * expand tilde from the passwd file.
354 globtilde(const Char *pattern, Char *patbuf, glob_t *pglob)
361 if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
364 /* Copy up to the end of the string or / */
365 for (p = pattern + 1, h = (char *) patbuf; *p && *p != BG_SLASH;
371 if (((char *) patbuf)[0] == BG_EOS) {
373 * handle a plain ~ or ~/ by expanding $HOME
374 * first and then trying the password file
376 if ((h = getenv("HOME")) == NULL) {
378 if ((pwd = getpwuid(getuid())) == NULL)
392 if ((pwd = getpwnam((char*) patbuf)) == NULL)
401 /* Copy the home directory */
402 for (b = patbuf; *h; *b++ = *h++)
405 /* Append the rest of the pattern */
406 while ((*b++ = *p++) != BG_EOS)
414 * The main glob() routine: compiles the pattern (optionally processing
415 * quotes), calls glob1() to do the real pattern matching, and finally
416 * sorts the list (unless unsorted operation is requested). Returns 0
417 * if things went well, nonzero if errors occurred. It is not an error
418 * to find no matches.
421 glob0(const Char *pattern, glob_t *pglob)
423 const Char *qpat, *qpatnext;
424 int c, err, oldflags, oldpathc;
425 Char *bufnext, patbuf[MAXPATHLEN+1];
427 qpat = globtilde(pattern, patbuf, pglob);
429 oldflags = pglob->gl_flags;
430 oldpathc = pglob->gl_pathc;
433 /* We don't need to check for buffer overflow any more. */
434 while ((c = *qpatnext++) != BG_EOS) {
440 if (*qpatnext == BG_EOS ||
441 g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
442 *bufnext++ = BG_LBRACKET;
452 *bufnext++ = CHAR(c);
453 if (*qpatnext == BG_RANGE &&
454 (c = qpatnext[1]) != BG_RBRACKET) {
456 *bufnext++ = CHAR(c);
459 } while ((c = *qpatnext++) != BG_RBRACKET);
460 pglob->gl_flags |= GLOB_MAGCHAR;
464 pglob->gl_flags |= GLOB_MAGCHAR;
468 pglob->gl_flags |= GLOB_MAGCHAR;
469 /* collapse adjacent stars to one,
470 * to avoid exponential behavior
472 if (bufnext == patbuf || bufnext[-1] != M_ALL)
476 *bufnext++ = CHAR(c);
482 qprintf("glob0:", patbuf);
483 #endif /* GLOB_DEBUG */
485 if ((err = glob1(patbuf, pglob)) != 0) {
486 pglob->gl_flags = oldflags;
491 * If there was no match we are going to append the pattern
492 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
493 * and the pattern did not contain any magic characters
494 * GLOB_NOMAGIC is there just for compatibility with csh.
496 if (pglob->gl_pathc == oldpathc &&
497 ((pglob->gl_flags & GLOB_NOCHECK) ||
498 ((pglob->gl_flags & GLOB_NOMAGIC) &&
499 !(pglob->gl_flags & GLOB_MAGCHAR))))
502 printf("calling globextend from glob0\n");
503 #endif /* GLOB_DEBUG */
504 pglob->gl_flags = oldflags;
505 return(globextend(qpat, pglob));
507 else if (!(pglob->gl_flags & GLOB_NOSORT))
508 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
509 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
510 pglob->gl_flags = oldflags;
515 compare(const void *p, const void *q)
517 return(strcmp(*(char **)p, *(char **)q));
521 glob1(Char *pattern, glob_t *pglob)
523 Char pathbuf[MAXPATHLEN+1];
525 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
526 if (*pattern == BG_EOS)
528 return(glob2(pathbuf, pathbuf, pattern, pglob));
532 * The functions glob2 and glob3 are mutually recursive; there is one level
533 * of recursion for each segment in the pattern that contains one or more
537 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
544 * Loop over pattern segments until end of pattern or until
545 * segment with meta character found.
547 for (anymeta = 0;;) {
548 if (*pattern == BG_EOS) { /* End of pattern? */
551 if (g_lstat(pathbuf, &sb, pglob))
554 if (((pglob->gl_flags & GLOB_MARK) &&
555 pathend[-1] != BG_SEP) && (S_ISDIR(sb.st_mode)
556 || (S_ISLNK(sb.st_mode) &&
557 (g_stat(pathbuf, &sb, pglob) == 0) &&
558 S_ISDIR(sb.st_mode)))) {
564 printf("calling globextend from glob2\n");
565 #endif /* GLOB_DEBUG */
566 return(globextend(pathbuf, pglob));
569 /* Find end of next segment, copy tentatively to pathend. */
572 while (*p != BG_EOS && *p != BG_SEP) {
578 if (!anymeta) { /* No expansion, do next segment. */
581 while (*pattern == BG_SEP)
582 *pathend++ = *pattern++;
583 } else /* Need expansion, recurse. */
584 return(glob3(pathbuf, pathend, pattern, p, pglob));
590 glob3(Char *pathbuf, Char *pathend, Char *pattern,
591 Char *restpattern, glob_t *pglob)
593 register Direntry_t *dp;
596 char buf[MAXPATHLEN];
599 * The readdirfunc declaration can't be prototyped, because it is
600 * assigned, below, to two functions which are prototyped in glob.h
601 * and dirent.h as taking pointers to differently typed opaque
604 Direntry_t *(*readdirfunc)();
609 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
610 /* TODO: don't call for ENOENT or ENOTDIR? */
611 if (pglob->gl_errfunc) {
612 g_Ctoc(pathbuf, buf);
613 if (pglob->gl_errfunc(buf, errno) ||
614 (pglob->gl_flags & GLOB_ERR))
622 /* Search directory for matching names. */
623 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
624 readdirfunc = pglob->gl_readdir;
626 readdirfunc = my_readdir;
627 while ((dp = (*readdirfunc)(dirp))) {
631 /* Initial BG_DOT must be matched literally. */
632 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
634 for (sc = (U8 *) dp->d_name, dc = pathend;
635 (*dc++ = *sc++) != BG_EOS;)
637 if (!match(pathend, pattern, restpattern)) {
641 err = glob2(pathbuf, --dc, restpattern, pglob);
646 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
647 (*pglob->gl_closedir)(dirp);
655 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
656 * add the new item, and update gl_pathc.
658 * This assumes the BSD realloc, which only copies the block when its size
659 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
662 * Return 0 if new item added, error code if memory couldn't be allocated.
664 * Invariant of the glob_t structure:
665 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
666 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
669 globextend(const Char *path, glob_t *pglob)
671 register char **pathv;
678 for (p = path; *p; p++)
679 (void)printf("%c", CHAR(*p));
681 #endif /* GLOB_DEBUG */
684 pathv = Renew(pglob->gl_pathv,
685 (2 + pglob->gl_pathc + pglob->gl_offs),char*);
687 New(0,pathv,(2 + pglob->gl_pathc + pglob->gl_offs),char*);
689 return(GLOB_NOSPACE);
691 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
692 /* first time around -- clear initial gl_offs items */
693 pathv += pglob->gl_offs;
694 for (i = pglob->gl_offs; --i >= 0; )
697 pglob->gl_pathv = pathv;
699 for (p = path; *p++;)
701 New(0, copy, p-path, char);
704 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
706 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
707 return(copy == NULL ? GLOB_NOSPACE : 0);
712 * pattern matching function for filenames. Each occurrence of the *
713 * pattern causes a recursion level.
716 match(register Char *name, register Char *pat, register Char *patend)
718 int ok, negate_range;
721 while (pat < patend) {
723 switch (c & M_MASK) {
728 if (match(name, pat, patend))
730 while (*name++ != BG_EOS);
733 if (*name++ == BG_EOS)
738 if ((k = *name++) == BG_EOS)
740 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
742 while (((c = *pat++) & M_MASK) != M_END)
743 if ((*pat & M_MASK) == M_RNG) {
744 if (c <= k && k <= pat[1])
749 if (ok == negate_range)
758 return(*name == BG_EOS);
761 /* Free allocated data belonging to a glob_t structure. */
763 bsd_globfree(glob_t *pglob)
768 if (pglob->gl_pathv != NULL) {
769 pp = pglob->gl_pathv + pglob->gl_offs;
770 for (i = pglob->gl_pathc; i--; ++pp)
773 Safefree(pglob->gl_pathv);
778 g_opendir(register Char *str, glob_t *pglob)
780 char buf[MAXPATHLEN];
787 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
788 return((*pglob->gl_opendir)(buf));
790 return(PerlDir_open(buf));
794 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
796 char buf[MAXPATHLEN];
799 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
800 return((*pglob->gl_lstat)(buf, sb));
802 return(PerlLIO_lstat(buf, sb));
804 return(PerlLIO_stat(buf, sb));
805 #endif /* HAS_LSTAT */
809 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
811 char buf[MAXPATHLEN];
814 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
815 return((*pglob->gl_stat)(buf, sb));
816 return(PerlLIO_stat(buf, sb));
820 g_strchr(Char *str, int ch)
831 g_strcat(Char *dst, const Char *src)
838 while((*dst++ = *src++) != BG_EOS)
846 g_Ctoc(register const Char *str, char *buf)
850 for (dc = buf; (*dc++ = *str++) != BG_EOS;)
856 qprintf(const char *str, register Char *s)
860 (void)printf("%s:\n", str);
862 (void)printf("%c", CHAR(*p));
865 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
868 (void)printf("%c", ismeta(*p) ? '_' : ' ');
871 #endif /* GLOB_DEBUG */