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.
71 struct passwd *getpwnam(char *);
72 struct passwd *getpwuid(Uid_t);
78 # define MAXPATHLEN PATH_MAX
80 # define MAXPATHLEN 1024
87 #define BG_LBRACKET '['
89 #define BG_QUESTION '?'
92 #define BG_RBRACKET ']'
99 #define BG_UNDERSCORE '_'
100 #define BG_LBRACE '{'
101 #define BG_RBRACE '}'
107 #define M_QUOTE 0x8000
108 #define M_PROTECT 0x4000
109 #define M_MASK 0xffff
110 #define M_ASCII 0x00ff
117 #define M_PROTECT 0x40
123 #endif /* !GLOB_DEBUG */
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(const void *, const void *);
138 static int ci_compare(const void *, const void *);
139 static void g_Ctoc(const Char *, char *);
140 static int g_lstat(Char *, Stat_t *, glob_t *);
141 static DIR *g_opendir(Char *, glob_t *);
142 static Char *g_strchr(Char *, int);
144 static Char *g_strcat(Char *, const Char *);
146 static int g_stat(Char *, Stat_t *, glob_t *);
147 static int glob0(const Char *, glob_t *);
148 static int glob1(Char *, glob_t *);
149 static int glob2(Char *, Char *, Char *, glob_t *);
150 static int glob3(Char *, Char *, Char *, Char *, glob_t *);
151 static int globextend(const Char *, glob_t *);
152 static const Char * globtilde(const Char *, Char *, glob_t *);
153 static int globexp1(const Char *, glob_t *);
154 static int globexp2(const Char *, const Char *, glob_t *, int *);
155 static int match(Char *, Char *, Char *, int);
157 static void qprintf(const char *, Char *);
158 #endif /* GLOB_DEBUG */
160 #ifdef PERL_IMPLICIT_CONTEXT
161 static Direntry_t * my_readdir(DIR*);
166 return PerlDir_read(d);
169 #define my_readdir readdir
173 bsd_glob(const char *pattern, int flags,
174 int (*errfunc)(const char *, int), glob_t *pglob)
178 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
180 patnext = (U8 *) pattern;
181 if (!(flags & GLOB_APPEND)) {
183 pglob->gl_pathv = NULL;
184 if (!(flags & GLOB_DOOFFS))
187 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
188 pglob->gl_errfunc = errfunc;
189 pglob->gl_matchc = 0;
192 bufend = bufnext + MAXPATHLEN;
194 /* Nasty hack to treat patterns like "C:*" correctly. In this
195 * case, the * should match any file in the current directory
196 * on the C: drive. However, the glob code does not treat the
197 * colon specially, so it looks for files beginning "C:" in
198 * the current directory. To fix this, change the pattern to
199 * add an explicit "./" at the start (just after the drive
200 * letter and colon - ie change to "C:./*").
202 if (isalpha(pattern[0]) && pattern[1] == ':' &&
203 pattern[2] != BG_SEP && pattern[2] != BG_SEP2 &&
204 bufend - bufnext > 4) {
205 *bufnext++ = pattern[0];
212 if (flags & GLOB_QUOTE) {
213 /* Protect the quoted characters. */
214 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
217 /* To avoid backslashitis on Win32,
218 * we only treat \ as a quoting character
219 * if it precedes one of the
220 * metacharacters []-{}~\
222 if ((c = *patnext++) != '[' && c != ']' &&
223 c != '-' && c != '{' && c != '}' &&
224 c != '~' && c != '\\') {
226 if ((c = *patnext++) == BG_EOS) {
231 *bufnext++ = c | M_PROTECT;
237 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
241 if (flags & GLOB_BRACE)
242 return globexp1(patbuf, pglob);
244 return glob0(patbuf, pglob);
248 * Expand recursively a glob {} pattern. When there is no more expansion
249 * invoke the standard globbing routine to glob the rest of the magic
252 static int globexp1(const Char *pattern, glob_t *pglob)
254 const Char* ptr = pattern;
257 /* Protect a single {}, for find(1), like csh */
258 if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
259 return glob0(pattern, pglob);
261 while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
262 if (!globexp2(ptr, pattern, pglob, &rv))
265 return glob0(pattern, pglob);
270 * Recursive brace globbing helper. Tries to expand a single brace.
271 * If it succeeds then it invokes globexp1 with the new pattern.
272 * If it fails then it tries to glob the rest of the pattern and returns.
274 static int globexp2(const Char *ptr, const Char *pattern,
275 glob_t *pglob, int *rv)
279 const Char *pe, *pm, *pl;
280 Char patbuf[MAXPATHLEN + 1];
282 /* copy part up to the brace */
283 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
287 /* Find the balanced brace */
288 for (i = 0, pe = ++ptr; *pe; pe++)
289 if (*pe == BG_LBRACKET) {
290 /* Ignore everything between [] */
291 for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
295 * We could not find a matching BG_RBRACKET.
296 * Ignore and just look for BG_RBRACE
301 else if (*pe == BG_LBRACE)
303 else if (*pe == BG_RBRACE) {
309 /* Non matching braces; just glob the pattern */
310 if (i != 0 || *pe == BG_EOS) {
311 *rv = glob0(patbuf, pglob);
315 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
318 /* Ignore everything between [] */
319 for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
323 * We could not find a matching BG_RBRACKET.
324 * Ignore and just look for BG_RBRACE
341 if (i && *pm == BG_COMMA)
344 /* Append the current string */
345 for (lm = ls; (pl < pm); *lm++ = *pl++)
348 * Append the rest of the pattern after the
351 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS;)
354 /* Expand the current pattern */
356 qprintf("globexp2:", patbuf);
357 #endif /* GLOB_DEBUG */
358 *rv = globexp1(patbuf, pglob);
360 /* move after the comma, to the next string */
375 * expand tilde from the passwd file.
378 globtilde(const Char *pattern, Char *patbuf, glob_t *pglob)
385 if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
388 /* Copy up to the end of the string or / */
389 for (p = pattern + 1, h = (char *) patbuf; *p && *p != BG_SLASH;
395 if (((char *) patbuf)[0] == BG_EOS) {
397 * handle a plain ~ or ~/ by expanding $HOME
398 * first and then trying the password file
400 if ((h = getenv("HOME")) == NULL) {
402 if ((pwd = getpwuid(getuid())) == NULL)
416 if ((pwd = getpwnam((char*) patbuf)) == NULL)
425 /* Copy the home directory */
426 for (b = patbuf; *h; *b++ = *h++)
429 /* Append the rest of the pattern */
430 while ((*b++ = *p++) != BG_EOS)
438 * The main glob() routine: compiles the pattern (optionally processing
439 * quotes), calls glob1() to do the real pattern matching, and finally
440 * sorts the list (unless unsorted operation is requested). Returns 0
441 * if things went well, nonzero if errors occurred. It is not an error
442 * to find no matches.
445 glob0(const Char *pattern, glob_t *pglob)
447 const Char *qpat, *qpatnext;
448 int c, err, oldflags, oldpathc;
449 Char *bufnext, patbuf[MAXPATHLEN+1];
451 qpat = globtilde(pattern, patbuf, pglob);
453 oldflags = pglob->gl_flags;
454 oldpathc = pglob->gl_pathc;
457 /* We don't need to check for buffer overflow any more. */
458 while ((c = *qpatnext++) != BG_EOS) {
464 if (*qpatnext == BG_EOS ||
465 g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
466 *bufnext++ = BG_LBRACKET;
476 *bufnext++ = CHAR(c);
477 if (*qpatnext == BG_RANGE &&
478 (c = qpatnext[1]) != BG_RBRACKET) {
480 *bufnext++ = CHAR(c);
483 } while ((c = *qpatnext++) != BG_RBRACKET);
484 pglob->gl_flags |= GLOB_MAGCHAR;
488 pglob->gl_flags |= GLOB_MAGCHAR;
492 pglob->gl_flags |= GLOB_MAGCHAR;
493 /* collapse adjacent stars to one,
494 * to avoid exponential behavior
496 if (bufnext == patbuf || bufnext[-1] != M_ALL)
500 *bufnext++ = CHAR(c);
506 qprintf("glob0:", patbuf);
507 #endif /* GLOB_DEBUG */
509 if ((err = glob1(patbuf, pglob)) != 0) {
510 pglob->gl_flags = oldflags;
515 * If there was no match we are going to append the pattern
516 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
517 * and the pattern did not contain any magic characters
518 * GLOB_NOMAGIC is there just for compatibility with csh.
520 if (pglob->gl_pathc == oldpathc &&
521 ((pglob->gl_flags & GLOB_NOCHECK) ||
522 ((pglob->gl_flags & GLOB_NOMAGIC) &&
523 !(pglob->gl_flags & GLOB_MAGCHAR))))
526 printf("calling globextend from glob0\n");
527 #endif /* GLOB_DEBUG */
528 pglob->gl_flags = oldflags;
529 return(globextend(qpat, pglob));
531 else if (!(pglob->gl_flags & GLOB_NOSORT))
532 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
533 pglob->gl_pathc - oldpathc, sizeof(char *),
534 (pglob->gl_flags & GLOB_NOCASE) ? ci_compare : compare);
535 pglob->gl_flags = oldflags;
540 ci_compare(const void *p, const void *q)
542 const char *pp = *(const char **)p;
543 const char *qq = *(const char **)q;
545 if (tolower(*pp) != tolower(*qq))
550 return (tolower(*pp) - tolower(*qq));
554 compare(const void *p, const void *q)
556 return(strcmp(*(char **)p, *(char **)q));
560 glob1(Char *pattern, glob_t *pglob)
562 Char pathbuf[MAXPATHLEN+1];
564 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
565 if (*pattern == BG_EOS)
567 return(glob2(pathbuf, pathbuf, pattern, pglob));
571 * The functions glob2 and glob3 are mutually recursive; there is one level
572 * of recursion for each segment in the pattern that contains one or more
576 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
583 * Loop over pattern segments until end of pattern or until
584 * segment with meta character found.
586 for (anymeta = 0;;) {
587 if (*pattern == BG_EOS) { /* End of pattern? */
590 if (g_lstat(pathbuf, &sb, pglob))
593 if (((pglob->gl_flags & GLOB_MARK) &&
594 pathend[-1] != BG_SEP
596 && pathend[-1] != BG_SEP2
598 ) && (S_ISDIR(sb.st_mode)
599 || (S_ISLNK(sb.st_mode) &&
600 (g_stat(pathbuf, &sb, pglob) == 0) &&
601 S_ISDIR(sb.st_mode)))) {
607 printf("calling globextend from glob2\n");
608 #endif /* GLOB_DEBUG */
609 return(globextend(pathbuf, pglob));
612 /* Find end of next segment, copy tentatively to pathend. */
615 while (*p != BG_EOS && *p != BG_SEP
625 if (!anymeta) { /* No expansion, do next segment. */
628 while (*pattern == BG_SEP
630 || *pattern == BG_SEP2
633 *pathend++ = *pattern++;
634 } else /* Need expansion, recurse. */
635 return(glob3(pathbuf, pathend, pattern, p, pglob));
641 glob3(Char *pathbuf, Char *pathend, Char *pattern,
642 Char *restpattern, glob_t *pglob)
644 register Direntry_t *dp;
648 char buf[MAXPATHLEN];
651 * The readdirfunc declaration can't be prototyped, because it is
652 * assigned, below, to two functions which are prototyped in glob.h
653 * and dirent.h as taking pointers to differently typed opaque
656 Direntry_t *(*readdirfunc)();
664 if (q - pathbuf > 5) {
666 if (q[0] == '.' && tolower(q[1]) == 'd' && tolower(q[2]) == 'i'
667 && tolower(q[3]) == 'r' && q[4] == '/')
676 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
677 /* TODO: don't call for ENOENT or ENOTDIR? */
678 if (pglob->gl_errfunc) {
679 g_Ctoc(pathbuf, buf);
680 if (pglob->gl_errfunc(buf, errno) ||
681 (pglob->gl_flags & GLOB_ERR))
688 nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
690 /* Search directory for matching names. */
691 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
692 readdirfunc = pglob->gl_readdir;
694 readdirfunc = my_readdir;
695 while ((dp = (*readdirfunc)(dirp))) {
699 /* Initial BG_DOT must be matched literally. */
700 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
702 for (sc = (U8 *) dp->d_name, dc = pathend;
703 (*dc++ = *sc++) != BG_EOS;)
705 if (!match(pathend, pattern, restpattern, nocase)) {
709 err = glob2(pathbuf, --dc, restpattern, pglob);
714 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
715 (*pglob->gl_closedir)(dirp);
723 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
724 * add the new item, and update gl_pathc.
726 * This assumes the BSD realloc, which only copies the block when its size
727 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
730 * Return 0 if new item added, error code if memory couldn't be allocated.
732 * Invariant of the glob_t structure:
733 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
734 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
737 globextend(const Char *path, glob_t *pglob)
739 register char **pathv;
746 for (p = path; *p; p++)
747 (void)printf("%c", CHAR(*p));
749 #endif /* GLOB_DEBUG */
752 pathv = Renew(pglob->gl_pathv,
753 (2 + pglob->gl_pathc + pglob->gl_offs),char*);
755 New(0,pathv,(2 + pglob->gl_pathc + pglob->gl_offs),char*);
757 return(GLOB_NOSPACE);
759 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
760 /* first time around -- clear initial gl_offs items */
761 pathv += pglob->gl_offs;
762 for (i = pglob->gl_offs; --i >= 0; )
765 pglob->gl_pathv = pathv;
767 for (p = path; *p++;)
769 New(0, copy, p-path, char);
772 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
774 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
775 return(copy == NULL ? GLOB_NOSPACE : 0);
780 * pattern matching function for filenames. Each occurrence of the *
781 * pattern causes a recursion level.
784 match(register Char *name, register Char *pat, register Char *patend, int nocase)
786 int ok, negate_range;
789 while (pat < patend) {
791 switch (c & M_MASK) {
796 if (match(name, pat, patend, nocase))
798 while (*name++ != BG_EOS);
801 if (*name++ == BG_EOS)
806 if ((k = *name++) == BG_EOS)
808 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
810 while (((c = *pat++) & M_MASK) != M_END)
811 if ((*pat & M_MASK) == M_RNG) {
813 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
816 if (c <= k && k <= pat[1])
820 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
822 if (ok == negate_range)
827 if (nocase ? (tolower(k) != tolower(c)) : (k != c))
832 return(*name == BG_EOS);
835 /* Free allocated data belonging to a glob_t structure. */
837 bsd_globfree(glob_t *pglob)
842 if (pglob->gl_pathv != NULL) {
843 pp = pglob->gl_pathv + pglob->gl_offs;
844 for (i = pglob->gl_pathc; i--; ++pp)
847 Safefree(pglob->gl_pathv);
852 g_opendir(register Char *str, glob_t *pglob)
854 char buf[MAXPATHLEN];
861 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
862 return((*pglob->gl_opendir)(buf));
864 return(PerlDir_open(buf));
868 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
870 char buf[MAXPATHLEN];
873 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
874 return((*pglob->gl_lstat)(buf, sb));
876 return(PerlLIO_lstat(buf, sb));
878 return(PerlLIO_stat(buf, sb));
879 #endif /* HAS_LSTAT */
883 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
885 char buf[MAXPATHLEN];
888 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
889 return((*pglob->gl_stat)(buf, sb));
890 return(PerlLIO_stat(buf, sb));
894 g_strchr(Char *str, int ch)
905 g_strcat(Char *dst, const Char *src)
912 while((*dst++ = *src++) != BG_EOS)
920 g_Ctoc(register const Char *str, char *buf)
924 for (dc = buf; (*dc++ = *str++) != BG_EOS;)
930 qprintf(const char *str, register Char *s)
934 (void)printf("%s:\n", str);
936 (void)printf("%c", CHAR(*p));
939 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
942 (void)printf("%c", ismeta(*p) ? '_' : ' ');
945 #endif /* GLOB_DEBUG */