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. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
35 #endif /* LIBC_SCCS and not lint */
38 * glob(3) -- a superset of the one defined in POSIX 1003.2.
40 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
42 * Optional extra services, controlled by flags not defined by POSIX:
45 * Escaping convention: \ inhibits any special meaning the following
46 * character might have (except \ at end of string is retained).
48 * Set in gl_flags if pattern contained a globbing character.
50 * Same as GLOB_NOCHECK, but it will only append pattern if it did
51 * not contain any magic characters. [Used in csh style globbing]
53 * Use alternately specified directory access functions.
55 * expand ~user/foo to the /home/dir/of/user/foo
57 * expand {1,2}{a,b} to 1a 1b 2a 2b
59 * Number of matches in the current invocation of glob.
61 * sort alphabetically like csh (case doesn't matter) instead of in ASCII
74 struct passwd *getpwnam(char *);
75 struct passwd *getpwuid(Uid_t);
81 # define MAXPATHLEN PATH_MAX
83 # define MAXPATHLEN 1024
90 #define BG_LBRACKET '['
92 #define BG_QUESTION '?'
95 #define BG_RBRACKET ']'
102 #define BG_UNDERSCORE '_'
103 #define BG_LBRACE '{'
104 #define BG_RBRACE '}'
110 #define M_QUOTE 0x8000
111 #define M_PROTECT 0x4000
112 #define M_MASK 0xffff
113 #define M_ASCII 0x00ff
120 #define M_PROTECT 0x40
126 #endif /* !GLOB_DEBUG */
129 #define CHAR(c) ((Char)((c)&M_ASCII))
130 #define META(c) ((Char)((c)|M_QUOTE))
131 #define M_ALL META('*')
132 #define M_END META(']')
133 #define M_NOT META('!')
134 #define M_ONE META('?')
135 #define M_RNG META('-')
136 #define M_SET META('[')
137 #define ismeta(c) (((c)&M_QUOTE) != 0)
140 static int compare(const void *, const void *);
141 static int ci_compare(const void *, const void *);
142 static void g_Ctoc(const Char *, char *);
143 static int g_lstat(Char *, Stat_t *, glob_t *);
144 static DIR *g_opendir(Char *, glob_t *);
145 static Char *g_strchr(Char *, int);
147 static Char *g_strcat(Char *, const Char *);
149 static int g_stat(Char *, Stat_t *, glob_t *);
150 static int glob0(const Char *, glob_t *);
151 static int glob1(Char *, glob_t *);
152 static int glob2(Char *, Char *, Char *, glob_t *);
153 static int glob3(Char *, Char *, Char *, Char *, glob_t *);
154 static int globextend(const Char *, glob_t *);
155 static const Char * globtilde(const Char *, Char *, glob_t *);
156 static int globexp1(const Char *, glob_t *);
157 static int globexp2(const Char *, const Char *, glob_t *, int *);
158 static int match(Char *, Char *, Char *, int);
160 static void qprintf(const char *, Char *);
161 #endif /* GLOB_DEBUG */
163 #ifdef PERL_IMPLICIT_CONTEXT
164 static Direntry_t * my_readdir(DIR*);
169 return PerlDir_read(d);
172 #define my_readdir readdir
176 bsd_glob(const char *pattern, int flags,
177 int (*errfunc)(const char *, int), glob_t *pglob)
181 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
183 patnext = (U8 *) pattern;
184 if (!(flags & GLOB_APPEND)) {
186 pglob->gl_pathv = NULL;
187 if (!(flags & GLOB_DOOFFS))
190 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
191 pglob->gl_errfunc = errfunc;
192 pglob->gl_matchc = 0;
195 bufend = bufnext + MAXPATHLEN;
197 /* Nasty hack to treat patterns like "C:*" correctly. In this
198 * case, the * should match any file in the current directory
199 * on the C: drive. However, the glob code does not treat the
200 * colon specially, so it looks for files beginning "C:" in
201 * the current directory. To fix this, change the pattern to
202 * add an explicit "./" at the start (just after the drive
203 * letter and colon - ie change to "C:./*").
205 if (isalpha(pattern[0]) && pattern[1] == ':' &&
206 pattern[2] != BG_SEP && pattern[2] != BG_SEP2 &&
207 bufend - bufnext > 4) {
208 *bufnext++ = pattern[0];
215 if (flags & GLOB_QUOTE) {
216 /* Protect the quoted characters. */
217 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
220 /* To avoid backslashitis on Win32,
221 * we only treat \ as a quoting character
222 * if it precedes one of the
223 * metacharacters []-{}~\
225 if ((c = *patnext++) != '[' && c != ']' &&
226 c != '-' && c != '{' && c != '}' &&
227 c != '~' && c != '\\') {
229 if ((c = *patnext++) == BG_EOS) {
234 *bufnext++ = c | M_PROTECT;
240 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
244 if (flags & GLOB_BRACE)
245 return globexp1(patbuf, pglob);
247 return glob0(patbuf, pglob);
251 * Expand recursively a glob {} pattern. When there is no more expansion
252 * invoke the standard globbing routine to glob the rest of the magic
255 static int globexp1(const Char *pattern, glob_t *pglob)
257 const Char* ptr = pattern;
260 /* Protect a single {}, for find(1), like csh */
261 if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
262 return glob0(pattern, pglob);
264 while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
265 if (!globexp2(ptr, pattern, pglob, &rv))
268 return glob0(pattern, pglob);
273 * Recursive brace globbing helper. Tries to expand a single brace.
274 * If it succeeds then it invokes globexp1 with the new pattern.
275 * If it fails then it tries to glob the rest of the pattern and returns.
277 static int globexp2(const Char *ptr, const Char *pattern,
278 glob_t *pglob, int *rv)
282 const Char *pe, *pm, *pl;
283 Char patbuf[MAXPATHLEN + 1];
285 /* copy part up to the brace */
286 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
290 /* Find the balanced brace */
291 for (i = 0, pe = ++ptr; *pe; pe++)
292 if (*pe == BG_LBRACKET) {
293 /* Ignore everything between [] */
294 for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
298 * We could not find a matching BG_RBRACKET.
299 * Ignore and just look for BG_RBRACE
304 else if (*pe == BG_LBRACE)
306 else if (*pe == BG_RBRACE) {
312 /* Non matching braces; just glob the pattern */
313 if (i != 0 || *pe == BG_EOS) {
314 *rv = glob0(patbuf, pglob);
318 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
321 /* Ignore everything between [] */
322 for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
326 * We could not find a matching BG_RBRACKET.
327 * Ignore and just look for BG_RBRACE
344 if (i && *pm == BG_COMMA)
347 /* Append the current string */
348 for (lm = ls; (pl < pm); *lm++ = *pl++)
351 * Append the rest of the pattern after the
354 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS;)
357 /* Expand the current pattern */
359 qprintf("globexp2:", patbuf);
360 #endif /* GLOB_DEBUG */
361 *rv = globexp1(patbuf, pglob);
363 /* move after the comma, to the next string */
378 * expand tilde from the passwd file.
381 globtilde(const Char *pattern, Char *patbuf, glob_t *pglob)
388 if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
391 /* Copy up to the end of the string or / */
392 for (p = pattern + 1, h = (char *) patbuf; *p && *p != BG_SLASH;
398 if (((char *) patbuf)[0] == BG_EOS) {
400 * handle a plain ~ or ~/ by expanding $HOME
401 * first and then trying the password file
403 if ((h = getenv("HOME")) == NULL) {
405 if ((pwd = getpwuid(getuid())) == NULL)
419 if ((pwd = getpwnam((char*) patbuf)) == NULL)
428 /* Copy the home directory */
429 for (b = patbuf; *h; *b++ = *h++)
432 /* Append the rest of the pattern */
433 while ((*b++ = *p++) != BG_EOS)
441 * The main glob() routine: compiles the pattern (optionally processing
442 * quotes), calls glob1() to do the real pattern matching, and finally
443 * sorts the list (unless unsorted operation is requested). Returns 0
444 * if things went well, nonzero if errors occurred. It is not an error
445 * to find no matches.
448 glob0(const Char *pattern, glob_t *pglob)
450 const Char *qpat, *qpatnext;
451 int c, err, oldflags, oldpathc;
452 Char *bufnext, patbuf[MAXPATHLEN+1];
454 qpat = globtilde(pattern, patbuf, pglob);
456 oldflags = pglob->gl_flags;
457 oldpathc = pglob->gl_pathc;
460 /* We don't need to check for buffer overflow any more. */
461 while ((c = *qpatnext++) != BG_EOS) {
467 if (*qpatnext == BG_EOS ||
468 g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
469 *bufnext++ = BG_LBRACKET;
479 *bufnext++ = CHAR(c);
480 if (*qpatnext == BG_RANGE &&
481 (c = qpatnext[1]) != BG_RBRACKET) {
483 *bufnext++ = CHAR(c);
486 } while ((c = *qpatnext++) != BG_RBRACKET);
487 pglob->gl_flags |= GLOB_MAGCHAR;
491 pglob->gl_flags |= GLOB_MAGCHAR;
495 pglob->gl_flags |= GLOB_MAGCHAR;
496 /* collapse adjacent stars to one,
497 * to avoid exponential behavior
499 if (bufnext == patbuf || bufnext[-1] != M_ALL)
503 *bufnext++ = CHAR(c);
509 qprintf("glob0:", patbuf);
510 #endif /* GLOB_DEBUG */
512 if ((err = glob1(patbuf, pglob)) != 0) {
513 pglob->gl_flags = oldflags;
518 * If there was no match we are going to append the pattern
519 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
520 * and the pattern did not contain any magic characters
521 * GLOB_NOMAGIC is there just for compatibility with csh.
523 if (pglob->gl_pathc == oldpathc &&
524 ((pglob->gl_flags & GLOB_NOCHECK) ||
525 ((pglob->gl_flags & GLOB_NOMAGIC) &&
526 !(pglob->gl_flags & GLOB_MAGCHAR))))
529 printf("calling globextend from glob0\n");
530 #endif /* GLOB_DEBUG */
531 pglob->gl_flags = oldflags;
532 return(globextend(qpat, pglob));
534 else if (!(pglob->gl_flags & GLOB_NOSORT))
535 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
536 pglob->gl_pathc - oldpathc, sizeof(char *),
537 (pglob->gl_flags & (GLOB_ALPHASORT|GLOB_NOCASE))
538 ? ci_compare : compare);
539 pglob->gl_flags = oldflags;
544 ci_compare(const void *p, const void *q)
546 const char *pp = *(const char **)p;
547 const char *qq = *(const char **)q;
549 if (tolower(*pp) != tolower(*qq))
554 return (tolower(*pp) - tolower(*qq));
558 compare(const void *p, const void *q)
560 return(strcmp(*(char **)p, *(char **)q));
564 glob1(Char *pattern, glob_t *pglob)
566 Char pathbuf[MAXPATHLEN+1];
568 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
569 if (*pattern == BG_EOS)
571 return(glob2(pathbuf, pathbuf, pattern, pglob));
575 * The functions glob2 and glob3 are mutually recursive; there is one level
576 * of recursion for each segment in the pattern that contains one or more
580 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
587 * Loop over pattern segments until end of pattern or until
588 * segment with meta character found.
590 for (anymeta = 0;;) {
591 if (*pattern == BG_EOS) { /* End of pattern? */
594 if (g_lstat(pathbuf, &sb, pglob))
597 if (((pglob->gl_flags & GLOB_MARK) &&
598 pathend[-1] != BG_SEP
600 && pathend[-1] != BG_SEP2
602 ) && (S_ISDIR(sb.st_mode)
603 || (S_ISLNK(sb.st_mode) &&
604 (g_stat(pathbuf, &sb, pglob) == 0) &&
605 S_ISDIR(sb.st_mode)))) {
611 printf("calling globextend from glob2\n");
612 #endif /* GLOB_DEBUG */
613 return(globextend(pathbuf, pglob));
616 /* Find end of next segment, copy tentatively to pathend. */
619 while (*p != BG_EOS && *p != BG_SEP
629 if (!anymeta) { /* No expansion, do next segment. */
632 while (*pattern == BG_SEP
634 || *pattern == BG_SEP2
637 *pathend++ = *pattern++;
638 } else /* Need expansion, recurse. */
639 return(glob3(pathbuf, pathend, pattern, p, pglob));
645 glob3(Char *pathbuf, Char *pathend, Char *pattern,
646 Char *restpattern, glob_t *pglob)
648 register Direntry_t *dp;
652 char buf[MAXPATHLEN];
655 * The readdirfunc declaration can't be prototyped, because it is
656 * assigned, below, to two functions which are prototyped in glob.h
657 * and dirent.h as taking pointers to differently typed opaque
660 Direntry_t *(*readdirfunc)();
668 if (q - pathbuf > 5) {
670 if (q[0] == '.' && tolower(q[1]) == 'd' && tolower(q[2]) == 'i'
671 && tolower(q[3]) == 'r' && q[4] == '/')
680 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
681 /* TODO: don't call for ENOENT or ENOTDIR? */
682 if (pglob->gl_errfunc) {
683 g_Ctoc(pathbuf, buf);
684 if (pglob->gl_errfunc(buf, errno) ||
685 (pglob->gl_flags & GLOB_ERR))
692 nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
694 /* Search directory for matching names. */
695 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
696 readdirfunc = pglob->gl_readdir;
698 readdirfunc = my_readdir;
699 while ((dp = (*readdirfunc)(dirp))) {
703 /* Initial BG_DOT must be matched literally. */
704 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
706 for (sc = (U8 *) dp->d_name, dc = pathend;
707 (*dc++ = *sc++) != BG_EOS;)
709 if (!match(pathend, pattern, restpattern, nocase)) {
713 err = glob2(pathbuf, --dc, restpattern, pglob);
718 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
719 (*pglob->gl_closedir)(dirp);
727 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
728 * add the new item, and update gl_pathc.
730 * This assumes the BSD realloc, which only copies the block when its size
731 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
734 * Return 0 if new item added, error code if memory couldn't be allocated.
736 * Invariant of the glob_t structure:
737 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
738 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
741 globextend(const Char *path, glob_t *pglob)
743 register char **pathv;
750 for (p = path; *p; p++)
751 (void)printf("%c", CHAR(*p));
753 #endif /* GLOB_DEBUG */
756 pathv = Renew(pglob->gl_pathv,
757 (2 + pglob->gl_pathc + pglob->gl_offs),char*);
759 New(0,pathv,(2 + pglob->gl_pathc + pglob->gl_offs),char*);
761 return(GLOB_NOSPACE);
763 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
764 /* first time around -- clear initial gl_offs items */
765 pathv += pglob->gl_offs;
766 for (i = pglob->gl_offs; --i >= 0; )
769 pglob->gl_pathv = pathv;
771 for (p = path; *p++;)
773 New(0, copy, p-path, char);
776 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
778 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
779 return(copy == NULL ? GLOB_NOSPACE : 0);
784 * pattern matching function for filenames. Each occurrence of the *
785 * pattern causes a recursion level.
788 match(register Char *name, register Char *pat, register Char *patend, int nocase)
790 int ok, negate_range;
793 while (pat < patend) {
795 switch (c & M_MASK) {
800 if (match(name, pat, patend, nocase))
802 while (*name++ != BG_EOS);
805 if (*name++ == BG_EOS)
810 if ((k = *name++) == BG_EOS)
812 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
814 while (((c = *pat++) & M_MASK) != M_END)
815 if ((*pat & M_MASK) == M_RNG) {
817 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
820 if (c <= k && k <= pat[1])
824 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
826 if (ok == negate_range)
831 if (nocase ? (tolower(k) != tolower(c)) : (k != c))
836 return(*name == BG_EOS);
839 /* Free allocated data belonging to a glob_t structure. */
841 bsd_globfree(glob_t *pglob)
846 if (pglob->gl_pathv != NULL) {
847 pp = pglob->gl_pathv + pglob->gl_offs;
848 for (i = pglob->gl_pathc; i--; ++pp)
851 Safefree(pglob->gl_pathv);
856 g_opendir(register Char *str, glob_t *pglob)
858 char buf[MAXPATHLEN];
865 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
866 return((*pglob->gl_opendir)(buf));
868 return(PerlDir_open(buf));
872 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
874 char buf[MAXPATHLEN];
877 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
878 return((*pglob->gl_lstat)(buf, sb));
880 return(PerlLIO_lstat(buf, sb));
882 return(PerlLIO_stat(buf, sb));
883 #endif /* HAS_LSTAT */
887 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
889 char buf[MAXPATHLEN];
892 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
893 return((*pglob->gl_stat)(buf, sb));
894 return(PerlLIO_stat(buf, sb));
898 g_strchr(Char *str, int ch)
909 g_strcat(Char *dst, const Char *src)
916 while((*dst++ = *src++) != BG_EOS)
924 g_Ctoc(register const Char *str, char *buf)
928 for (dc = buf; (*dc++ = *str++) != BG_EOS;)
934 qprintf(const char *str, register Char *s)
938 (void)printf("%s:\n", str);
940 (void)printf("%c", CHAR(*p));
943 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
946 (void)printf("%c", ismeta(*p) ? '_' : ' ');
949 #endif /* GLOB_DEBUG */