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