1 /* $OpenBSD: glob.c,v 1.25 2005/08/08 08:05:34 espie Exp $ */
3 * Copyright (c) 1989, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 /* OPENBSD ORIGINAL: lib/libc/gen/glob.c */
38 #include <sys/types.h>
49 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
50 !defined(GLOB_HAS_GL_MATCHC) || \
51 !defined(HAVE_DECL_GLOB_NOMATCH) || HAVE_DECL_GLOB_NOMATCH == 0
58 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
59 return(sysconf(_SC_ARG_MAX
));
61 return(256); /* XXX: arbitrary */
66 * glob(3) -- a superset of the one defined in POSIX 1003.2.
68 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
70 * Optional extra services, controlled by flags not defined by POSIX:
73 * Escaping convention: \ inhibits any special meaning the following
74 * character might have (except \ at end of string is retained).
76 * Set in gl_flags if pattern contained a globbing character.
78 * Same as GLOB_NOCHECK, but it will only append pattern if it did
79 * not contain any magic characters. [Used in csh style globbing]
81 * Use alternately specified directory access functions.
83 * expand ~user/foo to the /home/dir/of/user/foo
85 * expand {1,2}{a,b} to 1a 1b 2a 2b
87 * Number of matches in the current invocation of glob.
102 #undef TILDE /* Some platforms may already define it */
104 #define UNDERSCORE '_'
112 #define M_QUOTE 0x8000
113 #define M_PROTECT 0x4000
114 #define M_MASK 0xffff
115 #define M_ASCII 0x00ff
117 typedef u_short Char
;
122 #define M_PROTECT 0x40
131 #define CHAR(c) ((Char)((c)&M_ASCII))
132 #define META(c) ((Char)((c)|M_QUOTE))
133 #define M_ALL META('*')
134 #define M_END META(']')
135 #define M_NOT META('!')
136 #define M_ONE META('?')
137 #define M_RNG META('-')
138 #define M_SET META('[')
139 #define ismeta(c) (((c)&M_QUOTE) != 0)
142 static int compare(const void *, const void *);
143 static int g_Ctoc(const Char
*, char *, u_int
);
144 static int g_lstat(Char
*, struct stat
*, glob_t
*);
145 static DIR *g_opendir(Char
*, glob_t
*);
146 static Char
*g_strchr(Char
*, int);
147 static int g_stat(Char
*, struct stat
*, glob_t
*);
148 static int glob0(const Char
*, glob_t
*);
149 static int glob1(Char
*, Char
*, glob_t
*, size_t *);
150 static int glob2(Char
*, Char
*, Char
*, Char
*, Char
*, Char
*,
152 static int glob3(Char
*, Char
*, Char
*, Char
*, Char
*, Char
*,
153 Char
*, Char
*, glob_t
*, size_t *);
154 static int globextend(const Char
*, glob_t
*, size_t *);
156 globtilde(const Char
*, Char
*, size_t, glob_t
*);
157 static int globexp1(const Char
*, glob_t
*);
158 static int globexp2(const Char
*, const Char
*, glob_t
*, int *);
159 static int match(Char
*, Char
*, Char
*);
161 static void qprintf(const char *, Char
*);
165 glob(const char *pattern
, int flags
, int (*errfunc
)(const char *, int),
168 const u_char
*patnext
;
170 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
];
172 patnext
= (u_char
*) pattern
;
173 if (!(flags
& GLOB_APPEND
)) {
175 pglob
->gl_pathv
= NULL
;
176 if (!(flags
& GLOB_DOOFFS
))
179 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
180 pglob
->gl_errfunc
= errfunc
;
181 pglob
->gl_matchc
= 0;
184 bufend
= bufnext
+ MAXPATHLEN
- 1;
185 if (flags
& GLOB_NOESCAPE
)
186 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
189 /* Protect the quoted characters. */
190 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
192 if ((c
= *patnext
++) == EOS
) {
196 *bufnext
++ = c
| M_PROTECT
;
202 if (flags
& GLOB_BRACE
)
203 return globexp1(patbuf
, pglob
);
205 return glob0(patbuf
, pglob
);
209 * Expand recursively a glob {} pattern. When there is no more expansion
210 * invoke the standard globbing routine to glob the rest of the magic
214 globexp1(const Char
*pattern
, glob_t
*pglob
)
216 const Char
* ptr
= pattern
;
219 /* Protect a single {}, for find(1), like csh */
220 if (pattern
[0] == LBRACE
&& pattern
[1] == RBRACE
&& pattern
[2] == EOS
)
221 return glob0(pattern
, pglob
);
223 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, LBRACE
)) != NULL
)
224 if (!globexp2(ptr
, pattern
, pglob
, &rv
))
227 return glob0(pattern
, pglob
);
232 * Recursive brace globbing helper. Tries to expand a single brace.
233 * If it succeeds then it invokes globexp1 with the new pattern.
234 * If it fails then it tries to glob the rest of the pattern and returns.
237 globexp2(const Char
*ptr
, const Char
*pattern
, glob_t
*pglob
, int *rv
)
241 const Char
*pe
, *pm
, *pl
;
242 Char patbuf
[MAXPATHLEN
];
244 /* copy part up to the brace */
245 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
250 /* Find the balanced brace */
251 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
252 if (*pe
== LBRACKET
) {
253 /* Ignore everything between [] */
254 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
258 * We could not find a matching RBRACKET.
259 * Ignore and just look for RBRACE
263 } else if (*pe
== LBRACE
)
265 else if (*pe
== RBRACE
) {
271 /* Non matching braces; just glob the pattern */
272 if (i
!= 0 || *pe
== EOS
) {
273 *rv
= glob0(patbuf
, pglob
);
277 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++) {
280 /* Ignore everything between [] */
281 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
285 * We could not find a matching RBRACKET.
286 * Ignore and just look for RBRACE
303 if (i
&& *pm
== COMMA
)
306 /* Append the current string */
307 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
311 * Append the rest of the pattern after the
314 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
; )
317 /* Expand the current pattern */
319 qprintf("globexp2:", patbuf
);
321 *rv
= globexp1(patbuf
, pglob
);
323 /* move after the comma, to the next string */
339 * expand tilde from the passwd file.
342 globtilde(const Char
*pattern
, Char
*patbuf
, size_t patbuf_len
, glob_t
*pglob
)
349 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
352 /* Copy up to the end of the string or / */
353 eb
= &patbuf
[patbuf_len
- 1];
354 for (p
= pattern
+ 1, h
= (char *) patbuf
;
355 h
< (char *)eb
&& *p
&& *p
!= SLASH
; *h
++ = *p
++)
365 if (((char *) patbuf
)[0] == EOS
) {
367 * handle a plain ~ or ~/ by expanding $HOME
368 * first and then trying the password file
371 if (issetugid() != 0 || (h
= getenv("HOME")) == NULL
) {
373 if ((getuid() != geteuid()) || (h
= getenv("HOME")) == NULL
) {
374 if ((pwd
= getpwuid(getuid())) == NULL
)
383 if ((pwd
= getpwnam((char*) patbuf
)) == NULL
)
389 /* Copy the home directory */
390 for (b
= patbuf
; b
< eb
&& *h
; *b
++ = *h
++)
393 /* Append the rest of the pattern */
394 while (b
< eb
&& (*b
++ = *p
++) != EOS
)
403 * The main glob() routine: compiles the pattern (optionally processing
404 * quotes), calls glob1() to do the real pattern matching, and finally
405 * sorts the list (unless unsorted operation is requested). Returns 0
406 * if things went well, nonzero if errors occurred. It is not an error
407 * to find no matches.
410 glob0(const Char
*pattern
, glob_t
*pglob
)
412 const Char
*qpatnext
;
413 int c
, err
, oldpathc
;
414 Char
*bufnext
, patbuf
[MAXPATHLEN
];
417 qpatnext
= globtilde(pattern
, patbuf
, MAXPATHLEN
, pglob
);
418 oldpathc
= pglob
->gl_pathc
;
421 /* We don't need to check for buffer overflow any more. */
422 while ((c
= *qpatnext
++) != EOS
) {
428 if (*qpatnext
== EOS
||
429 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
430 *bufnext
++ = LBRACKET
;
440 *bufnext
++ = CHAR(c
);
441 if (*qpatnext
== RANGE
&&
442 (c
= qpatnext
[1]) != RBRACKET
) {
444 *bufnext
++ = CHAR(c
);
447 } while ((c
= *qpatnext
++) != RBRACKET
);
448 pglob
->gl_flags
|= GLOB_MAGCHAR
;
452 pglob
->gl_flags
|= GLOB_MAGCHAR
;
456 pglob
->gl_flags
|= GLOB_MAGCHAR
;
457 /* collapse adjacent stars to one,
458 * to avoid exponential behavior
460 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
464 *bufnext
++ = CHAR(c
);
470 qprintf("glob0:", patbuf
);
473 if ((err
= glob1(patbuf
, patbuf
+MAXPATHLEN
-1, pglob
, &limit
)) != 0)
477 * If there was no match we are going to append the pattern
478 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
479 * and the pattern did not contain any magic characters
480 * GLOB_NOMAGIC is there just for compatibility with csh.
482 if (pglob
->gl_pathc
== oldpathc
) {
483 if ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
484 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
485 !(pglob
->gl_flags
& GLOB_MAGCHAR
)))
486 return(globextend(pattern
, pglob
, &limit
));
488 return(GLOB_NOMATCH
);
490 if (!(pglob
->gl_flags
& GLOB_NOSORT
))
491 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
492 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
497 compare(const void *p
, const void *q
)
499 return(strcmp(*(char **)p
, *(char **)q
));
503 glob1(Char
*pattern
, Char
*pattern_last
, glob_t
*pglob
, size_t *limitp
)
505 Char pathbuf
[MAXPATHLEN
];
507 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
510 return(glob2(pathbuf
, pathbuf
+MAXPATHLEN
-1,
511 pathbuf
, pathbuf
+MAXPATHLEN
-1,
512 pattern
, pattern_last
, pglob
, limitp
));
516 * The functions glob2 and glob3 are mutually recursive; there is one level
517 * of recursion for each segment in the pattern that contains one or more
521 glob2(Char
*pathbuf
, Char
*pathbuf_last
, Char
*pathend
, Char
*pathend_last
,
522 Char
*pattern
, Char
*pattern_last
, glob_t
*pglob
, size_t *limitp
)
529 * Loop over pattern segments until end of pattern or until
530 * segment with meta character found.
532 for (anymeta
= 0;;) {
533 if (*pattern
== EOS
) { /* End of pattern? */
535 if (g_lstat(pathbuf
, &sb
, pglob
))
538 if (((pglob
->gl_flags
& GLOB_MARK
) &&
539 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
) ||
540 (S_ISLNK(sb
.st_mode
) &&
541 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
542 S_ISDIR(sb
.st_mode
)))) {
543 if (pathend
+1 > pathend_last
)
549 return(globextend(pathbuf
, pglob
, limitp
));
552 /* Find end of next segment, copy tentatively to pathend. */
555 while (*p
!= EOS
&& *p
!= SEP
) {
558 if (q
+1 > pathend_last
)
563 if (!anymeta
) { /* No expansion, do next segment. */
566 while (*pattern
== SEP
) {
567 if (pathend
+1 > pathend_last
)
569 *pathend
++ = *pattern
++;
572 /* Need expansion, recurse. */
573 return(glob3(pathbuf
, pathbuf_last
, pathend
,
574 pathend_last
, pattern
, pattern_last
,
575 p
, pattern_last
, pglob
, limitp
));
581 glob3(Char
*pathbuf
, Char
*pathbuf_last
, Char
*pathend
, Char
*pathend_last
,
582 Char
*pattern
, Char
*pattern_last
, Char
*restpattern
,
583 Char
*restpattern_last
, glob_t
*pglob
, size_t *limitp
)
588 char buf
[MAXPATHLEN
];
591 * The readdirfunc declaration can't be prototyped, because it is
592 * assigned, below, to two functions which are prototyped in glob.h
593 * and dirent.h as taking pointers to differently typed opaque
596 struct dirent
*(*readdirfunc
)(void *);
598 if (pathend
> pathend_last
)
603 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
604 /* TODO: don't call for ENOENT or ENOTDIR? */
605 if (pglob
->gl_errfunc
) {
606 if (g_Ctoc(pathbuf
, buf
, sizeof(buf
)))
607 return(GLOB_ABORTED
);
608 if (pglob
->gl_errfunc(buf
, errno
) ||
609 pglob
->gl_flags
& GLOB_ERR
)
610 return(GLOB_ABORTED
);
617 /* Search directory for matching names. */
618 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
619 readdirfunc
= pglob
->gl_readdir
;
621 readdirfunc
= (struct dirent
*(*)(void *))readdir
;
622 while ((dp
= (*readdirfunc
)(dirp
))) {
626 /* Initial DOT must be matched literally. */
627 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
630 sc
= (u_char
*) dp
->d_name
;
631 while (dc
< pathend_last
&& (*dc
++ = *sc
++) != EOS
)
633 if (dc
>= pathend_last
) {
639 if (!match(pathend
, pattern
, restpattern
)) {
643 err
= glob2(pathbuf
, pathbuf_last
, --dc
, pathend_last
,
644 restpattern
, restpattern_last
, pglob
, limitp
);
649 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
650 (*pglob
->gl_closedir
)(dirp
);
658 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
659 * add the new item, and update gl_pathc.
661 * This assumes the BSD realloc, which only copies the block when its size
662 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
665 * Return 0 if new item added, error code if memory couldn't be allocated.
667 * Invariant of the glob_t structure:
668 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
669 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
672 globextend(const Char
*path
, glob_t
*pglob
, size_t *limitp
)
680 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
681 pathv
= pglob
->gl_pathv
? realloc((char *)pglob
->gl_pathv
, newsize
) :
684 if (pglob
->gl_pathv
) {
685 free(pglob
->gl_pathv
);
686 pglob
->gl_pathv
= NULL
;
688 return(GLOB_NOSPACE
);
691 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
692 /* first time around -- clear initial gl_offs items */
693 pathv
+= pglob
->gl_offs
;
694 for (i
= pglob
->gl_offs
; --i
>= 0; )
697 pglob
->gl_pathv
= pathv
;
699 for (p
= path
; *p
++;)
701 len
= (size_t)(p
- path
);
703 if ((copy
= malloc(len
)) != NULL
) {
704 if (g_Ctoc(path
, copy
, len
)) {
706 return(GLOB_NOSPACE
);
708 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
710 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
712 if ((pglob
->gl_flags
& GLOB_LIMIT
) &&
713 newsize
+ *limitp
>= (u_int
) get_arg_max()) {
715 return(GLOB_NOSPACE
);
718 return(copy
== NULL
? GLOB_NOSPACE
: 0);
723 * pattern matching function for filenames. Each occurrence of the *
724 * pattern causes a recursion level.
727 match(Char
*name
, Char
*pat
, Char
*patend
)
729 int ok
, negate_range
;
732 while (pat
< patend
) {
734 switch (c
& M_MASK
) {
739 if (match(name
, pat
, patend
))
741 } while (*name
++ != EOS
);
749 if ((k
= *name
++) == EOS
)
751 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
753 while (((c
= *pat
++) & M_MASK
) != M_END
)
754 if ((*pat
& M_MASK
) == M_RNG
) {
755 if (c
<= k
&& k
<= pat
[1])
760 if (ok
== negate_range
)
769 return(*name
== EOS
);
772 /* Free allocated data belonging to a glob_t structure. */
774 globfree(glob_t
*pglob
)
779 if (pglob
->gl_pathv
!= NULL
) {
780 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
781 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
784 free(pglob
->gl_pathv
);
785 pglob
->gl_pathv
= NULL
;
790 g_opendir(Char
*str
, glob_t
*pglob
)
792 char buf
[MAXPATHLEN
];
795 strlcpy(buf
, ".", sizeof buf
);
797 if (g_Ctoc(str
, buf
, sizeof(buf
)))
801 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
802 return((*pglob
->gl_opendir
)(buf
));
804 return(opendir(buf
));
808 g_lstat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
810 char buf
[MAXPATHLEN
];
812 if (g_Ctoc(fn
, buf
, sizeof(buf
)))
814 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
815 return((*pglob
->gl_lstat
)(buf
, sb
));
816 return(lstat(buf
, sb
));
820 g_stat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
822 char buf
[MAXPATHLEN
];
824 if (g_Ctoc(fn
, buf
, sizeof(buf
)))
826 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
827 return((*pglob
->gl_stat
)(buf
, sb
));
828 return(stat(buf
, sb
));
832 g_strchr(Char
*str
, int ch
)
842 g_Ctoc(const Char
*str
, char *buf
, u_int len
)
846 if ((*buf
++ = *str
++) == EOS
)
854 qprintf(const char *str
, Char
*s
)
858 (void)printf("%s:\n", str
);
860 (void)printf("%c", CHAR(*p
));
863 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
866 (void)printf("%c", ismeta(*p
) ? '_' : ' ');
871 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
872 !defined(GLOB_HAS_GL_MATCHC) */