1 /* $NetBSD: glob.c,v 1.1.1.2 2014/04/24 12:45:52 pettai Exp $ */
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
36 * glob(3) -- a superset of the one defined in POSIX 1003.2.
38 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
40 * Optional extra services, controlled by flags not defined by POSIX:
43 * Escaping convention: \ inhibits any special meaning the following
44 * character might have (except \ at end of string is retained).
46 * Set in gl_flags if pattern contained a globbing character.
48 * Same as GLOB_NOCHECK, but it will only append pattern if it did
49 * not contain any magic characters. [Used in csh style globbing]
51 * Use alternately specified directory access functions.
53 * expand ~user/foo to the /home/dir/of/user/foo
55 * expand {1,2}{a,b} to 1a 1b 2a 2b
57 * Number of matches in the current invocation of glob.
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h>
65 #ifdef HAVE_SYS_TYPES_H
66 #include <sys/types.h>
68 #ifdef HAVE_SYS_STAT_H
91 #include <krb5/roken.h>
94 #define ARG_MAX _POSIX_ARG_MAX
97 #define CHAR_DOLLAR '$'
100 #define CHAR_LBRACKET '['
102 #define CHAR_QUESTION '?'
103 #define CHAR_QUOTE '\\'
104 #define CHAR_RANGE '-'
105 #define CHAR_RBRACKET ']'
107 #define CHAR_STAR '*'
108 #define CHAR_TILDE '~'
109 #define CHAR_UNDERSCORE '_'
110 #define CHAR_LBRACE '{'
111 #define CHAR_RBRACE '}'
112 #define CHAR_SLASH '/'
113 #define CHAR_COMMA ','
117 #define M_QUOTE 0x8000
118 #define M_PROTECT 0x4000
119 #define M_MASK 0xffff
120 #define M_ASCII 0x00ff
122 typedef u_short Char
;
127 #define M_PROTECT 0x40
136 #define CHAR(c) ((Char)((c)&M_ASCII))
137 #define META(c) ((Char)((c)|M_QUOTE))
138 #define M_ALL META('*')
139 #define M_END META(']')
140 #define M_NOT META('!')
141 #define M_ONE META('?')
142 #define M_RNG META('-')
143 #define M_SET META('[')
144 #define ismeta(c) (((c)&M_QUOTE) != 0)
147 static int compare (const void *, const void *);
148 static void g_Ctoc (const Char
*, char *);
149 static int g_lstat (Char
*, struct stat
*, glob_t
*);
150 static DIR *g_opendir (Char
*, glob_t
*);
151 static Char
*g_strchr (const Char
*, int);
153 static Char
*g_strcat (Char
*, const Char
*);
155 static int g_stat (Char
*, struct stat
*, glob_t
*);
156 static int glob0 (const Char
*, glob_t
*);
157 static int glob1 (Char
*, glob_t
*, size_t *);
158 static int glob2 (Char
*, Char
*, Char
*, glob_t
*, size_t *);
159 static int glob3 (Char
*, Char
*, Char
*, Char
*, glob_t
*, size_t *);
160 static int globextend (const Char
*, glob_t
*, size_t *);
161 static const Char
* globtilde (const Char
*, Char
*, glob_t
*);
162 static int globexp1 (const Char
*, glob_t
*);
163 static int globexp2 (const Char
*, const Char
*, glob_t
*, int *);
164 static int match (Char
*, Char
*, Char
*);
166 static void qprintf (const char *, Char
*);
169 ROKEN_LIB_FUNCTION
int ROKEN_LIB_CALL
170 glob(const char *pattern
,
172 int (*errfunc
)(const char *, int),
175 const u_char
*patnext
;
177 Char
*bufnext
, *bufend
, patbuf
[MaxPathLen
+1];
179 patnext
= (const u_char
*) pattern
;
180 if (!(flags
& GLOB_APPEND
)) {
182 pglob
->gl_pathv
= NULL
;
183 if (!(flags
& GLOB_DOOFFS
))
186 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
187 pglob
->gl_errfunc
= errfunc
;
188 pglob
->gl_matchc
= 0;
191 bufend
= bufnext
+ MaxPathLen
;
192 if (flags
& GLOB_QUOTE
) {
193 /* Protect the quoted characters. */
194 while (bufnext
< bufend
&& (c
= *patnext
++) != CHAR_EOS
)
195 if (c
== CHAR_QUOTE
) {
196 if ((c
= *patnext
++) == CHAR_EOS
) {
200 *bufnext
++ = c
| M_PROTECT
;
206 while (bufnext
< bufend
&& (c
= *patnext
++) != CHAR_EOS
)
210 if (flags
& GLOB_BRACE
)
211 return globexp1(patbuf
, pglob
);
213 return glob0(patbuf
, pglob
);
217 * Expand recursively a glob {} pattern. When there is no more expansion
218 * invoke the standard globbing routine to glob the rest of the magic
221 static int globexp1(const Char
*pattern
, glob_t
*pglob
)
223 const Char
* ptr
= pattern
;
226 /* Protect a single {}, for find(1), like csh */
227 if (pattern
[0] == CHAR_LBRACE
&& pattern
[1] == CHAR_RBRACE
&& pattern
[2] == CHAR_EOS
)
228 return glob0(pattern
, pglob
);
230 while ((ptr
= (const Char
*) g_strchr(ptr
, CHAR_LBRACE
)) != NULL
)
231 if (!globexp2(ptr
, pattern
, pglob
, &rv
))
234 return glob0(pattern
, pglob
);
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.
243 static int globexp2(const Char
*ptr
, const Char
*pattern
,
244 glob_t
*pglob
, int *rv
)
248 const Char
*pe
, *pm
, *pl
;
249 Char patbuf
[MaxPathLen
+ 1];
251 /* copy part up to the brace */
252 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
256 /* Find the balanced brace */
257 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
258 if (*pe
== CHAR_LBRACKET
) {
259 /* Ignore everything between [] */
260 for (pm
= pe
++; *pe
!= CHAR_RBRACKET
&& *pe
!= CHAR_EOS
; pe
++)
262 if (*pe
== CHAR_EOS
) {
264 * We could not find a matching CHAR_RBRACKET.
265 * Ignore and just look for CHAR_RBRACE
270 else if (*pe
== CHAR_LBRACE
)
272 else if (*pe
== CHAR_RBRACE
) {
278 /* Non matching braces; just glob the pattern */
279 if (i
!= 0 || *pe
== CHAR_EOS
) {
280 *rv
= glob0(patbuf
, pglob
);
284 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
287 /* Ignore everything between [] */
288 for (pl
= pm
++; *pm
!= CHAR_RBRACKET
&& *pm
!= CHAR_EOS
; pm
++)
290 if (*pm
== CHAR_EOS
) {
292 * We could not find a matching CHAR_RBRACKET.
293 * Ignore and just look for CHAR_RBRACE
310 if (i
&& *pm
== CHAR_COMMA
)
313 /* Append the current string */
314 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
317 * Append the rest of the pattern after the
320 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != CHAR_EOS
;)
323 /* Expand the current pattern */
325 qprintf("globexp2:", patbuf
);
327 *rv
= globexp1(patbuf
, pglob
);
329 /* move after the comma, to the next string */
344 * expand tilde from the passwd file.
347 globtilde(const Char
*pattern
, Char
*patbuf
, glob_t
*pglob
)
354 if (*pattern
!= CHAR_TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
357 /* Copy up to the end of the string or / */
358 for (p
= pattern
+ 1, h
= (char *) patbuf
; *p
&& *p
!= CHAR_SLASH
;
364 if (((char *) patbuf
)[0] == CHAR_EOS
) {
366 * handle a plain ~ or ~/ by expanding $HOME
367 * first and then trying the password file
369 if ((h
= getenv("HOME")) == NULL
) {
370 if ((pwd
= k_getpwuid(getuid())) == NULL
)
380 if ((pwd
= k_getpwnam((char*) patbuf
)) == NULL
)
386 /* Copy the home directory */
387 for (b
= patbuf
; *h
; *b
++ = *h
++)
390 /* Append the rest of the pattern */
391 while ((*b
++ = *p
++) != CHAR_EOS
)
399 * The main glob() routine: compiles the pattern (optionally processing
400 * quotes), calls glob1() to do the real pattern matching, and finally
401 * sorts the list (unless unsorted operation is requested). Returns 0
402 * if things went well, nonzero if errors occurred. It is not an error
403 * to find no matches.
406 glob0(const Char
*pattern
, glob_t
*pglob
)
408 const Char
*qpatnext
;
409 int c
, err
, oldpathc
;
410 Char
*bufnext
, patbuf
[MaxPathLen
+1];
413 qpatnext
= globtilde(pattern
, patbuf
, pglob
);
414 oldpathc
= pglob
->gl_pathc
;
417 /* We don't need to check for buffer overflow any more. */
418 while ((c
= *qpatnext
++) != CHAR_EOS
) {
424 if (*qpatnext
== CHAR_EOS
||
425 g_strchr(qpatnext
+1, CHAR_RBRACKET
) == NULL
) {
426 *bufnext
++ = CHAR_LBRACKET
;
436 *bufnext
++ = CHAR(c
);
437 if (*qpatnext
== CHAR_RANGE
&&
438 (c
= qpatnext
[1]) != CHAR_RBRACKET
) {
440 *bufnext
++ = CHAR(c
);
443 } while ((c
= *qpatnext
++) != CHAR_RBRACKET
);
444 pglob
->gl_flags
|= GLOB_MAGCHAR
;
448 pglob
->gl_flags
|= GLOB_MAGCHAR
;
452 pglob
->gl_flags
|= GLOB_MAGCHAR
;
453 /* collapse adjacent stars to one,
454 * to avoid exponential behavior
456 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
460 *bufnext
++ = CHAR(c
);
466 qprintf("glob0:", patbuf
);
469 if ((err
= glob1(patbuf
, pglob
, &limit
)) != 0)
473 * If there was no match we are going to append the pattern
474 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
475 * and the pattern did not contain any magic characters
476 * GLOB_NOMAGIC is there just for compatibility with csh.
478 if (pglob
->gl_pathc
== oldpathc
&&
479 ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
480 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
481 !(pglob
->gl_flags
& GLOB_MAGCHAR
))))
482 return(globextend(pattern
, pglob
, &limit
));
483 else if (!(pglob
->gl_flags
& GLOB_NOSORT
))
484 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
485 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
490 compare(const void *p
, const void *q
)
492 return(strcmp(*(char **)p
, *(char **)q
));
496 glob1(Char
*pattern
, glob_t
*pglob
, size_t *limit
)
498 Char pathbuf
[MaxPathLen
+1];
500 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
501 if (*pattern
== CHAR_EOS
)
503 return(glob2(pathbuf
, pathbuf
, pattern
, pglob
, limit
));
507 * The functions glob2 and glob3 are mutually recursive; there is one level
508 * of recursion for each segment in the pattern that contains one or more
513 #if defined(S_IFLNK) && defined(S_IFMT)
514 #define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
516 #define S_ISLNK(mode) 0
521 glob2(Char
*pathbuf
, Char
*pathend
, Char
*pattern
, glob_t
*pglob
,
529 * Loop over pattern segments until end of pattern or until
530 * segment with meta character found.
532 for (anymeta
= 0;;) {
533 if (*pattern
== CHAR_EOS
) { /* End of pattern? */
535 if (g_lstat(pathbuf
, &sb
, pglob
))
538 if (((pglob
->gl_flags
& GLOB_MARK
) &&
539 pathend
[-1] != CHAR_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 *pathend
++ = CHAR_SEP
;
547 return(globextend(pathbuf
, pglob
, limit
));
550 /* Find end of next segment, copy tentatively to pathend. */
553 while (*p
!= CHAR_EOS
&& *p
!= CHAR_SEP
) {
559 if (!anymeta
) { /* No expansion, do next segment. */
562 while (*pattern
== CHAR_SEP
)
563 *pathend
++ = *pattern
++;
564 } else /* Need expansion, recurse. */
565 return(glob3(pathbuf
, pathend
, pattern
, p
, pglob
,
572 glob3(Char
*pathbuf
, Char
*pathend
, Char
*pattern
, Char
*restpattern
,
573 glob_t
*pglob
, size_t *limit
)
578 char buf
[MaxPathLen
];
581 * The readdirfunc declaration can't be prototyped, because it is
582 * assigned, below, to two functions which are prototyped in glob.h
583 * and dirent.h as taking pointers to differently typed opaque
586 struct dirent
*(*readdirfunc
)(void *);
591 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
592 /* TODO: don't call for ENOENT or ENOTDIR? */
593 if (pglob
->gl_errfunc
) {
594 g_Ctoc(pathbuf
, buf
);
595 if (pglob
->gl_errfunc(buf
, errno
) ||
596 pglob
->gl_flags
& GLOB_ERR
)
604 /* Search directory for matching names. */
605 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
606 readdirfunc
= pglob
->gl_readdir
;
608 readdirfunc
= (struct dirent
*(*)(void *))readdir
;
609 while ((dp
= (*readdirfunc
)(dirp
))) {
613 /* Initial CHAR_DOT must be matched literally. */
614 if (dp
->d_name
[0] == CHAR_DOT
&& *pattern
!= CHAR_DOT
)
616 for (sc
= (u_char
*) dp
->d_name
, dc
= pathend
;
617 (*dc
++ = *sc
++) != CHAR_EOS
;)
619 if (!match(pathend
, pattern
, restpattern
)) {
623 err
= glob2(pathbuf
, --dc
, restpattern
, pglob
, limit
);
628 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
629 (*pglob
->gl_closedir
)(dirp
);
637 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
638 * add the new item, and update gl_pathc.
640 * This assumes the BSD realloc, which only copies the block when its size
641 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
644 * Return 0 if new item added, error code if memory couldn't be allocated.
646 * Invariant of the glob_t structure:
647 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
648 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
651 globextend(const Char
*path
, glob_t
*pglob
, size_t *limit
)
659 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
660 pathv
= pglob
->gl_pathv
?
661 realloc(pglob
->gl_pathv
, newsize
) :
664 return(GLOB_NOSPACE
);
666 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
667 /* first time around -- clear initial gl_offs items */
668 pathv
+= pglob
->gl_offs
;
669 for (i
= pglob
->gl_offs
; --i
>= 0; )
672 pglob
->gl_pathv
= pathv
;
674 for (p
= path
; *p
++;)
676 len
= (size_t)(p
- path
);
678 if ((copy
= malloc(len
)) != NULL
) {
680 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
682 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
684 if ((pglob
->gl_flags
& GLOB_LIMIT
) && (newsize
+ *limit
) >= ARG_MAX
) {
686 return(GLOB_NOSPACE
);
689 return(copy
== NULL
? GLOB_NOSPACE
: 0);
694 * pattern matching function for filenames. Each occurrence of the *
695 * pattern causes a recursion level.
698 match(Char
*name
, Char
*pat
, Char
*patend
)
700 int ok
, negate_range
;
703 while (pat
< patend
) {
705 switch (c
& M_MASK
) {
710 if (match(name
, pat
, patend
))
712 while (*name
++ != CHAR_EOS
);
715 if (*name
++ == CHAR_EOS
)
720 if ((k
= *name
++) == CHAR_EOS
)
722 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != CHAR_EOS
)
724 while (((c
= *pat
++) & M_MASK
) != M_END
)
725 if ((*pat
& M_MASK
) == M_RNG
) {
726 if (c
<= k
&& k
<= pat
[1])
731 if (ok
== negate_range
)
740 return(*name
== CHAR_EOS
);
743 /* Free allocated data belonging to a glob_t structure. */
744 ROKEN_LIB_FUNCTION
void ROKEN_LIB_CALL
745 globfree(glob_t
*pglob
)
750 if (pglob
->gl_pathv
!= NULL
) {
751 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
752 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
755 free(pglob
->gl_pathv
);
756 pglob
->gl_pathv
= NULL
;
761 g_opendir(Char
*str
, glob_t
*pglob
)
763 char buf
[MaxPathLen
];
766 strlcpy(buf
, ".", sizeof(buf
));
770 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
771 return((*pglob
->gl_opendir
)(buf
));
773 return(opendir(buf
));
777 g_lstat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
779 char buf
[MaxPathLen
];
782 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
783 return((*pglob
->gl_lstat
)(buf
, sb
));
784 return(lstat(buf
, sb
));
788 g_stat(Char
*fn
, struct stat
*sb
, glob_t
*pglob
)
790 char buf
[MaxPathLen
];
793 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
794 return((*pglob
->gl_stat
)(buf
, sb
));
795 return(stat(buf
, sb
));
799 g_strchr(const Char
*str
, int ch
)
810 g_strcat(Char
*dst
, const Char
*src
)
817 while((*dst
++ = *src
++) != CHAR_EOS
)
825 g_Ctoc(const Char
*str
, char *buf
)
829 for (dc
= buf
; (*dc
++ = *str
++) != CHAR_EOS
;)
835 qprintf(const Char
*str
, Char
*s
)
839 printf("%s:\n", str
);
841 printf("%c", CHAR(*p
));
844 printf("%c", *p
& M_PROTECT
? '"' : ' ');
847 printf("%c", ismeta(*p
) ? '_' : ' ');