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
34 * glob(3) -- a superset of the one defined in POSIX 1003.2.
36 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
38 * Optional extra services, controlled by flags not defined by POSIX:
41 * Escaping convention: \ inhibits any special meaning the following
42 * character might have (except \ at end of string is retained).
44 * Set in gl_flags if pattern contained a globbing character.
46 * Same as GLOB_NOCHECK, but it will only append pattern if it did
47 * not contain any magic characters. [Used in csh style globbing]
49 * Use alternately specified directory access functions.
51 * expand ~user/foo to the /home/dir/of/user/foo
53 * expand {1,2}{a,b} to 1a 1b 2a 2b
55 * Number of matches in the current invocation of glob.
60 #ifdef HAVE_SYS_PARAM_H
61 #include <sys/param.h>
63 #ifdef HAVE_SYS_TYPES_H
64 #include <sys/types.h>
66 #ifdef HAVE_SYS_STAT_H
92 #define ARG_MAX _POSIX_ARG_MAX
95 #define CHAR_DOLLAR '$'
98 #define CHAR_LBRACKET '['
100 #define CHAR_QUESTION '?'
101 #define CHAR_QUOTE '\\'
102 #define CHAR_RANGE '-'
103 #define CHAR_RBRACKET ']'
105 #define CHAR_STAR '*'
106 #define CHAR_TILDE '~'
107 #define CHAR_UNDERSCORE '_'
108 #define CHAR_LBRACE '{'
109 #define CHAR_RBRACE '}'
110 #define CHAR_SLASH '/'
111 #define CHAR_COMMA ','
115 #define M_QUOTE 0x8000
116 #define M_PROTECT 0x4000
117 #define M_MASK 0xffff
118 #define M_ASCII 0x00ff
120 typedef u_short Char
;
125 #define M_PROTECT 0x40
134 #define CHAR(c) ((Char)((c)&M_ASCII))
135 #define META(c) ((Char)((c)|M_QUOTE))
136 #define M_ALL META('*')
137 #define M_END META(']')
138 #define M_NOT META('!')
139 #define M_ONE META('?')
140 #define M_RNG META('-')
141 #define M_SET META('[')
142 #define ismeta(c) (((c)&M_QUOTE) != 0)
145 static int compare (const void *, const void *);
146 static void g_Ctoc (const Char
*, char *);
147 static int g_lstat (Char
*, struct stat
*, glob_t
*);
148 static DIR *g_opendir (Char
*, glob_t
*);
149 static Char
*g_strchr (const Char
*, int);
151 static Char
*g_strcat (Char
*, const Char
*);
153 static int g_stat (Char
*, struct stat
*, glob_t
*);
154 static int glob0 (const Char
*, glob_t
*);
155 static int glob1 (Char
*, glob_t
*, size_t *);
156 static int glob2 (Char
*, Char
*, Char
*, glob_t
*, size_t *);
157 static int glob3 (Char
*, Char
*, Char
*, Char
*, glob_t
*, size_t *);
158 static int globextend (const Char
*, glob_t
*, size_t *);
159 static const Char
* globtilde (const Char
*, Char
*, glob_t
*);
160 static int globexp1 (const Char
*, glob_t
*);
161 static int globexp2 (const Char
*, const Char
*, glob_t
*, int *);
162 static int match (Char
*, Char
*, Char
*);
164 static void qprintf (const char *, Char
*);
167 int ROKEN_LIB_FUNCTION
168 glob(const char *pattern
,
170 int (*errfunc
)(const char *, int),
173 const u_char
*patnext
;
175 Char
*bufnext
, *bufend
, patbuf
[MaxPathLen
+1];
177 patnext
= (const u_char
*) pattern
;
178 if (!(flags
& GLOB_APPEND
)) {
180 pglob
->gl_pathv
= NULL
;
181 if (!(flags
& GLOB_DOOFFS
))
184 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
185 pglob
->gl_errfunc
= errfunc
;
186 pglob
->gl_matchc
= 0;
189 bufend
= bufnext
+ MaxPathLen
;
190 if (flags
& GLOB_QUOTE
) {
191 /* Protect the quoted characters. */
192 while (bufnext
< bufend
&& (c
= *patnext
++) != CHAR_EOS
)
193 if (c
== CHAR_QUOTE
) {
194 if ((c
= *patnext
++) == CHAR_EOS
) {
198 *bufnext
++ = c
| M_PROTECT
;
204 while (bufnext
< bufend
&& (c
= *patnext
++) != CHAR_EOS
)
208 if (flags
& GLOB_BRACE
)
209 return globexp1(patbuf
, pglob
);
211 return glob0(patbuf
, pglob
);
215 * Expand recursively a glob {} pattern. When there is no more expansion
216 * invoke the standard globbing routine to glob the rest of the magic
219 static int globexp1(const Char
*pattern
, glob_t
*pglob
)
221 const Char
* ptr
= pattern
;
224 /* Protect a single {}, for find(1), like csh */
225 if (pattern
[0] == CHAR_LBRACE
&& pattern
[1] == CHAR_RBRACE
&& pattern
[2] == CHAR_EOS
)
226 return glob0(pattern
, pglob
);
228 while ((ptr
= (const Char
*) g_strchr(ptr
, CHAR_LBRACE
)) != NULL
)
229 if (!globexp2(ptr
, pattern
, pglob
, &rv
))
232 return glob0(pattern
, pglob
);
237 * Recursive brace globbing helper. Tries to expand a single brace.
238 * If it succeeds then it invokes globexp1 with the new pattern.
239 * If it fails then it tries to glob the rest of the pattern and returns.
241 static int globexp2(const Char
*ptr
, const Char
*pattern
,
242 glob_t
*pglob
, int *rv
)
246 const Char
*pe
, *pm
, *pl
;
247 Char patbuf
[MaxPathLen
+ 1];
249 /* copy part up to the brace */
250 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
254 /* Find the balanced brace */
255 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
256 if (*pe
== CHAR_LBRACKET
) {
257 /* Ignore everything between [] */
258 for (pm
= pe
++; *pe
!= CHAR_RBRACKET
&& *pe
!= CHAR_EOS
; pe
++)
260 if (*pe
== CHAR_EOS
) {
262 * We could not find a matching CHAR_RBRACKET.
263 * Ignore and just look for CHAR_RBRACE
268 else if (*pe
== CHAR_LBRACE
)
270 else if (*pe
== CHAR_RBRACE
) {
276 /* Non matching braces; just glob the pattern */
277 if (i
!= 0 || *pe
== CHAR_EOS
) {
278 *rv
= glob0(patbuf
, pglob
);
282 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
285 /* Ignore everything between [] */
286 for (pl
= pm
++; *pm
!= CHAR_RBRACKET
&& *pm
!= CHAR_EOS
; pm
++)
288 if (*pm
== CHAR_EOS
) {
290 * We could not find a matching CHAR_RBRACKET.
291 * Ignore and just look for CHAR_RBRACE
308 if (i
&& *pm
== CHAR_COMMA
)
311 /* Append the current string */
312 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
315 * Append the rest of the pattern after the
318 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != CHAR_EOS
;)
321 /* Expand the current pattern */
323 qprintf("globexp2:", patbuf
);
325 *rv
= globexp1(patbuf
, pglob
);
327 /* move after the comma, to the next string */
342 * expand tilde from the passwd file.
345 globtilde(const Char
*pattern
, Char
*patbuf
, glob_t
*pglob
)
352 if (*pattern
!= CHAR_TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
355 /* Copy up to the end of the string or / */
356 for (p
= pattern
+ 1, h
= (char *) patbuf
; *p
&& *p
!= CHAR_SLASH
;
362 if (((char *) patbuf
)[0] == CHAR_EOS
) {
364 * handle a plain ~ or ~/ by expanding $HOME
365 * first and then trying the password file
367 if ((h
= getenv("HOME")) == NULL
) {
368 if ((pwd
= k_getpwuid(getuid())) == NULL
)
378 if ((pwd
= k_getpwnam((char*) patbuf
)) == NULL
)
384 /* Copy the home directory */
385 for (b
= patbuf
; *h
; *b
++ = *h
++)
388 /* Append the rest of the pattern */
389 while ((*b
++ = *p
++) != CHAR_EOS
)
397 * The main glob() routine: compiles the pattern (optionally processing
398 * quotes), calls glob1() to do the real pattern matching, and finally
399 * sorts the list (unless unsorted operation is requested). Returns 0
400 * if things went well, nonzero if errors occurred. It is not an error
401 * to find no matches.
404 glob0(const Char
*pattern
, glob_t
*pglob
)
406 const Char
*qpatnext
;
407 int c
, err
, oldpathc
;
408 Char
*bufnext
, patbuf
[MaxPathLen
+1];
411 qpatnext
= globtilde(pattern
, patbuf
, pglob
);
412 oldpathc
= pglob
->gl_pathc
;
415 /* We don't need to check for buffer overflow any more. */
416 while ((c
= *qpatnext
++) != CHAR_EOS
) {
422 if (*qpatnext
== CHAR_EOS
||
423 g_strchr(qpatnext
+1, CHAR_RBRACKET
) == NULL
) {
424 *bufnext
++ = CHAR_LBRACKET
;
434 *bufnext
++ = CHAR(c
);
435 if (*qpatnext
== CHAR_RANGE
&&
436 (c
= qpatnext
[1]) != CHAR_RBRACKET
) {
438 *bufnext
++ = CHAR(c
);
441 } while ((c
= *qpatnext
++) != CHAR_RBRACKET
);
442 pglob
->gl_flags
|= GLOB_MAGCHAR
;
446 pglob
->gl_flags
|= GLOB_MAGCHAR
;
450 pglob
->gl_flags
|= GLOB_MAGCHAR
;
451 /* collapse adjacent stars to one,
452 * to avoid exponential behavior
454 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
458 *bufnext
++ = CHAR(c
);
464 qprintf("glob0:", patbuf
);
467 if ((err
= glob1(patbuf
, pglob
, &limit
)) != 0)
471 * If there was no match we are going to append the pattern
472 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
473 * and the pattern did not contain any magic characters
474 * GLOB_NOMAGIC is there just for compatibility with csh.
476 if (pglob
->gl_pathc
== oldpathc
&&
477 ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
478 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
479 !(pglob
->gl_flags
& GLOB_MAGCHAR
))))
480 return(globextend(pattern
, pglob
, &limit
));
481 else if (!(pglob
->gl_flags
& GLOB_NOSORT
))
482 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
483 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
488 compare(const void *p
, const void *q
)
490 return(strcmp(*(char **)p
, *(char **)q
));
494 glob1(Char
*pattern
, glob_t
*pglob
, size_t *limit
)
496 Char pathbuf
[MaxPathLen
+1];
498 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
499 if (*pattern
== CHAR_EOS
)
501 return(glob2(pathbuf
, pathbuf
, pattern
, pglob
, limit
));
505 * The functions glob2 and glob3 are mutually recursive; there is one level
506 * of recursion for each segment in the pattern that contains one or more
511 #if defined(S_IFLNK) && defined(S_IFMT)
512 #define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
514 #define S_ISLNK(mode) 0
519 glob2(Char
*pathbuf
, Char
*pathend
, Char
*pattern
, glob_t
*pglob
,
527 * Loop over pattern segments until end of pattern or until
528 * segment with meta character found.
530 for (anymeta
= 0;;) {
531 if (*pattern
== CHAR_EOS
) { /* End of pattern? */
533 if (g_lstat(pathbuf
, &sb
, pglob
))
536 if (((pglob
->gl_flags
& GLOB_MARK
) &&
537 pathend
[-1] != CHAR_SEP
) && (S_ISDIR(sb
.st_mode
)
538 || (S_ISLNK(sb
.st_mode
) &&
539 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
540 S_ISDIR(sb
.st_mode
)))) {
541 *pathend
++ = CHAR_SEP
;
545 return(globextend(pathbuf
, pglob
, limit
));
548 /* Find end of next segment, copy tentatively to pathend. */
551 while (*p
!= CHAR_EOS
&& *p
!= CHAR_SEP
) {
557 if (!anymeta
) { /* No expansion, do next segment. */
560 while (*pattern
== CHAR_SEP
)
561 *pathend
++ = *pattern
++;
562 } else /* Need expansion, recurse. */
563 return(glob3(pathbuf
, pathend
, pattern
, p
, pglob
,
570 glob3(Char
*pathbuf
, Char
*pathend
, Char
*pattern
, Char
*restpattern
,
571 glob_t
*pglob
, size_t *limit
)
576 char buf
[MaxPathLen
];
579 * The readdirfunc declaration can't be prototyped, because it is
580 * assigned, below, to two functions which are prototyped in glob.h
581 * and dirent.h as taking pointers to differently typed opaque
584 struct dirent
*(*readdirfunc
)(void *);
589 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
590 /* TODO: don't call for ENOENT or ENOTDIR? */
591 if (pglob
->gl_errfunc
) {
592 g_Ctoc(pathbuf
, buf
);
593 if (pglob
->gl_errfunc(buf
, errno
) ||
594 pglob
->gl_flags
& GLOB_ERR
)
602 /* Search directory for matching names. */
603 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
604 readdirfunc
= pglob
->gl_readdir
;
606 readdirfunc
= (struct dirent
*(*)(void *))readdir
;
607 while ((dp
= (*readdirfunc
)(dirp
))) {
611 /* Initial CHAR_DOT must be matched literally. */
612 if (dp
->d_name
[0] == CHAR_DOT
&& *pattern
!= CHAR_DOT
)
614 for (sc
= (u_char
*) dp
->d_name
, dc
= pathend
;
615 (*dc
++ = *sc
++) != CHAR_EOS
;)
617 if (!match(pathend
, pattern
, restpattern
)) {
621 err
= glob2(pathbuf
, --dc
, restpattern
, pglob
, limit
);
626 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
627 (*pglob
->gl_closedir
)(dirp
);
635 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
636 * add the new item, and update gl_pathc.
638 * This assumes the BSD realloc, which only copies the block when its size
639 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
642 * Return 0 if new item added, error code if memory couldn't be allocated.
644 * Invariant of the glob_t structure:
645 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
646 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
649 globextend(const Char
*path
, glob_t
*pglob
, size_t *limit
)
657 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
658 pathv
= pglob
->gl_pathv
?
659 realloc(pglob
->gl_pathv
, newsize
) :
662 return(GLOB_NOSPACE
);
664 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
665 /* first time around -- clear initial gl_offs items */
666 pathv
+= pglob
->gl_offs
;
667 for (i
= pglob
->gl_offs
; --i
>= 0; )
670 pglob
->gl_pathv
= pathv
;
672 for (p
= path
; *p
++;)
674 len
= (size_t)(p
- path
);
676 if ((copy
= malloc(len
)) != NULL
) {
678 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
680 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
682 if ((pglob
->gl_flags
& GLOB_LIMIT
) && (newsize
+ *limit
) >= ARG_MAX
) {
684 return(GLOB_NOSPACE
);
687 return(copy
== NULL
? GLOB_NOSPACE
: 0);
692 * pattern matching function for filenames. Each occurrence of the *
693 * pattern causes a recursion level.
696 match(Char
*name
, Char
*pat
, Char
*patend
)
698 int ok
, negate_range
;
701 while (pat
< patend
) {
703 switch (c
& M_MASK
) {
708 if (match(name
, pat
, patend
))
710 while (*name
++ != CHAR_EOS
);
713 if (*name
++ == CHAR_EOS
)
718 if ((k
= *name
++) == CHAR_EOS
)
720 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != CHAR_EOS
)
722 while (((c
= *pat
++) & M_MASK
) != M_END
)
723 if ((*pat
& M_MASK
) == M_RNG
) {
724 if (c
<= k
&& k
<= pat
[1])
729 if (ok
== negate_range
)
738 return(*name
== CHAR_EOS
);
741 /* Free allocated data belonging to a glob_t structure. */
742 void ROKEN_LIB_FUNCTION
743 globfree(glob_t
*pglob
)
748 if (pglob
->gl_pathv
!= NULL
) {
749 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
750 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
753 free(pglob
->gl_pathv
);
754 pglob
->gl_pathv
= NULL
;
759 g_opendir(Char
*str
, glob_t
*pglob
)
761 char buf
[MaxPathLen
];
764 strlcpy(buf
, ".", sizeof(buf
));
768 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
769 return((*pglob
->gl_opendir
)(buf
));
771 return(opendir(buf
));
775 g_lstat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
777 char buf
[MaxPathLen
];
780 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
781 return((*pglob
->gl_lstat
)(buf
, sb
));
782 return(lstat(buf
, sb
));
786 g_stat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
788 char buf
[MaxPathLen
];
791 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
792 return((*pglob
->gl_stat
)(buf
, sb
));
793 return(stat(buf
, sb
));
797 g_strchr(const Char
*str
, int ch
)
808 g_strcat(Char
*dst
, const Char
*src
)
815 while((*dst
++ = *src
++) != CHAR_EOS
)
823 g_Ctoc(const Char
*str
, char *buf
)
827 for (dc
= buf
; (*dc
++ = *str
++) != CHAR_EOS
;)
833 qprintf(const Char
*str
, Char
*s
)
837 printf("%s:\n", str
);
839 printf("%c", CHAR(*p
));
842 printf("%c", *p
& M_PROTECT
? '"' : ' ');
845 printf("%c", ismeta(*p
) ? '_' : ' ');