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 * 4. 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 #define _NO_GLOB /* Cygwin provides its own glob. */
39 #if defined(LIBC_SCCS) && !defined(lint)
40 static char sccsid
[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
41 #endif /* LIBC_SCCS and not lint */
42 #include <sys/cdefs.h>
45 * glob(3) -- a superset of the one defined in POSIX 1003.2.
47 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
49 * Optional extra services, controlled by flags not defined by POSIX:
52 * Escaping convention: \ inhibits any special meaning the following
53 * character might have (except \ at end of string is retained).
55 * Set in gl_flags if pattern contained a globbing character.
57 * Same as GLOB_NOCHECK, but it will only append pattern if it did
58 * not contain any magic characters. [Used in csh style globbing]
60 * Use alternately specified directory access functions.
62 * expand ~user/foo to the /home/dir/of/user/foo
64 * expand {1,2}{a,b} to 1a 1b 2a 2b
66 * Number of matches in the current invocation of glob.
69 #include <sys/param.h>
70 #include <sys/types.h>
98 #define UNDERSCORE '_'
106 #define M_QUOTE 0x8000
107 #define M_PROTECT 0x4000
108 #define M_MASK 0xffff
109 #define M_ASCII 0x00ff
111 typedef u_short Char
;
116 #define M_PROTECT 0x40
125 #define CHAR(c) ((Char)((c)&M_ASCII))
126 #define META(c) ((Char)((c)|M_QUOTE))
127 #define M_ALL META('*')
128 #define M_END META(']')
129 #define M_NOT META('!')
130 #define M_ONE META('?')
131 #define M_RNG META('-')
132 #define M_SET META('[')
133 #define ismeta(c) (((c)&M_QUOTE) != 0)
136 static int compare(const void *, const void *);
137 static int g_Ctoc(const Char
*, char *, u_int
);
138 static int g_lstat(Char
*, struct stat
*, glob_t
*);
139 static DIR *g_opendir(Char
*, glob_t
*);
140 static Char
*g_strchr(Char
*, int);
142 static Char
*g_strcat(Char
*, const Char
*);
144 static int g_stat(Char
*, struct stat
*, glob_t
*);
145 static int glob0(const Char
*, glob_t
*, int *);
146 static int glob1(Char
*, glob_t
*, int *);
147 static int glob2(Char
*, Char
*, Char
*, Char
*, glob_t
*, int *);
148 static int glob3(Char
*, Char
*, Char
*, Char
*, Char
*, glob_t
*, int *);
149 static int globextend(const Char
*, glob_t
*, int *);
151 globtilde(const Char
*, Char
*, size_t, glob_t
*);
152 static int globexp1(const Char
*, glob_t
*, int *);
153 static int globexp2(const Char
*, const Char
*, glob_t
*, int *, int *);
154 static int match(Char
*, Char
*, Char
*);
156 static void qprintf(const char *, Char
*);
160 glob(pattern
, flags
, errfunc
, pglob
)
161 const char *__restrict pattern
;
162 int flags
, (*errfunc
)(const char *, int);
163 glob_t
*__restrict pglob
;
165 const u_char
*patnext
;
167 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
];
169 patnext
= (u_char
*) pattern
;
170 if (!(flags
& GLOB_APPEND
)) {
172 pglob
->gl_pathv
= NULL
;
173 if (!(flags
& GLOB_DOOFFS
))
176 if (flags
& GLOB_LIMIT
) {
177 limit
= pglob
->gl_matchc
;
182 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
183 pglob
->gl_errfunc
= errfunc
;
184 pglob
->gl_matchc
= 0;
187 bufend
= bufnext
+ MAXPATHLEN
- 1;
188 if (flags
& GLOB_QUOTE
) {
189 /* Protect the quoted characters. */
190 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
192 if ((c
= *patnext
++) == EOS
) {
196 *bufnext
++ = c
| M_PROTECT
;
202 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
206 if (flags
& GLOB_BRACE
)
207 return globexp1(patbuf
, pglob
, &limit
);
209 return glob0(patbuf
, pglob
, &limit
);
213 * Expand recursively a glob {} pattern. When there is no more expansion
214 * invoke the standard globbing routine to glob the rest of the magic
218 globexp1(pattern
, pglob
, limit
)
223 const Char
* ptr
= pattern
;
226 /* Protect a single {}, for find(1), like csh */
227 if (pattern
[0] == LBRACE
&& pattern
[1] == RBRACE
&& pattern
[2] == EOS
)
228 return glob0(pattern
, pglob
, limit
);
230 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, LBRACE
)) != NULL
)
231 if (!globexp2(ptr
, pattern
, pglob
, &rv
, limit
))
234 return glob0(pattern
, pglob
, limit
);
239 * Recursive brace globbing helper. Tries to expand a single brace.
240 * If it succeeds then it invokes globexp1 with the new pattern.
241 * If it fails then it tries to glob the rest of the pattern and returns.
244 globexp2(ptr
, pattern
, pglob
, rv
, limit
)
245 const Char
*ptr
, *pattern
;
251 const Char
*pe
, *pm
, *pl
;
252 Char patbuf
[MAXPATHLEN
];
254 /* copy part up to the brace */
255 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
260 /* Find the balanced brace */
261 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
262 if (*pe
== LBRACKET
) {
263 /* Ignore everything between [] */
264 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
268 * We could not find a matching RBRACKET.
269 * Ignore and just look for RBRACE
274 else if (*pe
== LBRACE
)
276 else if (*pe
== RBRACE
) {
282 /* Non matching braces; just glob the pattern */
283 if (i
!= 0 || *pe
== EOS
) {
284 *rv
= glob0(patbuf
, pglob
, limit
);
288 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
291 /* Ignore everything between [] */
292 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
296 * We could not find a matching RBRACKET.
297 * Ignore and just look for RBRACE
314 if (i
&& *pm
== COMMA
)
317 /* Append the current string */
318 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
321 * Append the rest of the pattern after the
324 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
;)
327 /* Expand the current pattern */
329 qprintf("globexp2:", patbuf
);
331 *rv
= globexp1(patbuf
, pglob
, limit
);
333 /* move after the comma, to the next string */
348 * expand tilde from the passwd file.
351 globtilde(pattern
, patbuf
, patbuf_len
, pglob
)
362 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
366 * Copy up to the end of the string or /
368 eb
= &patbuf
[patbuf_len
- 1];
369 for (p
= pattern
+ 1, h
= (char *) patbuf
;
370 h
< (char *)eb
&& *p
&& *p
!= SLASH
; *h
++ = *p
++)
375 if (((char *) patbuf
)[0] == EOS
) {
377 * handle a plain ~ or ~/ by expanding $HOME first (iff
378 * we're not running setuid or setgid) and then trying
382 #ifndef __NETBSD_SYSCALLS
385 (h
= getenv("HOME")) == NULL
) {
386 /* If we are not EL/IX level 4, we cannot use getpwxxx interfaces */
387 #if !defined(_ELIX_LEVEL) || _ELIX_LEVEL >= 4
388 if (((h
= getlogin()) != NULL
&&
389 (pwd
= getpwnam(h
)) != NULL
) ||
390 (pwd
= getpwuid(getuid())) != NULL
)
393 #endif /* !_ELIX_LEVEL || _ELIX_LEVEL >= 4 */
402 #if !defined(_ELIX_LEVEL) || _ELIX_LEVEL >= 4
403 if ((pwd
= getpwnam((char*) patbuf
)) != NULL
)
406 #endif /* !_ELIX_LEVEL || _ELIX_LEVEL >= 4 */
410 /* Copy the home directory */
411 for (b
= patbuf
; b
< eb
&& *h
; *b
++ = *h
++)
414 /* Append the rest of the pattern */
415 while (b
< eb
&& (*b
++ = *p
++) != EOS
)
424 * The main glob() routine: compiles the pattern (optionally processing
425 * quotes), calls glob1() to do the real pattern matching, and finally
426 * sorts the list (unless unsorted operation is requested). Returns 0
427 * if things went well, nonzero if errors occurred. It is not an error
428 * to find no matches.
431 glob0(pattern
, pglob
, limit
)
436 const Char
*qpatnext
;
437 int c
, err
, oldpathc
;
438 Char
*bufnext
, patbuf
[MAXPATHLEN
];
440 qpatnext
= globtilde(pattern
, patbuf
, MAXPATHLEN
, pglob
);
441 oldpathc
= pglob
->gl_pathc
;
444 /* We don't need to check for buffer overflow any more. */
445 while ((c
= *qpatnext
++) != EOS
) {
451 if (*qpatnext
== EOS
||
452 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
453 *bufnext
++ = LBRACKET
;
463 *bufnext
++ = CHAR(c
);
464 if (*qpatnext
== RANGE
&&
465 (c
= qpatnext
[1]) != RBRACKET
) {
467 *bufnext
++ = CHAR(c
);
470 } while ((c
= *qpatnext
++) != RBRACKET
);
471 pglob
->gl_flags
|= GLOB_MAGCHAR
;
475 pglob
->gl_flags
|= GLOB_MAGCHAR
;
479 pglob
->gl_flags
|= GLOB_MAGCHAR
;
480 /* collapse adjacent stars to one,
481 * to avoid exponential behavior
483 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
487 *bufnext
++ = CHAR(c
);
493 qprintf("glob0:", patbuf
);
496 if ((err
= glob1(patbuf
, pglob
, limit
)) != 0)
500 * If there was no match we are going to append the pattern
501 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
502 * and the pattern did not contain any magic characters
503 * GLOB_NOMAGIC is there just for compatibility with csh.
505 if (pglob
->gl_pathc
== oldpathc
) {
506 if ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
507 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
508 !(pglob
->gl_flags
& GLOB_MAGCHAR
)))
509 return(globextend(pattern
, pglob
, limit
));
511 return(GLOB_NOMATCH
);
513 else if (!(pglob
->gl_flags
& GLOB_NOSORT
))
514 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
515 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
523 return(strcmp(*(char **)p
, *(char **)q
));
527 glob1(pattern
, pglob
, limit
)
532 Char pathbuf
[MAXPATHLEN
];
534 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
537 return(glob2(pathbuf
, pathbuf
, pathbuf
+ MAXPATHLEN
- 1,
538 pattern
, pglob
, limit
));
542 * The functions glob2 and glob3 are mutually recursive; there is one level
543 * of recursion for each segment in the pattern that contains one or more
547 glob2(pathbuf
, pathend
, pathend_last
, pattern
, pglob
, limit
)
548 Char
*pathbuf
, *pathend
, *pathend_last
, *pattern
;
557 * Loop over pattern segments until end of pattern or until
558 * segment with meta character found.
560 for (anymeta
= 0;;) {
561 if (*pattern
== EOS
) { /* End of pattern? */
563 if (g_lstat(pathbuf
, &sb
, pglob
))
566 if (((pglob
->gl_flags
& GLOB_MARK
) &&
567 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
)
568 || (S_ISLNK(sb
.st_mode
) &&
569 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
570 S_ISDIR(sb
.st_mode
)))) {
571 if (pathend
+ 1 > pathend_last
)
577 return(globextend(pathbuf
, pglob
, limit
));
580 /* Find end of next segment, copy tentatively to pathend. */
583 while (*p
!= EOS
&& *p
!= SEP
) {
586 if (q
+ 1 > pathend_last
)
591 if (!anymeta
) { /* No expansion, do next segment. */
594 while (*pattern
== SEP
) {
595 if (pathend
+ 1 > pathend_last
)
597 *pathend
++ = *pattern
++;
599 } else /* Need expansion, recurse. */
600 return(glob3(pathbuf
, pathend
, pathend_last
, pattern
, p
,
607 glob3(pathbuf
, pathend
, pathend_last
, pattern
, restpattern
, pglob
, limit
)
608 Char
*pathbuf
, *pathend
, *pathend_last
, *pattern
, *restpattern
;
615 char buf
[MAXPATHLEN
];
618 * The readdirfunc declaration can't be prototyped, because it is
619 * assigned, below, to two functions which are prototyped in glob.h
620 * and dirent.h as taking pointers to differently typed opaque
623 struct dirent
*(*readdirfunc
)();
625 if (pathend
> pathend_last
)
630 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
631 /* TODO: don't call for ENOENT or ENOTDIR? */
632 if (pglob
->gl_errfunc
) {
633 if (g_Ctoc(pathbuf
, buf
, sizeof(buf
)))
635 if (pglob
->gl_errfunc(buf
, errno
) ||
636 pglob
->gl_flags
& GLOB_ERR
)
644 /* Search directory for matching names. */
645 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
646 readdirfunc
= pglob
->gl_readdir
;
648 readdirfunc
= readdir
;
649 while ((dp
= (*readdirfunc
)(dirp
))) {
653 /* Initial DOT must be matched literally. */
654 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
657 sc
= (u_char
*) dp
->d_name
;
658 while (dc
< pathend_last
&& (*dc
++ = *sc
++) != EOS
)
660 if (!match(pathend
, pattern
, restpattern
)) {
664 err
= glob2(pathbuf
, --dc
, pathend_last
, restpattern
,
670 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
671 (*pglob
->gl_closedir
)(dirp
);
679 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
680 * add the new item, and update gl_pathc.
682 * This assumes the BSD realloc, which only copies the block when its size
683 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
686 * Return 0 if new item added, error code if memory couldn't be allocated.
688 * Invariant of the glob_t structure:
689 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
690 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
693 globextend(path
, pglob
, limit
)
704 if (*limit
&& pglob
->gl_pathc
> *limit
) {
706 return (GLOB_NOSPACE
);
709 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
710 pathv
= pglob
->gl_pathv
?
711 realloc((char *)pglob
->gl_pathv
, newsize
) :
714 if (pglob
->gl_pathv
) {
715 free(pglob
->gl_pathv
);
716 pglob
->gl_pathv
= NULL
;
718 return(GLOB_NOSPACE
);
721 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
722 /* first time around -- clear initial gl_offs items */
723 pathv
+= pglob
->gl_offs
;
724 for (i
= pglob
->gl_offs
; --i
>= 0; )
727 pglob
->gl_pathv
= pathv
;
729 for (p
= path
; *p
++;)
731 len
= (size_t)(p
- path
);
732 if ((copy
= malloc(len
)) != NULL
) {
733 if (g_Ctoc(path
, copy
, len
)) {
735 return (GLOB_NOSPACE
);
737 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
739 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
740 return(copy
== NULL
? GLOB_NOSPACE
: 0);
744 * pattern matching function for filenames. Each occurrence of the *
745 * pattern causes a recursion level.
748 match(name
, pat
, patend
)
749 Char
*name
, *pat
, *patend
;
751 int ok
, negate_range
;
754 while (pat
< patend
) {
756 switch (c
& M_MASK
) {
761 if (match(name
, pat
, patend
))
763 while (*name
++ != EOS
);
771 if ((k
= *name
++) == EOS
)
773 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
775 while (((c
= *pat
++) & M_MASK
) != M_END
)
776 if ((*pat
& M_MASK
) == M_RNG
) {
777 if (__collate_load_error
?
778 CHAR(c
) <= CHAR(k
) && CHAR(k
) <= CHAR(pat
[1]) :
779 __collate_range_cmp(CHAR(c
), CHAR(k
)) <= 0
780 && __collate_range_cmp(CHAR(k
), CHAR(pat
[1])) <= 0
786 if (ok
== negate_range
)
795 return(*name
== EOS
);
798 /* Free allocated data belonging to a glob_t structure. */
806 if (pglob
->gl_pathv
!= NULL
) {
807 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
808 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
811 free(pglob
->gl_pathv
);
812 pglob
->gl_pathv
= NULL
;
817 g_opendir(str
, pglob
)
821 char buf
[MAXPATHLEN
];
826 if (g_Ctoc(str
, buf
, sizeof(buf
)))
830 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
831 return((*pglob
->gl_opendir
)(buf
));
833 return(opendir(buf
));
837 g_lstat(fn
, sb
, pglob
)
842 char buf
[MAXPATHLEN
];
844 if (g_Ctoc(fn
, buf
, sizeof(buf
))) {
845 errno
= ENAMETOOLONG
;
848 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
849 return((*pglob
->gl_lstat
)(buf
, sb
));
850 return(lstat(buf
, sb
));
854 g_stat(fn
, sb
, pglob
)
859 char buf
[MAXPATHLEN
];
861 if (g_Ctoc(fn
, buf
, sizeof(buf
))) {
862 errno
= ENAMETOOLONG
;
865 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
866 return((*pglob
->gl_stat
)(buf
, sb
));
867 return(stat(buf
, sb
));
883 g_Ctoc(str
, buf
, len
)
890 if ((*buf
++ = *str
++) == '\0')
904 (void)printf("%s:\n", str
);
906 (void)printf("%c", CHAR(*p
));
909 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
912 (void)printf("%c", ismeta(*p
) ? '_' : ' ');
916 #endif /* !_NO_GLOB */