Integrate changes #9678,9679 from maintline into mainperl.
[p5sagit/p5-mst-13.2.git] / ext / File / Glob / bsd_glob.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Guido van Rossum.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)glob.c      8.3 (Berkeley) 10/13/93";
35 /* most changes between the version above and the one below have been ported:
36 static char sscsid[]=  "$OpenBSD: glob.c,v 1.8.10.1 2001/04/10 jason Exp $";
37  */
38 #endif /* LIBC_SCCS and not lint */
39
40 /*
41  * glob(3) -- a superset of the one defined in POSIX 1003.2.
42  *
43  * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
44  *
45  * Optional extra services, controlled by flags not defined by POSIX:
46  *
47  * GLOB_QUOTE:
48  *      Escaping convention: \ inhibits any special meaning the following
49  *      character might have (except \ at end of string is retained).
50  * GLOB_MAGCHAR:
51  *      Set in gl_flags if pattern contained a globbing character.
52  * GLOB_NOMAGIC:
53  *      Same as GLOB_NOCHECK, but it will only append pattern if it did
54  *      not contain any magic characters.  [Used in csh style globbing]
55  * GLOB_ALTDIRFUNC:
56  *      Use alternately specified directory access functions.
57  * GLOB_TILDE:
58  *      expand ~user/foo to the /home/dir/of/user/foo
59  * GLOB_BRACE:
60  *      expand {1,2}{a,b} to 1a 1b 2a 2b
61  * gl_matchc:
62  *      Number of matches in the current invocation of glob.
63  * GLOB_ALPHASORT:
64  *      sort alphabetically like csh (case doesn't matter) instead of in ASCII
65  *      order
66  */
67
68 #include <EXTERN.h>
69 #include <perl.h>
70 #include <XSUB.h>
71
72 #include "bsd_glob.h"
73 #ifdef I_PWD
74 #       include <pwd.h>
75 #else
76 #ifdef HAS_PASSWD
77         struct passwd *getpwnam(char *);
78         struct passwd *getpwuid(Uid_t);
79 #endif
80 #endif
81
82 #ifndef MAXPATHLEN
83 #  ifdef PATH_MAX
84 #    define     MAXPATHLEN      PATH_MAX
85 #    ifdef MACOS_TRADITIONAL
86 #      define   MAXPATHLEN      255
87 #    else
88 #      define   MAXPATHLEN      1024
89 #    endif
90 #  endif
91 #endif
92
93 #ifdef I_LIMITS
94 #include <limits.h>
95 #endif
96
97 #ifndef ARG_MAX
98 #  ifdef _SC_ARG_MAX
99 #    define     ARG_MAX         (sysconf(_SC_ARG_MAX))
100 #  else
101 #    ifdef _POSIX_ARG_MAX
102 #      define   ARG_MAX         _POSIX_ARG_MAX
103 #    else
104 #      ifdef WIN32
105 #        define ARG_MAX         14500   /* from VC's limits.h */
106 #      else
107 #        define ARG_MAX         4096    /* from POSIX, be conservative */
108 #      endif
109 #    endif
110 #  endif
111 #endif
112
113 #define BG_DOLLAR       '$'
114 #define BG_DOT          '.'
115 #define BG_EOS          '\0'
116 #define BG_LBRACKET     '['
117 #define BG_NOT          '!'
118 #define BG_QUESTION     '?'
119 #define BG_QUOTE        '\\'
120 #define BG_RANGE        '-'
121 #define BG_RBRACKET     ']'
122 #ifdef MACOS_TRADITIONAL
123 #  define       BG_SEP  ':'
124 #else
125 #  define       BG_SEP  '/'
126 #endif
127 #ifdef DOSISH
128 #define BG_SEP2         '\\'
129 #endif
130 #define BG_STAR         '*'
131 #define BG_TILDE        '~'
132 #define BG_UNDERSCORE   '_'
133 #define BG_LBRACE       '{'
134 #define BG_RBRACE       '}'
135 #define BG_SLASH        '/'
136 #define BG_COMMA        ','
137
138 #ifndef GLOB_DEBUG
139
140 #define M_QUOTE         0x8000
141 #define M_PROTECT       0x4000
142 #define M_MASK          0xffff
143 #define M_ASCII         0x00ff
144
145 typedef U16 Char;
146
147 #else
148
149 #define M_QUOTE         0x80
150 #define M_PROTECT       0x40
151 #define M_MASK          0xff
152 #define M_ASCII         0x7f
153
154 typedef U8 Char;
155
156 #endif /* !GLOB_DEBUG */
157
158
159 #define CHAR(c)         ((Char)((c)&M_ASCII))
160 #define META(c)         ((Char)((c)|M_QUOTE))
161 #define M_ALL           META('*')
162 #define M_END           META(']')
163 #define M_NOT           META('!')
164 #define M_ONE           META('?')
165 #define M_RNG           META('-')
166 #define M_SET           META('[')
167 #define ismeta(c)       (((c)&M_QUOTE) != 0)
168
169
170 static int       compare(const void *, const void *);
171 static int       ci_compare(const void *, const void *);
172 static int       g_Ctoc(const Char *, char *, STRLEN);
173 static int       g_lstat(Char *, Stat_t *, glob_t *);
174 static DIR      *g_opendir(Char *, glob_t *);
175 static Char     *g_strchr(Char *, int);
176 static int       g_stat(Char *, Stat_t *, glob_t *);
177 static int       glob0(const Char *, glob_t *);
178 static int       glob1(Char *, Char *, glob_t *, size_t *);
179 static int       glob2(Char *, Char *, Char *, Char *, Char *, Char *,
180                        glob_t *, size_t *);
181 static int       glob3(Char *, Char *, Char *, Char *, Char *, Char *,
182                        Char *, Char *, glob_t *, size_t *);
183 static int       globextend(const Char *, glob_t *, size_t *);
184 static const Char *
185                  globtilde(const Char *, Char *, size_t, glob_t *);
186 static int       globexp1(const Char *, glob_t *);
187 static int       globexp2(const Char *, const Char *, glob_t *, int *);
188 static int       match(Char *, Char *, Char *, int);
189 #ifdef GLOB_DEBUG
190 static void      qprintf(const char *, Char *);
191 #endif /* GLOB_DEBUG */
192
193 #ifdef PERL_IMPLICIT_CONTEXT
194 static Direntry_t *     my_readdir(DIR*);
195
196 static Direntry_t *
197 my_readdir(DIR *d)
198 {
199     return PerlDir_read(d);
200 }
201 #else
202 #define my_readdir      readdir
203 #endif
204
205 int
206 bsd_glob(const char *pattern, int flags,
207          int (*errfunc)(const char *, int), glob_t *pglob)
208 {
209         const U8 *patnext;
210         int c;
211         Char *bufnext, *bufend, patbuf[MAXPATHLEN];
212
213         patnext = (U8 *) pattern;
214         if (!(flags & GLOB_APPEND)) {
215                 pglob->gl_pathc = 0;
216                 pglob->gl_pathv = NULL;
217                 if (!(flags & GLOB_DOOFFS))
218                         pglob->gl_offs = 0;
219         }
220         pglob->gl_flags = flags & ~GLOB_MAGCHAR;
221         pglob->gl_errfunc = errfunc;
222         pglob->gl_matchc = 0;
223
224         bufnext = patbuf;
225         bufend = bufnext + MAXPATHLEN - 1;
226 #ifdef DOSISH
227         /* Nasty hack to treat patterns like "C:*" correctly. In this
228          * case, the * should match any file in the current directory
229          * on the C: drive. However, the glob code does not treat the
230          * colon specially, so it looks for files beginning "C:" in
231          * the current directory. To fix this, change the pattern to
232          * add an explicit "./" at the start (just after the drive
233          * letter and colon - ie change to "C:./*").
234          */
235         if (isalpha(pattern[0]) && pattern[1] == ':' &&
236             pattern[2] != BG_SEP && pattern[2] != BG_SEP2 &&
237             bufend - bufnext > 4) {
238                 *bufnext++ = pattern[0];
239                 *bufnext++ = ':';
240                 *bufnext++ = '.';
241                 *bufnext++ = BG_SEP;
242                 patnext += 2;
243         }
244 #endif
245         if (flags & GLOB_QUOTE) {
246                 /* Protect the quoted characters. */
247                 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
248                         if (c == BG_QUOTE) {
249 #ifdef DOSISH
250                                     /* To avoid backslashitis on Win32,
251                                      * we only treat \ as a quoting character
252                                      * if it precedes one of the
253                                      * metacharacters []-{}~\
254                                      */
255                                 if ((c = *patnext++) != '[' && c != ']' &&
256                                     c != '-' && c != '{' && c != '}' &&
257                                     c != '~' && c != '\\') {
258 #else
259                                 if ((c = *patnext++) == BG_EOS) {
260 #endif
261                                         c = BG_QUOTE;
262                                         --patnext;
263                                 }
264                                 *bufnext++ = c | M_PROTECT;
265                         } else
266                                 *bufnext++ = c;
267         } else
268                 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
269                         *bufnext++ = c;
270         *bufnext = BG_EOS;
271
272         if (flags & GLOB_BRACE)
273             return globexp1(patbuf, pglob);
274         else
275             return glob0(patbuf, pglob);
276 }
277
278 /*
279  * Expand recursively a glob {} pattern. When there is no more expansion
280  * invoke the standard globbing routine to glob the rest of the magic
281  * characters
282  */
283 static int
284 globexp1(const Char *pattern, glob_t *pglob)
285 {
286         const Char* ptr = pattern;
287         int rv;
288
289         /* Protect a single {}, for find(1), like csh */
290         if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
291                 return glob0(pattern, pglob);
292
293         while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
294                 if (!globexp2(ptr, pattern, pglob, &rv))
295                         return rv;
296
297         return glob0(pattern, pglob);
298 }
299
300
301 /*
302  * Recursive brace globbing helper. Tries to expand a single brace.
303  * If it succeeds then it invokes globexp1 with the new pattern.
304  * If it fails then it tries to glob the rest of the pattern and returns.
305  */
306 static int
307 globexp2(const Char *ptr, const Char *pattern,
308          glob_t *pglob, int *rv)
309 {
310         int     i;
311         Char   *lm, *ls;
312         const Char *pe, *pm, *pl;
313         Char    patbuf[MAXPATHLEN];
314
315         /* copy part up to the brace */
316         for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
317                 ;
318         *lm = BG_EOS;
319         ls = lm;
320
321         /* Find the balanced brace */
322         for (i = 0, pe = ++ptr; *pe; pe++)
323                 if (*pe == BG_LBRACKET) {
324                         /* Ignore everything between [] */
325                         for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
326                                 ;
327                         if (*pe == BG_EOS) {
328                                 /*
329                                  * We could not find a matching BG_RBRACKET.
330                                  * Ignore and just look for BG_RBRACE
331                                  */
332                                 pe = pm;
333                         }
334                 } else if (*pe == BG_LBRACE)
335                         i++;
336                 else if (*pe == BG_RBRACE) {
337                         if (i == 0)
338                                 break;
339                         i--;
340                 }
341
342         /* Non matching braces; just glob the pattern */
343         if (i != 0 || *pe == BG_EOS) {
344                 *rv = glob0(patbuf, pglob);
345                 return 0;
346         }
347
348         for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
349                 switch (*pm) {
350                 case BG_LBRACKET:
351                         /* Ignore everything between [] */
352                         for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
353                                 ;
354                         if (*pm == BG_EOS) {
355                                 /*
356                                  * We could not find a matching BG_RBRACKET.
357                                  * Ignore and just look for BG_RBRACE
358                                  */
359                                 pm = pl;
360                         }
361                         break;
362
363                 case BG_LBRACE:
364                         i++;
365                         break;
366
367                 case BG_RBRACE:
368                         if (i) {
369                                 i--;
370                                 break;
371                         }
372                         /* FALLTHROUGH */
373                 case BG_COMMA:
374                         if (i && *pm == BG_COMMA)
375                                 break;
376                         else {
377                                 /* Append the current string */
378                                 for (lm = ls; (pl < pm); *lm++ = *pl++)
379                                         ;
380
381                                 /*
382                                  * Append the rest of the pattern after the
383                                  * closing brace
384                                  */
385                                 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS; )
386                                         ;
387
388                                 /* Expand the current pattern */
389 #ifdef GLOB_DEBUG
390                                 qprintf("globexp2:", patbuf);
391 #endif /* GLOB_DEBUG */
392                                 *rv = globexp1(patbuf, pglob);
393
394                                 /* move after the comma, to the next string */
395                                 pl = pm + 1;
396                         }
397                         break;
398
399                 default:
400                         break;
401                 }
402         }
403         *rv = 0;
404         return 0;
405 }
406
407
408
409 /*
410  * expand tilde from the passwd file.
411  */
412 static const Char *
413 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
414 {
415         struct passwd *pwd;
416         char *h;
417         const Char *p;
418         Char *b, *eb;
419
420         if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
421                 return pattern;
422
423         /* Copy up to the end of the string or / */
424         eb = &patbuf[patbuf_len - 1];
425         for (p = pattern + 1, h = (char *) patbuf;
426              h < (char*)eb && *p && *p != BG_SLASH; *h++ = *p++)
427                 ;
428
429         *h = BG_EOS;
430
431 #if 0
432         if (h == (char *)eb)
433                 return what;
434 #endif
435
436         if (((char *) patbuf)[0] == BG_EOS) {
437                 /*
438                  * handle a plain ~ or ~/ by expanding $HOME
439                  * first and then trying the password file
440                  */
441                 if ((h = getenv("HOME")) == NULL) {
442 #ifdef HAS_PASSWD
443                         if ((pwd = getpwuid(getuid())) == NULL)
444                                 return pattern;
445                         else
446                                 h = pwd->pw_dir;
447 #else
448                         return pattern;
449 #endif
450                 }
451         } else {
452                 /*
453                  * Expand a ~user
454                  */
455 #ifdef HAS_PASSWD
456                 if ((pwd = getpwnam((char*) patbuf)) == NULL)
457                         return pattern;
458                 else
459                         h = pwd->pw_dir;
460 #else
461                 return pattern;
462 #endif
463         }
464
465         /* Copy the home directory */
466         for (b = patbuf; b < eb && *h; *b++ = *h++)
467                 ;
468
469         /* Append the rest of the pattern */
470         while (b < eb && (*b++ = *p++) != BG_EOS)
471                 ;
472         *b = BG_EOS;
473
474         return patbuf;
475 }
476
477
478 /*
479  * The main glob() routine: compiles the pattern (optionally processing
480  * quotes), calls glob1() to do the real pattern matching, and finally
481  * sorts the list (unless unsorted operation is requested).  Returns 0
482  * if things went well, nonzero if errors occurred.  It is not an error
483  * to find no matches.
484  */
485 static int
486 glob0(const Char *pattern, glob_t *pglob)
487 {
488         const Char *qpat, *qpatnext;
489         int c, err, oldflags, oldpathc;
490         Char *bufnext, patbuf[MAXPATHLEN];
491         size_t limit = 0;
492
493 #ifdef MACOS_TRADITIONAL
494         if ( (*pattern == BG_TILDE) && (pglob->gl_flags & GLOB_TILDE) ) {
495                 return(globextend(pattern, pglob));
496         }
497 #endif
498
499         qpat = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
500         qpatnext = qpat;
501         oldflags = pglob->gl_flags;
502         oldpathc = pglob->gl_pathc;
503         bufnext = patbuf;
504
505         /* We don't need to check for buffer overflow any more. */
506         while ((c = *qpatnext++) != BG_EOS) {
507                 switch (c) {
508                 case BG_LBRACKET:
509                         c = *qpatnext;
510                         if (c == BG_NOT)
511                                 ++qpatnext;
512                         if (*qpatnext == BG_EOS ||
513                             g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
514                                 *bufnext++ = BG_LBRACKET;
515                                 if (c == BG_NOT)
516                                         --qpatnext;
517                                 break;
518                         }
519                         *bufnext++ = M_SET;
520                         if (c == BG_NOT)
521                                 *bufnext++ = M_NOT;
522                         c = *qpatnext++;
523                         do {
524                                 *bufnext++ = CHAR(c);
525                                 if (*qpatnext == BG_RANGE &&
526                                     (c = qpatnext[1]) != BG_RBRACKET) {
527                                         *bufnext++ = M_RNG;
528                                         *bufnext++ = CHAR(c);
529                                         qpatnext += 2;
530                                 }
531                         } while ((c = *qpatnext++) != BG_RBRACKET);
532                         pglob->gl_flags |= GLOB_MAGCHAR;
533                         *bufnext++ = M_END;
534                         break;
535                 case BG_QUESTION:
536                         pglob->gl_flags |= GLOB_MAGCHAR;
537                         *bufnext++ = M_ONE;
538                         break;
539                 case BG_STAR:
540                         pglob->gl_flags |= GLOB_MAGCHAR;
541                         /* collapse adjacent stars to one,
542                          * to avoid exponential behavior
543                          */
544                         if (bufnext == patbuf || bufnext[-1] != M_ALL)
545                                 *bufnext++ = M_ALL;
546                         break;
547                 default:
548                         *bufnext++ = CHAR(c);
549                         break;
550                 }
551         }
552         *bufnext = BG_EOS;
553 #ifdef GLOB_DEBUG
554         qprintf("glob0:", patbuf);
555 #endif /* GLOB_DEBUG */
556
557         if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0) {
558                 pglob->gl_flags = oldflags;
559                 return(err);
560         }
561
562         /*
563          * If there was no match we are going to append the pattern
564          * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
565          * and the pattern did not contain any magic characters
566          * GLOB_NOMAGIC is there just for compatibility with csh.
567          */
568         if (pglob->gl_pathc == oldpathc &&
569             ((pglob->gl_flags & GLOB_NOCHECK) ||
570               ((pglob->gl_flags & GLOB_NOMAGIC) &&
571                !(pglob->gl_flags & GLOB_MAGCHAR))))
572         {
573 #ifdef GLOB_DEBUG
574                 printf("calling globextend from glob0\n");
575 #endif /* GLOB_DEBUG */
576                 pglob->gl_flags = oldflags;
577                 return(globextend(qpat, pglob, &limit));
578         }
579         else if (!(pglob->gl_flags & GLOB_NOSORT))
580                 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
581                     pglob->gl_pathc - oldpathc, sizeof(char *), 
582                     (pglob->gl_flags & (GLOB_ALPHASORT|GLOB_NOCASE))
583                         ? ci_compare : compare);
584         pglob->gl_flags = oldflags;
585         return(0);
586 }
587
588 static int
589 ci_compare(const void *p, const void *q)
590 {
591         const char *pp = *(const char **)p;
592         const char *qq = *(const char **)q;
593         int ci;
594         while (*pp && *qq) {
595                 if (tolower(*pp) != tolower(*qq))
596                         break;
597                 ++pp;
598                 ++qq;
599         }
600         ci = tolower(*pp) - tolower(*qq);
601         if (ci == 0)
602                 return compare(p, q);
603         return ci;
604 }
605
606 static int
607 compare(const void *p, const void *q)
608 {
609         return(strcmp(*(char **)p, *(char **)q));
610 }
611
612 static int
613 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
614 {
615         Char pathbuf[MAXPATHLEN];
616
617         /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
618         if (*pattern == BG_EOS)
619                 return(0);
620         return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
621                      pathbuf, pathbuf+MAXPATHLEN-1,
622                      pattern, pattern_last, pglob, limitp));
623 }
624
625 /*
626  * The functions glob2 and glob3 are mutually recursive; there is one level
627  * of recursion for each segment in the pattern that contains one or more
628  * meta characters.
629  */
630 static int
631 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
632       Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
633 {
634         Stat_t sb;
635         Char *p, *q;
636         int anymeta;
637
638         /*
639          * Loop over pattern segments until end of pattern or until
640          * segment with meta character found.
641          */
642         for (anymeta = 0;;) {
643                 if (*pattern == BG_EOS) {               /* End of pattern? */
644                         *pathend = BG_EOS;
645                         if (g_lstat(pathbuf, &sb, pglob))
646                                 return(0);
647
648                         if (((pglob->gl_flags & GLOB_MARK) &&
649                             pathend[-1] != BG_SEP
650 #ifdef DOSISH
651                             && pathend[-1] != BG_SEP2
652 #endif
653                             ) && (S_ISDIR(sb.st_mode) ||
654                                   (S_ISLNK(sb.st_mode) &&
655                             (g_stat(pathbuf, &sb, pglob) == 0) &&
656                             S_ISDIR(sb.st_mode)))) {
657                                 if (pathend+1 > pathend_last)
658                                         return (1);
659                                 *pathend++ = BG_SEP;
660                                 *pathend = BG_EOS;
661                         }
662                         ++pglob->gl_matchc;
663 #ifdef GLOB_DEBUG
664                         printf("calling globextend from glob2\n");
665 #endif /* GLOB_DEBUG */
666                         return(globextend(pathbuf, pglob, limitp));
667                 }
668
669                 /* Find end of next segment, copy tentatively to pathend. */
670                 q = pathend;
671                 p = pattern;
672                 while (*p != BG_EOS && *p != BG_SEP
673 #ifdef DOSISH
674                        && *p != BG_SEP2
675 #endif
676                        ) {
677                         if (ismeta(*p))
678                                 anymeta = 1;
679                         if (q+1 > pathend_last)
680                                 return (1);
681                         *q++ = *p++;
682                 }
683
684                 if (!anymeta) {         /* No expansion, do next segment. */
685                         pathend = q;
686                         pattern = p;
687                         while (*pattern == BG_SEP
688 #ifdef DOSISH
689                                || *pattern == BG_SEP2
690 #endif
691                                ) {
692                                 if (pathend+1 > pathend_last)
693                                         return (1);
694                                 *pathend++ = *pattern++;
695                         }
696                 } else
697                         /* Need expansion, recurse. */
698                         return(glob3(pathbuf, pathbuf_last, pathend,
699                                      pathend_last, pattern, pattern_last,
700                                      p, pattern_last, pglob, limitp));
701         }
702         /* NOTREACHED */
703 }
704
705 static int
706 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
707       Char *pattern, Char *pattern_last,
708       Char *restpattern, Char *restpattern_last, glob_t *pglob, size_t *limitp)
709 {
710         register Direntry_t *dp;
711         DIR *dirp;
712         int err;
713         int nocase;
714         char buf[MAXPATHLEN];
715
716         /*
717          * The readdirfunc declaration can't be prototyped, because it is
718          * assigned, below, to two functions which are prototyped in glob.h
719          * and dirent.h as taking pointers to differently typed opaque
720          * structures.
721          */
722         Direntry_t *(*readdirfunc)(DIR*);
723
724         if (pathend > pathend_last)
725                 return (1);
726         *pathend = BG_EOS;
727         errno = 0;
728
729 #ifdef VMS
730         {
731                 Char *q = pathend;
732                 if (q - pathbuf > 5) {
733                         q -= 5;
734                         if (q[0] == '.' &&
735                             tolower(q[1]) == 'd' && tolower(q[2]) == 'i' &&
736                             tolower(q[3]) == 'r' && q[4] == '/')
737                         {
738                                 q[0] = '/';
739                                 q[1] = BG_EOS;
740                                 pathend = q+1;
741                         }
742                 }
743         }
744 #endif
745         if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
746                 /* TODO: don't call for ENOENT or ENOTDIR? */
747                 if (pglob->gl_errfunc) {
748                         if (g_Ctoc(pathbuf, buf, sizeof(buf)))
749                                 return (GLOB_ABEND);
750                         if (pglob->gl_errfunc(buf, errno) ||
751                             (pglob->gl_flags & GLOB_ERR))
752                                 return (GLOB_ABEND);
753                 }
754                 return(0);
755         }
756
757         err = 0;
758         nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
759
760         /* Search directory for matching names. */
761         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
762                 readdirfunc = (Direntry_t *(*)(DIR *))pglob->gl_readdir;
763         else
764                 readdirfunc = my_readdir;
765         while ((dp = (*readdirfunc)(dirp))) {
766                 register U8 *sc;
767                 register Char *dc;
768
769                 /* Initial BG_DOT must be matched literally. */
770                 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
771                         continue;
772                 dc = pathend;
773                 sc = (U8 *) dp->d_name;
774                 while (dc < pathend_last && (*dc++ = *sc++) != BG_EOS)
775                         ;
776                 if (dc >= pathend_last) {
777                         *dc = BG_EOS;
778                         err = 1;
779                         break;
780                 }
781
782                 if (!match(pathend, pattern, restpattern, nocase)) {
783                         *pathend = BG_EOS;
784                         continue;
785                 }
786                 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
787                             restpattern, restpattern_last, pglob, limitp);
788                 if (err)
789                         break;
790         }
791
792         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
793                 (*pglob->gl_closedir)(dirp);
794         else
795                 PerlDir_close(dirp);
796         return(err);
797 }
798
799
800 /*
801  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
802  * add the new item, and update gl_pathc.
803  *
804  * This assumes the BSD realloc, which only copies the block when its size
805  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
806  * behavior.
807  *
808  * Return 0 if new item added, error code if memory couldn't be allocated.
809  *
810  * Invariant of the glob_t structure:
811  *      Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
812  *      gl_pathv points to (gl_offs + gl_pathc + 1) items.
813  */
814 static int
815 globextend(const Char *path, glob_t *pglob, size_t *limitp)
816 {
817         register char **pathv;
818         register int i;
819         STRLEN newsize, len;
820         char *copy;
821         const Char *p;
822
823 #ifdef GLOB_DEBUG
824         printf("Adding ");
825         for (p = path; *p; p++)
826                 (void)printf("%c", CHAR(*p));
827         printf("\n");
828 #endif /* GLOB_DEBUG */
829
830         newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
831         if (pglob->gl_pathv)
832                 pathv = Renew(pglob->gl_pathv,newsize,char*);
833         else
834                 New(0,pathv,newsize,char*);
835         if (pathv == NULL) {
836                 if (pglob->gl_pathv) {
837                         Safefree(pglob->gl_pathv);
838                         pglob->gl_pathv = NULL;
839                 }
840                 return(GLOB_NOSPACE);
841         }
842
843         if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
844                 /* first time around -- clear initial gl_offs items */
845                 pathv += pglob->gl_offs;
846                 for (i = pglob->gl_offs; --i >= 0; )
847                         *--pathv = NULL;
848         }
849         pglob->gl_pathv = pathv;
850
851         for (p = path; *p++;)
852                 ;
853         len = (STRLEN)(p - path);
854         *limitp += len;
855         New(0, copy, p-path, char);
856         if (copy != NULL) {
857                 if (g_Ctoc(path, copy, len)) {
858                         Safefree(copy);
859                         return(GLOB_NOSPACE);
860                 }
861                 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
862         }
863         pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
864
865         if ((pglob->gl_flags & GLOB_LIMIT) &&
866             newsize + *limitp >= ARG_MAX) {
867                 errno = 0;
868                 return(GLOB_NOSPACE);
869         }
870
871         return(copy == NULL ? GLOB_NOSPACE : 0);
872 }
873
874
875 /*
876  * pattern matching function for filenames.  Each occurrence of the *
877  * pattern causes a recursion level.
878  */
879 static int
880 match(register Char *name, register Char *pat, register Char *patend, int nocase)
881 {
882         int ok, negate_range;
883         Char c, k;
884
885         while (pat < patend) {
886                 c = *pat++;
887                 switch (c & M_MASK) {
888                 case M_ALL:
889                         if (pat == patend)
890                                 return(1);
891                         do
892                             if (match(name, pat, patend, nocase))
893                                     return(1);
894                         while (*name++ != BG_EOS)
895                                 ;
896                         return(0);
897                 case M_ONE:
898                         if (*name++ == BG_EOS)
899                                 return(0);
900                         break;
901                 case M_SET:
902                         ok = 0;
903                         if ((k = *name++) == BG_EOS)
904                                 return(0);
905                         if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
906                                 ++pat;
907                         while (((c = *pat++) & M_MASK) != M_END)
908                                 if ((*pat & M_MASK) == M_RNG) {
909                                         if (nocase) {
910                                                 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
911                                                         ok = 1;
912                                         } else {
913                                                 if (c <= k && k <= pat[1])
914                                                         ok = 1;
915                                         }
916                                         pat += 2;
917                                 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
918                                         ok = 1;
919                         if (ok == negate_range)
920                                 return(0);
921                         break;
922                 default:
923                         k = *name++;
924                         if (nocase ? (tolower(k) != tolower(c)) : (k != c))
925                                 return(0);
926                         break;
927                 }
928         }
929         return(*name == BG_EOS);
930 }
931
932 /* Free allocated data belonging to a glob_t structure. */
933 void
934 bsd_globfree(glob_t *pglob)
935 {
936         register int i;
937         register char **pp;
938
939         if (pglob->gl_pathv != NULL) {
940                 pp = pglob->gl_pathv + pglob->gl_offs;
941                 for (i = pglob->gl_pathc; i--; ++pp)
942                         if (*pp)
943                                 Safefree(*pp);
944                 Safefree(pglob->gl_pathv);
945                 pglob->gl_pathv = NULL;
946         }
947 }
948
949 static DIR *
950 g_opendir(register Char *str, glob_t *pglob)
951 {
952         char buf[MAXPATHLEN];
953
954         if (!*str) {
955 #ifdef MACOS_TRADITIONAL
956                 strcpy(buf, ":");
957 #else
958                 strcpy(buf, ".");
959 #endif
960         } else {
961                 if (g_Ctoc(str, buf, sizeof(buf)))
962                         return(NULL);
963         }
964
965         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
966                 return((*pglob->gl_opendir)(buf));
967
968         return(PerlDir_open(buf));
969 }
970
971 static int
972 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
973 {
974         char buf[MAXPATHLEN];
975
976         if (g_Ctoc(fn, buf, sizeof(buf)))
977                 return(-1);
978         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
979                 return((*pglob->gl_lstat)(buf, sb));
980 #ifdef HAS_LSTAT
981         return(PerlLIO_lstat(buf, sb));
982 #else
983         return(PerlLIO_stat(buf, sb));
984 #endif /* HAS_LSTAT */
985 }
986
987 static int
988 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
989 {
990         char buf[MAXPATHLEN];
991
992         if (g_Ctoc(fn, buf, sizeof(buf)))
993                 return(-1);
994         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
995                 return((*pglob->gl_stat)(buf, sb));
996         return(PerlLIO_stat(buf, sb));
997 }
998
999 static Char *
1000 g_strchr(Char *str, int ch)
1001 {
1002         do {
1003                 if (*str == ch)
1004                         return (str);
1005         } while (*str++);
1006         return (NULL);
1007 }
1008
1009 static int
1010 g_Ctoc(register const Char *str, char *buf, STRLEN len)
1011 {
1012         while (len--) {
1013                 if ((*buf++ = *str++) == BG_EOS)
1014                         return (0);
1015         }
1016         return (1);
1017 }
1018
1019 #ifdef GLOB_DEBUG
1020 static void
1021 qprintf(const char *str, register Char *s)
1022 {
1023         register Char *p;
1024
1025         (void)printf("%s:\n", str);
1026         for (p = s; *p; p++)
1027                 (void)printf("%c", CHAR(*p));
1028         (void)printf("\n");
1029         for (p = s; *p; p++)
1030                 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
1031         (void)printf("\n");
1032         for (p = s; *p; p++)
1033                 (void)printf("%c", ismeta(*p) ? '_' : ' ');
1034         (void)printf("\n");
1035 }
1036 #endif /* GLOB_DEBUG */