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