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