]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - lib/libc/gen/glob.c
MFC r285340:
[FreeBSD/stable/8.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 * __restrict pattern, int flags,
189          int (*errfunc)(const char *, int), glob_t * __restrict pglob)
190 {
191         struct glob_limit limit = { 0, 0, 0, 0, 0 };
192         const char *patnext;
193         Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
194         mbstate_t mbs;
195         wchar_t wc;
196         size_t clen;
197
198         patnext = pattern;
199         if (!(flags & GLOB_APPEND)) {
200                 pglob->gl_pathc = 0;
201                 pglob->gl_pathv = NULL;
202                 if (!(flags & GLOB_DOOFFS))
203                         pglob->gl_offs = 0;
204         }
205         if (flags & GLOB_LIMIT) {
206                 limit.l_path_lim = pglob->gl_matchc;
207                 if (limit.l_path_lim == 0)
208                         limit.l_path_lim = GLOB_LIMIT_PATH;
209         }
210         pglob->gl_flags = flags & ~GLOB_MAGCHAR;
211         pglob->gl_errfunc = errfunc;
212         pglob->gl_matchc = 0;
213
214         bufnext = patbuf;
215         bufend = bufnext + MAXPATHLEN - 1;
216         if (flags & GLOB_NOESCAPE) {
217                 memset(&mbs, 0, sizeof(mbs));
218                 while (bufend - bufnext >= MB_CUR_MAX) {
219                         clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
220                         if (clen == (size_t)-1 || clen == (size_t)-2)
221                                 return (GLOB_NOMATCH);
222                         else if (clen == 0)
223                                 break;
224                         *bufnext++ = wc;
225                         patnext += clen;
226                 }
227         } else {
228                 /* Protect the quoted characters. */
229                 memset(&mbs, 0, sizeof(mbs));
230                 while (bufend - bufnext >= MB_CUR_MAX) {
231                         if (*patnext == QUOTE) {
232                                 if (*++patnext == EOS) {
233                                         *bufnext++ = QUOTE | M_PROTECT;
234                                         continue;
235                                 }
236                                 prot = M_PROTECT;
237                         } else
238                                 prot = 0;
239                         clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
240                         if (clen == (size_t)-1 || clen == (size_t)-2)
241                                 return (GLOB_NOMATCH);
242                         else if (clen == 0)
243                                 break;
244                         *bufnext++ = wc | prot;
245                         patnext += clen;
246                 }
247         }
248         *bufnext = EOS;
249
250         if (flags & GLOB_BRACE)
251             return globexp1(patbuf, pglob, &limit);
252         else
253             return glob0(patbuf, pglob, &limit);
254 }
255
256 /*
257  * Expand recursively a glob {} pattern. When there is no more expansion
258  * invoke the standard globbing routine to glob the rest of the magic
259  * characters
260  */
261 static int
262 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
263 {
264         const Char* ptr = pattern;
265         int rv;
266
267         if ((pglob->gl_flags & GLOB_LIMIT) &&
268             limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
269                 errno = 0;
270                 return (GLOB_NOSPACE);
271         }
272
273         /* Protect a single {}, for find(1), like csh */
274         if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
275                 return glob0(pattern, pglob, limit);
276
277         while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
278                 if (!globexp2(ptr, pattern, pglob, &rv, limit))
279                         return rv;
280
281         return glob0(pattern, pglob, limit);
282 }
283
284
285 /*
286  * Recursive brace globbing helper. Tries to expand a single brace.
287  * If it succeeds then it invokes globexp1 with the new pattern.
288  * If it fails then it tries to glob the rest of the pattern and returns.
289  */
290 static int
291 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
292     struct glob_limit *limit)
293 {
294         int     i;
295         Char   *lm, *ls;
296         const Char *pe, *pm, *pm1, *pl;
297         Char    patbuf[MAXPATHLEN];
298
299         /* copy part up to the brace */
300         for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
301                 continue;
302         *lm = EOS;
303         ls = lm;
304
305         /* Find the balanced brace */
306         for (i = 0, pe = ++ptr; *pe; pe++)
307                 if (*pe == LBRACKET) {
308                         /* Ignore everything between [] */
309                         for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
310                                 continue;
311                         if (*pe == EOS) {
312                                 /*
313                                  * We could not find a matching RBRACKET.
314                                  * Ignore and just look for RBRACE
315                                  */
316                                 pe = pm;
317                         }
318                 }
319                 else if (*pe == LBRACE)
320                         i++;
321                 else if (*pe == RBRACE) {
322                         if (i == 0)
323                                 break;
324                         i--;
325                 }
326
327         /* Non matching braces; just glob the pattern */
328         if (i != 0 || *pe == EOS) {
329                 *rv = glob0(patbuf, pglob, limit);
330                 return 0;
331         }
332
333         for (i = 0, pl = pm = ptr; pm <= pe; pm++)
334                 switch (*pm) {
335                 case LBRACKET:
336                         /* Ignore everything between [] */
337                         for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
338                                 continue;
339                         if (*pm == EOS) {
340                                 /*
341                                  * We could not find a matching RBRACKET.
342                                  * Ignore and just look for RBRACE
343                                  */
344                                 pm = pm1;
345                         }
346                         break;
347
348                 case LBRACE:
349                         i++;
350                         break;
351
352                 case RBRACE:
353                         if (i) {
354                             i--;
355                             break;
356                         }
357                         /* FALLTHROUGH */
358                 case COMMA:
359                         if (i && *pm == COMMA)
360                                 break;
361                         else {
362                                 /* Append the current string */
363                                 for (lm = ls; (pl < pm); *lm++ = *pl++)
364                                         continue;
365                                 /*
366                                  * Append the rest of the pattern after the
367                                  * closing brace
368                                  */
369                                 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
370                                         continue;
371
372                                 /* Expand the current pattern */
373 #ifdef DEBUG
374                                 qprintf("globexp2:", patbuf);
375 #endif
376                                 *rv = globexp1(patbuf, pglob, limit);
377
378                                 /* move after the comma, to the next string */
379                                 pl = pm + 1;
380                         }
381                         break;
382
383                 default:
384                         break;
385                 }
386         *rv = 0;
387         return 0;
388 }
389
390
391
392 /*
393  * expand tilde from the passwd file.
394  */
395 static const Char *
396 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
397 {
398         struct passwd *pwd;
399         char *h;
400         const Char *p;
401         Char *b, *eb;
402
403         if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
404                 return pattern;
405
406         /* 
407          * Copy up to the end of the string or / 
408          */
409         eb = &patbuf[patbuf_len - 1];
410         for (p = pattern + 1, h = (char *) patbuf;
411             h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
412                 continue;
413
414         *h = EOS;
415
416         if (((char *) patbuf)[0] == EOS) {
417                 /*
418                  * handle a plain ~ or ~/ by expanding $HOME first (iff
419                  * we're not running setuid or setgid) and then trying
420                  * the password file
421                  */
422                 if (issetugid() != 0 ||
423                     (h = getenv("HOME")) == NULL) {
424                         if (((h = getlogin()) != NULL &&
425                              (pwd = getpwnam(h)) != NULL) ||
426                             (pwd = getpwuid(getuid())) != NULL)
427                                 h = pwd->pw_dir;
428                         else
429                                 return pattern;
430                 }
431         }
432         else {
433                 /*
434                  * Expand a ~user
435                  */
436                 if ((pwd = getpwnam((char*) patbuf)) == NULL)
437                         return pattern;
438                 else
439                         h = pwd->pw_dir;
440         }
441
442         /* Copy the home directory */
443         for (b = patbuf; b < eb && *h; *b++ = *h++)
444                 continue;
445
446         /* Append the rest of the pattern */
447         while (b < eb && (*b++ = *p++) != EOS)
448                 continue;
449         *b = EOS;
450
451         return patbuf;
452 }
453
454
455 /*
456  * The main glob() routine: compiles the pattern (optionally processing
457  * quotes), calls glob1() to do the real pattern matching, and finally
458  * sorts the list (unless unsorted operation is requested).  Returns 0
459  * if things went well, nonzero if errors occurred.
460  */
461 static int
462 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
463 {
464         const Char *qpatnext;
465         int err;
466         size_t oldpathc;
467         Char *bufnext, c, patbuf[MAXPATHLEN];
468
469         qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
470         oldpathc = pglob->gl_pathc;
471         bufnext = patbuf;
472
473         /* We don't need to check for buffer overflow any more. */
474         while ((c = *qpatnext++) != EOS) {
475                 switch (c) {
476                 case LBRACKET:
477                         c = *qpatnext;
478                         if (c == NOT)
479                                 ++qpatnext;
480                         if (*qpatnext == EOS ||
481                             g_strchr(qpatnext+1, RBRACKET) == NULL) {
482                                 *bufnext++ = LBRACKET;
483                                 if (c == NOT)
484                                         --qpatnext;
485                                 break;
486                         }
487                         *bufnext++ = M_SET;
488                         if (c == NOT)
489                                 *bufnext++ = M_NOT;
490                         c = *qpatnext++;
491                         do {
492                                 *bufnext++ = CHAR(c);
493                                 if (*qpatnext == RANGE &&
494                                     (c = qpatnext[1]) != RBRACKET) {
495                                         *bufnext++ = M_RNG;
496                                         *bufnext++ = CHAR(c);
497                                         qpatnext += 2;
498                                 }
499                         } while ((c = *qpatnext++) != RBRACKET);
500                         pglob->gl_flags |= GLOB_MAGCHAR;
501                         *bufnext++ = M_END;
502                         break;
503                 case QUESTION:
504                         pglob->gl_flags |= GLOB_MAGCHAR;
505                         *bufnext++ = M_ONE;
506                         break;
507                 case STAR:
508                         pglob->gl_flags |= GLOB_MAGCHAR;
509                         /* collapse adjacent stars to one,
510                          * to avoid exponential behavior
511                          */
512                         if (bufnext == patbuf || bufnext[-1] != M_ALL)
513                             *bufnext++ = M_ALL;
514                         break;
515                 default:
516                         *bufnext++ = CHAR(c);
517                         break;
518                 }
519         }
520         *bufnext = EOS;
521 #ifdef DEBUG
522         qprintf("glob0:", patbuf);
523 #endif
524
525         if ((err = glob1(patbuf, pglob, limit)) != 0)
526                 return(err);
527
528         /*
529          * If there was no match we are going to append the pattern
530          * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
531          * and the pattern did not contain any magic characters
532          * GLOB_NOMAGIC is there just for compatibility with csh.
533          */
534         if (pglob->gl_pathc == oldpathc) {
535                 if (((pglob->gl_flags & GLOB_NOCHECK) ||
536                     ((pglob->gl_flags & GLOB_NOMAGIC) &&
537                         !(pglob->gl_flags & GLOB_MAGCHAR))))
538                         return(globextend(pattern, pglob, limit));
539                 else
540                         return(GLOB_NOMATCH);
541         }
542         if (!(pglob->gl_flags & GLOB_NOSORT))
543                 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
544                     pglob->gl_pathc - oldpathc, sizeof(char *), compare);
545         return(0);
546 }
547
548 static int
549 compare(const void *p, const void *q)
550 {
551         return(strcmp(*(char **)p, *(char **)q));
552 }
553
554 static int
555 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
556 {
557         Char pathbuf[MAXPATHLEN];
558
559         /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
560         if (*pattern == EOS)
561                 return(0);
562         return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
563             pattern, pglob, limit));
564 }
565
566 /*
567  * The functions glob2 and glob3 are mutually recursive; there is one level
568  * of recursion for each segment in the pattern that contains one or more
569  * meta characters.
570  */
571 static int
572 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
573       glob_t *pglob, struct glob_limit *limit)
574 {
575         struct stat sb;
576         Char *p, *q;
577         int anymeta;
578
579         /*
580          * Loop over pattern segments until end of pattern or until
581          * segment with meta character found.
582          */
583         for (anymeta = 0;;) {
584                 if (*pattern == EOS) {          /* End of pattern? */
585                         *pathend = EOS;
586                         if (g_lstat(pathbuf, &sb, pglob))
587                                 return(0);
588
589                         if ((pglob->gl_flags & GLOB_LIMIT) &&
590                             limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
591                                 errno = 0;
592                                 if (pathend + 1 > pathend_last)
593                                         return (GLOB_ABORTED);
594                                 *pathend++ = SEP;
595                                 *pathend = EOS;
596                                 return (GLOB_NOSPACE);
597                         }
598                         if (((pglob->gl_flags & GLOB_MARK) &&
599                             pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
600                             || (S_ISLNK(sb.st_mode) &&
601                             (g_stat(pathbuf, &sb, pglob) == 0) &&
602                             S_ISDIR(sb.st_mode)))) {
603                                 if (pathend + 1 > pathend_last)
604                                         return (GLOB_ABORTED);
605                                 *pathend++ = SEP;
606                                 *pathend = EOS;
607                         }
608                         ++pglob->gl_matchc;
609                         return(globextend(pathbuf, pglob, limit));
610                 }
611
612                 /* Find end of next segment, copy tentatively to pathend. */
613                 q = pathend;
614                 p = pattern;
615                 while (*p != EOS && *p != SEP) {
616                         if (ismeta(*p))
617                                 anymeta = 1;
618                         if (q + 1 > pathend_last)
619                                 return (GLOB_ABORTED);
620                         *q++ = *p++;
621                 }
622
623                 if (!anymeta) {         /* No expansion, do next segment. */
624                         pathend = q;
625                         pattern = p;
626                         while (*pattern == SEP) {
627                                 if (pathend + 1 > pathend_last)
628                                         return (GLOB_ABORTED);
629                                 *pathend++ = *pattern++;
630                         }
631                 } else                  /* Need expansion, recurse. */
632                         return(glob3(pathbuf, pathend, pathend_last, pattern, p,
633                             pglob, limit));
634         }
635         /* NOTREACHED */
636 }
637
638 static int
639 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
640       Char *pattern, Char *restpattern,
641       glob_t *pglob, struct glob_limit *limit)
642 {
643         struct dirent *dp;
644         DIR *dirp;
645         int err;
646         char buf[MAXPATHLEN];
647
648         /*
649          * The readdirfunc declaration can't be prototyped, because it is
650          * assigned, below, to two functions which are prototyped in glob.h
651          * and dirent.h as taking pointers to differently typed opaque
652          * structures.
653          */
654         struct dirent *(*readdirfunc)();
655
656         if (pathend > pathend_last)
657                 return (GLOB_ABORTED);
658         *pathend = EOS;
659         errno = 0;
660
661         if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
662                 /* TODO: don't call for ENOENT or ENOTDIR? */
663                 if (pglob->gl_errfunc) {
664                         if (g_Ctoc(pathbuf, buf, sizeof(buf)))
665                                 return (GLOB_ABORTED);
666                         if (pglob->gl_errfunc(buf, errno) ||
667                             pglob->gl_flags & GLOB_ERR)
668                                 return (GLOB_ABORTED);
669                 }
670                 return(0);
671         }
672
673         err = 0;
674
675         /* Search directory for matching names. */
676         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
677                 readdirfunc = pglob->gl_readdir;
678         else
679                 readdirfunc = readdir;
680         while ((dp = (*readdirfunc)(dirp))) {
681                 char *sc;
682                 Char *dc;
683                 wchar_t wc;
684                 size_t clen;
685                 mbstate_t mbs;
686
687                 if ((pglob->gl_flags & GLOB_LIMIT) &&
688                     limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
689                         errno = 0;
690                         if (pathend + 1 > pathend_last)
691                                 err = GLOB_ABORTED;
692                         else {
693                                 *pathend++ = SEP;
694                                 *pathend = EOS;
695                                 err = GLOB_NOSPACE;
696                         }
697                         break;
698                 }
699
700                 /* Initial DOT must be matched literally. */
701                 if (dp->d_name[0] == DOT && *pattern != DOT)
702                         continue;
703                 memset(&mbs, 0, sizeof(mbs));
704                 dc = pathend;
705                 sc = dp->d_name;
706                 while (dc < pathend_last) {
707                         clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
708                         if (clen == (size_t)-1 || clen == (size_t)-2) {
709                                 wc = *sc;
710                                 clen = 1;
711                                 memset(&mbs, 0, sizeof(mbs));
712                         }
713                         if ((*dc++ = wc) == EOS)
714                                 break;
715                         sc += clen;
716                 }
717                 if (!match(pathend, pattern, restpattern)) {
718                         *pathend = EOS;
719                         continue;
720                 }
721                 err = glob2(pathbuf, --dc, pathend_last, restpattern,
722                     pglob, limit);
723                 if (err)
724                         break;
725         }
726
727         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
728                 (*pglob->gl_closedir)(dirp);
729         else
730                 closedir(dirp);
731         return(err);
732 }
733
734
735 /*
736  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
737  * add the new item, and update gl_pathc.
738  *
739  * This assumes the BSD realloc, which only copies the block when its size
740  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
741  * behavior.
742  *
743  * Return 0 if new item added, error code if memory couldn't be allocated.
744  *
745  * Invariant of the glob_t structure:
746  *      Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
747  *      gl_pathv points to (gl_offs + gl_pathc + 1) items.
748  */
749 static int
750 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
751 {
752         char **pathv;
753         size_t i, newsize, len;
754         char *copy;
755         const Char *p;
756
757         if ((pglob->gl_flags & GLOB_LIMIT) &&
758             pglob->gl_matchc > limit->l_path_lim) {
759                 errno = 0;
760                 return (GLOB_NOSPACE);
761         }
762
763         newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
764         /* realloc(NULL, newsize) is equivalent to malloc(newsize). */
765         pathv = realloc((void *)pglob->gl_pathv, newsize);
766         if (pathv == NULL)
767                 return(GLOB_NOSPACE);
768
769         if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
770                 /* first time around -- clear initial gl_offs items */
771                 pathv += pglob->gl_offs;
772                 for (i = pglob->gl_offs + 1; --i > 0; )
773                         *--pathv = NULL;
774         }
775         pglob->gl_pathv = pathv;
776
777         for (p = path; *p++;)
778                 continue;
779         len = MB_CUR_MAX * (size_t)(p - path);  /* XXX overallocation */
780         limit->l_string_cnt += len;
781         if ((pglob->gl_flags & GLOB_LIMIT) &&
782             limit->l_string_cnt >= GLOB_LIMIT_STRING) {
783                 errno = 0;
784                 return (GLOB_NOSPACE);
785         }
786         if ((copy = malloc(len)) != NULL) {
787                 if (g_Ctoc(path, copy, len)) {
788                         free(copy);
789                         return (GLOB_NOSPACE);
790                 }
791                 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
792         }
793         pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
794         return(copy == NULL ? GLOB_NOSPACE : 0);
795 }
796
797 /*
798  * pattern matching function for filenames.  Each occurrence of the *
799  * pattern causes a recursion level.
800  */
801 static int
802 match(Char *name, Char *pat, Char *patend)
803 {
804         int ok, negate_range;
805         Char c, k;
806
807         while (pat < patend) {
808                 c = *pat++;
809                 switch (c & M_MASK) {
810                 case M_ALL:
811                         if (pat == patend)
812                                 return(1);
813                         do
814                             if (match(name, pat, patend))
815                                     return(1);
816                         while (*name++ != EOS);
817                         return(0);
818                 case M_ONE:
819                         if (*name++ == EOS)
820                                 return(0);
821                         break;
822                 case M_SET:
823                         ok = 0;
824                         if ((k = *name++) == EOS)
825                                 return(0);
826                         if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
827                                 ++pat;
828                         while (((c = *pat++) & M_MASK) != M_END)
829                                 if ((*pat & M_MASK) == M_RNG) {
830                                         if (__collate_load_error ?
831                                             CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
832                                                __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
833                                             && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
834                                            )
835                                                 ok = 1;
836                                         pat += 2;
837                                 } else if (c == k)
838                                         ok = 1;
839                         if (ok == negate_range)
840                                 return(0);
841                         break;
842                 default:
843                         if (*name++ != c)
844                                 return(0);
845                         break;
846                 }
847         }
848         return(*name == EOS);
849 }
850
851 /* Free allocated data belonging to a glob_t structure. */
852 void
853 globfree(glob_t *pglob)
854 {
855         size_t i;
856         char **pp;
857
858         if (pglob->gl_pathv != NULL) {
859                 pp = pglob->gl_pathv + pglob->gl_offs;
860                 for (i = pglob->gl_pathc; i--; ++pp)
861                         if (*pp)
862                                 free(*pp);
863                 free(pglob->gl_pathv);
864                 pglob->gl_pathv = NULL;
865         }
866 }
867
868 static DIR *
869 g_opendir(Char *str, glob_t *pglob)
870 {
871         char buf[MAXPATHLEN];
872
873         if (!*str)
874                 strcpy(buf, ".");
875         else {
876                 if (g_Ctoc(str, buf, sizeof(buf)))
877                         return (NULL);
878         }
879
880         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
881                 return((*pglob->gl_opendir)(buf));
882
883         return(opendir(buf));
884 }
885
886 static int
887 g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
888 {
889         char buf[MAXPATHLEN];
890
891         if (g_Ctoc(fn, buf, sizeof(buf))) {
892                 errno = ENAMETOOLONG;
893                 return (-1);
894         }
895         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
896                 return((*pglob->gl_lstat)(buf, sb));
897         return(lstat(buf, sb));
898 }
899
900 static int
901 g_stat(Char *fn, struct stat *sb, glob_t *pglob)
902 {
903         char buf[MAXPATHLEN];
904
905         if (g_Ctoc(fn, buf, sizeof(buf))) {
906                 errno = ENAMETOOLONG;
907                 return (-1);
908         }
909         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
910                 return((*pglob->gl_stat)(buf, sb));
911         return(stat(buf, sb));
912 }
913
914 static const Char *
915 g_strchr(const Char *str, wchar_t ch)
916 {
917
918         do {
919                 if (*str == ch)
920                         return (str);
921         } while (*str++);
922         return (NULL);
923 }
924
925 static int
926 g_Ctoc(const Char *str, char *buf, size_t len)
927 {
928         mbstate_t mbs;
929         size_t clen;
930
931         memset(&mbs, 0, sizeof(mbs));
932         while (len >= MB_CUR_MAX) {
933                 clen = wcrtomb(buf, *str, &mbs);
934                 if (clen == (size_t)-1)
935                         return (1);
936                 if (*str == L'\0')
937                         return (0);
938                 str++;
939                 buf += clen;
940                 len -= clen;
941         }
942         return (1);
943 }
944
945 #ifdef DEBUG
946 static void
947 qprintf(const char *str, Char *s)
948 {
949         Char *p;
950
951         (void)printf("%s:\n", str);
952         for (p = s; *p; p++)
953                 (void)printf("%c", CHAR(*p));
954         (void)printf("\n");
955         for (p = s; *p; p++)
956                 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
957         (void)printf("\n");
958         for (p = s; *p; p++)
959                 (void)printf("%c", ismeta(*p) ? '_' : ' ');
960         (void)printf("\n");
961 }
962 #endif