]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - lib/libc/gen/glob.c
Fix Denial of Service vulnerability in named(8) with DNS64. [13:01]
[FreeBSD/releng/9.0.git] / lib / libc / gen / glob.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Guido van Rossum.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)glob.c      8.3 (Berkeley) 10/13/93";
35 #endif /* LIBC_SCCS and not lint */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 /*
40  * glob(3) -- a superset of the one defined in POSIX 1003.2.
41  *
42  * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
43  *
44  * Optional extra services, controlled by flags not defined by POSIX:
45  *
46  * GLOB_QUOTE:
47  *      Escaping convention: \ inhibits any special meaning the following
48  *      character might have (except \ at end of string is retained).
49  * GLOB_MAGCHAR:
50  *      Set in gl_flags if pattern contained a globbing character.
51  * GLOB_NOMAGIC:
52  *      Same as GLOB_NOCHECK, but it will only append pattern if it did
53  *      not contain any magic characters.  [Used in csh style globbing]
54  * GLOB_ALTDIRFUNC:
55  *      Use alternately specified directory access functions.
56  * GLOB_TILDE:
57  *      expand ~user/foo to the /home/dir/of/user/foo
58  * GLOB_BRACE:
59  *      expand {1,2}{a,b} to 1a 1b 2a 2b
60  * gl_matchc:
61  *      Number of matches in the current invocation of glob.
62  */
63
64 /*
65  * Some notes on multibyte character support:
66  * 1. Patterns with illegal byte sequences match nothing - even if
67  *    GLOB_NOCHECK is specified.
68  * 2. Illegal byte sequences in filenames are handled by treating them as
69  *    single-byte characters with a value of the first byte of the sequence
70  *    cast to wchar_t.
71  * 3. State-dependent encodings are not currently supported.
72  */
73
74 #include <sys/param.h>
75 #include <sys/stat.h>
76
77 #include <ctype.h>
78 #include <dirent.h>
79 #include <errno.h>
80 #include <glob.h>
81 #include <limits.h>
82 #include <pwd.h>
83 #include <stdint.h>
84 #include <stdio.h>
85 #include <stdlib.h>
86 #include <string.h>
87 #include <unistd.h>
88 #include <wchar.h>
89
90 #include "collate.h"
91
92 /*
93  * glob(3) expansion limits. Stop the expansion if any of these limits
94  * is reached. This caps the runtime in the face of DoS attacks. See
95  * also CVE-2010-2632
96  */
97 #define GLOB_LIMIT_BRACE        128     /* number of brace calls */
98 #define GLOB_LIMIT_PATH         65536   /* number of path elements */
99 #define GLOB_LIMIT_READDIR      16384   /* number of readdirs */
100 #define GLOB_LIMIT_STAT         1024    /* number of stat system calls */
101 #define GLOB_LIMIT_STRING       ARG_MAX /* maximum total size for paths */
102
103 struct glob_limit {
104         size_t  l_brace_cnt;
105         size_t  l_path_lim;
106         size_t  l_readdir_cnt;  
107         size_t  l_stat_cnt;     
108         size_t  l_string_cnt;
109 };
110
111 #define DOLLAR          '$'
112 #define DOT             '.'
113 #define EOS             '\0'
114 #define LBRACKET        '['
115 #define NOT             '!'
116 #define QUESTION        '?'
117 #define QUOTE           '\\'
118 #define RANGE           '-'
119 #define RBRACKET        ']'
120 #define SEP             '/'
121 #define STAR            '*'
122 #define TILDE           '~'
123 #define UNDERSCORE      '_'
124 #define LBRACE          '{'
125 #define RBRACE          '}'
126 #define SLASH           '/'
127 #define COMMA           ','
128
129 #ifndef DEBUG
130
131 #define M_QUOTE         0x8000000000ULL
132 #define M_PROTECT       0x4000000000ULL
133 #define M_MASK          0xffffffffffULL
134 #define M_CHAR          0x00ffffffffULL
135
136 typedef uint_fast64_t Char;
137
138 #else
139
140 #define M_QUOTE         0x80
141 #define M_PROTECT       0x40
142 #define M_MASK          0xff
143 #define M_CHAR          0x7f
144
145 typedef char Char;
146
147 #endif
148
149
150 #define CHAR(c)         ((Char)((c)&M_CHAR))
151 #define META(c)         ((Char)((c)|M_QUOTE))
152 #define M_ALL           META('*')
153 #define M_END           META(']')
154 #define M_NOT           META('!')
155 #define M_ONE           META('?')
156 #define M_RNG           META('-')
157 #define M_SET           META('[')
158 #define ismeta(c)       (((c)&M_QUOTE) != 0)
159
160
161 static int       compare(const void *, const void *);
162 static int       g_Ctoc(const Char *, char *, size_t);
163 static int       g_lstat(Char *, struct stat *, glob_t *);
164 static DIR      *g_opendir(Char *, glob_t *);
165 static const Char *g_strchr(const Char *, wchar_t);
166 #ifdef notdef
167 static Char     *g_strcat(Char *, const Char *);
168 #endif
169 static int       g_stat(Char *, struct stat *, glob_t *);
170 static int       glob0(const Char *, glob_t *, struct glob_limit *);
171 static int       glob1(Char *, glob_t *, struct glob_limit *);
172 static int       glob2(Char *, Char *, Char *, Char *, glob_t *,
173     struct glob_limit *);
174 static int       glob3(Char *, Char *, Char *, Char *, Char *, glob_t *,
175     struct glob_limit *);
176 static int       globextend(const Char *, glob_t *, struct glob_limit *);
177 static const Char *
178                  globtilde(const Char *, Char *, size_t, glob_t *);
179 static int       globexp1(const Char *, glob_t *, struct glob_limit *);
180 static int       globexp2(const Char *, const Char *, glob_t *, int *,
181     struct glob_limit *);
182 static int       match(Char *, Char *, Char *);
183 #ifdef DEBUG
184 static void      qprintf(const char *, Char *);
185 #endif
186
187 int
188 glob(const char *pattern, int flags, int (*errfunc)(const char *, int), glob_t *pglob)
189 {
190         struct glob_limit limit = { 0, 0, 0, 0, 0 };
191         const char *patnext;
192         Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
193         mbstate_t mbs;
194         wchar_t wc;
195         size_t clen;
196
197         patnext = pattern;
198         if (!(flags & GLOB_APPEND)) {
199                 pglob->gl_pathc = 0;
200                 pglob->gl_pathv = NULL;
201                 if (!(flags & GLOB_DOOFFS))
202                         pglob->gl_offs = 0;
203         }
204         if (flags & GLOB_LIMIT) {
205                 limit.l_path_lim = pglob->gl_matchc;
206                 if (limit.l_path_lim == 0)
207                         limit.l_path_lim = GLOB_LIMIT_PATH;
208         }
209         pglob->gl_flags = flags & ~GLOB_MAGCHAR;
210         pglob->gl_errfunc = errfunc;
211         pglob->gl_matchc = 0;
212
213         bufnext = patbuf;
214         bufend = bufnext + MAXPATHLEN - 1;
215         if (flags & GLOB_NOESCAPE) {
216                 memset(&mbs, 0, sizeof(mbs));
217                 while (bufend - bufnext >= MB_CUR_MAX) {
218                         clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
219                         if (clen == (size_t)-1 || clen == (size_t)-2)
220                                 return (GLOB_NOMATCH);
221                         else if (clen == 0)
222                                 break;
223                         *bufnext++ = wc;
224                         patnext += clen;
225                 }
226         } else {
227                 /* Protect the quoted characters. */
228                 memset(&mbs, 0, sizeof(mbs));
229                 while (bufend - bufnext >= MB_CUR_MAX) {
230                         if (*patnext == QUOTE) {
231                                 if (*++patnext == EOS) {
232                                         *bufnext++ = QUOTE | M_PROTECT;
233                                         continue;
234                                 }
235                                 prot = M_PROTECT;
236                         } else
237                                 prot = 0;
238                         clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
239                         if (clen == (size_t)-1 || clen == (size_t)-2)
240                                 return (GLOB_NOMATCH);
241                         else if (clen == 0)
242                                 break;
243                         *bufnext++ = wc | prot;
244                         patnext += clen;
245                 }
246         }
247         *bufnext = EOS;
248
249         if (flags & GLOB_BRACE)
250             return globexp1(patbuf, pglob, &limit);
251         else
252             return glob0(patbuf, pglob, &limit);
253 }
254
255 /*
256  * Expand recursively a glob {} pattern. When there is no more expansion
257  * invoke the standard globbing routine to glob the rest of the magic
258  * characters
259  */
260 static int
261 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
262 {
263         const Char* ptr = pattern;
264         int rv;
265
266         if ((pglob->gl_flags & GLOB_LIMIT) &&
267             limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
268                 errno = 0;
269                 return (GLOB_NOSPACE);
270         }
271
272         /* Protect a single {}, for find(1), like csh */
273         if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
274                 return glob0(pattern, pglob, limit);
275
276         while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
277                 if (!globexp2(ptr, pattern, pglob, &rv, limit))
278                         return rv;
279
280         return glob0(pattern, pglob, limit);
281 }
282
283
284 /*
285  * Recursive brace globbing helper. Tries to expand a single brace.
286  * If it succeeds then it invokes globexp1 with the new pattern.
287  * If it fails then it tries to glob the rest of the pattern and returns.
288  */
289 static int
290 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
291     struct glob_limit *limit)
292 {
293         int     i;
294         Char   *lm, *ls;
295         const Char *pe, *pm, *pm1, *pl;
296         Char    patbuf[MAXPATHLEN];
297
298         /* copy part up to the brace */
299         for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
300                 continue;
301         *lm = EOS;
302         ls = lm;
303
304         /* Find the balanced brace */
305         for (i = 0, pe = ++ptr; *pe; pe++)
306                 if (*pe == LBRACKET) {
307                         /* Ignore everything between [] */
308                         for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
309                                 continue;
310                         if (*pe == EOS) {
311                                 /*
312                                  * We could not find a matching RBRACKET.
313                                  * Ignore and just look for RBRACE
314                                  */
315                                 pe = pm;
316                         }
317                 }
318                 else if (*pe == LBRACE)
319                         i++;
320                 else if (*pe == RBRACE) {
321                         if (i == 0)
322                                 break;
323                         i--;
324                 }
325
326         /* Non matching braces; just glob the pattern */
327         if (i != 0 || *pe == EOS) {
328                 *rv = glob0(patbuf, pglob, limit);
329                 return 0;
330         }
331
332         for (i = 0, pl = pm = ptr; pm <= pe; pm++)
333                 switch (*pm) {
334                 case LBRACKET:
335                         /* Ignore everything between [] */
336                         for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
337                                 continue;
338                         if (*pm == EOS) {
339                                 /*
340                                  * We could not find a matching RBRACKET.
341                                  * Ignore and just look for RBRACE
342                                  */
343                                 pm = pm1;
344                         }
345                         break;
346
347                 case LBRACE:
348                         i++;
349                         break;
350
351                 case RBRACE:
352                         if (i) {
353                             i--;
354                             break;
355                         }
356                         /* FALLTHROUGH */
357                 case COMMA:
358                         if (i && *pm == COMMA)
359                                 break;
360                         else {
361                                 /* Append the current string */
362                                 for (lm = ls; (pl < pm); *lm++ = *pl++)
363                                         continue;
364                                 /*
365                                  * Append the rest of the pattern after the
366                                  * closing brace
367                                  */
368                                 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
369                                         continue;
370
371                                 /* Expand the current pattern */
372 #ifdef DEBUG
373                                 qprintf("globexp2:", patbuf);
374 #endif
375                                 *rv = globexp1(patbuf, pglob, limit);
376
377                                 /* move after the comma, to the next string */
378                                 pl = pm + 1;
379                         }
380                         break;
381
382                 default:
383                         break;
384                 }
385         *rv = 0;
386         return 0;
387 }
388
389
390
391 /*
392  * expand tilde from the passwd file.
393  */
394 static const Char *
395 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
396 {
397         struct passwd *pwd;
398         char *h;
399         const Char *p;
400         Char *b, *eb;
401
402         if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
403                 return pattern;
404
405         /* 
406          * Copy up to the end of the string or / 
407          */
408         eb = &patbuf[patbuf_len - 1];
409         for (p = pattern + 1, h = (char *) patbuf;
410             h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
411                 continue;
412
413         *h = EOS;
414
415         if (((char *) patbuf)[0] == EOS) {
416                 /*
417                  * handle a plain ~ or ~/ by expanding $HOME first (iff
418                  * we're not running setuid or setgid) and then trying
419                  * the password file
420                  */
421                 if (issetugid() != 0 ||
422                     (h = getenv("HOME")) == NULL) {
423                         if (((h = getlogin()) != NULL &&
424                              (pwd = getpwnam(h)) != NULL) ||
425                             (pwd = getpwuid(getuid())) != NULL)
426                                 h = pwd->pw_dir;
427                         else
428                                 return pattern;
429                 }
430         }
431         else {
432                 /*
433                  * Expand a ~user
434                  */
435                 if ((pwd = getpwnam((char*) patbuf)) == NULL)
436                         return pattern;
437                 else
438                         h = pwd->pw_dir;
439         }
440
441         /* Copy the home directory */
442         for (b = patbuf; b < eb && *h; *b++ = *h++)
443                 continue;
444
445         /* Append the rest of the pattern */
446         while (b < eb && (*b++ = *p++) != EOS)
447                 continue;
448         *b = EOS;
449
450         return patbuf;
451 }
452
453
454 /*
455  * The main glob() routine: compiles the pattern (optionally processing
456  * quotes), calls glob1() to do the real pattern matching, and finally
457  * sorts the list (unless unsorted operation is requested).  Returns 0
458  * if things went well, nonzero if errors occurred.
459  */
460 static int
461 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
462 {
463         const Char *qpatnext;
464         int err;
465         size_t oldpathc;
466         Char *bufnext, c, patbuf[MAXPATHLEN];
467
468         qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
469         oldpathc = pglob->gl_pathc;
470         bufnext = patbuf;
471
472         /* We don't need to check for buffer overflow any more. */
473         while ((c = *qpatnext++) != EOS) {
474                 switch (c) {
475                 case LBRACKET:
476                         c = *qpatnext;
477                         if (c == NOT)
478                                 ++qpatnext;
479                         if (*qpatnext == EOS ||
480                             g_strchr(qpatnext+1, RBRACKET) == NULL) {
481                                 *bufnext++ = LBRACKET;
482                                 if (c == NOT)
483                                         --qpatnext;
484                                 break;
485                         }
486                         *bufnext++ = M_SET;
487                         if (c == NOT)
488                                 *bufnext++ = M_NOT;
489                         c = *qpatnext++;
490                         do {
491                                 *bufnext++ = CHAR(c);
492                                 if (*qpatnext == RANGE &&
493                                     (c = qpatnext[1]) != RBRACKET) {
494                                         *bufnext++ = M_RNG;
495                                         *bufnext++ = CHAR(c);
496                                         qpatnext += 2;
497                                 }
498                         } while ((c = *qpatnext++) != RBRACKET);
499                         pglob->gl_flags |= GLOB_MAGCHAR;
500                         *bufnext++ = M_END;
501                         break;
502                 case QUESTION:
503                         pglob->gl_flags |= GLOB_MAGCHAR;
504                         *bufnext++ = M_ONE;
505                         break;
506                 case STAR:
507                         pglob->gl_flags |= GLOB_MAGCHAR;
508                         /* collapse adjacent stars to one,
509                          * to avoid exponential behavior
510                          */
511                         if (bufnext == patbuf || bufnext[-1] != M_ALL)
512                             *bufnext++ = M_ALL;
513                         break;
514                 default:
515                         *bufnext++ = CHAR(c);
516                         break;
517                 }
518         }
519         *bufnext = EOS;
520 #ifdef DEBUG
521         qprintf("glob0:", patbuf);
522 #endif
523
524         if ((err = glob1(patbuf, pglob, limit)) != 0)
525                 return(err);
526
527         /*
528          * If there was no match we are going to append the pattern
529          * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
530          * and the pattern did not contain any magic characters
531          * GLOB_NOMAGIC is there just for compatibility with csh.
532          */
533         if (pglob->gl_pathc == oldpathc) {
534                 if (((pglob->gl_flags & GLOB_NOCHECK) ||
535                     ((pglob->gl_flags & GLOB_NOMAGIC) &&
536                         !(pglob->gl_flags & GLOB_MAGCHAR))))
537                         return(globextend(pattern, pglob, limit));
538                 else
539                         return(GLOB_NOMATCH);
540         }
541         if (!(pglob->gl_flags & GLOB_NOSORT))
542                 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
543                     pglob->gl_pathc - oldpathc, sizeof(char *), compare);
544         return(0);
545 }
546
547 static int
548 compare(const void *p, const void *q)
549 {
550         return(strcmp(*(char **)p, *(char **)q));
551 }
552
553 static int
554 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
555 {
556         Char pathbuf[MAXPATHLEN];
557
558         /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
559         if (*pattern == EOS)
560                 return(0);
561         return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
562             pattern, pglob, limit));
563 }
564
565 /*
566  * The functions glob2 and glob3 are mutually recursive; there is one level
567  * of recursion for each segment in the pattern that contains one or more
568  * meta characters.
569  */
570 static int
571 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
572       glob_t *pglob, struct glob_limit *limit)
573 {
574         struct stat sb;
575         Char *p, *q;
576         int anymeta;
577
578         /*
579          * Loop over pattern segments until end of pattern or until
580          * segment with meta character found.
581          */
582         for (anymeta = 0;;) {
583                 if (*pattern == EOS) {          /* End of pattern? */
584                         *pathend = EOS;
585                         if (g_lstat(pathbuf, &sb, pglob))
586                                 return(0);
587
588                         if ((pglob->gl_flags & GLOB_LIMIT) &&
589                             limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
590                                 errno = 0;
591                                 if (pathend + 1 > pathend_last)
592                                         return (GLOB_ABORTED);
593                                 *pathend++ = SEP;
594                                 *pathend = EOS;
595                                 return (GLOB_NOSPACE);
596                         }
597                         if (((pglob->gl_flags & GLOB_MARK) &&
598                             pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
599                             || (S_ISLNK(sb.st_mode) &&
600                             (g_stat(pathbuf, &sb, pglob) == 0) &&
601                             S_ISDIR(sb.st_mode)))) {
602                                 if (pathend + 1 > pathend_last)
603                                         return (GLOB_ABORTED);
604                                 *pathend++ = SEP;
605                                 *pathend = EOS;
606                         }
607                         ++pglob->gl_matchc;
608                         return(globextend(pathbuf, pglob, limit));
609                 }
610
611                 /* Find end of next segment, copy tentatively to pathend. */
612                 q = pathend;
613                 p = pattern;
614                 while (*p != EOS && *p != SEP) {
615                         if (ismeta(*p))
616                                 anymeta = 1;
617                         if (q + 1 > pathend_last)
618                                 return (GLOB_ABORTED);
619                         *q++ = *p++;
620                 }
621
622                 if (!anymeta) {         /* No expansion, do next segment. */
623                         pathend = q;
624                         pattern = p;
625                         while (*pattern == SEP) {
626                                 if (pathend + 1 > pathend_last)
627                                         return (GLOB_ABORTED);
628                                 *pathend++ = *pattern++;
629                         }
630                 } else                  /* Need expansion, recurse. */
631                         return(glob3(pathbuf, pathend, pathend_last, pattern, p,
632                             pglob, limit));
633         }
634         /* NOTREACHED */
635 }
636
637 static int
638 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
639       Char *pattern, Char *restpattern,
640       glob_t *pglob, struct glob_limit *limit)
641 {
642         struct dirent *dp;
643         DIR *dirp;
644         int err;
645         char buf[MAXPATHLEN];
646
647         /*
648          * The readdirfunc declaration can't be prototyped, because it is
649          * assigned, below, to two functions which are prototyped in glob.h
650          * and dirent.h as taking pointers to differently typed opaque
651          * structures.
652          */
653         struct dirent *(*readdirfunc)();
654
655         if (pathend > pathend_last)
656                 return (GLOB_ABORTED);
657         *pathend = EOS;
658         errno = 0;
659
660         if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
661                 /* TODO: don't call for ENOENT or ENOTDIR? */
662                 if (pglob->gl_errfunc) {
663                         if (g_Ctoc(pathbuf, buf, sizeof(buf)))
664                                 return (GLOB_ABORTED);
665                         if (pglob->gl_errfunc(buf, errno) ||
666                             pglob->gl_flags & GLOB_ERR)
667                                 return (GLOB_ABORTED);
668                 }
669                 return(0);
670         }
671
672         err = 0;
673
674         /* Search directory for matching names. */
675         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
676                 readdirfunc = pglob->gl_readdir;
677         else
678                 readdirfunc = readdir;
679         while ((dp = (*readdirfunc)(dirp))) {
680                 char *sc;
681                 Char *dc;
682                 wchar_t wc;
683                 size_t clen;
684                 mbstate_t mbs;
685
686                 if ((pglob->gl_flags & GLOB_LIMIT) &&
687                     limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
688                         errno = 0;
689                         if (pathend + 1 > pathend_last)
690                                 err = GLOB_ABORTED;
691                         else {
692                                 *pathend++ = SEP;
693                                 *pathend = EOS;
694                                 err = GLOB_NOSPACE;
695                         }
696                         break;
697                 }
698
699                 /* Initial DOT must be matched literally. */
700                 if (dp->d_name[0] == DOT && *pattern != DOT)
701                         continue;
702                 memset(&mbs, 0, sizeof(mbs));
703                 dc = pathend;
704                 sc = dp->d_name;
705                 while (dc < pathend_last) {
706                         clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
707                         if (clen == (size_t)-1 || clen == (size_t)-2) {
708                                 wc = *sc;
709                                 clen = 1;
710                                 memset(&mbs, 0, sizeof(mbs));
711                         }
712                         if ((*dc++ = wc) == EOS)
713                                 break;
714                         sc += clen;
715                 }
716                 if (!match(pathend, pattern, restpattern)) {
717                         *pathend = EOS;
718                         continue;
719                 }
720                 err = glob2(pathbuf, --dc, pathend_last, restpattern,
721                     pglob, limit);
722                 if (err)
723                         break;
724         }
725
726         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
727                 (*pglob->gl_closedir)(dirp);
728         else
729                 closedir(dirp);
730         return(err);
731 }
732
733
734 /*
735  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
736  * add the new item, and update gl_pathc.
737  *
738  * This assumes the BSD realloc, which only copies the block when its size
739  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
740  * behavior.
741  *
742  * Return 0 if new item added, error code if memory couldn't be allocated.
743  *
744  * Invariant of the glob_t structure:
745  *      Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
746  *      gl_pathv points to (gl_offs + gl_pathc + 1) items.
747  */
748 static int
749 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
750 {
751         char **pathv;
752         size_t i, newsize, len;
753         char *copy;
754         const Char *p;
755
756         if ((pglob->gl_flags & GLOB_LIMIT) &&
757             pglob->gl_matchc > limit->l_path_lim) {
758                 errno = 0;
759                 return (GLOB_NOSPACE);
760         }
761
762         newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
763         pathv = pglob->gl_pathv ?
764                     realloc((char *)pglob->gl_pathv, newsize) :
765                     malloc(newsize);
766         if (pathv == NULL) {
767                 if (pglob->gl_pathv) {
768                         free(pglob->gl_pathv);
769                         pglob->gl_pathv = NULL;
770                 }
771                 return(GLOB_NOSPACE);
772         }
773
774         if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
775                 /* first time around -- clear initial gl_offs items */
776                 pathv += pglob->gl_offs;
777                 for (i = pglob->gl_offs + 1; --i > 0; )
778                         *--pathv = NULL;
779         }
780         pglob->gl_pathv = pathv;
781
782         for (p = path; *p++;)
783                 continue;
784         len = MB_CUR_MAX * (size_t)(p - path);  /* XXX overallocation */
785         limit->l_string_cnt += len;
786         if ((pglob->gl_flags & GLOB_LIMIT) &&
787             limit->l_string_cnt >= GLOB_LIMIT_STRING) {
788                 errno = 0;
789                 return (GLOB_NOSPACE);
790         }
791         if ((copy = malloc(len)) != NULL) {
792                 if (g_Ctoc(path, copy, len)) {
793                         free(copy);
794                         return (GLOB_NOSPACE);
795                 }
796                 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
797         }
798         pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
799         return(copy == NULL ? GLOB_NOSPACE : 0);
800 }
801
802 /*
803  * pattern matching function for filenames.  Each occurrence of the *
804  * pattern causes a recursion level.
805  */
806 static int
807 match(Char *name, Char *pat, Char *patend)
808 {
809         int ok, negate_range;
810         Char c, k;
811
812         while (pat < patend) {
813                 c = *pat++;
814                 switch (c & M_MASK) {
815                 case M_ALL:
816                         if (pat == patend)
817                                 return(1);
818                         do
819                             if (match(name, pat, patend))
820                                     return(1);
821                         while (*name++ != EOS);
822                         return(0);
823                 case M_ONE:
824                         if (*name++ == EOS)
825                                 return(0);
826                         break;
827                 case M_SET:
828                         ok = 0;
829                         if ((k = *name++) == EOS)
830                                 return(0);
831                         if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
832                                 ++pat;
833                         while (((c = *pat++) & M_MASK) != M_END)
834                                 if ((*pat & M_MASK) == M_RNG) {
835                                         if (__collate_load_error ?
836                                             CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
837                                                __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
838                                             && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
839                                            )
840                                                 ok = 1;
841                                         pat += 2;
842                                 } else if (c == k)
843                                         ok = 1;
844                         if (ok == negate_range)
845                                 return(0);
846                         break;
847                 default:
848                         if (*name++ != c)
849                                 return(0);
850                         break;
851                 }
852         }
853         return(*name == EOS);
854 }
855
856 /* Free allocated data belonging to a glob_t structure. */
857 void
858 globfree(glob_t *pglob)
859 {
860         size_t i;
861         char **pp;
862
863         if (pglob->gl_pathv != NULL) {
864                 pp = pglob->gl_pathv + pglob->gl_offs;
865                 for (i = pglob->gl_pathc; i--; ++pp)
866                         if (*pp)
867                                 free(*pp);
868                 free(pglob->gl_pathv);
869                 pglob->gl_pathv = NULL;
870         }
871 }
872
873 static DIR *
874 g_opendir(Char *str, glob_t *pglob)
875 {
876         char buf[MAXPATHLEN];
877
878         if (!*str)
879                 strcpy(buf, ".");
880         else {
881                 if (g_Ctoc(str, buf, sizeof(buf)))
882                         return (NULL);
883         }
884
885         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
886                 return((*pglob->gl_opendir)(buf));
887
888         return(opendir(buf));
889 }
890
891 static int
892 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
893 {
894         char buf[MAXPATHLEN];
895
896         if (g_Ctoc(fn, buf, sizeof(buf))) {
897                 errno = ENAMETOOLONG;
898                 return (-1);
899         }
900         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
901                 return((*pglob->gl_lstat)(buf, sb));
902         return(lstat(buf, sb));
903 }
904
905 static int
906 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
907 {
908         char buf[MAXPATHLEN];
909
910         if (g_Ctoc(fn, buf, sizeof(buf))) {
911                 errno = ENAMETOOLONG;
912                 return (-1);
913         }
914         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
915                 return((*pglob->gl_stat)(buf, sb));
916         return(stat(buf, sb));
917 }
918
919 static const Char *
920 g_strchr(const Char *str, wchar_t ch)
921 {
922
923         do {
924                 if (*str == ch)
925                         return (str);
926         } while (*str++);
927         return (NULL);
928 }
929
930 static int
931 g_Ctoc(const Char *str, char *buf, size_t len)
932 {
933         mbstate_t mbs;
934         size_t clen;
935
936         memset(&mbs, 0, sizeof(mbs));
937         while (len >= MB_CUR_MAX) {
938                 clen = wcrtomb(buf, *str, &mbs);
939                 if (clen == (size_t)-1)
940                         return (1);
941                 if (*str == L'\0')
942                         return (0);
943                 str++;
944                 buf += clen;
945                 len -= clen;
946         }
947         return (1);
948 }
949
950 #ifdef DEBUG
951 static void
952 qprintf(const char *str, Char *s)
953 {
954         Char *p;
955
956         (void)printf("%s:\n", str);
957         for (p = s; *p; p++)
958                 (void)printf("%c", CHAR(*p));
959         (void)printf("\n");
960         for (p = s; *p; p++)
961                 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
962         (void)printf("\n");
963         for (p = s; *p; p++)
964                 (void)printf("%c", ismeta(*p) ? '_' : ' ');
965         (void)printf("\n");
966 }
967 #endif