- (djm) [defines.h] Add IP DSCP defines
[openssh-git.git] / openbsd-compat / glob.c
blobe52bef7298152882fe41dd8f39ae6bcd81dc4cb0
1 /* $OpenBSD: glob.c,v 1.33 2010/09/26 22:15:39 djm Exp $ */
2 /*
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
7 * Guido van Rossum.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
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
31 * SUCH DAMAGE.
34 /* OPENBSD ORIGINAL: lib/libc/gen/glob.c */
37 * glob(3) -- a superset of the one defined in POSIX 1003.2.
39 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
41 * Optional extra services, controlled by flags not defined by POSIX:
43 * GLOB_QUOTE:
44 * Escaping convention: \ inhibits any special meaning the following
45 * character might have (except \ at end of string is retained).
46 * GLOB_MAGCHAR:
47 * Set in gl_flags if pattern contained a globbing character.
48 * GLOB_NOMAGIC:
49 * Same as GLOB_NOCHECK, but it will only append pattern if it did
50 * not contain any magic characters. [Used in csh style globbing]
51 * GLOB_ALTDIRFUNC:
52 * Use alternately specified directory access functions.
53 * GLOB_TILDE:
54 * expand ~user/foo to the /home/dir/of/user/foo
55 * GLOB_BRACE:
56 * expand {1,2}{a,b} to 1a 1b 2a 2b
57 * gl_matchc:
58 * Number of matches in the current invocation of glob.
61 #include "includes.h"
63 #include <sys/types.h>
64 #include <sys/stat.h>
66 #include <dirent.h>
67 #include <ctype.h>
68 #include <errno.h>
69 #include <pwd.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
74 #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
75 !defined(GLOB_HAS_GL_MATCHC) || !defined(GLOB_HAS_GL_STATV) || \
76 !defined(HAVE_DECL_GLOB_NOMATCH) || HAVE_DECL_GLOB_NOMATCH == 0 || \
77 defined(BROKEN_GLOB)
79 static long
80 get_arg_max(void)
82 #ifdef ARG_MAX
83 return(ARG_MAX);
84 #elif defined(HAVE_SYSCONF) && defined(_SC_ARG_MAX)
85 return(sysconf(_SC_ARG_MAX));
86 #else
87 return(256); /* XXX: arbitrary */
88 #endif
91 #include "charclass.h"
93 #define DOLLAR '$'
94 #define DOT '.'
95 #define EOS '\0'
96 #define LBRACKET '['
97 #define NOT '!'
98 #define QUESTION '?'
99 #define QUOTE '\\'
100 #define RANGE '-'
101 #define RBRACKET ']'
102 #define SEP '/'
103 #define STAR '*'
104 #define TILDE '~'
105 #define UNDERSCORE '_'
106 #define LBRACE '{'
107 #define RBRACE '}'
108 #define SLASH '/'
109 #define COMMA ','
111 #ifndef DEBUG
113 #define M_QUOTE 0x8000
114 #define M_PROTECT 0x4000
115 #define M_MASK 0xffff
116 #define M_ASCII 0x00ff
118 typedef u_short Char;
120 #else
122 #define M_QUOTE 0x80
123 #define M_PROTECT 0x40
124 #define M_MASK 0xff
125 #define M_ASCII 0x7f
127 typedef char Char;
129 #endif
132 #define CHAR(c) ((Char)((c)&M_ASCII))
133 #define META(c) ((Char)((c)|M_QUOTE))
134 #define M_ALL META('*')
135 #define M_END META(']')
136 #define M_NOT META('!')
137 #define M_ONE META('?')
138 #define M_RNG META('-')
139 #define M_SET META('[')
140 #define M_CLASS META(':')
141 #define ismeta(c) (((c)&M_QUOTE) != 0)
144 static int compare(const void *, const void *);
145 static int g_Ctoc(const Char *, char *, u_int);
146 static int g_lstat(Char *, struct stat *, glob_t *);
147 static DIR *g_opendir(Char *, glob_t *);
148 static Char *g_strchr(const Char *, int);
149 static int g_strncmp(const Char *, const char *, size_t);
150 static int g_stat(Char *, struct stat *, glob_t *);
151 static int glob0(const Char *, glob_t *);
152 static int glob1(Char *, Char *, glob_t *, size_t *);
153 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
154 glob_t *, size_t *);
155 static int glob3(Char *, Char *, Char *, Char *, Char *,
156 Char *, Char *, glob_t *, size_t *);
157 static int globextend(const Char *, glob_t *, size_t *, struct stat *);
158 static const Char *
159 globtilde(const Char *, Char *, size_t, glob_t *);
160 static int globexp1(const Char *, glob_t *);
161 static int globexp2(const Char *, const Char *, glob_t *);
162 static int match(Char *, Char *, Char *);
163 #ifdef DEBUG
164 static void qprintf(const char *, Char *);
165 #endif
168 glob(const char *pattern, int flags, int (*errfunc)(const char *, int),
169 glob_t *pglob)
171 const u_char *patnext;
172 int c;
173 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
175 patnext = (u_char *) pattern;
176 if (!(flags & GLOB_APPEND)) {
177 pglob->gl_pathc = 0;
178 pglob->gl_pathv = NULL;
179 pglob->gl_statv = NULL;
180 if (!(flags & GLOB_DOOFFS))
181 pglob->gl_offs = 0;
183 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
184 pglob->gl_errfunc = errfunc;
185 pglob->gl_matchc = 0;
187 bufnext = patbuf;
188 bufend = bufnext + MAXPATHLEN - 1;
189 if (flags & GLOB_NOESCAPE)
190 while (bufnext < bufend && (c = *patnext++) != EOS)
191 *bufnext++ = c;
192 else {
193 /* Protect the quoted characters. */
194 while (bufnext < bufend && (c = *patnext++) != EOS)
195 if (c == QUOTE) {
196 if ((c = *patnext++) == EOS) {
197 c = QUOTE;
198 --patnext;
200 *bufnext++ = c | M_PROTECT;
201 } else
202 *bufnext++ = c;
204 *bufnext = EOS;
206 if (flags & GLOB_BRACE)
207 return globexp1(patbuf, pglob);
208 else
209 return glob0(patbuf, pglob);
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
215 * characters
217 static int
218 globexp1(const Char *pattern, glob_t *pglob)
220 const Char* ptr = pattern;
222 /* Protect a single {}, for find(1), like csh */
223 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
224 return glob0(pattern, pglob);
226 if ((ptr = (const Char *) g_strchr(ptr, LBRACE)) != NULL)
227 return globexp2(ptr, pattern, pglob);
229 return glob0(pattern, pglob);
234 * Recursive brace globbing helper. Tries to expand a single brace.
235 * If it succeeds then it invokes globexp1 with the new pattern.
236 * If it fails then it tries to glob the rest of the pattern and returns.
238 static int
239 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob)
241 int i, rv;
242 Char *lm, *ls;
243 const Char *pe, *pm, *pl;
244 Char patbuf[MAXPATHLEN];
246 /* copy part up to the brace */
247 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
249 *lm = EOS;
250 ls = lm;
252 /* Find the balanced brace */
253 for (i = 0, pe = ++ptr; *pe; pe++)
254 if (*pe == LBRACKET) {
255 /* Ignore everything between [] */
256 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
258 if (*pe == EOS) {
260 * We could not find a matching RBRACKET.
261 * Ignore and just look for RBRACE
263 pe = pm;
265 } else if (*pe == LBRACE)
266 i++;
267 else if (*pe == RBRACE) {
268 if (i == 0)
269 break;
270 i--;
273 /* Non matching braces; just glob the pattern */
274 if (i != 0 || *pe == EOS)
275 return glob0(patbuf, pglob);
277 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
278 switch (*pm) {
279 case LBRACKET:
280 /* Ignore everything between [] */
281 for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
283 if (*pm == EOS) {
285 * We could not find a matching RBRACKET.
286 * Ignore and just look for RBRACE
288 pm = pl;
290 break;
292 case LBRACE:
293 i++;
294 break;
296 case RBRACE:
297 if (i) {
298 i--;
299 break;
301 /* FALLTHROUGH */
302 case COMMA:
303 if (i && *pm == COMMA)
304 break;
305 else {
306 /* Append the current string */
307 for (lm = ls; (pl < pm); *lm++ = *pl++)
311 * Append the rest of the pattern after the
312 * closing brace
314 for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
317 /* Expand the current pattern */
318 #ifdef DEBUG
319 qprintf("globexp2:", patbuf);
320 #endif
321 rv = globexp1(patbuf, pglob);
322 if (rv && rv != GLOB_NOMATCH)
323 return rv;
325 /* move after the comma, to the next string */
326 pl = pm + 1;
328 break;
330 default:
331 break;
334 return 0;
340 * expand tilde from the passwd file.
342 static const Char *
343 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
345 struct passwd *pwd;
346 char *h;
347 const Char *p;
348 Char *b, *eb;
350 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
351 return pattern;
353 /* Copy up to the end of the string or / */
354 eb = &patbuf[patbuf_len - 1];
355 for (p = pattern + 1, h = (char *) patbuf;
356 h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
359 *h = EOS;
361 #if 0
362 if (h == (char *)eb)
363 return what;
364 #endif
366 if (((char *) patbuf)[0] == EOS) {
368 * handle a plain ~ or ~/ by expanding $HOME
369 * first and then trying the password file
371 #if 0
372 if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
373 #endif
374 if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
375 if ((pwd = getpwuid(getuid())) == NULL)
376 return pattern;
377 else
378 h = pwd->pw_dir;
380 } else {
382 * Expand a ~user
384 if ((pwd = getpwnam((char*) patbuf)) == NULL)
385 return pattern;
386 else
387 h = pwd->pw_dir;
390 /* Copy the home directory */
391 for (b = patbuf; b < eb && *h; *b++ = *h++)
394 /* Append the rest of the pattern */
395 while (b < eb && (*b++ = *p++) != EOS)
397 *b = EOS;
399 return patbuf;
402 static int
403 g_strncmp(const Char *s1, const char *s2, size_t n)
405 int rv = 0;
407 while (n--) {
408 rv = *(Char *)s1 - *(const unsigned char *)s2++;
409 if (rv)
410 break;
411 if (*s1++ == '\0')
412 break;
414 return rv;
417 static int
418 g_charclass(const Char **patternp, Char **bufnextp)
420 const Char *pattern = *patternp + 1;
421 Char *bufnext = *bufnextp;
422 const Char *colon;
423 struct cclass *cc;
424 size_t len;
426 if ((colon = g_strchr(pattern, ':')) == NULL || colon[1] != ']')
427 return 1; /* not a character class */
429 len = (size_t)(colon - pattern);
430 for (cc = cclasses; cc->name != NULL; cc++) {
431 if (!g_strncmp(pattern, cc->name, len) && cc->name[len] == '\0')
432 break;
434 if (cc->name == NULL)
435 return -1; /* invalid character class */
436 *bufnext++ = M_CLASS;
437 *bufnext++ = (Char)(cc - &cclasses[0]);
438 *bufnextp = bufnext;
439 *patternp += len + 3;
441 return 0;
445 * The main glob() routine: compiles the pattern (optionally processing
446 * quotes), calls glob1() to do the real pattern matching, and finally
447 * sorts the list (unless unsorted operation is requested). Returns 0
448 * if things went well, nonzero if errors occurred. It is not an error
449 * to find no matches.
451 static int
452 glob0(const Char *pattern, glob_t *pglob)
454 const Char *qpatnext;
455 int c, err, oldpathc;
456 Char *bufnext, patbuf[MAXPATHLEN];
457 size_t limit = 0;
459 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
460 oldpathc = pglob->gl_pathc;
461 bufnext = patbuf;
463 /* We don't need to check for buffer overflow any more. */
464 while ((c = *qpatnext++) != EOS) {
465 switch (c) {
466 case LBRACKET:
467 c = *qpatnext;
468 if (c == NOT)
469 ++qpatnext;
470 if (*qpatnext == EOS ||
471 g_strchr(qpatnext+1, RBRACKET) == NULL) {
472 *bufnext++ = LBRACKET;
473 if (c == NOT)
474 --qpatnext;
475 break;
477 *bufnext++ = M_SET;
478 if (c == NOT)
479 *bufnext++ = M_NOT;
480 c = *qpatnext++;
481 do {
482 if (c == LBRACKET && *qpatnext == ':') {
483 do {
484 err = g_charclass(&qpatnext,
485 &bufnext);
486 if (err)
487 break;
488 c = *qpatnext++;
489 } while (c == LBRACKET && *qpatnext == ':');
490 if (err == -1 &&
491 !(pglob->gl_flags & GLOB_NOCHECK))
492 return GLOB_NOMATCH;
493 if (c == RBRACKET)
494 break;
496 *bufnext++ = CHAR(c);
497 if (*qpatnext == RANGE &&
498 (c = qpatnext[1]) != RBRACKET) {
499 *bufnext++ = M_RNG;
500 *bufnext++ = CHAR(c);
501 qpatnext += 2;
503 } while ((c = *qpatnext++) != RBRACKET);
504 pglob->gl_flags |= GLOB_MAGCHAR;
505 *bufnext++ = M_END;
506 break;
507 case QUESTION:
508 pglob->gl_flags |= GLOB_MAGCHAR;
509 *bufnext++ = M_ONE;
510 break;
511 case STAR:
512 pglob->gl_flags |= GLOB_MAGCHAR;
513 /* collapse adjacent stars to one,
514 * to avoid exponential behavior
516 if (bufnext == patbuf || bufnext[-1] != M_ALL)
517 *bufnext++ = M_ALL;
518 break;
519 default:
520 *bufnext++ = CHAR(c);
521 break;
524 *bufnext = EOS;
525 #ifdef DEBUG
526 qprintf("glob0:", patbuf);
527 #endif
529 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0)
530 return(err);
533 * If there was no match we are going to append the pattern
534 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
535 * and the pattern did not contain any magic characters
536 * GLOB_NOMAGIC is there just for compatibility with csh.
538 if (pglob->gl_pathc == oldpathc) {
539 if ((pglob->gl_flags & GLOB_NOCHECK) ||
540 ((pglob->gl_flags & GLOB_NOMAGIC) &&
541 !(pglob->gl_flags & GLOB_MAGCHAR)))
542 return(globextend(pattern, pglob, &limit, NULL));
543 else
544 return(GLOB_NOMATCH);
546 if (!(pglob->gl_flags & GLOB_NOSORT))
547 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
548 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
549 return(0);
552 static int
553 compare(const void *p, const void *q)
555 return(strcmp(*(char **)p, *(char **)q));
558 static int
559 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
561 Char pathbuf[MAXPATHLEN];
563 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
564 if (*pattern == EOS)
565 return(0);
566 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
567 pathbuf, pathbuf+MAXPATHLEN-1,
568 pattern, pattern_last, pglob, limitp));
572 * The functions glob2 and glob3 are mutually recursive; there is one level
573 * of recursion for each segment in the pattern that contains one or more
574 * meta characters.
576 static int
577 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
578 Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
580 struct stat sb;
581 Char *p, *q;
582 int anymeta;
585 * Loop over pattern segments until end of pattern or until
586 * segment with meta character found.
588 for (anymeta = 0;;) {
589 if (*pattern == EOS) { /* End of pattern? */
590 *pathend = EOS;
591 if (g_lstat(pathbuf, &sb, pglob))
592 return(0);
594 if (((pglob->gl_flags & GLOB_MARK) &&
595 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
596 (S_ISLNK(sb.st_mode) &&
597 (g_stat(pathbuf, &sb, pglob) == 0) &&
598 S_ISDIR(sb.st_mode)))) {
599 if (pathend+1 > pathend_last)
600 return (1);
601 *pathend++ = SEP;
602 *pathend = EOS;
604 ++pglob->gl_matchc;
605 return(globextend(pathbuf, pglob, limitp, &sb));
608 /* Find end of next segment, copy tentatively to pathend. */
609 q = pathend;
610 p = pattern;
611 while (*p != EOS && *p != SEP) {
612 if (ismeta(*p))
613 anymeta = 1;
614 if (q+1 > pathend_last)
615 return (1);
616 *q++ = *p++;
619 if (!anymeta) { /* No expansion, do next segment. */
620 pathend = q;
621 pattern = p;
622 while (*pattern == SEP) {
623 if (pathend+1 > pathend_last)
624 return (1);
625 *pathend++ = *pattern++;
627 } else
628 /* Need expansion, recurse. */
629 return(glob3(pathbuf, pathbuf_last, pathend,
630 pathend_last, pattern, p, pattern_last,
631 pglob, limitp));
633 /* NOTREACHED */
636 static int
637 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
638 Char *pattern, Char *restpattern, Char *restpattern_last, glob_t *pglob,
639 size_t *limitp)
641 struct dirent *dp;
642 DIR *dirp;
643 int err;
644 char buf[MAXPATHLEN];
647 * The readdirfunc declaration can't be prototyped, because it is
648 * assigned, below, to two functions which are prototyped in glob.h
649 * and dirent.h as taking pointers to differently typed opaque
650 * structures.
652 struct dirent *(*readdirfunc)(void *);
654 if (pathend > pathend_last)
655 return (1);
656 *pathend = EOS;
657 errno = 0;
659 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
660 /* TODO: don't call for ENOENT or ENOTDIR? */
661 if (pglob->gl_errfunc) {
662 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
663 return(GLOB_ABORTED);
664 if (pglob->gl_errfunc(buf, errno) ||
665 pglob->gl_flags & GLOB_ERR)
666 return(GLOB_ABORTED);
668 return(0);
671 err = 0;
673 /* Search directory for matching names. */
674 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
675 readdirfunc = pglob->gl_readdir;
676 else
677 readdirfunc = (struct dirent *(*)(void *))readdir;
678 while ((dp = (*readdirfunc)(dirp))) {
679 u_char *sc;
680 Char *dc;
682 /* Initial DOT must be matched literally. */
683 if (dp->d_name[0] == DOT && *pattern != DOT)
684 continue;
685 dc = pathend;
686 sc = (u_char *) dp->d_name;
687 while (dc < pathend_last && (*dc++ = *sc++) != EOS)
689 if (dc >= pathend_last) {
690 *dc = EOS;
691 err = 1;
692 break;
695 if (!match(pathend, pattern, restpattern)) {
696 *pathend = EOS;
697 continue;
699 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
700 restpattern, restpattern_last, pglob, limitp);
701 if (err)
702 break;
705 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
706 (*pglob->gl_closedir)(dirp);
707 else
708 closedir(dirp);
709 return(err);
714 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
715 * add the new item, and update gl_pathc.
717 * This assumes the BSD realloc, which only copies the block when its size
718 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
719 * behavior.
721 * Return 0 if new item added, error code if memory couldn't be allocated.
723 * Invariant of the glob_t structure:
724 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
725 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
727 static int
728 globextend(const Char *path, glob_t *pglob, size_t *limitp, struct stat *sb)
730 char **pathv;
731 ssize_t i;
732 size_t newn, len;
733 char *copy = NULL;
734 const Char *p;
735 struct stat **statv;
737 newn = 2 + pglob->gl_pathc + pglob->gl_offs;
738 if (SIZE_MAX / sizeof(*pathv) <= newn ||
739 SIZE_MAX / sizeof(*statv) <= newn) {
740 nospace:
741 for (i = pglob->gl_offs; i < newn - 2; i++) {
742 if (pglob->gl_pathv && pglob->gl_pathv[i])
743 free(pglob->gl_pathv[i]);
744 if ((pglob->gl_flags & GLOB_KEEPSTAT) != 0 &&
745 pglob->gl_pathv && pglob->gl_pathv[i])
746 free(pglob->gl_statv[i]);
748 if (pglob->gl_pathv) {
749 free(pglob->gl_pathv);
750 pglob->gl_pathv = NULL;
752 if (pglob->gl_statv) {
753 free(pglob->gl_statv);
754 pglob->gl_statv = NULL;
756 return(GLOB_NOSPACE);
759 pathv = realloc(pglob->gl_pathv, newn * sizeof(*pathv));
760 if (pathv == NULL)
761 goto nospace;
762 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
763 /* first time around -- clear initial gl_offs items */
764 pathv += pglob->gl_offs;
765 for (i = pglob->gl_offs; --i >= 0; )
766 *--pathv = NULL;
768 pglob->gl_pathv = pathv;
770 if ((pglob->gl_flags & GLOB_KEEPSTAT) != 0) {
771 statv = realloc(pglob->gl_statv, newn * sizeof(*statv));
772 if (statv == NULL)
773 goto nospace;
774 if (pglob->gl_statv == NULL && pglob->gl_offs > 0) {
775 /* first time around -- clear initial gl_offs items */
776 statv += pglob->gl_offs;
777 for (i = pglob->gl_offs; --i >= 0; )
778 *--statv = NULL;
780 pglob->gl_statv = statv;
781 if (sb == NULL)
782 statv[pglob->gl_offs + pglob->gl_pathc] = NULL;
783 else {
784 if ((statv[pglob->gl_offs + pglob->gl_pathc] =
785 malloc(sizeof(**statv))) == NULL)
786 goto copy_error;
787 memcpy(statv[pglob->gl_offs + pglob->gl_pathc], sb,
788 sizeof(*sb));
790 statv[pglob->gl_offs + pglob->gl_pathc + 1] = NULL;
793 for (p = path; *p++;)
795 len = (size_t)(p - path);
796 *limitp += len;
797 if ((copy = malloc(len)) != NULL) {
798 if (g_Ctoc(path, copy, len)) {
799 free(copy);
800 return(GLOB_NOSPACE);
802 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
804 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
806 if ((pglob->gl_flags & GLOB_LIMIT) &&
807 (newn * sizeof(*pathv)) + *limitp >= (u_int) get_arg_max()) {
808 errno = 0;
809 return(GLOB_NOSPACE);
811 copy_error:
812 return(copy == NULL ? GLOB_NOSPACE : 0);
817 * pattern matching function for filenames. Each occurrence of the *
818 * pattern causes a recursion level.
820 static int
821 match(Char *name, Char *pat, Char *patend)
823 int ok, negate_range;
824 Char c, k;
826 while (pat < patend) {
827 c = *pat++;
828 switch (c & M_MASK) {
829 case M_ALL:
830 if (pat == patend)
831 return(1);
832 do {
833 if (match(name, pat, patend))
834 return(1);
835 } while (*name++ != EOS);
836 return(0);
837 case M_ONE:
838 if (*name++ == EOS)
839 return(0);
840 break;
841 case M_SET:
842 ok = 0;
843 if ((k = *name++) == EOS)
844 return(0);
845 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
846 ++pat;
847 while (((c = *pat++) & M_MASK) != M_END) {
848 if ((c & M_MASK) == M_CLASS) {
849 int idx = *pat & M_MASK;
850 if (idx < NCCLASSES &&
851 cclasses[idx].isctype(k))
852 ok = 1;
853 ++pat;
855 if ((*pat & M_MASK) == M_RNG) {
856 if (c <= k && k <= pat[1])
857 ok = 1;
858 pat += 2;
859 } else if (c == k)
860 ok = 1;
862 if (ok == negate_range)
863 return(0);
864 break;
865 default:
866 if (*name++ != c)
867 return(0);
868 break;
871 return(*name == EOS);
874 /* Free allocated data belonging to a glob_t structure. */
875 void
876 globfree(glob_t *pglob)
878 int i;
879 char **pp;
881 if (pglob->gl_pathv != NULL) {
882 pp = pglob->gl_pathv + pglob->gl_offs;
883 for (i = pglob->gl_pathc; i--; ++pp)
884 if (*pp)
885 free(*pp);
886 free(pglob->gl_pathv);
887 pglob->gl_pathv = NULL;
889 if (pglob->gl_statv != NULL) {
890 for (i = 0; i < pglob->gl_pathc; i++) {
891 if (pglob->gl_statv[i] != NULL)
892 free(pglob->gl_statv[i]);
894 free(pglob->gl_statv);
895 pglob->gl_statv = NULL;
899 static DIR *
900 g_opendir(Char *str, glob_t *pglob)
902 char buf[MAXPATHLEN];
904 if (!*str)
905 strlcpy(buf, ".", sizeof buf);
906 else {
907 if (g_Ctoc(str, buf, sizeof(buf)))
908 return(NULL);
911 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
912 return((*pglob->gl_opendir)(buf));
914 return(opendir(buf));
917 static int
918 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
920 char buf[MAXPATHLEN];
922 if (g_Ctoc(fn, buf, sizeof(buf)))
923 return(-1);
924 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
925 return((*pglob->gl_lstat)(buf, sb));
926 return(lstat(buf, sb));
929 static int
930 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
932 char buf[MAXPATHLEN];
934 if (g_Ctoc(fn, buf, sizeof(buf)))
935 return(-1);
936 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
937 return((*pglob->gl_stat)(buf, sb));
938 return(stat(buf, sb));
941 static Char *
942 g_strchr(const Char *str, int ch)
944 do {
945 if (*str == ch)
946 return ((Char *)str);
947 } while (*str++);
948 return (NULL);
951 static int
952 g_Ctoc(const Char *str, char *buf, u_int len)
955 while (len--) {
956 if ((*buf++ = *str++) == EOS)
957 return (0);
959 return (1);
962 #ifdef DEBUG
963 static void
964 qprintf(const char *str, Char *s)
966 Char *p;
968 (void)printf("%s:\n", str);
969 for (p = s; *p; p++)
970 (void)printf("%c", CHAR(*p));
971 (void)printf("\n");
972 for (p = s; *p; p++)
973 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
974 (void)printf("\n");
975 for (p = s; *p; p++)
976 (void)printf("%c", ismeta(*p) ? '_' : ' ');
977 (void)printf("\n");
979 #endif
981 #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
982 !defined(GLOB_HAS_GL_MATCHC) || !defined(GLOB_HAS_GL_STATV) */