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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
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.
66 #ifdef HAVE_SYS_PARAM_H
67 #include <sys/param.h>
69 #ifdef HAVE_SYS_TYPES_H
70 #include <sys/types.h>
72 #ifdef HAVE_SYS_STAT_H
94 #define CHAR_DOLLAR '$'
97 #define CHAR_LBRACKET '['
99 #define CHAR_QUESTION '?'
100 #define CHAR_QUOTE '\\'
101 #define CHAR_RANGE '-'
102 #define CHAR_RBRACKET ']'
104 #define CHAR_STAR '*'
105 #define CHAR_TILDE '~'
106 #define CHAR_UNDERSCORE '_'
107 #define CHAR_LBRACE '{'
108 #define CHAR_RBRACE '}'
109 #define CHAR_SLASH '/'
110 #define CHAR_COMMA ','
114 #define M_QUOTE 0x8000
115 #define M_PROTECT 0x4000
116 #define M_MASK 0xffff
117 #define M_ASCII 0x00ff
119 typedef u_short Char
;
124 #define M_PROTECT 0x40
133 #define CHAR(c) ((Char)((c)&M_ASCII))
134 #define META(c) ((Char)((c)|M_QUOTE))
135 #define M_ALL META('*')
136 #define M_END META(']')
137 #define M_NOT META('!')
138 #define M_ONE META('?')
139 #define M_RNG META('-')
140 #define M_SET META('[')
141 #define ismeta(c) (((c)&M_QUOTE) != 0)
144 static int compare (const void *, const void *);
145 static void g_Ctoc (const Char
*, char *);
146 static int g_lstat (Char
*, struct stat
*, glob_t
*);
147 static DIR *g_opendir (Char
*, glob_t
*);
148 static Char
*g_strchr (Char
*, int);
150 static Char
*g_strcat (Char
*, const Char
*);
152 static int g_stat (Char
*, struct stat
*, glob_t
*);
153 static int glob0 (const Char
*, glob_t
*);
154 static int glob1 (Char
*, glob_t
*);
155 static int glob2 (Char
*, Char
*, Char
*, glob_t
*);
156 static int glob3 (Char
*, Char
*, Char
*, Char
*, glob_t
*);
157 static int globextend (const Char
*, glob_t
*);
158 static const Char
* globtilde (const Char
*, Char
*, glob_t
*);
159 static int globexp1 (const Char
*, glob_t
*);
160 static int globexp2 (const Char
*, const Char
*, glob_t
*, int *);
161 static int match (Char
*, Char
*, Char
*);
163 static void qprintf (const char *, Char
*);
167 glob(const char *pattern
,
169 int (*errfunc
)(const char *, int),
172 const u_char
*patnext
;
174 Char
*bufnext
, *bufend
, patbuf
[MaxPathLen
+1];
176 patnext
= (u_char
*) 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
++) != CHAR_EOS
)
192 if (c
== CHAR_QUOTE
) {
193 if ((c
= *patnext
++) == CHAR_EOS
) {
197 *bufnext
++ = c
| M_PROTECT
;
203 while (bufnext
< bufend
&& (c
= *patnext
++) != CHAR_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] == CHAR_LBRACE
&& pattern
[1] == CHAR_RBRACE
&& pattern
[2] == CHAR_EOS
)
225 return glob0(pattern
, pglob
);
227 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, CHAR_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
== CHAR_LBRACKET
) {
256 /* Ignore everything between [] */
257 for (pm
= pe
++; *pe
!= CHAR_RBRACKET
&& *pe
!= CHAR_EOS
; pe
++)
259 if (*pe
== CHAR_EOS
) {
261 * We could not find a matching CHAR_RBRACKET.
262 * Ignore and just look for CHAR_RBRACE
267 else if (*pe
== CHAR_LBRACE
)
269 else if (*pe
== CHAR_RBRACE
) {
275 /* Non matching braces; just glob the pattern */
276 if (i
!= 0 || *pe
== CHAR_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
!= CHAR_RBRACKET
&& *pm
!= CHAR_EOS
; pm
++)
287 if (*pm
== CHAR_EOS
) {
289 * We could not find a matching CHAR_RBRACKET.
290 * Ignore and just look for CHAR_RBRACE
307 if (i
&& *pm
== CHAR_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
++) != CHAR_EOS
;)
320 /* Expand the current pattern */
322 qprintf("globexp2:", patbuf
);
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
!= CHAR_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
!= CHAR_SLASH
;
361 if (((char *) patbuf
)[0] == CHAR_EOS
) {
363 * handle a plain ~ or ~/ by expanding $HOME
364 * first and then trying the password file
366 if ((h
= getenv("HOME")) == NULL
) {
367 if ((pwd
= k_getpwuid(getuid())) == NULL
)
377 if ((pwd
= k_getpwnam((char*) patbuf
)) == NULL
)
383 /* Copy the home directory */
384 for (b
= patbuf
; *h
; *b
++ = *h
++)
387 /* Append the rest of the pattern */
388 while ((*b
++ = *p
++) != CHAR_EOS
)
396 * The main glob() routine: compiles the pattern (optionally processing
397 * quotes), calls glob1() to do the real pattern matching, and finally
398 * sorts the list (unless unsorted operation is requested). Returns 0
399 * if things went well, nonzero if errors occurred. It is not an error
400 * to find no matches.
403 glob0(const Char
*pattern
, glob_t
*pglob
)
405 const Char
*qpatnext
;
406 int c
, err
, oldpathc
;
407 Char
*bufnext
, patbuf
[MaxPathLen
+1];
409 qpatnext
= globtilde(pattern
, patbuf
, pglob
);
410 oldpathc
= pglob
->gl_pathc
;
413 /* We don't need to check for buffer overflow any more. */
414 while ((c
= *qpatnext
++) != CHAR_EOS
) {
420 if (*qpatnext
== CHAR_EOS
||
421 g_strchr((Char
*) qpatnext
+1, CHAR_RBRACKET
) == NULL
) {
422 *bufnext
++ = CHAR_LBRACKET
;
432 *bufnext
++ = CHAR(c
);
433 if (*qpatnext
== CHAR_RANGE
&&
434 (c
= qpatnext
[1]) != CHAR_RBRACKET
) {
436 *bufnext
++ = CHAR(c
);
439 } while ((c
= *qpatnext
++) != CHAR_RBRACKET
);
440 pglob
->gl_flags
|= GLOB_MAGCHAR
;
444 pglob
->gl_flags
|= GLOB_MAGCHAR
;
448 pglob
->gl_flags
|= GLOB_MAGCHAR
;
449 /* collapse adjacent stars to one,
450 * to avoid exponential behavior
452 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
456 *bufnext
++ = CHAR(c
);
462 qprintf("glob0:", patbuf
);
465 if ((err
= glob1(patbuf
, pglob
)) != 0)
469 * If there was no match we are going to append the pattern
470 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
471 * and the pattern did not contain any magic characters
472 * GLOB_NOMAGIC is there just for compatibility with csh.
474 if (pglob
->gl_pathc
== oldpathc
&&
475 ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
476 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
477 !(pglob
->gl_flags
& GLOB_MAGCHAR
))))
478 return(globextend(pattern
, pglob
));
479 else if (!(pglob
->gl_flags
& GLOB_NOSORT
))
480 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
481 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
486 compare(const void *p
, const void *q
)
488 return(strcmp(*(char **)p
, *(char **)q
));
492 glob1(Char
*pattern
, glob_t
*pglob
)
494 Char pathbuf
[MaxPathLen
+1];
496 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
497 if (*pattern
== CHAR_EOS
)
499 return(glob2(pathbuf
, pathbuf
, pattern
, pglob
));
503 * The functions glob2 and glob3 are mutually recursive; there is one level
504 * of recursion for each segment in the pattern that contains one or more
509 #if defined(S_IFLNK) && defined(S_IFMT)
510 #define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
512 #define S_ISLNK(mode) 0
517 glob2(Char
*pathbuf
, Char
*pathend
, Char
*pattern
, glob_t
*pglob
)
524 * Loop over pattern segments until end of pattern or until
525 * segment with meta character found.
527 for (anymeta
= 0;;) {
528 if (*pattern
== CHAR_EOS
) { /* End of pattern? */
530 if (g_lstat(pathbuf
, &sb
, pglob
))
533 if (((pglob
->gl_flags
& GLOB_MARK
) &&
534 pathend
[-1] != CHAR_SEP
) && (S_ISDIR(sb
.st_mode
)
535 || (S_ISLNK(sb
.st_mode
) &&
536 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
537 S_ISDIR(sb
.st_mode
)))) {
538 *pathend
++ = CHAR_SEP
;
542 return(globextend(pathbuf
, pglob
));
545 /* Find end of next segment, copy tentatively to pathend. */
548 while (*p
!= CHAR_EOS
&& *p
!= CHAR_SEP
) {
554 if (!anymeta
) { /* No expansion, do next segment. */
557 while (*pattern
== CHAR_SEP
)
558 *pathend
++ = *pattern
++;
559 } else /* Need expansion, recurse. */
560 return(glob3(pathbuf
, pathend
, pattern
, p
, pglob
));
562 /* CHAR_NOTREACHED */
566 glob3(Char
*pathbuf
, Char
*pathend
, Char
*pattern
, Char
*restpattern
,
572 char buf
[MaxPathLen
];
575 * The readdirfunc declaration can't be prototyped, because it is
576 * assigned, below, to two functions which are prototyped in glob.h
577 * and dirent.h as taking pointers to differently typed opaque
580 struct dirent
*(*readdirfunc
)(void *);
585 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
586 /* TODO: don't call for ENOENT or ENOTDIR? */
587 if (pglob
->gl_errfunc
) {
588 g_Ctoc(pathbuf
, buf
);
589 if (pglob
->gl_errfunc(buf
, errno
) ||
590 pglob
->gl_flags
& GLOB_ERR
)
598 /* Search directory for matching names. */
599 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
600 readdirfunc
= pglob
->gl_readdir
;
602 readdirfunc
= (struct dirent
*(*)(void *))readdir
;
603 while ((dp
= (*readdirfunc
)(dirp
))) {
607 /* Initial CHAR_DOT must be matched literally. */
608 if (dp
->d_name
[0] == CHAR_DOT
&& *pattern
!= CHAR_DOT
)
610 for (sc
= (u_char
*) dp
->d_name
, dc
= pathend
;
611 (*dc
++ = *sc
++) != CHAR_EOS
;)
613 if (!match(pathend
, pattern
, restpattern
)) {
617 err
= glob2(pathbuf
, --dc
, restpattern
, pglob
);
622 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
623 (*pglob
->gl_closedir
)(dirp
);
631 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
632 * add the new item, and update gl_pathc.
634 * This assumes the BSD realloc, which only copies the block when its size
635 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
638 * Return 0 if new item added, error code if memory couldn't be allocated.
640 * Invariant of the glob_t structure:
641 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
642 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
645 globextend(const Char
*path
, glob_t
*pglob
)
653 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
654 pathv
= pglob
->gl_pathv
?
655 realloc(pglob
->gl_pathv
, newsize
) :
658 return(GLOB_NOSPACE
);
660 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
661 /* first time around -- clear initial gl_offs items */
662 pathv
+= pglob
->gl_offs
;
663 for (i
= pglob
->gl_offs
; --i
>= 0; )
666 pglob
->gl_pathv
= pathv
;
668 for (p
= path
; *p
++;)
670 if ((copy
= malloc(p
- path
)) != NULL
) {
672 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
674 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
675 return(copy
== NULL
? GLOB_NOSPACE
: 0);
680 * pattern matching function for filenames. Each occurrence of the *
681 * pattern causes a recursion level.
684 match(Char
*name
, Char
*pat
, Char
*patend
)
686 int ok
, negate_range
;
689 while (pat
< patend
) {
691 switch (c
& M_MASK
) {
696 if (match(name
, pat
, patend
))
698 while (*name
++ != CHAR_EOS
);
701 if (*name
++ == CHAR_EOS
)
706 if ((k
= *name
++) == CHAR_EOS
)
708 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != CHAR_EOS
)
710 while (((c
= *pat
++) & M_MASK
) != M_END
)
711 if ((*pat
& M_MASK
) == M_RNG
) {
712 if (c
<= k
&& k
<= pat
[1])
717 if (ok
== negate_range
)
726 return(*name
== CHAR_EOS
);
729 /* Free allocated data belonging to a glob_t structure. */
731 globfree(glob_t
*pglob
)
736 if (pglob
->gl_pathv
!= NULL
) {
737 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
738 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
741 free(pglob
->gl_pathv
);
746 g_opendir(Char
*str
, glob_t
*pglob
)
748 char buf
[MaxPathLen
];
751 strcpy_truncate(buf
, ".", sizeof(buf
));
755 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
756 return((*pglob
->gl_opendir
)(buf
));
758 return(opendir(buf
));
762 g_lstat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
764 char buf
[MaxPathLen
];
767 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
768 return((*pglob
->gl_lstat
)(buf
, sb
));
769 return(lstat(buf
, sb
));
773 g_stat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
775 char buf
[MaxPathLen
];
778 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
779 return((*pglob
->gl_stat
)(buf
, sb
));
780 return(stat(buf
, sb
));
784 g_strchr(Char
*str
, int ch
)
795 g_strcat(Char
*dst
, const Char
*src
)
802 while((*dst
++ = *src
++) != CHAR_EOS
)
810 g_Ctoc(const Char
*str
, char *buf
)
814 for (dc
= buf
; (*dc
++ = *str
++) != CHAR_EOS
;)
820 qprintf(const Char
*str
, Char
*s
)
824 printf("%s:\n", str
);
826 printf("%c", CHAR(*p
));
829 printf("%c", *p
& M_PROTECT
? '"' : ' ');
832 printf("%c", ismeta(*p
) ? '_' : ' ');