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
82 # ifdef MACOS_TRADITIONAL
83 # define MAXPATHLEN 255
85 # define MAXPATHLEN 1024
93 #define BG_LBRACKET '['
95 #define BG_QUESTION '?'
98 #define BG_RBRACKET ']'
99 #ifdef MACOS_TRADITIONAL
109 #define BG_UNDERSCORE '_'
110 #define BG_LBRACE '{'
111 #define BG_RBRACE '}'
117 #define M_QUOTE 0x8000
118 #define M_PROTECT 0x4000
119 #define M_MASK 0xffff
120 #define M_ASCII 0x00ff
127 #define M_PROTECT 0x40
133 #endif /* !GLOB_DEBUG */
136 #define CHAR(c) ((Char)((c)&M_ASCII))
137 #define META(c) ((Char)((c)|M_QUOTE))
138 #define M_ALL META('*')
139 #define M_END META(']')
140 #define M_NOT META('!')
141 #define M_ONE META('?')
142 #define M_RNG META('-')
143 #define M_SET META('[')
144 #define ismeta(c) (((c)&M_QUOTE) != 0)
147 static int compare(const void *, const void *);
148 static int ci_compare(const void *, const void *);
149 static void g_Ctoc(const Char *, char *);
150 static int g_lstat(Char *, Stat_t *, glob_t *);
151 static DIR *g_opendir(Char *, glob_t *);
152 static Char *g_strchr(Char *, int);
154 static Char *g_strcat(Char *, const Char *);
156 static int g_stat(Char *, Stat_t *, glob_t *);
157 static int glob0(const Char *, glob_t *);
158 static int glob1(Char *, glob_t *);
159 static int glob2(Char *, Char *, Char *, glob_t *);
160 static int glob3(Char *, Char *, Char *, Char *, glob_t *);
161 static int globextend(const Char *, glob_t *);
162 static const Char * globtilde(const Char *, Char *, glob_t *);
163 static int globexp1(const Char *, glob_t *);
164 static int globexp2(const Char *, const Char *, glob_t *, int *);
165 static int match(Char *, Char *, Char *, int);
167 static void qprintf(const char *, Char *);
168 #endif /* GLOB_DEBUG */
170 #ifdef PERL_IMPLICIT_CONTEXT
171 static Direntry_t * my_readdir(DIR*);
176 return PerlDir_read(d);
179 #define my_readdir readdir
183 bsd_glob(const char *pattern, int flags,
184 int (*errfunc)(const char *, int), glob_t *pglob)
188 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
190 patnext = (U8 *) pattern;
191 if (!(flags & GLOB_APPEND)) {
193 pglob->gl_pathv = NULL;
194 if (!(flags & GLOB_DOOFFS))
197 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
198 pglob->gl_errfunc = errfunc;
199 pglob->gl_matchc = 0;
202 bufend = bufnext + MAXPATHLEN;
204 /* Nasty hack to treat patterns like "C:*" correctly. In this
205 * case, the * should match any file in the current directory
206 * on the C: drive. However, the glob code does not treat the
207 * colon specially, so it looks for files beginning "C:" in
208 * the current directory. To fix this, change the pattern to
209 * add an explicit "./" at the start (just after the drive
210 * letter and colon - ie change to "C:./*").
212 if (isalpha(pattern[0]) && pattern[1] == ':' &&
213 pattern[2] != BG_SEP && pattern[2] != BG_SEP2 &&
214 bufend - bufnext > 4) {
215 *bufnext++ = pattern[0];
222 if (flags & GLOB_QUOTE) {
223 /* Protect the quoted characters. */
224 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
227 /* To avoid backslashitis on Win32,
228 * we only treat \ as a quoting character
229 * if it precedes one of the
230 * metacharacters []-{}~\
232 if ((c = *patnext++) != '[' && c != ']' &&
233 c != '-' && c != '{' && c != '}' &&
234 c != '~' && c != '\\') {
236 if ((c = *patnext++) == BG_EOS) {
241 *bufnext++ = c | M_PROTECT;
247 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
251 if (flags & GLOB_BRACE)
252 return globexp1(patbuf, pglob);
254 return glob0(patbuf, pglob);
258 * Expand recursively a glob {} pattern. When there is no more expansion
259 * invoke the standard globbing routine to glob the rest of the magic
262 static int globexp1(const Char *pattern, glob_t *pglob)
264 const Char* ptr = pattern;
267 /* Protect a single {}, for find(1), like csh */
268 if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
269 return glob0(pattern, pglob);
271 while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
272 if (!globexp2(ptr, pattern, pglob, &rv))
275 return glob0(pattern, pglob);
280 * Recursive brace globbing helper. Tries to expand a single brace.
281 * If it succeeds then it invokes globexp1 with the new pattern.
282 * If it fails then it tries to glob the rest of the pattern and returns.
284 static int globexp2(const Char *ptr, const Char *pattern,
285 glob_t *pglob, int *rv)
289 const Char *pe, *pm, *pl;
290 Char patbuf[MAXPATHLEN + 1];
292 /* copy part up to the brace */
293 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
297 /* Find the balanced brace */
298 for (i = 0, pe = ++ptr; *pe; pe++)
299 if (*pe == BG_LBRACKET) {
300 /* Ignore everything between [] */
301 for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
305 * We could not find a matching BG_RBRACKET.
306 * Ignore and just look for BG_RBRACE
311 else if (*pe == BG_LBRACE)
313 else if (*pe == BG_RBRACE) {
319 /* Non matching braces; just glob the pattern */
320 if (i != 0 || *pe == BG_EOS) {
321 *rv = glob0(patbuf, pglob);
325 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
328 /* Ignore everything between [] */
329 for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
333 * We could not find a matching BG_RBRACKET.
334 * Ignore and just look for BG_RBRACE
351 if (i && *pm == BG_COMMA)
354 /* Append the current string */
355 for (lm = ls; (pl < pm); *lm++ = *pl++)
358 * Append the rest of the pattern after the
361 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS;)
364 /* Expand the current pattern */
366 qprintf("globexp2:", patbuf);
367 #endif /* GLOB_DEBUG */
368 *rv = globexp1(patbuf, pglob);
370 /* move after the comma, to the next string */
385 * expand tilde from the passwd file.
388 globtilde(const Char *pattern, Char *patbuf, glob_t *pglob)
395 if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
398 /* Copy up to the end of the string or / */
399 for (p = pattern + 1, h = (char *) patbuf; *p && *p != BG_SLASH;
405 if (((char *) patbuf)[0] == BG_EOS) {
407 * handle a plain ~ or ~/ by expanding $HOME
408 * first and then trying the password file
410 if ((h = getenv("HOME")) == NULL) {
412 if ((pwd = getpwuid(getuid())) == NULL)
426 if ((pwd = getpwnam((char*) patbuf)) == NULL)
435 /* Copy the home directory */
436 for (b = patbuf; *h; *b++ = *h++)
439 /* Append the rest of the pattern */
440 while ((*b++ = *p++) != BG_EOS)
448 * The main glob() routine: compiles the pattern (optionally processing
449 * quotes), calls glob1() to do the real pattern matching, and finally
450 * sorts the list (unless unsorted operation is requested). Returns 0
451 * if things went well, nonzero if errors occurred. It is not an error
452 * to find no matches.
455 glob0(const Char *pattern, glob_t *pglob)
457 const Char *qpat, *qpatnext;
458 int c, err, oldflags, oldpathc;
459 Char *bufnext, patbuf[MAXPATHLEN+1];
461 #ifdef MACOS_TRADITIONAL
462 if ( (*pattern == BG_TILDE) && (pglob->gl_flags & GLOB_TILDE) ) {
463 return(globextend(pattern, pglob));
467 qpat = globtilde(pattern, patbuf, pglob);
469 oldflags = pglob->gl_flags;
470 oldpathc = pglob->gl_pathc;
473 /* We don't need to check for buffer overflow any more. */
474 while ((c = *qpatnext++) != BG_EOS) {
480 if (*qpatnext == BG_EOS ||
481 g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
482 *bufnext++ = BG_LBRACKET;
492 *bufnext++ = CHAR(c);
493 if (*qpatnext == BG_RANGE &&
494 (c = qpatnext[1]) != BG_RBRACKET) {
496 *bufnext++ = CHAR(c);
499 } while ((c = *qpatnext++) != BG_RBRACKET);
500 pglob->gl_flags |= GLOB_MAGCHAR;
504 pglob->gl_flags |= GLOB_MAGCHAR;
508 pglob->gl_flags |= GLOB_MAGCHAR;
509 /* collapse adjacent stars to one,
510 * to avoid exponential behavior
512 if (bufnext == patbuf || bufnext[-1] != M_ALL)
516 *bufnext++ = CHAR(c);
522 qprintf("glob0:", patbuf);
523 #endif /* GLOB_DEBUG */
525 if ((err = glob1(patbuf, pglob)) != 0) {
526 pglob->gl_flags = oldflags;
531 * If there was no match we are going to append the pattern
532 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
533 * and the pattern did not contain any magic characters
534 * GLOB_NOMAGIC is there just for compatibility with csh.
536 if (pglob->gl_pathc == oldpathc &&
537 ((pglob->gl_flags & GLOB_NOCHECK) ||
538 ((pglob->gl_flags & GLOB_NOMAGIC) &&
539 !(pglob->gl_flags & GLOB_MAGCHAR))))
542 printf("calling globextend from glob0\n");
543 #endif /* GLOB_DEBUG */
544 pglob->gl_flags = oldflags;
545 return(globextend(qpat, pglob));
547 else if (!(pglob->gl_flags & GLOB_NOSORT))
548 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
549 pglob->gl_pathc - oldpathc, sizeof(char *),
550 (pglob->gl_flags & (GLOB_ALPHASORT|GLOB_NOCASE))
551 ? ci_compare : compare);
552 pglob->gl_flags = oldflags;
557 ci_compare(const void *p, const void *q)
559 const char *pp = *(const char **)p;
560 const char *qq = *(const char **)q;
563 if (tolower(*pp) != tolower(*qq))
568 ci = tolower(*pp) - tolower(*qq);
570 return compare(p, q);
575 compare(const void *p, const void *q)
577 return(strcmp(*(char **)p, *(char **)q));
581 glob1(Char *pattern, glob_t *pglob)
583 Char pathbuf[MAXPATHLEN+1];
585 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
586 if (*pattern == BG_EOS)
588 return(glob2(pathbuf, pathbuf, pattern, pglob));
592 * The functions glob2 and glob3 are mutually recursive; there is one level
593 * of recursion for each segment in the pattern that contains one or more
597 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
604 * Loop over pattern segments until end of pattern or until
605 * segment with meta character found.
607 for (anymeta = 0;;) {
608 if (*pattern == BG_EOS) { /* End of pattern? */
611 if (g_lstat(pathbuf, &sb, pglob))
614 if (((pglob->gl_flags & GLOB_MARK) &&
615 pathend[-1] != BG_SEP
617 && pathend[-1] != BG_SEP2
619 ) && (S_ISDIR(sb.st_mode)
620 || (S_ISLNK(sb.st_mode) &&
621 (g_stat(pathbuf, &sb, pglob) == 0) &&
622 S_ISDIR(sb.st_mode)))) {
628 printf("calling globextend from glob2\n");
629 #endif /* GLOB_DEBUG */
630 return(globextend(pathbuf, pglob));
633 /* Find end of next segment, copy tentatively to pathend. */
636 while (*p != BG_EOS && *p != BG_SEP
646 if (!anymeta) { /* No expansion, do next segment. */
649 while (*pattern == BG_SEP
651 || *pattern == BG_SEP2
654 *pathend++ = *pattern++;
655 } else /* Need expansion, recurse. */
656 return(glob3(pathbuf, pathend, pattern, p, pglob));
662 glob3(Char *pathbuf, Char *pathend, Char *pattern,
663 Char *restpattern, glob_t *pglob)
665 register Direntry_t *dp;
669 char buf[MAXPATHLEN];
672 * The readdirfunc declaration can't be prototyped, because it is
673 * assigned, below, to two functions which are prototyped in glob.h
674 * and dirent.h as taking pointers to differently typed opaque
677 Direntry_t *(*readdirfunc)(DIR*);
685 if (q - pathbuf > 5) {
687 if (q[0] == '.' && tolower(q[1]) == 'd' && tolower(q[2]) == 'i'
688 && tolower(q[3]) == 'r' && q[4] == '/')
697 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
698 /* TODO: don't call for ENOENT or ENOTDIR? */
699 if (pglob->gl_errfunc) {
700 g_Ctoc(pathbuf, buf);
701 if (pglob->gl_errfunc(buf, errno) ||
702 (pglob->gl_flags & GLOB_ERR))
709 nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
711 /* Search directory for matching names. */
712 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
713 readdirfunc = (Direntry_t *(*)(DIR *))pglob->gl_readdir;
715 readdirfunc = my_readdir;
716 while ((dp = (*readdirfunc)(dirp))) {
720 /* Initial BG_DOT must be matched literally. */
721 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
723 for (sc = (U8 *) dp->d_name, dc = pathend;
724 (*dc++ = *sc++) != BG_EOS;)
726 if (!match(pathend, pattern, restpattern, nocase)) {
730 err = glob2(pathbuf, --dc, restpattern, pglob);
735 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
736 (*pglob->gl_closedir)(dirp);
744 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
745 * add the new item, and update gl_pathc.
747 * This assumes the BSD realloc, which only copies the block when its size
748 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
751 * Return 0 if new item added, error code if memory couldn't be allocated.
753 * Invariant of the glob_t structure:
754 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
755 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
758 globextend(const Char *path, glob_t *pglob)
760 register char **pathv;
767 for (p = path; *p; p++)
768 (void)printf("%c", CHAR(*p));
770 #endif /* GLOB_DEBUG */
773 pathv = Renew(pglob->gl_pathv,
774 (2 + pglob->gl_pathc + pglob->gl_offs),char*);
776 New(0,pathv,(2 + pglob->gl_pathc + pglob->gl_offs),char*);
778 return(GLOB_NOSPACE);
780 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
781 /* first time around -- clear initial gl_offs items */
782 pathv += pglob->gl_offs;
783 for (i = pglob->gl_offs; --i >= 0; )
786 pglob->gl_pathv = pathv;
788 for (p = path; *p++;)
790 New(0, copy, p-path, char);
793 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
795 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
796 return(copy == NULL ? GLOB_NOSPACE : 0);
801 * pattern matching function for filenames. Each occurrence of the *
802 * pattern causes a recursion level.
805 match(register Char *name, register Char *pat, register Char *patend, int nocase)
807 int ok, negate_range;
810 while (pat < patend) {
812 switch (c & M_MASK) {
817 if (match(name, pat, patend, nocase))
819 while (*name++ != BG_EOS);
822 if (*name++ == BG_EOS)
827 if ((k = *name++) == BG_EOS)
829 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
831 while (((c = *pat++) & M_MASK) != M_END)
832 if ((*pat & M_MASK) == M_RNG) {
834 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
837 if (c <= k && k <= pat[1])
841 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
843 if (ok == negate_range)
848 if (nocase ? (tolower(k) != tolower(c)) : (k != c))
853 return(*name == BG_EOS);
856 /* Free allocated data belonging to a glob_t structure. */
858 bsd_globfree(glob_t *pglob)
863 if (pglob->gl_pathv != NULL) {
864 pp = pglob->gl_pathv + pglob->gl_offs;
865 for (i = pglob->gl_pathc; i--; ++pp)
868 Safefree(pglob->gl_pathv);
873 g_opendir(register Char *str, glob_t *pglob)
875 char buf[MAXPATHLEN];
878 #ifdef MACOS_TRADITIONAL
887 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
888 return((*pglob->gl_opendir)(buf));
890 return(PerlDir_open(buf));
894 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
896 char buf[MAXPATHLEN];
899 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
900 return((*pglob->gl_lstat)(buf, sb));
902 return(PerlLIO_lstat(buf, sb));
904 return(PerlLIO_stat(buf, sb));
905 #endif /* HAS_LSTAT */
909 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
911 char buf[MAXPATHLEN];
914 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
915 return((*pglob->gl_stat)(buf, sb));
916 return(PerlLIO_stat(buf, sb));
920 g_strchr(Char *str, int ch)
931 g_strcat(Char *dst, const Char *src)
938 while((*dst++ = *src++) != BG_EOS)
946 g_Ctoc(register const Char *str, char *buf)
950 for (dc = buf; (*dc++ = *str++) != BG_EOS;)
956 qprintf(const char *str, register Char *s)
960 (void)printf("%s:\n", str);
962 (void)printf("%c", CHAR(*p));
965 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
968 (void)printf("%c", ismeta(*p) ? '_' : ' ');
971 #endif /* GLOB_DEBUG */