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
37 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid
[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
41 static char rcsid
[] = "$OpenBSD: glob.c,v 1.8 1998/08/14 21:39:30 deraadt Exp $";
43 #endif /* LIBC_SCCS and not lint */
46 * glob(3) -- a superset of the one defined in POSIX 1003.2.
48 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
50 * Optional extra services, controlled by flags not defined by POSIX:
53 * Escaping convention: \ inhibits any special meaning the following
54 * character might have (except \ at end of string is retained).
56 * Set in gl_flags if pattern contained a globbing character.
58 * Same as GLOB_NOCHECK, but it will only append pattern if it did
59 * not contain any magic characters. [Used in csh style globbing]
61 * Use alternately specified directory access functions.
63 * expand ~user/foo to the /home/dir/of/user/foo
65 * expand {1,2}{a,b} to 1a 1b 2a 2b
67 * Number of matches in the current invocation of glob.
72 #include <sys/param.h>
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 void g_Ctoc (const Char
*, char *);
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);
148 static Char
*g_strcat (Char
*, const Char
*);
150 static int g_stat (Char
*, struct stat
*, glob_t
*);
151 static int glob0 (const Char
*, glob_t
*);
152 static int glob1 (Char
*, glob_t
*);
153 static int glob2 (Char
*, Char
*, Char
*, glob_t
*);
154 static int glob3 (Char
*, Char
*, Char
*, Char
*, glob_t
*);
155 static int globextend (const Char
*, glob_t
*);
156 static const Char
* 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 openbsd_glob(pattern
, flags
, errfunc
, pglob
)
167 int flags
, (*errfunc
) __P((const char *, int));
170 const u_char
*patnext
;
172 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
+1];
174 patnext
= (u_char
*) pattern
;
175 if (!(flags
& GLOB_APPEND
)) {
177 pglob
->gl_pathv
= NULL
;
178 if (!(flags
& GLOB_DOOFFS
))
181 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
182 pglob
->gl_errfunc
= errfunc
;
183 pglob
->gl_matchc
= 0;
186 bufend
= bufnext
+ MAXPATHLEN
;
187 if (flags
& GLOB_NOESCAPE
)
188 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
191 /* Protect the quoted characters. */
192 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
194 if ((c
= *patnext
++) == EOS
) {
198 *bufnext
++ = c
| M_PROTECT
;
205 if (flags
& GLOB_BRACE
)
206 return globexp1(patbuf
, pglob
);
208 return glob0(patbuf
, pglob
);
212 * Expand recursively a glob {} pattern. When there is no more expansion
213 * invoke the standard globbing routine to glob the rest of the magic
216 static int globexp1(pattern
, pglob
)
220 const Char
* ptr
= pattern
;
223 /* Protect a single {}, for find(1), like csh */
224 if (pattern
[0] == LBRACE
&& pattern
[1] == RBRACE
&& pattern
[2] == EOS
)
225 return glob0(pattern
, pglob
);
227 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, 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(ptr
, pattern
, pglob
, rv
)
241 const Char
*ptr
, *pattern
;
247 const Char
*pe
, *pm
, *pl
;
248 Char patbuf
[MAXPATHLEN
+ 1];
250 /* copy part up to the brace */
251 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
255 /* Find the balanced brace */
256 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
257 if (*pe
== LBRACKET
) {
258 /* Ignore everything between [] */
259 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
263 * We could not find a matching RBRACKET.
264 * Ignore and just look for RBRACE
269 else if (*pe
== LBRACE
)
271 else if (*pe
== RBRACE
) {
277 /* Non matching braces; just glob the pattern */
278 if (i
!= 0 || *pe
== EOS
) {
279 *rv
= glob0(patbuf
, pglob
);
283 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
286 /* Ignore everything between [] */
287 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
291 * We could not find a matching RBRACKET.
292 * Ignore and just look for RBRACE
309 if (i
&& *pm
== COMMA
)
312 /* Append the current string */
313 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
316 * Append the rest of the pattern after the
319 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
;)
322 /* Expand the current pattern */
324 qprintf("globexp2:", patbuf
);
326 *rv
= globexp1(patbuf
, pglob
);
328 /* move after the comma, to the next string */
343 * expand tilde from the passwd file.
346 globtilde(pattern
, patbuf
, patbuf_len
, pglob
)
357 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
360 /* Copy up to the end of the string or / */
361 eb
= &patbuf
[patbuf_len
- 1];
362 for (p
= pattern
+ 1, h
= (char *) patbuf
;
363 h
< (char *)eb
&& *p
&& *p
!= SLASH
; *h
++ = *p
++)
368 if (((char *) patbuf
)[0] == EOS
) {
370 * handle a plain ~ or ~/ by expanding $HOME
371 * first and then trying the password file
373 #ifdef HAVE_ISSETUGID
374 if (issetugid() != 0 || (h
= getenv("HOME")) == NULL
) {
376 if ((pwd
= getpwuid(getuid())) == NULL
)
380 #ifdef HAVE_ISSETUGID
388 if ((pwd
= getpwnam((char*) patbuf
)) == NULL
)
394 /* Copy the home directory */
395 for (b
= patbuf
; b
< eb
&& *h
; *b
++ = *h
++)
398 /* Append the rest of the pattern */
399 while (b
< eb
&& (*b
++ = *p
++) != EOS
)
408 * The main glob() routine: compiles the pattern (optionally processing
409 * quotes), calls glob1() to do the real pattern matching, and finally
410 * sorts the list (unless unsorted operation is requested). Returns 0
411 * if things went well, nonzero if errors occurred. It is not an error
412 * to find no matches.
415 glob0(pattern
, pglob
)
419 const Char
*qpatnext
;
420 int c
, err
, oldpathc
;
421 Char
*bufnext
, patbuf
[MAXPATHLEN
+1];
423 qpatnext
= globtilde(pattern
, patbuf
, sizeof(patbuf
) / sizeof(Char
),
425 oldpathc
= pglob
->gl_pathc
;
428 /* We don't need to check for buffer overflow any more. */
429 while ((c
= *qpatnext
++) != EOS
) {
435 if (*qpatnext
== EOS
||
436 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
437 *bufnext
++ = LBRACKET
;
447 *bufnext
++ = CHAR(c
);
448 if (*qpatnext
== RANGE
&&
449 (c
= qpatnext
[1]) != RBRACKET
) {
451 *bufnext
++ = CHAR(c
);
454 } while ((c
= *qpatnext
++) != RBRACKET
);
455 pglob
->gl_flags
|= GLOB_MAGCHAR
;
459 pglob
->gl_flags
|= GLOB_MAGCHAR
;
463 pglob
->gl_flags
|= GLOB_MAGCHAR
;
464 /* collapse adjacent stars to one,
465 * to avoid exponential behavior
467 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
471 *bufnext
++ = CHAR(c
);
477 qprintf("glob0:", patbuf
);
480 if ((err
= glob1(patbuf
, pglob
)) != 0)
484 * If there was no match we are going to append the pattern
485 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
486 * and the pattern did not contain any magic characters
487 * GLOB_NOMAGIC is there just for compatibility with csh.
489 if (pglob
->gl_pathc
== oldpathc
) {
490 if ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
491 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
492 !(pglob
->gl_flags
& GLOB_MAGCHAR
)))
493 return(globextend(pattern
, pglob
));
495 return(GLOB_NOMATCH
);
497 if (!(pglob
->gl_flags
& GLOB_NOSORT
))
498 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
499 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
507 return(strcmp(*(char **)p
, *(char **)q
));
511 glob1(pattern
, pglob
)
515 Char pathbuf
[MAXPATHLEN
+1];
517 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
520 return(glob2(pathbuf
, pathbuf
, pattern
, pglob
));
524 * The functions glob2 and glob3 are mutually recursive; there is one level
525 * of recursion for each segment in the pattern that contains one or more
529 glob2(pathbuf
, pathend
, pattern
, pglob
)
530 Char
*pathbuf
, *pathend
, *pattern
;
538 * Loop over pattern segments until end of pattern or until
539 * segment with meta character found.
541 for (anymeta
= 0;;) {
542 if (*pattern
== EOS
) { /* End of pattern? */
544 if (g_lstat(pathbuf
, &sb
, pglob
))
547 if (((pglob
->gl_flags
& GLOB_MARK
) &&
548 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
)
549 || (S_ISLNK(sb
.st_mode
) &&
550 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
551 S_ISDIR(sb
.st_mode
)))) {
556 return(globextend(pathbuf
, pglob
));
559 /* Find end of next segment, copy tentatively to pathend. */
562 while (*p
!= EOS
&& *p
!= SEP
) {
568 if (!anymeta
) { /* No expansion, do next segment. */
571 while (*pattern
== SEP
)
572 *pathend
++ = *pattern
++;
573 } else /* Need expansion, recurse. */
574 return(glob3(pathbuf
, pathend
, pattern
, p
, pglob
));
580 glob3(pathbuf
, pathend
, pattern
, restpattern
, pglob
)
581 Char
*pathbuf
, *pathend
, *pattern
, *restpattern
;
584 register struct dirent
*dp
;
587 char buf
[MAXPATHLEN
];
590 * The readdirfunc declaration can't be prototyped, because it is
591 * assigned, below, to two functions which are prototyped in glob.h
592 * and dirent.h as taking pointers to differently typed opaque
595 struct dirent
*(*readdirfunc
)();
600 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
601 /* TODO: don't call for ENOENT or ENOTDIR? */
602 if (pglob
->gl_errfunc
) {
603 g_Ctoc(pathbuf
, buf
);
604 if (pglob
->gl_errfunc(buf
, errno
) ||
605 pglob
->gl_flags
& GLOB_ERR
)
606 return (GLOB_ABORTED
);
613 /* Search directory for matching names. */
614 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
615 readdirfunc
= pglob
->gl_readdir
;
617 readdirfunc
= readdir
;
618 while ((dp
= (*readdirfunc
)(dirp
))) {
622 /* Initial DOT must be matched literally. */
623 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
625 for (sc
= (u_char
*) dp
->d_name
, dc
= pathend
;
626 (*dc
++ = *sc
++) != EOS
;)
628 if (!match(pathend
, pattern
, restpattern
)) {
632 err
= glob2(pathbuf
, --dc
, restpattern
, pglob
);
637 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
638 (*pglob
->gl_closedir
)(dirp
);
646 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
647 * add the new item, and update gl_pathc.
649 * This assumes the BSD realloc, which only copies the block when its size
650 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
653 * Return 0 if new item added, error code if memory couldn't be allocated.
655 * Invariant of the glob_t structure:
656 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
657 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
660 globextend(path
, pglob
)
664 register char **pathv
;
670 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
671 pathv
= pglob
->gl_pathv
?
672 realloc((char *)pglob
->gl_pathv
, newsize
) :
676 free(pglob
->gl_pathv
);
677 return(GLOB_NOSPACE
);
680 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
681 /* first time around -- clear initial gl_offs items */
682 pathv
+= pglob
->gl_offs
;
683 for (i
= pglob
->gl_offs
; --i
>= 0; )
686 pglob
->gl_pathv
= pathv
;
688 for (p
= path
; *p
++;)
690 if ((copy
= malloc(p
- path
)) != NULL
) {
692 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
694 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
695 return(copy
== NULL
? GLOB_NOSPACE
: 0);
700 * pattern matching function for filenames. Each occurrence of the *
701 * pattern causes a recursion level.
704 match(name
, pat
, patend
)
705 register Char
*name
, *pat
, *patend
;
707 int ok
, negate_range
;
710 while (pat
< patend
) {
712 switch (c
& M_MASK
) {
717 if (match(name
, pat
, patend
))
719 while (*name
++ != EOS
);
727 if ((k
= *name
++) == EOS
)
729 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
731 while (((c
= *pat
++) & M_MASK
) != M_END
)
732 if ((*pat
& M_MASK
) == M_RNG
) {
733 if (c
<= k
&& k
<= pat
[1])
738 if (ok
== negate_range
)
747 return(*name
== EOS
);
750 /* Free allocated data belonging to a glob_t structure. */
752 openbsd_globfree(pglob
)
758 if (pglob
->gl_pathv
!= NULL
) {
759 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
760 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
763 free(pglob
->gl_pathv
);
768 g_opendir(str
, pglob
)
772 char buf
[MAXPATHLEN
];
779 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
780 return((*pglob
->gl_opendir
)(buf
));
782 return(opendir(buf
));
786 g_lstat(fn
, sb
, pglob
)
791 char buf
[MAXPATHLEN
];
794 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
795 return((*pglob
->gl_lstat
)(buf
, sb
));
796 return(lstat(buf
, sb
));
800 g_stat(fn
, sb
, pglob
)
805 char buf
[MAXPATHLEN
];
808 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
809 return((*pglob
->gl_stat
)(buf
, sb
));
810 return(stat(buf
, sb
));
836 while((*dst
++ = *src
++) != EOS
)
845 register const Char
*str
;
850 for (dc
= buf
; (*dc
++ = *str
++) != EOS
;)
862 (void)printf("%s:\n", str
);
864 (void)printf("%c", CHAR(*p
));
867 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
870 (void)printf("%c", ismeta(*p
) ? '_' : ' ');