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