Integrate macperl changes from Chris Nandor:
[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 #if defined(HAS_PASSWD) && !defined(VMS)
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 MACOS_TRADITIONAL
99 #    define             ARG_MAX         65536   /* Mac OS is actually unlimited */
100 #  else
101 #    ifdef _SC_ARG_MAX
102 #      define           ARG_MAX         (sysconf(_SC_ARG_MAX))
103 #    else
104 #      ifdef _POSIX_ARG_MAX
105 #        define         ARG_MAX         _POSIX_ARG_MAX
106 #      else
107 #        ifdef WIN32
108 #          define       ARG_MAX         14500   /* from VC's limits.h */
109 #        else
110 #          define       ARG_MAX         4096    /* from POSIX, be conservative */
111 #        endif
112 #      endif
113 #    endif
114 #  endif
115 #endif
116
117 #define BG_DOLLAR       '$'
118 #define BG_DOT          '.'
119 #define BG_EOS          '\0'
120 #define BG_LBRACKET     '['
121 #define BG_NOT          '!'
122 #define BG_QUESTION     '?'
123 #define BG_QUOTE        '\\'
124 #define BG_RANGE        '-'
125 #define BG_RBRACKET     ']'
126 #ifdef MACOS_TRADITIONAL
127 #  define       BG_SEP  ':'
128 #else
129 #  define       BG_SEP  '/'
130 #endif
131 #ifdef DOSISH
132 #define BG_SEP2         '\\'
133 #endif
134 #define BG_STAR         '*'
135 #define BG_TILDE        '~'
136 #define BG_UNDERSCORE   '_'
137 #define BG_LBRACE       '{'
138 #define BG_RBRACE       '}'
139 #define BG_SLASH        '/'
140 #define BG_COMMA        ','
141
142 #ifndef GLOB_DEBUG
143
144 #define M_QUOTE         0x8000
145 #define M_PROTECT       0x4000
146 #define M_MASK          0xffff
147 #define M_ASCII         0x00ff
148
149 typedef U16 Char;
150
151 #else
152
153 #define M_QUOTE         0x80
154 #define M_PROTECT       0x40
155 #define M_MASK          0xff
156 #define M_ASCII         0x7f
157
158 typedef U8 Char;
159
160 #endif /* !GLOB_DEBUG */
161
162
163 #define CHAR(c)         ((Char)((c)&M_ASCII))
164 #define META(c)         ((Char)((c)|M_QUOTE))
165 #define M_ALL           META('*')
166 #define M_END           META(']')
167 #define M_NOT           META('!')
168 #define M_ONE           META('?')
169 #define M_RNG           META('-')
170 #define M_SET           META('[')
171 #define ismeta(c)       (((c)&M_QUOTE) != 0)
172
173
174 static int       compare(const void *, const void *);
175 static int       ci_compare(const void *, const void *);
176 static int       g_Ctoc(const Char *, char *, STRLEN);
177 static int       g_lstat(Char *, Stat_t *, glob_t *);
178 static DIR      *g_opendir(Char *, glob_t *);
179 static Char     *g_strchr(Char *, int);
180 static int       g_stat(Char *, Stat_t *, glob_t *);
181 static int       glob0(const Char *, glob_t *);
182 static int       glob1(Char *, Char *, glob_t *, size_t *);
183 static int       glob2(Char *, Char *, Char *, Char *, Char *, Char *,
184                        glob_t *, size_t *);
185 static int       glob3(Char *, Char *, Char *, Char *, Char *, Char *,
186                        Char *, Char *, glob_t *, size_t *);
187 static int       globextend(const Char *, glob_t *, size_t *);
188 static const Char *
189                  globtilde(const Char *, Char *, size_t, glob_t *);
190 static int       globexp1(const Char *, glob_t *);
191 static int       globexp2(const Char *, const Char *, glob_t *, int *);
192 static int       match(Char *, Char *, Char *, int);
193 #ifdef GLOB_DEBUG
194 static void      qprintf(const char *, Char *);
195 #endif /* GLOB_DEBUG */
196
197 #ifdef PERL_IMPLICIT_CONTEXT
198 static Direntry_t *     my_readdir(DIR*);
199
200 static Direntry_t *
201 my_readdir(DIR *d)
202 {
203     return PerlDir_read(d);
204 }
205 #else
206 #define my_readdir      readdir
207 #endif
208
209 #ifdef MACOS_TRADITIONAL
210 #include <Files.h>
211 #include <Types.h>
212 #include <string.h>
213
214 #define NO_UPDIR_ERR 1  /* updir resolving failed */
215
216 static Boolean g_matchVol; /* global variable */
217 static short updir(char *path);
218 static short resolve_updirs(char *new_pattern);
219 static void remove_trColon(char *path);
220 static short glob_mark_Mac(Char *pathbuf, Char *pathend, Char *pathend_last);
221 static OSErr GetVolInfo(short volume, Boolean indexed, FSSpec *spec);
222 static void name_f_FSSpec(StrFileName volname, FSSpec *spec);
223
224 #endif
225
226 int
227 bsd_glob(const char *pattern, int flags,
228          int (*errfunc)(const char *, int), glob_t *pglob)
229 {
230         const U8 *patnext;
231         int c;
232         Char *bufnext, *bufend, patbuf[MAXPATHLEN];
233
234 #ifdef MACOS_TRADITIONAL
235         char *new_pat, *p, *np;
236         int err;
237         size_t len;
238 #endif
239
240 #ifndef MACOS_TRADITIONAL
241         patnext = (U8 *) pattern;
242 #endif
243         if (!(flags & GLOB_APPEND)) {
244                 pglob->gl_pathc = 0;
245                 pglob->gl_pathv = NULL;
246                 if (!(flags & GLOB_DOOFFS))
247                         pglob->gl_offs = 0;
248         }
249         pglob->gl_flags = flags & ~GLOB_MAGCHAR;
250         pglob->gl_errfunc = errfunc;
251         pglob->gl_matchc = 0;
252
253         bufnext = patbuf;
254         bufend = bufnext + MAXPATHLEN - 1;
255 #ifdef DOSISH
256         /* Nasty hack to treat patterns like "C:*" correctly. In this
257          * case, the * should match any file in the current directory
258          * on the C: drive. However, the glob code does not treat the
259          * colon specially, so it looks for files beginning "C:" in
260          * the current directory. To fix this, change the pattern to
261          * add an explicit "./" at the start (just after the drive
262          * letter and colon - ie change to "C:./").
263          */
264         if (isalpha(pattern[0]) && pattern[1] == ':' &&
265             pattern[2] != BG_SEP && pattern[2] != BG_SEP2 &&
266             bufend - bufnext > 4) {
267                 *bufnext++ = pattern[0];
268                 *bufnext++ = ':';
269                 *bufnext++ = '.';
270                 *bufnext++ = BG_SEP;
271                 patnext += 2;
272         }
273 #endif
274
275 #ifdef MACOS_TRADITIONAL
276         /* Check if we need to match a volume name (e.g. '*HD:*') */
277         g_matchVol = false;
278         p = (char *) pattern;
279         if (*p != BG_SEP) {
280             p++;
281             while (*p != BG_EOS) {
282                 if (*p == BG_SEP) {
283                     g_matchVol = true;
284                     break;
285                 }
286                 p++;
287             }
288         }
289
290         /* Transform the pattern:
291          * (a) Resolve updirs, e.g.
292          *     '*:t*p::'       -> '*:'
293          *         ':a*:tmp::::'   -> '::'
294          *         ':base::t*p:::' -> '::'
295          *     '*HD::'         -> return 0 (error, quit silently)
296          *
297          * (b) Remove a single trailing ':', unless it's a "match volume only"
298          *     pattern like '*HD:'; e.g.
299          *     '*:tmp:' -> '*:tmp'  but
300          *     '*HD:'   -> '*HD:'
301          *     (If we don't do that, even filenames will have a trailing ':' in
302          *     the result.)
303          */
304
305         /* We operate on a copy of the pattern */
306         len = strlen(pattern);
307         New(0, new_pat, len + 1, char);
308         if (new_pat == NULL)
309             return (GLOB_NOSPACE);
310
311         p = (char *) pattern;
312         np = new_pat;
313         while (*np++ = *p++) ;
314
315         /* Resolve updirs ... */
316         err = resolve_updirs(new_pat);
317         if (err) {
318             Safefree(new_pat);
319             /* The pattern is incorrect: tried to move
320                up above the volume root, see above.
321                We quit silently. */
322             return 0;
323         }
324         /* remove trailing colon ... */
325         remove_trColon(new_pat);
326         patnext = (U8 *) new_pat;
327
328 #endif /* MACOS_TRADITIONAL */
329
330         if (flags & GLOB_QUOTE) {
331                 /* Protect the quoted characters. */
332                 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
333                         if (c == BG_QUOTE) {
334 #ifdef DOSISH
335                                     /* To avoid backslashitis on Win32,
336                                      * we only treat \ as a quoting character
337                                      * if it precedes one of the
338                                      * metacharacters []-{}~\
339                                      */
340                                 if ((c = *patnext++) != '[' && c != ']' &&
341                                     c != '-' && c != '{' && c != '}' &&
342                                     c != '~' && c != '\\') {
343 #else
344                                 if ((c = *patnext++) == BG_EOS) {
345 #endif
346                                         c = BG_QUOTE;
347                                         --patnext;
348                                 }
349                                 *bufnext++ = c | M_PROTECT;
350                         } else
351                                 *bufnext++ = c;
352         } else
353                 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
354                         *bufnext++ = c;
355         *bufnext = BG_EOS;
356
357 #ifdef MACOS_TRADITIONAL
358         if (flags & GLOB_BRACE)
359             err = globexp1(patbuf, pglob);
360         else
361             err = glob0(patbuf, pglob);
362         Safefree(new_pat);
363         return err;
364 #else
365         if (flags & GLOB_BRACE)
366             return globexp1(patbuf, pglob);
367         else
368             return glob0(patbuf, pglob);
369 #endif
370 }
371
372 /*
373  * Expand recursively a glob {} pattern. When there is no more expansion
374  * invoke the standard globbing routine to glob the rest of the magic
375  * characters
376  */
377 static int
378 globexp1(const Char *pattern, glob_t *pglob)
379 {
380         const Char* ptr = pattern;
381         int rv;
382
383         /* Protect a single {}, for find(1), like csh */
384         if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
385                 return glob0(pattern, pglob);
386
387         while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
388                 if (!globexp2(ptr, pattern, pglob, &rv))
389                         return rv;
390
391         return glob0(pattern, pglob);
392 }
393
394
395 /*
396  * Recursive brace globbing helper. Tries to expand a single brace.
397  * If it succeeds then it invokes globexp1 with the new pattern.
398  * If it fails then it tries to glob the rest of the pattern and returns.
399  */
400 static int
401 globexp2(const Char *ptr, const Char *pattern,
402          glob_t *pglob, int *rv)
403 {
404         int     i;
405         Char   *lm, *ls;
406         const Char *pe, *pm, *pl;
407         Char    patbuf[MAXPATHLEN];
408
409         /* copy part up to the brace */
410         for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
411                 ;
412         *lm = BG_EOS;
413         ls = lm;
414
415         /* Find the balanced brace */
416         for (i = 0, pe = ++ptr; *pe; pe++)
417                 if (*pe == BG_LBRACKET) {
418                         /* Ignore everything between [] */
419                         for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
420                                 ;
421                         if (*pe == BG_EOS) {
422                                 /*
423                                  * We could not find a matching BG_RBRACKET.
424                                  * Ignore and just look for BG_RBRACE
425                                  */
426                                 pe = pm;
427                         }
428                 } else if (*pe == BG_LBRACE)
429                         i++;
430                 else if (*pe == BG_RBRACE) {
431                         if (i == 0)
432                                 break;
433                         i--;
434                 }
435
436         /* Non matching braces; just glob the pattern */
437         if (i != 0 || *pe == BG_EOS) {
438                 *rv = glob0(patbuf, pglob);
439                 return 0;
440         }
441
442         for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
443                 switch (*pm) {
444                 case BG_LBRACKET:
445                         /* Ignore everything between [] */
446                         for (pl = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
447                                 ;
448                         if (*pm == BG_EOS) {
449                                 /*
450                                  * We could not find a matching BG_RBRACKET.
451                                  * Ignore and just look for BG_RBRACE
452                                  */
453                                 pm = pl;
454                         }
455                         break;
456
457                 case BG_LBRACE:
458                         i++;
459                         break;
460
461                 case BG_RBRACE:
462                         if (i) {
463                                 i--;
464                                 break;
465                         }
466                         /* FALLTHROUGH */
467                 case BG_COMMA:
468                         if (i && *pm == BG_COMMA)
469                                 break;
470                         else {
471                                 /* Append the current string */
472                                 for (lm = ls; (pl < pm); *lm++ = *pl++)
473                                         ;
474
475                                 /*
476                                  * Append the rest of the pattern after the
477                                  * closing brace
478                                  */
479                                 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS; )
480                                         ;
481
482                                 /* Expand the current pattern */
483 #ifdef GLOB_DEBUG
484                                 qprintf("globexp2:", patbuf);
485 #endif /* GLOB_DEBUG */
486                                 *rv = globexp1(patbuf, pglob);
487
488                                 /* move after the comma, to the next string */
489                                 pl = pm + 1;
490                         }
491                         break;
492
493                 default:
494                         break;
495                 }
496         }
497         *rv = 0;
498         return 0;
499 }
500
501
502
503 /*
504  * expand tilde from the passwd file.
505  */
506 static const Char *
507 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
508 {
509         struct passwd *pwd;
510         char *h;
511         const Char *p;
512         Char *b, *eb;
513
514         if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
515                 return pattern;
516
517         /* Copy up to the end of the string or / */
518         eb = &patbuf[patbuf_len - 1];
519         for (p = pattern + 1, h = (char *) patbuf;
520              h < (char*)eb && *p && *p != BG_SLASH; *h++ = *p++)
521                 ;
522
523         *h = BG_EOS;
524
525 #if 0
526         if (h == (char *)eb)
527                 return what;
528 #endif
529
530         if (((char *) patbuf)[0] == BG_EOS) {
531                 /*
532                  * handle a plain ~ or ~/ by expanding $HOME
533                  * first and then trying the password file
534                  */
535                 if ((h = getenv("HOME")) == NULL) {
536 #ifdef HAS_PASSWD
537                         if ((pwd = getpwuid(getuid())) == NULL)
538                                 return pattern;
539                         else
540                                 h = pwd->pw_dir;
541 #else
542                         return pattern;
543 #endif
544                 }
545         } else {
546                 /*
547                  * Expand a ~user
548                  */
549 #ifdef HAS_PASSWD
550                 if ((pwd = getpwnam((char*) patbuf)) == NULL)
551                         return pattern;
552                 else
553                         h = pwd->pw_dir;
554 #else
555                 return pattern;
556 #endif
557         }
558
559         /* Copy the home directory */
560         for (b = patbuf; b < eb && *h; *b++ = *h++)
561                 ;
562
563         /* Append the rest of the pattern */
564         while (b < eb && (*b++ = *p++) != BG_EOS)
565                 ;
566         *b = BG_EOS;
567
568         return patbuf;
569 }
570
571
572 /*
573  * The main glob() routine: compiles the pattern (optionally processing
574  * quotes), calls glob1() to do the real pattern matching, and finally
575  * sorts the list (unless unsorted operation is requested).  Returns 0
576  * if things went well, nonzero if errors occurred.  It is not an error
577  * to find no matches.
578  */
579 static int
580 glob0(const Char *pattern, glob_t *pglob)
581 {
582         const Char *qpat, *qpatnext;
583         int c, err, oldflags, oldpathc;
584         Char *bufnext, patbuf[MAXPATHLEN];
585         size_t limit = 0;
586
587 #ifdef MACOS_TRADITIONAL
588         if ( (*pattern == BG_TILDE) && (pglob->gl_flags & GLOB_TILDE) ) {
589                 return(globextend(pattern, pglob, &limit));
590         }
591 #endif
592
593         qpat = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
594         qpatnext = qpat;
595         oldflags = pglob->gl_flags;
596         oldpathc = pglob->gl_pathc;
597         bufnext = patbuf;
598
599         /* We don't need to check for buffer overflow any more. */
600         while ((c = *qpatnext++) != BG_EOS) {
601                 switch (c) {
602                 case BG_LBRACKET:
603                         c = *qpatnext;
604                         if (c == BG_NOT)
605                                 ++qpatnext;
606                         if (*qpatnext == BG_EOS ||
607                             g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
608                                 *bufnext++ = BG_LBRACKET;
609                                 if (c == BG_NOT)
610                                         --qpatnext;
611                                 break;
612                         }
613                         *bufnext++ = M_SET;
614                         if (c == BG_NOT)
615                                 *bufnext++ = M_NOT;
616                         c = *qpatnext++;
617                         do {
618                                 *bufnext++ = CHAR(c);
619                                 if (*qpatnext == BG_RANGE &&
620                                     (c = qpatnext[1]) != BG_RBRACKET) {
621                                         *bufnext++ = M_RNG;
622                                         *bufnext++ = CHAR(c);
623                                         qpatnext += 2;
624                                 }
625                         } while ((c = *qpatnext++) != BG_RBRACKET);
626                         pglob->gl_flags |= GLOB_MAGCHAR;
627                         *bufnext++ = M_END;
628                         break;
629                 case BG_QUESTION:
630                         pglob->gl_flags |= GLOB_MAGCHAR;
631                         *bufnext++ = M_ONE;
632                         break;
633                 case BG_STAR:
634                         pglob->gl_flags |= GLOB_MAGCHAR;
635                         /* collapse adjacent stars to one,
636                          * to avoid exponential behavior
637                          */
638                         if (bufnext == patbuf || bufnext[-1] != M_ALL)
639                                 *bufnext++ = M_ALL;
640                         break;
641                 default:
642                         *bufnext++ = CHAR(c);
643                         break;
644                 }
645         }
646         *bufnext = BG_EOS;
647 #ifdef GLOB_DEBUG
648         qprintf("glob0:", patbuf);
649 #endif /* GLOB_DEBUG */
650
651         if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0) {
652                 pglob->gl_flags = oldflags;
653                 return(err);
654         }
655
656         /*
657          * If there was no match we are going to append the pattern
658          * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
659          * and the pattern did not contain any magic characters
660          * GLOB_NOMAGIC is there just for compatibility with csh.
661          */
662         if (pglob->gl_pathc == oldpathc &&
663             ((pglob->gl_flags & GLOB_NOCHECK) ||
664               ((pglob->gl_flags & GLOB_NOMAGIC) &&
665                !(pglob->gl_flags & GLOB_MAGCHAR))))
666         {
667 #ifdef GLOB_DEBUG
668                 printf("calling globextend from glob0\n");
669 #endif /* GLOB_DEBUG */
670                 pglob->gl_flags = oldflags;
671                 return(globextend(qpat, pglob, &limit));
672         }
673         else if (!(pglob->gl_flags & GLOB_NOSORT))
674                 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
675                     pglob->gl_pathc - oldpathc, sizeof(char *),
676                     (pglob->gl_flags & (GLOB_ALPHASORT|GLOB_NOCASE))
677                         ? ci_compare : compare);
678         pglob->gl_flags = oldflags;
679         return(0);
680 }
681
682 static int
683 ci_compare(const void *p, const void *q)
684 {
685         const char *pp = *(const char **)p;
686         const char *qq = *(const char **)q;
687         int ci;
688         while (*pp && *qq) {
689                 if (toLOWER(*pp) != toLOWER(*qq))
690                         break;
691                 ++pp;
692                 ++qq;
693         }
694         ci = toLOWER(*pp) - toLOWER(*qq);
695         if (ci == 0)
696                 return compare(p, q);
697         return ci;
698 }
699
700 static int
701 compare(const void *p, const void *q)
702 {
703         return(strcmp(*(char **)p, *(char **)q));
704 }
705
706 static int
707 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
708 {
709         Char pathbuf[MAXPATHLEN];
710
711         /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
712         if (*pattern == BG_EOS)
713                 return(0);
714         return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
715                      pathbuf, pathbuf+MAXPATHLEN-1,
716                      pattern, pattern_last, pglob, limitp));
717 }
718
719 /*
720  * The functions glob2 and glob3 are mutually recursive; there is one level
721  * of recursion for each segment in the pattern that contains one or more
722  * meta characters.
723  */
724 static int
725 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
726       Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
727 {
728         Stat_t sb;
729         Char *p, *q;
730         int anymeta;
731
732         /*
733          * Loop over pattern segments until end of pattern or until
734          * segment with meta character found.
735          */
736         for (anymeta = 0;;) {
737                 if (*pattern == BG_EOS) {               /* End of pattern? */
738                         *pathend = BG_EOS;
739                         if (g_lstat(pathbuf, &sb, pglob))
740                                 return(0);
741
742                         if (((pglob->gl_flags & GLOB_MARK) &&
743                             pathend[-1] != BG_SEP
744 #ifdef DOSISH
745                             && pathend[-1] != BG_SEP2
746 #endif
747                             ) && (S_ISDIR(sb.st_mode) ||
748                                   (S_ISLNK(sb.st_mode) &&
749                             (g_stat(pathbuf, &sb, pglob) == 0) &&
750                             S_ISDIR(sb.st_mode)))) {
751 #ifdef MACOS_TRADITIONAL
752                                 short err;
753                                 err = glob_mark_Mac(pathbuf, pathend, pathend_last);
754                                 if (err)
755                                         return (err);
756 #else
757                                 if (pathend+1 > pathend_last)
758                                         return (1);
759                                 *pathend++ = BG_SEP;
760                                 *pathend = BG_EOS;
761 #endif
762                         }
763                         ++pglob->gl_matchc;
764 #ifdef GLOB_DEBUG
765                         printf("calling globextend from glob2\n");
766 #endif /* GLOB_DEBUG */
767                         return(globextend(pathbuf, pglob, limitp));
768                 }
769
770                 /* Find end of next segment, copy tentatively to pathend. */
771                 q = pathend;
772                 p = pattern;
773                 while (*p != BG_EOS && *p != BG_SEP
774 #ifdef DOSISH
775                        && *p != BG_SEP2
776 #endif
777                        ) {
778                         if (ismeta(*p))
779                                 anymeta = 1;
780                         if (q+1 > pathend_last)
781                                 return (1);
782                         *q++ = *p++;
783                 }
784
785                 if (!anymeta) {         /* No expansion, do next segment. */
786                         pathend = q;
787                         pattern = p;
788                         while (*pattern == BG_SEP
789 #ifdef DOSISH
790                                || *pattern == BG_SEP2
791 #endif
792                                ) {
793                                 if (pathend+1 > pathend_last)
794                                         return (1);
795                                 *pathend++ = *pattern++;
796                         }
797                 } else
798                         /* Need expansion, recurse. */
799                         return(glob3(pathbuf, pathbuf_last, pathend,
800                                      pathend_last, pattern, pattern_last,
801                                      p, pattern_last, pglob, limitp));
802         }
803         /* NOTREACHED */
804 }
805
806 static int
807 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
808       Char *pattern, Char *pattern_last,
809       Char *restpattern, Char *restpattern_last, glob_t *pglob, size_t *limitp)
810 {
811         register Direntry_t *dp;
812         DIR *dirp;
813         int err;
814         int nocase;
815         char buf[MAXPATHLEN];
816
817         /*
818          * The readdirfunc declaration can't be prototyped, because it is
819          * assigned, below, to two functions which are prototyped in glob.h
820          * and dirent.h as taking pointers to differently typed opaque
821          * structures.
822          */
823         Direntry_t *(*readdirfunc)(DIR*);
824
825         if (pathend > pathend_last)
826                 return (1);
827         *pathend = BG_EOS;
828         errno = 0;
829
830 #ifdef VMS
831         {
832                 Char *q = pathend;
833                 if (q - pathbuf > 5) {
834                         q -= 5;
835                         if (q[0] == '.' &&
836                             tolower(q[1]) == 'd' && tolower(q[2]) == 'i' &&
837                             tolower(q[3]) == 'r' && q[4] == '/')
838                         {
839                                 q[0] = '/';
840                                 q[1] = BG_EOS;
841                                 pathend = q+1;
842                         }
843                 }
844         }
845 #endif
846
847 #ifdef MACOS_TRADITIONAL
848         if ((!*pathbuf) && (g_matchVol)) {
849             FSSpec spec;
850             short index;
851             StrFileName vol_name; /* unsigned char[64] on MacOS */
852
853             err = 0;
854             nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
855
856             /* Get and match a list of volume names */
857             for (index = 0; !GetVolInfo(index+1, true, &spec); ++index) {
858                 register U8 *sc;
859                 register Char *dc;
860
861                 name_f_FSSpec(vol_name, &spec);
862
863                 /* Initial BG_DOT must be matched literally. */
864                 if (*vol_name == BG_DOT && *pattern != BG_DOT)
865                     continue;
866                 dc = pathend;
867                 sc = (U8 *) vol_name;
868                 while (dc < pathend_last && (*dc++ = *sc++) != BG_EOS)
869                     ;
870                 if (dc >= pathend_last) {
871                     *dc = BG_EOS;
872                     err = 1;
873                     break;
874                 }
875
876                 if (!match(pathend, pattern, restpattern, nocase)) {
877                     *pathend = BG_EOS;
878                     continue;
879                 }
880                 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
881                     restpattern, restpattern_last, pglob, limitp);
882                 if (err)
883                     break;
884             }
885             return(err);
886
887         } else { /* open dir */
888 #endif /* MACOS_TRADITIONAL */
889
890         if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
891                 /* TODO: don't call for ENOENT or ENOTDIR? */
892                 if (pglob->gl_errfunc) {
893                         if (g_Ctoc(pathbuf, buf, sizeof(buf)))
894                                 return (GLOB_ABEND);
895                         if (pglob->gl_errfunc(buf, errno) ||
896                             (pglob->gl_flags & GLOB_ERR))
897                                 return (GLOB_ABEND);
898                 }
899                 return(0);
900         }
901
902         err = 0;
903         nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
904
905         /* Search directory for matching names. */
906         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
907                 readdirfunc = (Direntry_t *(*)(DIR *))pglob->gl_readdir;
908         else
909                 readdirfunc = my_readdir;
910         while ((dp = (*readdirfunc)(dirp))) {
911                 register U8 *sc;
912                 register Char *dc;
913
914                 /* Initial BG_DOT must be matched literally. */
915                 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
916                         continue;
917                 dc = pathend;
918                 sc = (U8 *) dp->d_name;
919                 while (dc < pathend_last && (*dc++ = *sc++) != BG_EOS)
920                         ;
921                 if (dc >= pathend_last) {
922                         *dc = BG_EOS;
923                         err = 1;
924                         break;
925                 }
926
927                 if (!match(pathend, pattern, restpattern, nocase)) {
928                         *pathend = BG_EOS;
929                         continue;
930                 }
931                 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
932                             restpattern, restpattern_last, pglob, limitp);
933                 if (err)
934                         break;
935         }
936
937         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
938                 (*pglob->gl_closedir)(dirp);
939         else
940                 PerlDir_close(dirp);
941         return(err);
942
943 #ifdef MACOS_TRADITIONAL
944         }
945 #endif
946 }
947
948
949 /*
950  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
951  * add the new item, and update gl_pathc.
952  *
953  * This assumes the BSD realloc, which only copies the block when its size
954  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
955  * behavior.
956  *
957  * Return 0 if new item added, error code if memory couldn't be allocated.
958  *
959  * Invariant of the glob_t structure:
960  *      Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
961  *      gl_pathv points to (gl_offs + gl_pathc + 1) items.
962  */
963 static int
964 globextend(const Char *path, glob_t *pglob, size_t *limitp)
965 {
966         register char **pathv;
967         register int i;
968         STRLEN newsize, len;
969         char *copy;
970         const Char *p;
971
972 #ifdef GLOB_DEBUG
973         printf("Adding ");
974         for (p = path; *p; p++)
975                 (void)printf("%c", CHAR(*p));
976         printf("\n");
977 #endif /* GLOB_DEBUG */
978
979         newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
980         if (pglob->gl_pathv)
981                 pathv = Renew(pglob->gl_pathv,newsize,char*);
982         else
983                 New(0,pathv,newsize,char*);
984         if (pathv == NULL) {
985                 if (pglob->gl_pathv) {
986                         Safefree(pglob->gl_pathv);
987                         pglob->gl_pathv = NULL;
988                 }
989                 return(GLOB_NOSPACE);
990         }
991
992         if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
993                 /* first time around -- clear initial gl_offs items */
994                 pathv += pglob->gl_offs;
995                 for (i = pglob->gl_offs; --i >= 0; )
996                         *--pathv = NULL;
997         }
998         pglob->gl_pathv = pathv;
999
1000         for (p = path; *p++;)
1001                 ;
1002         len = (STRLEN)(p - path);
1003         *limitp += len;
1004         New(0, copy, p-path, char);
1005         if (copy != NULL) {
1006                 if (g_Ctoc(path, copy, len)) {
1007                         Safefree(copy);
1008                         return(GLOB_NOSPACE);
1009                 }
1010                 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
1011         }
1012         pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1013
1014         if ((pglob->gl_flags & GLOB_LIMIT) &&
1015             newsize + *limitp >= ARG_MAX) {
1016                 errno = 0;
1017                 return(GLOB_NOSPACE);
1018         }
1019
1020         return(copy == NULL ? GLOB_NOSPACE : 0);
1021 }
1022
1023
1024 /*
1025  * pattern matching function for filenames.  Each occurrence of the *
1026  * pattern causes a recursion level.
1027  */
1028 static int
1029 match(register Char *name, register Char *pat, register Char *patend, int nocase)
1030 {
1031         int ok, negate_range;
1032         Char c, k;
1033
1034         while (pat < patend) {
1035                 c = *pat++;
1036                 switch (c & M_MASK) {
1037                 case M_ALL:
1038                         if (pat == patend)
1039                                 return(1);
1040                         do
1041                             if (match(name, pat, patend, nocase))
1042                                     return(1);
1043                         while (*name++ != BG_EOS)
1044                                 ;
1045                         return(0);
1046                 case M_ONE:
1047                         if (*name++ == BG_EOS)
1048                                 return(0);
1049                         break;
1050                 case M_SET:
1051                         ok = 0;
1052                         if ((k = *name++) == BG_EOS)
1053                                 return(0);
1054                         if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
1055                                 ++pat;
1056                         while (((c = *pat++) & M_MASK) != M_END)
1057                                 if ((*pat & M_MASK) == M_RNG) {
1058                                         if (nocase) {
1059                                                 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
1060                                                         ok = 1;
1061                                         } else {
1062                                                 if (c <= k && k <= pat[1])
1063                                                         ok = 1;
1064                                         }
1065                                         pat += 2;
1066                                 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
1067                                         ok = 1;
1068                         if (ok == negate_range)
1069                                 return(0);
1070                         break;
1071                 default:
1072                         k = *name++;
1073                         if (nocase ? (tolower(k) != tolower(c)) : (k != c))
1074                                 return(0);
1075                         break;
1076                 }
1077         }
1078         return(*name == BG_EOS);
1079 }
1080
1081 /* Free allocated data belonging to a glob_t structure. */
1082 void
1083 bsd_globfree(glob_t *pglob)
1084 {
1085         register int i;
1086         register char **pp;
1087
1088         if (pglob->gl_pathv != NULL) {
1089                 pp = pglob->gl_pathv + pglob->gl_offs;
1090                 for (i = pglob->gl_pathc; i--; ++pp)
1091                         if (*pp)
1092                                 Safefree(*pp);
1093                 Safefree(pglob->gl_pathv);
1094                 pglob->gl_pathv = NULL;
1095         }
1096 }
1097
1098 static DIR *
1099 g_opendir(register Char *str, glob_t *pglob)
1100 {
1101         char buf[MAXPATHLEN];
1102
1103         if (!*str) {
1104 #ifdef MACOS_TRADITIONAL
1105                 strcpy(buf, ":");
1106 #else
1107                 strcpy(buf, ".");
1108 #endif
1109         } else {
1110                 if (g_Ctoc(str, buf, sizeof(buf)))
1111                         return(NULL);
1112         }
1113
1114         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1115                 return((*pglob->gl_opendir)(buf));
1116
1117         return(PerlDir_open(buf));
1118 }
1119
1120 static int
1121 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
1122 {
1123         char buf[MAXPATHLEN];
1124
1125         if (g_Ctoc(fn, buf, sizeof(buf)))
1126                 return(-1);
1127         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1128                 return((*pglob->gl_lstat)(buf, sb));
1129 #ifdef HAS_LSTAT
1130         return(PerlLIO_lstat(buf, sb));
1131 #else
1132         return(PerlLIO_stat(buf, sb));
1133 #endif /* HAS_LSTAT */
1134 }
1135
1136 static int
1137 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
1138 {
1139         char buf[MAXPATHLEN];
1140
1141         if (g_Ctoc(fn, buf, sizeof(buf)))
1142                 return(-1);
1143         if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1144                 return((*pglob->gl_stat)(buf, sb));
1145         return(PerlLIO_stat(buf, sb));
1146 }
1147
1148 static Char *
1149 g_strchr(Char *str, int ch)
1150 {
1151         do {
1152                 if (*str == ch)
1153                         return (str);
1154         } while (*str++);
1155         return (NULL);
1156 }
1157
1158 static int
1159 g_Ctoc(register const Char *str, char *buf, STRLEN len)
1160 {
1161         while (len--) {
1162                 if ((*buf++ = *str++) == BG_EOS)
1163                         return (0);
1164         }
1165         return (1);
1166 }
1167
1168 #ifdef GLOB_DEBUG
1169 static void
1170 qprintf(const char *str, register Char *s)
1171 {
1172         register Char *p;
1173
1174         (void)printf("%s:\n", str);
1175         for (p = s; *p; p++)
1176                 (void)printf("%c", CHAR(*p));
1177         (void)printf("\n");
1178         for (p = s; *p; p++)
1179                 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
1180         (void)printf("\n");
1181         for (p = s; *p; p++)
1182                 (void)printf("%c", ismeta(*p) ? '_' : ' ');
1183         (void)printf("\n");
1184 }
1185 #endif /* GLOB_DEBUG */
1186
1187
1188 #ifdef MACOS_TRADITIONAL
1189
1190 /* Replace the last occurence of the pattern ":[^:]+::", e.g. ":lib::",
1191    with a single ':', if possible. It is not an error, if the pattern
1192    doesn't match (we return -1), but if there are two consecutive colons
1193    '::', there must be a preceding ':[^:]+'. Hence,  a volume path like
1194    "HD::" is considered to be an error (we return 1), that is, it can't
1195    be resolved. We return 0 on success.
1196 */
1197
1198 static short
1199 updir(char *path)
1200 {
1201         char *pb, *pe, *lastchar;
1202         char *bgn_mark, *end_mark;
1203         char *f, *m, *b; /* front, middle, back */
1204         size_t len;
1205
1206         len = strlen(path);
1207         lastchar = path + (len-1);
1208         b = lastchar;
1209         m = lastchar-1;
1210         f = lastchar-2;
1211
1212         /* find a '[^:]::' (e.g. b::) pattern ... */
1213         while ( !( (*f != BG_SEP) && (*m == BG_SEP) && (*b == BG_SEP) )
1214                 && (f >= path)) {
1215                 f--;
1216                 m--;
1217                 b--;
1218         }
1219
1220         if (f < path) { /* no (more) match */
1221                 return -1;
1222         }
1223
1224         end_mark = b;
1225
1226         /* ... and now find its preceding colon ':' */
1227         while ((*f != BG_SEP) && (f >= path)) {
1228                 f--;
1229         }
1230         if (f < path) {
1231                 /* No preceding colon found, must be a
1232                    volume path. We can't move up the
1233                    tree and that's an error */
1234                 return 1;
1235         }
1236         bgn_mark = f;
1237
1238         /* Shrink path, i.e. exclude all characters between
1239            bgn_mark and end_mark */
1240
1241         pb = bgn_mark;
1242         pe = end_mark;
1243         while (*pb++ = *pe++) ;
1244         return 0;
1245 }
1246
1247
1248 /* Resolve all updirs in pattern. */
1249
1250 static short
1251 resolve_updirs(char *new_pattern)
1252 {
1253         short err;
1254
1255         do {
1256                 err = updir(new_pattern);
1257         } while (!err);
1258         if (err == 1) {
1259                 return NO_UPDIR_ERR;
1260         }
1261         return 0;
1262 }
1263
1264
1265 /* Remove a trailing colon from the path, but only if it's
1266    not a volume path (e.g. HD:) and not a path consisting
1267    solely of colons. */
1268
1269 static void
1270 remove_trColon(char *path)
1271 {
1272         char *lastchar, *lc;
1273
1274         /* if path matches the pattern /:[^:]+:$/, we can
1275            remove the trailing ':' */
1276
1277         lc = lastchar = path + (strlen(path) - 1);
1278         if (*lastchar == BG_SEP) {
1279                 /* there's a trailing ':', there must be at least
1280                    one preceding char != ':' and a preceding ':' */
1281                 lc--;
1282                 if ((*lc != BG_SEP) && (lc >= path)) {
1283                         lc--;
1284                 } else {
1285                         return;
1286                 }
1287                 while ((*lc != BG_SEP) && (lc >= path)) {
1288                         lc--;
1289                 }
1290                 if (lc >= path) {
1291                         /* ... there's a preceding ':', we remove
1292                            the trailing colon */
1293                         *lastchar = BG_EOS;
1294                 }
1295         }
1296 }
1297
1298
1299 /* With the GLOB_MARK flag on, we append a colon, if pathbuf
1300    is a directory. If the directory name contains no colons,
1301    e.g. 'lib', we can't simply append a ':', since this (e.g.
1302    'lib:') is not a valid (relative) path on Mac OS. Instead,
1303    we add a leading _and_ trailing ':'. */
1304
1305 static short
1306 glob_mark_Mac(Char *pathbuf, Char *pathend, Char *pathend_last)
1307 {
1308         Char *p, *pe;
1309         Boolean is_file = true;
1310
1311         /* check if pathbuf contains a ':',
1312            i.e. is not a file name */
1313         p = pathbuf;
1314         while (*p != BG_EOS) {
1315                 if (*p == BG_SEP) {
1316                         is_file = false;
1317                         break;
1318                 }
1319                 p++;
1320         }
1321
1322         if (is_file) {
1323                 if (pathend+2 > pathend_last) {
1324                         return (1);
1325                 }
1326                 /* right shift one char */
1327                 pe = p = pathend;
1328                 p--;
1329                 pathend++;
1330                 while (p >= pathbuf) {
1331                         *pe-- = *p--;
1332                 }
1333                 /* first char becomes a colon */
1334                 *pathbuf = BG_SEP;
1335                 /* append a colon */
1336                 *pathend++ = BG_SEP;
1337                 *pathend = BG_EOS;
1338
1339         } else {
1340                 if (pathend+1 > pathend_last) {
1341                         return (1);
1342                 }
1343                 *pathend++ = BG_SEP;
1344                 *pathend = BG_EOS;
1345         }
1346         return 0;
1347 }
1348
1349
1350 /* Return a FSSpec record for the specified volume
1351    (borrowed from MacPerl.xs). */
1352
1353 static OSErr
1354 GetVolInfo(short volume, Boolean indexed, FSSpec* spec)
1355 {
1356         OSErr           err; /* OSErr: 16-bit integer */
1357         HParamBlockRec  pb;
1358
1359         pb.volumeParam.ioNamePtr        = spec->name;
1360         pb.volumeParam.ioVRefNum        = indexed ? 0 : volume;
1361         pb.volumeParam.ioVolIndex       = indexed ? volume : 0;
1362
1363         if (err = PBHGetVInfoSync(&pb))
1364                 return err;
1365
1366         spec->vRefNum   = pb.volumeParam.ioVRefNum;
1367         spec->parID     = 1;
1368
1369         return noErr; /* 0 */
1370 }
1371
1372 /* Extract a C name from a FSSpec. Note that there are
1373    no leading or trailing colons. */
1374
1375 static void
1376 name_f_FSSpec(StrFileName name, FSSpec *spec)
1377 {
1378         unsigned char *nc;
1379         const short len = spec->name[0];
1380         short i;
1381
1382         /* FSSpec.name is a Pascal string,
1383            convert it to C ... */
1384         nc = name;
1385         for (i=1; i<=len; i++) {
1386                 *nc++ = spec->name[i];
1387         }
1388         *nc = BG_EOS;
1389 }
1390
1391 #endif /* MACOS_TRADITIONAL */