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