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 ']'
96 #define BG_UNDERSCORE '_'
104 #define M_QUOTE 0x8000
105 #define M_PROTECT 0x4000
106 #define M_MASK 0xffff
107 #define M_ASCII 0x00ff
114 #define M_PROTECT 0x40
120 #endif /* !GLOB_DEBUG */
123 #define CHAR(c) ((Char)((c)&M_ASCII))
124 #define META(c) ((Char)((c)|M_QUOTE))
125 #define M_ALL META('*')
126 #define M_END META(']')
127 #define M_NOT META('!')
128 #define M_ONE META('?')
129 #define M_RNG META('-')
130 #define M_SET META('[')
131 #define ismeta(c) (((c)&M_QUOTE) != 0)
134 static int compare(const void *, const void *);
135 static void g_Ctoc(const Char *, char *);
136 static int g_lstat(Char *, Stat_t *, glob_t *);
137 static DIR *g_opendir(Char *, glob_t *);
138 static Char *g_strchr(Char *, int);
140 static Char *g_strcat(Char *, const Char *);
142 static int g_stat(Char *, Stat_t *, glob_t *);
143 static int glob0(const Char *, glob_t *);
144 static int glob1(Char *, glob_t *);
145 static int glob2(Char *, Char *, Char *, glob_t *);
146 static int glob3(Char *, Char *, Char *, Char *, glob_t *);
147 static int globextend(const Char *, glob_t *);
148 static const Char * globtilde(const Char *, Char *, glob_t *);
149 static int globexp1(const Char *, glob_t *);
150 static int globexp2(const Char *, const Char *, glob_t *, int *);
151 static int match(Char *, Char *, Char *);
153 static void qprintf(const char *, Char *);
154 #endif /* GLOB_DEBUG */
156 #ifdef PERL_IMPLICIT_CONTEXT
157 static Direntry_t * my_readdir(DIR*);
162 return PerlDir_read(d);
165 #define my_readdir readdir
169 bsd_glob(const char *pattern, int flags,
170 int (*errfunc)(const char *, int), glob_t *pglob)
174 Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
176 patnext = (U8 *) pattern;
177 if (!(flags & GLOB_APPEND)) {
179 pglob->gl_pathv = NULL;
180 if (!(flags & GLOB_DOOFFS))
183 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
184 pglob->gl_errfunc = errfunc;
185 pglob->gl_matchc = 0;
188 bufend = bufnext + MAXPATHLEN;
189 if (flags & GLOB_QUOTE) {
190 /* Protect the quoted characters. */
191 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
193 if ((c = *patnext++) == BG_EOS) {
197 *bufnext++ = c | M_PROTECT;
203 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
207 if (flags & GLOB_BRACE)
208 return globexp1(patbuf, pglob);
210 return glob0(patbuf, pglob);
214 * Expand recursively a glob {} pattern. When there is no more expansion
215 * invoke the standard globbing routine to glob the rest of the magic
218 static int globexp1(const Char *pattern, glob_t *pglob)
220 const Char* ptr = pattern;
223 /* Protect a single {}, for find(1), like csh */
224 if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
225 return glob0(pattern, pglob);
227 while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
228 if (!globexp2(ptr, pattern, pglob, &rv))
231 return glob0(pattern, pglob);
236 * Recursive brace globbing helper. Tries to expand a single brace.
237 * If it succeeds then it invokes globexp1 with the new pattern.
238 * If it fails then it tries to glob the rest of the pattern and returns.
240 static int globexp2(const Char *ptr, const Char *pattern,
241 glob_t *pglob, int *rv)
245 const Char *pe, *pm, *pl;
246 Char patbuf[MAXPATHLEN + 1];
248 /* copy part up to the brace */
249 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
253 /* Find the balanced brace */
254 for (i = 0, pe = ++ptr; *pe; pe++)
255 if (*pe == BG_LBRACKET) {
256 /* Ignore everything between [] */
257 for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
261 * We could not find a matching BG_RBRACKET.
262 * Ignore and just look for BG_RBRACE
267 else if (*pe == BG_LBRACE)
269 else if (*pe == BG_RBRACE) {
275 /* Non matching braces; just glob the pattern */
276 if (i != 0 || *pe == BG_EOS) {
277 *rv = glob0(patbuf, pglob);
281 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
284 /* Ignore everything between [] */
285 for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
289 * We could not find a matching BG_RBRACKET.
290 * Ignore and just look for BG_RBRACE
307 if (i && *pm == BG_COMMA)
310 /* Append the current string */
311 for (lm = ls; (pl < pm); *lm++ = *pl++)
314 * Append the rest of the pattern after the
317 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS;)
320 /* Expand the current pattern */
322 qprintf("globexp2:", patbuf);
323 #endif /* GLOB_DEBUG */
324 *rv = globexp1(patbuf, pglob);
326 /* move after the comma, to the next string */
341 * expand tilde from the passwd file.
344 globtilde(const Char *pattern, Char *patbuf, glob_t *pglob)
351 if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
354 /* Copy up to the end of the string or / */
355 for (p = pattern + 1, h = (char *) patbuf; *p && *p != BG_SLASH;
361 if (((char *) patbuf)[0] == BG_EOS) {
363 * handle a plain ~ or ~/ by expanding $HOME
364 * first and then trying the password file
366 if ((h = getenv("HOME")) == NULL) {
368 if ((pwd = getpwuid(getuid())) == NULL)
382 if ((pwd = getpwnam((char*) patbuf)) == NULL)
391 /* Copy the home directory */
392 for (b = patbuf; *h; *b++ = *h++)
395 /* Append the rest of the pattern */
396 while ((*b++ = *p++) != BG_EOS)
404 * The main glob() routine: compiles the pattern (optionally processing
405 * quotes), calls glob1() to do the real pattern matching, and finally
406 * sorts the list (unless unsorted operation is requested). Returns 0
407 * if things went well, nonzero if errors occurred. It is not an error
408 * to find no matches.
411 glob0(const Char *pattern, glob_t *pglob)
413 const Char *qpat, *qpatnext;
414 int c, err, oldflags, oldpathc;
415 Char *bufnext, patbuf[MAXPATHLEN+1];
417 qpat = globtilde(pattern, patbuf, pglob);
419 oldflags = pglob->gl_flags;
420 oldpathc = pglob->gl_pathc;
423 /* We don't need to check for buffer overflow any more. */
424 while ((c = *qpatnext++) != BG_EOS) {
430 if (*qpatnext == BG_EOS ||
431 g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
432 *bufnext++ = BG_LBRACKET;
442 *bufnext++ = CHAR(c);
443 if (*qpatnext == BG_RANGE &&
444 (c = qpatnext[1]) != BG_RBRACKET) {
446 *bufnext++ = CHAR(c);
449 } while ((c = *qpatnext++) != BG_RBRACKET);
450 pglob->gl_flags |= GLOB_MAGCHAR;
454 pglob->gl_flags |= GLOB_MAGCHAR;
458 pglob->gl_flags |= GLOB_MAGCHAR;
459 /* collapse adjacent stars to one,
460 * to avoid exponential behavior
462 if (bufnext == patbuf || bufnext[-1] != M_ALL)
466 *bufnext++ = CHAR(c);
472 qprintf("glob0:", patbuf);
473 #endif /* GLOB_DEBUG */
475 if ((err = glob1(patbuf, pglob)) != 0) {
476 pglob->gl_flags = oldflags;
481 * If there was no match we are going to append the pattern
482 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
483 * and the pattern did not contain any magic characters
484 * GLOB_NOMAGIC is there just for compatibility with csh.
486 if (pglob->gl_pathc == oldpathc &&
487 ((pglob->gl_flags & GLOB_NOCHECK) ||
488 ((pglob->gl_flags & GLOB_NOMAGIC) &&
489 !(pglob->gl_flags & GLOB_MAGCHAR))))
492 printf("calling globextend from glob0\n");
493 #endif /* GLOB_DEBUG */
494 pglob->gl_flags = oldflags;
495 return(globextend(qpat, pglob));
497 else if (!(pglob->gl_flags & GLOB_NOSORT))
498 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
499 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
500 pglob->gl_flags = oldflags;
505 compare(const void *p, const void *q)
507 return(strcmp(*(char **)p, *(char **)q));
511 glob1(Char *pattern, glob_t *pglob)
513 Char pathbuf[MAXPATHLEN+1];
515 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
516 if (*pattern == BG_EOS)
518 return(glob2(pathbuf, pathbuf, pattern, pglob));
522 * The functions glob2 and glob3 are mutually recursive; there is one level
523 * of recursion for each segment in the pattern that contains one or more
527 glob2(Char *pathbuf, Char *pathend, Char *pattern, glob_t *pglob)
534 * Loop over pattern segments until end of pattern or until
535 * segment with meta character found.
537 for (anymeta = 0;;) {
538 if (*pattern == BG_EOS) { /* End of pattern? */
541 if (g_lstat(pathbuf, &sb, pglob))
544 if (((pglob->gl_flags & GLOB_MARK) &&
545 pathend[-1] != BG_SEP) && (S_ISDIR(sb.st_mode)
546 || (S_ISLNK(sb.st_mode) &&
547 (g_stat(pathbuf, &sb, pglob) == 0) &&
548 S_ISDIR(sb.st_mode)))) {
554 printf("calling globextend from glob2\n");
555 #endif /* GLOB_DEBUG */
556 return(globextend(pathbuf, pglob));
559 /* Find end of next segment, copy tentatively to pathend. */
562 while (*p != BG_EOS && *p != BG_SEP) {
568 if (!anymeta) { /* No expansion, do next segment. */
571 while (*pattern == BG_SEP)
572 *pathend++ = *pattern++;
573 } else /* Need expansion, recurse. */
574 return(glob3(pathbuf, pathend, pattern, p, pglob));
580 glob3(Char *pathbuf, Char *pathend, Char *pattern,
581 Char *restpattern, glob_t *pglob)
583 register Direntry_t *dp;
586 char buf[MAXPATHLEN];
589 * The readdirfunc declaration can't be prototyped, because it is
590 * assigned, below, to two functions which are prototyped in glob.h
591 * and dirent.h as taking pointers to differently typed opaque
594 Direntry_t *(*readdirfunc)();
599 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
600 /* TODO: don't call for ENOENT or ENOTDIR? */
601 if (pglob->gl_errfunc) {
602 g_Ctoc(pathbuf, buf);
603 if (pglob->gl_errfunc(buf, errno) ||
604 (pglob->gl_flags & GLOB_ERR))
612 /* Search directory for matching names. */
613 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
614 readdirfunc = pglob->gl_readdir;
616 readdirfunc = my_readdir;
617 while ((dp = (*readdirfunc)(dirp))) {
621 /* Initial BG_DOT must be matched literally. */
622 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
624 for (sc = (U8 *) dp->d_name, dc = pathend;
625 (*dc++ = *sc++) != BG_EOS;)
627 if (!match(pathend, pattern, restpattern)) {
631 err = glob2(pathbuf, --dc, restpattern, pglob);
636 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
637 (*pglob->gl_closedir)(dirp);
645 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
646 * add the new item, and update gl_pathc.
648 * This assumes the BSD realloc, which only copies the block when its size
649 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
652 * Return 0 if new item added, error code if memory couldn't be allocated.
654 * Invariant of the glob_t structure:
655 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
656 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
659 globextend(const Char *path, glob_t *pglob)
661 register char **pathv;
668 for (p = path; *p; p++)
669 (void)printf("%c", CHAR(*p));
671 #endif /* GLOB_DEBUG */
674 pathv = Renew(pglob->gl_pathv,
675 (2 + pglob->gl_pathc + pglob->gl_offs),char*);
677 New(0,pathv,(2 + pglob->gl_pathc + pglob->gl_offs),char*);
679 return(GLOB_NOSPACE);
681 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
682 /* first time around -- clear initial gl_offs items */
683 pathv += pglob->gl_offs;
684 for (i = pglob->gl_offs; --i >= 0; )
687 pglob->gl_pathv = pathv;
689 for (p = path; *p++;)
691 New(0, copy, p-path, char);
694 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
696 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
697 return(copy == NULL ? GLOB_NOSPACE : 0);
702 * pattern matching function for filenames. Each occurrence of the *
703 * pattern causes a recursion level.
706 match(register Char *name, register Char *pat, register Char *patend)
708 int ok, negate_range;
711 while (pat < patend) {
713 switch (c & M_MASK) {
718 if (match(name, pat, patend))
720 while (*name++ != BG_EOS);
723 if (*name++ == BG_EOS)
728 if ((k = *name++) == BG_EOS)
730 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
732 while (((c = *pat++) & M_MASK) != M_END)
733 if ((*pat & M_MASK) == M_RNG) {
734 if (c <= k && k <= pat[1])
739 if (ok == negate_range)
748 return(*name == BG_EOS);
751 /* Free allocated data belonging to a glob_t structure. */
753 bsd_globfree(glob_t *pglob)
758 if (pglob->gl_pathv != NULL) {
759 pp = pglob->gl_pathv + pglob->gl_offs;
760 for (i = pglob->gl_pathc; i--; ++pp)
763 Safefree(pglob->gl_pathv);
768 g_opendir(register Char *str, glob_t *pglob)
770 char buf[MAXPATHLEN];
777 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
778 return((*pglob->gl_opendir)(buf));
780 return(PerlDir_open(buf));
784 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
786 char buf[MAXPATHLEN];
789 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
790 return((*pglob->gl_lstat)(buf, sb));
792 return(PerlLIO_lstat(buf, sb));
794 return(PerlLIO_stat(buf, sb));
795 #endif /* HAS_LSTAT */
799 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
801 char buf[MAXPATHLEN];
804 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
805 return((*pglob->gl_stat)(buf, sb));
806 return(PerlLIO_stat(buf, sb));
810 g_strchr(Char *str, int ch)
821 g_strcat(Char *dst, const Char *src)
828 while((*dst++ = *src++) != BG_EOS)
836 g_Ctoc(register const Char *str, char *buf)
840 for (dc = buf; (*dc++ = *str++) != BG_EOS;)
846 qprintf(const char *str, register Char *s)
850 (void)printf("%s:\n", str);
852 (void)printf("%c", CHAR(*p));
855 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
858 (void)printf("%c", ismeta(*p) ? '_' : ' ');
861 #endif /* GLOB_DEBUG */