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