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