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