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;
550 if (tolower(*pp) != tolower(*qq))
555 ci = tolower(*pp) - tolower(*qq);
557 return compare(p, q);
562 compare(const void *p, const void *q)
564 return(strcmp(*(char **)p, *(char **)q));
568 glob1(Char *pattern, glob_t *pglob)
570 Char pathbuf[MAXPATHLEN+1];
572 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
573 if (*pattern == BG_EOS)
575 return(glob2(pathbuf, pathbuf, pattern, pglob));
579 * The functions glob2 and glob3 are mutually recursive; there is one level
580 * of recursion for each segment in the pattern that contains one or more
584 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
591 * Loop over pattern segments until end of pattern or until
592 * segment with meta character found.
594 for (anymeta = 0;;) {
595 if (*pattern == BG_EOS) { /* End of pattern? */
598 if (g_lstat(pathbuf, &sb, pglob))
601 if (((pglob->gl_flags & GLOB_MARK) &&
602 pathend[-1] != BG_SEP
604 && pathend[-1] != BG_SEP2
606 ) && (S_ISDIR(sb.st_mode)
607 || (S_ISLNK(sb.st_mode) &&
608 (g_stat(pathbuf, &sb, pglob) == 0) &&
609 S_ISDIR(sb.st_mode)))) {
615 printf("calling globextend from glob2\n");
616 #endif /* GLOB_DEBUG */
617 return(globextend(pathbuf, pglob));
620 /* Find end of next segment, copy tentatively to pathend. */
623 while (*p != BG_EOS && *p != BG_SEP
633 if (!anymeta) { /* No expansion, do next segment. */
636 while (*pattern == BG_SEP
638 || *pattern == BG_SEP2
641 *pathend++ = *pattern++;
642 } else /* Need expansion, recurse. */
643 return(glob3(pathbuf, pathend, pattern, p, pglob));
649 glob3(Char *pathbuf, Char *pathend, Char *pattern,
650 Char *restpattern, glob_t *pglob)
652 register Direntry_t *dp;
656 char buf[MAXPATHLEN];
659 * The readdirfunc declaration can't be prototyped, because it is
660 * assigned, below, to two functions which are prototyped in glob.h
661 * and dirent.h as taking pointers to differently typed opaque
664 Direntry_t *(*readdirfunc)();
672 if (q - pathbuf > 5) {
674 if (q[0] == '.' && tolower(q[1]) == 'd' && tolower(q[2]) == 'i'
675 && tolower(q[3]) == 'r' && q[4] == '/')
684 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
685 /* TODO: don't call for ENOENT or ENOTDIR? */
686 if (pglob->gl_errfunc) {
687 g_Ctoc(pathbuf, buf);
688 if (pglob->gl_errfunc(buf, errno) ||
689 (pglob->gl_flags & GLOB_ERR))
696 nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
698 /* Search directory for matching names. */
699 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
700 readdirfunc = pglob->gl_readdir;
702 readdirfunc = my_readdir;
703 while ((dp = (*readdirfunc)(dirp))) {
707 /* Initial BG_DOT must be matched literally. */
708 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
710 for (sc = (U8 *) dp->d_name, dc = pathend;
711 (*dc++ = *sc++) != BG_EOS;)
713 if (!match(pathend, pattern, restpattern, nocase)) {
717 err = glob2(pathbuf, --dc, restpattern, pglob);
722 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
723 (*pglob->gl_closedir)(dirp);
731 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
732 * add the new item, and update gl_pathc.
734 * This assumes the BSD realloc, which only copies the block when its size
735 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
738 * Return 0 if new item added, error code if memory couldn't be allocated.
740 * Invariant of the glob_t structure:
741 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
742 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
745 globextend(const Char *path, glob_t *pglob)
747 register char **pathv;
754 for (p = path; *p; p++)
755 (void)printf("%c", CHAR(*p));
757 #endif /* GLOB_DEBUG */
760 pathv = Renew(pglob->gl_pathv,
761 (2 + pglob->gl_pathc + pglob->gl_offs),char*);
763 New(0,pathv,(2 + pglob->gl_pathc + pglob->gl_offs),char*);
765 return(GLOB_NOSPACE);
767 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
768 /* first time around -- clear initial gl_offs items */
769 pathv += pglob->gl_offs;
770 for (i = pglob->gl_offs; --i >= 0; )
773 pglob->gl_pathv = pathv;
775 for (p = path; *p++;)
777 New(0, copy, p-path, char);
780 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
782 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
783 return(copy == NULL ? GLOB_NOSPACE : 0);
788 * pattern matching function for filenames. Each occurrence of the *
789 * pattern causes a recursion level.
792 match(register Char *name, register Char *pat, register Char *patend, int nocase)
794 int ok, negate_range;
797 while (pat < patend) {
799 switch (c & M_MASK) {
804 if (match(name, pat, patend, nocase))
806 while (*name++ != BG_EOS);
809 if (*name++ == BG_EOS)
814 if ((k = *name++) == BG_EOS)
816 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
818 while (((c = *pat++) & M_MASK) != M_END)
819 if ((*pat & M_MASK) == M_RNG) {
821 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
824 if (c <= k && k <= pat[1])
828 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
830 if (ok == negate_range)
835 if (nocase ? (tolower(k) != tolower(c)) : (k != c))
840 return(*name == BG_EOS);
843 /* Free allocated data belonging to a glob_t structure. */
845 bsd_globfree(glob_t *pglob)
850 if (pglob->gl_pathv != NULL) {
851 pp = pglob->gl_pathv + pglob->gl_offs;
852 for (i = pglob->gl_pathc; i--; ++pp)
855 Safefree(pglob->gl_pathv);
860 g_opendir(register Char *str, glob_t *pglob)
862 char buf[MAXPATHLEN];
869 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
870 return((*pglob->gl_opendir)(buf));
872 return(PerlDir_open(buf));
876 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
878 char buf[MAXPATHLEN];
881 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
882 return((*pglob->gl_lstat)(buf, sb));
884 return(PerlLIO_lstat(buf, sb));
886 return(PerlLIO_stat(buf, sb));
887 #endif /* HAS_LSTAT */
891 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
893 char buf[MAXPATHLEN];
896 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
897 return((*pglob->gl_stat)(buf, sb));
898 return(PerlLIO_stat(buf, sb));
902 g_strchr(Char *str, int ch)
913 g_strcat(Char *dst, const Char *src)
920 while((*dst++ = *src++) != BG_EOS)
928 g_Ctoc(register const Char *str, char *buf)
932 for (dc = buf; (*dc++ = *str++) != BG_EOS;)
938 qprintf(const char *str, register Char *s)
942 (void)printf("%s:\n", str);
944 (void)printf("%c", CHAR(*p));
947 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
950 (void)printf("%c", ismeta(*p) ? '_' : ' ');
953 #endif /* GLOB_DEBUG */