1 /* OPENBSD ORIGINAL: lib/libc/gen/glob.c */
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
44 return(sysconf(_SC_ARG_MAX
));
46 return(256); /* XXX: arbitrary */
50 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
51 !defined(GLOB_HAS_GL_MATCHC)
53 #if defined(LIBC_SCCS) && !defined(lint)
55 static char sccsid
[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
57 static char rcsid
[] = "$OpenBSD: glob.c,v 1.22 2003/06/25 21:16:47 deraadt Exp $";
59 #endif /* LIBC_SCCS and not lint */
62 * glob(3) -- a superset of the one defined in POSIX 1003.2.
64 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
66 * Optional extra services, controlled by flags not defined by POSIX:
69 * Escaping convention: \ inhibits any special meaning the following
70 * character might have (except \ at end of string is retained).
72 * Set in gl_flags if pattern contained a globbing character.
74 * Same as GLOB_NOCHECK, but it will only append pattern if it did
75 * not contain any magic characters. [Used in csh style globbing]
77 * Use alternately specified directory access functions.
79 * expand ~user/foo to the /home/dir/of/user/foo
81 * expand {1,2}{a,b} to 1a 1b 2a 2b
83 * Number of matches in the current invocation of glob.
98 #undef TILDE /* Some platforms may already define it */
100 #define UNDERSCORE '_'
108 #define M_QUOTE 0x8000
109 #define M_PROTECT 0x4000
110 #define M_MASK 0xffff
111 #define M_ASCII 0x00ff
113 typedef u_short Char
;
118 #define M_PROTECT 0x40
127 #define CHAR(c) ((Char)((c)&M_ASCII))
128 #define META(c) ((Char)((c)|M_QUOTE))
129 #define M_ALL META('*')
130 #define M_END META(']')
131 #define M_NOT META('!')
132 #define M_ONE META('?')
133 #define M_RNG META('-')
134 #define M_SET META('[')
135 #define ismeta(c) (((c)&M_QUOTE) != 0)
138 static int compare(const void *, const void *);
139 static int g_Ctoc(const Char
*, char *, u_int
);
140 static int g_lstat(Char
*, struct stat
*, glob_t
*);
141 static DIR *g_opendir(Char
*, glob_t
*);
142 static Char
*g_strchr(Char
*, int);
143 static int g_stat(Char
*, struct stat
*, glob_t
*);
144 static int glob0(const Char
*, glob_t
*);
145 static int glob1(Char
*, Char
*, glob_t
*, size_t *);
146 static int glob2(Char
*, Char
*, Char
*, Char
*, Char
*, Char
*,
148 static int glob3(Char
*, Char
*, Char
*, Char
*, Char
*, Char
*,
149 Char
*, Char
*, glob_t
*, size_t *);
150 static int globextend(const Char
*, glob_t
*, size_t *);
152 globtilde(const Char
*, Char
*, size_t, glob_t
*);
153 static int globexp1(const Char
*, glob_t
*);
154 static int globexp2(const Char
*, const Char
*, glob_t
*, int *);
155 static int match(Char
*, Char
*, Char
*);
157 static void qprintf(const char *, Char
*);
161 glob(pattern
, flags
, errfunc
, pglob
)
163 int flags
, (*errfunc
)(const char *, int);
166 const u_char
*patnext
;
168 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
];
170 patnext
= (u_char
*) pattern
;
171 if (!(flags
& GLOB_APPEND
)) {
173 pglob
->gl_pathv
= NULL
;
174 if (!(flags
& GLOB_DOOFFS
))
177 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
178 pglob
->gl_errfunc
= errfunc
;
179 pglob
->gl_matchc
= 0;
182 bufend
= bufnext
+ MAXPATHLEN
- 1;
183 if (flags
& GLOB_NOESCAPE
)
184 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
187 /* Protect the quoted characters. */
188 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
190 if ((c
= *patnext
++) == EOS
) {
194 *bufnext
++ = c
| M_PROTECT
;
200 if (flags
& GLOB_BRACE
)
201 return globexp1(patbuf
, pglob
);
203 return glob0(patbuf
, pglob
);
207 * Expand recursively a glob {} pattern. When there is no more expansion
208 * invoke the standard globbing routine to glob the rest of the magic
212 globexp1(pattern
, 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(ptr
, pattern
, pglob
, rv
)
238 const Char
*ptr
, *pattern
;
244 const Char
*pe
, *pm
, *pl
;
245 Char patbuf
[MAXPATHLEN
];
247 /* copy part up to the brace */
248 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
== LBRACKET
) {
256 /* Ignore everything between [] */
257 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
261 * We could not find a matching RBRACKET.
262 * Ignore and just look for RBRACE
266 } else if (*pe
== LBRACE
)
268 else if (*pe
== RBRACE
) {
274 /* Non matching braces; just glob the pattern */
275 if (i
!= 0 || *pe
== EOS
) {
276 *rv
= glob0(patbuf
, pglob
);
280 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++) {
283 /* Ignore everything between [] */
284 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
288 * We could not find a matching RBRACKET.
289 * Ignore and just look for RBRACE
306 if (i
&& *pm
== COMMA
)
309 /* Append the current string */
310 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
314 * Append the rest of the pattern after the
317 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
; )
320 /* Expand the current pattern */
322 qprintf("globexp2:", patbuf
);
324 *rv
= globexp1(patbuf
, pglob
);
326 /* move after the comma, to the next string */
342 * expand tilde from the passwd file.
345 globtilde(pattern
, patbuf
, patbuf_len
, pglob
)
356 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
359 /* Copy up to the end of the string or / */
360 eb
= &patbuf
[patbuf_len
- 1];
361 for (p
= pattern
+ 1, h
= (char *) patbuf
;
362 h
< (char *)eb
&& *p
&& *p
!= SLASH
; *h
++ = *p
++)
372 if (((char *) patbuf
)[0] == EOS
) {
374 * handle a plain ~ or ~/ by expanding $HOME
375 * first and then trying the password file
378 if (issetugid() != 0 || (h
= getenv("HOME")) == NULL
) {
380 if ((getuid() != geteuid()) || (h
= getenv("HOME")) == NULL
) {
381 if ((pwd
= getpwuid(getuid())) == NULL
)
390 if ((pwd
= getpwnam((char*) patbuf
)) == NULL
)
396 /* Copy the home directory */
397 for (b
= patbuf
; b
< eb
&& *h
; *b
++ = *h
++)
400 /* Append the rest of the pattern */
401 while (b
< eb
&& (*b
++ = *p
++) != EOS
)
410 * The main glob() routine: compiles the pattern (optionally processing
411 * quotes), calls glob1() to do the real pattern matching, and finally
412 * sorts the list (unless unsorted operation is requested). Returns 0
413 * if things went well, nonzero if errors occurred. It is not an error
414 * to find no matches.
417 glob0(pattern
, pglob
)
421 const Char
*qpatnext
;
422 int c
, err
, oldpathc
;
423 Char
*bufnext
, patbuf
[MAXPATHLEN
];
426 qpatnext
= globtilde(pattern
, patbuf
, MAXPATHLEN
, pglob
);
427 oldpathc
= pglob
->gl_pathc
;
430 /* We don't need to check for buffer overflow any more. */
431 while ((c
= *qpatnext
++) != EOS
) {
437 if (*qpatnext
== EOS
||
438 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
439 *bufnext
++ = LBRACKET
;
449 *bufnext
++ = CHAR(c
);
450 if (*qpatnext
== RANGE
&&
451 (c
= qpatnext
[1]) != RBRACKET
) {
453 *bufnext
++ = CHAR(c
);
456 } while ((c
= *qpatnext
++) != RBRACKET
);
457 pglob
->gl_flags
|= GLOB_MAGCHAR
;
461 pglob
->gl_flags
|= GLOB_MAGCHAR
;
465 pglob
->gl_flags
|= GLOB_MAGCHAR
;
466 /* collapse adjacent stars to one,
467 * to avoid exponential behavior
469 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
473 *bufnext
++ = CHAR(c
);
479 qprintf("glob0:", patbuf
);
482 if ((err
= glob1(patbuf
, patbuf
+MAXPATHLEN
-1, pglob
, &limit
)) != 0)
486 * If there was no match we are going to append the pattern
487 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
488 * and the pattern did not contain any magic characters
489 * GLOB_NOMAGIC is there just for compatibility with csh.
491 if (pglob
->gl_pathc
== oldpathc
) {
492 if ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
493 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
494 !(pglob
->gl_flags
& GLOB_MAGCHAR
)))
495 return(globextend(pattern
, pglob
, &limit
));
497 return(GLOB_NOMATCH
);
499 if (!(pglob
->gl_flags
& GLOB_NOSORT
))
500 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
501 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
509 return(strcmp(*(char **)p
, *(char **)q
));
513 glob1(pattern
, pattern_last
, pglob
, limitp
)
514 Char
*pattern
, *pattern_last
;
518 Char pathbuf
[MAXPATHLEN
];
520 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
523 return(glob2(pathbuf
, pathbuf
+MAXPATHLEN
-1,
524 pathbuf
, pathbuf
+MAXPATHLEN
-1,
525 pattern
, pattern_last
, pglob
, limitp
));
529 * The functions glob2 and glob3 are mutually recursive; there is one level
530 * of recursion for each segment in the pattern that contains one or more
534 glob2(pathbuf
, pathbuf_last
, pathend
, pathend_last
, pattern
,
535 pattern_last
, pglob
, limitp
)
536 Char
*pathbuf
, *pathbuf_last
, *pathend
, *pathend_last
;
537 Char
*pattern
, *pattern_last
;
546 * Loop over pattern segments until end of pattern or until
547 * segment with meta character found.
549 for (anymeta
= 0;;) {
550 if (*pattern
== EOS
) { /* End of pattern? */
552 if (g_lstat(pathbuf
, &sb
, pglob
))
555 if (((pglob
->gl_flags
& GLOB_MARK
) &&
556 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
) ||
557 (S_ISLNK(sb
.st_mode
) &&
558 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
559 S_ISDIR(sb
.st_mode
)))) {
560 if (pathend
+1 > pathend_last
)
566 return(globextend(pathbuf
, pglob
, limitp
));
569 /* Find end of next segment, copy tentatively to pathend. */
572 while (*p
!= EOS
&& *p
!= SEP
) {
575 if (q
+1 > pathend_last
)
580 if (!anymeta
) { /* No expansion, do next segment. */
583 while (*pattern
== SEP
) {
584 if (pathend
+1 > pathend_last
)
586 *pathend
++ = *pattern
++;
589 /* Need expansion, recurse. */
590 return(glob3(pathbuf
, pathbuf_last
, pathend
,
591 pathend_last
, pattern
, pattern_last
,
592 p
, pattern_last
, pglob
, limitp
));
598 glob3(pathbuf
, pathbuf_last
, pathend
, pathend_last
, pattern
, pattern_last
,
599 restpattern
, restpattern_last
, pglob
, limitp
)
600 Char
*pathbuf
, *pathbuf_last
, *pathend
, *pathend_last
;
601 Char
*pattern
, *pattern_last
, *restpattern
, *restpattern_last
;
605 register struct dirent
*dp
;
608 char buf
[MAXPATHLEN
];
611 * The readdirfunc declaration can't be prototyped, because it is
612 * assigned, below, to two functions which are prototyped in glob.h
613 * and dirent.h as taking pointers to differently typed opaque
616 struct dirent
*(*readdirfunc
)(void *);
618 if (pathend
> pathend_last
)
623 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
624 /* TODO: don't call for ENOENT or ENOTDIR? */
625 if (pglob
->gl_errfunc
) {
626 if (g_Ctoc(pathbuf
, buf
, sizeof(buf
)))
627 return(GLOB_ABORTED
);
628 if (pglob
->gl_errfunc(buf
, errno
) ||
629 pglob
->gl_flags
& GLOB_ERR
)
630 return(GLOB_ABORTED
);
637 /* Search directory for matching names. */
638 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
639 readdirfunc
= pglob
->gl_readdir
;
641 readdirfunc
= (struct dirent
*(*)(void *))readdir
;
642 while ((dp
= (*readdirfunc
)(dirp
))) {
646 /* Initial DOT must be matched literally. */
647 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
650 sc
= (u_char
*) dp
->d_name
;
651 while (dc
< pathend_last
&& (*dc
++ = *sc
++) != EOS
)
653 if (dc
>= pathend_last
) {
659 if (!match(pathend
, pattern
, restpattern
)) {
663 err
= glob2(pathbuf
, pathbuf_last
, --dc
, pathend_last
,
664 restpattern
, restpattern_last
, pglob
, limitp
);
669 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
670 (*pglob
->gl_closedir
)(dirp
);
678 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
679 * add the new item, and update gl_pathc.
681 * This assumes the BSD realloc, which only copies the block when its size
682 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
685 * Return 0 if new item added, error code if memory couldn't be allocated.
687 * Invariant of the glob_t structure:
688 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
689 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
692 globextend(path
, pglob
, limitp
)
697 register char **pathv
;
703 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
704 pathv
= pglob
->gl_pathv
? realloc((char *)pglob
->gl_pathv
, newsize
) :
707 if (pglob
->gl_pathv
) {
708 free(pglob
->gl_pathv
);
709 pglob
->gl_pathv
= NULL
;
711 return(GLOB_NOSPACE
);
714 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
715 /* first time around -- clear initial gl_offs items */
716 pathv
+= pglob
->gl_offs
;
717 for (i
= pglob
->gl_offs
; --i
>= 0; )
720 pglob
->gl_pathv
= pathv
;
722 for (p
= path
; *p
++;)
724 len
= (size_t)(p
- path
);
726 if ((copy
= malloc(len
)) != NULL
) {
727 if (g_Ctoc(path
, copy
, len
)) {
729 return(GLOB_NOSPACE
);
731 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
733 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
735 if ((pglob
->gl_flags
& GLOB_LIMIT
) &&
736 newsize
+ *limitp
>= (u_int
) get_arg_max()) {
738 return(GLOB_NOSPACE
);
741 return(copy
== NULL
? GLOB_NOSPACE
: 0);
746 * pattern matching function for filenames. Each occurrence of the *
747 * pattern causes a recursion level.
750 match(name
, pat
, patend
)
751 register Char
*name
, *pat
, *patend
;
753 int ok
, negate_range
;
756 while (pat
< patend
) {
758 switch (c
& M_MASK
) {
763 if (match(name
, pat
, patend
))
765 while (*name
++ != EOS
)
774 if ((k
= *name
++) == EOS
)
776 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
778 while (((c
= *pat
++) & M_MASK
) != M_END
)
779 if ((*pat
& M_MASK
) == M_RNG
) {
780 if (c
<= k
&& k
<= pat
[1])
785 if (ok
== negate_range
)
794 return(*name
== EOS
);
797 /* Free allocated data belonging to a glob_t structure. */
805 if (pglob
->gl_pathv
!= NULL
) {
806 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
807 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
810 free(pglob
->gl_pathv
);
811 pglob
->gl_pathv
= NULL
;
816 g_opendir(str
, pglob
)
820 char buf
[MAXPATHLEN
];
823 strlcpy(buf
, ".", sizeof buf
);
825 if (g_Ctoc(str
, buf
, sizeof(buf
)))
829 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
830 return((*pglob
->gl_opendir
)(buf
));
832 return(opendir(buf
));
836 g_lstat(fn
, sb
, pglob
)
841 char buf
[MAXPATHLEN
];
843 if (g_Ctoc(fn
, buf
, sizeof(buf
)))
845 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
846 return((*pglob
->gl_lstat
)(buf
, sb
));
847 return(lstat(buf
, sb
));
851 g_stat(fn
, sb
, pglob
)
856 char buf
[MAXPATHLEN
];
858 if (g_Ctoc(fn
, buf
, sizeof(buf
)))
860 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
861 return((*pglob
->gl_stat
)(buf
, sb
));
862 return(stat(buf
, sb
));
878 g_Ctoc(str
, buf
, len
)
879 register const Char
*str
;
885 if ((*buf
++ = *str
++) == EOS
)
899 (void)printf("%s:\n", str
);
901 (void)printf("%c", CHAR(*p
));
904 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
907 (void)printf("%c", ismeta(*p
) ? '_' : ' ');
912 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
913 !defined(GLOB_HAS_GL_MATCHC) */