1 /**************************************************************************
2   mcw_glob.c -- slightly adapted from glob.c in tcsh-6.05
3                 (made to compile without support files besides mcw_glob.h)
4              -- added routines MCW_*_expand at end
5 ***************************************************************************/
6 
7 /*
8  * Copyright (c) 1989 The Regents of the University of California.
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to Berkeley by
12  * Guido van Rossum.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  */
42 
43 /*
44  * Glob: the interface is a superset of the one defined in POSIX 1003.2,
45  * draft 9.
46  *
47  * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
48  *
49  * Optional extra services, controlled by flags not defined by POSIX:
50  *
51  * GLOB_QUOTE:
52  *	Escaping convention: \ inhibits any special meaning the following
53  *	character might have (except \ at end of string is retained).
54  * GLOB_MAGCHAR:
55  *	Set in gl_flags if pattern contained a globbing character.
56  * GLOB_ALTNOT:
57  *	Use ^ instead of ! for "not".
58  * gl_matchc:
59  *	Number of matches in the current invocation of glob.
60  */
61 
62 
63 /** the following were in "sh.h",
64     but I put them here to get rid of the need for that file -- RWCox **/
65 
66 #define xfree     free
67 #define xmalloc   malloc
68 #define xrealloc  realloc
69 
70 #ifdef SPARKY
71 #undef _POSIX_SOURCE
72 #endif
73 
74 #include <sys/types.h>
75 #include <sys/param.h>
76 #include <sys/stat.h>
77 #include <dirent.h>
78 #include <ctype.h>
79 typedef void * ptr_t;
80 
81 /** don't use sh.h any more **/
82 
83 #if 0
84 #  define Char __Char
85 #  include "sh.h"
86 #  undef Char
87 #  undef QUOTE
88 #  undef TILDE
89 #  undef META
90 #  undef CHAR
91 #  undef ismeta
92 #  undef Strchr
93 #endif
94 
95 #include "l_mcw_glob.h"
96 
97 /* added for direction control on sorting                14 Feb 2005 [rickr] */
98 static int g_sort_dir = 1 ;       /* 1 = small to large, -1 = large to small */
99 
100 #ifndef S_ISDIR
101 #define S_ISDIR(a)	(((a) & S_IFMT) == S_IFDIR)
102 #endif
103 
104 #if !defined(S_ISLNK) && defined(S_IFLNK)
105 #define S_ISLNK(a)	(((a) & S_IFMT) == S_IFLNK)
106 #endif
107 
108 #if !defined(S_ISLNK) && !defined(lstat)
109 #define lstat stat
110 #endif
111 
112 typedef unsigned short Char;
113 
114 #undef  __P
115 #define __P(a) a
116 
117 static	int	 glob1 		__P((Char *, glob_t *, int));
118 static	int	 glob2		__P((Char *, Char *, Char *, glob_t *, int));
119 static	int	 glob3		__P((Char *, Char *, Char *, Char *,
120 				     glob_t *, int));
121 static	int	 globextend	__P((Char *, glob_t *));
122 static	int	 match		__P((Char *, Char *, Char *, int));
123 #ifndef __clipper__
124 static	int	 compare	__P((const ptr_t, const ptr_t));
125 #endif
126 static 	DIR	*Opendir	__P((Char *));
127 #ifdef S_IFLNK
128 static	int	 Lstat		__P((Char *, struct stat *));
129 #endif
130 static 	Char 	*Strchr		__P((Char *, int));
131 #ifdef DEBUG
132 static	void	 qprintf	__P((Char *));
133 #endif
134 
135 #define	DOLLAR		'$'
136 #define	DOT		'.'
137 #define	EOS		'\0'
138 #define	LBRACKET	'['
139 #define	NOT		'!'
140 #define ALTNOT		'^'
141 #define	QUESTION	'?'
142 #define	QUOTE		'\\'
143 #define	RANGE		'-'
144 #define	RBRACKET	']'
145 #define	SEP		'/'
146 #define	STAR		'*'
147 #define	TILDE		'~'
148 #define	UNDERSCORE	'_'
149 
150 #define	M_META		0x8000
151 #define M_PROTECT	0x4000
152 #define	M_MASK		0xffff
153 #define	M_ASCII		0x00ff
154 
155 #define	CHAR(c)		((c)&M_ASCII)
156 #define	META(c)		((c)|M_META)
157 #define	M_ALL		META('*')
158 #define	M_END		META(']')
159 #define	M_NOT		META('!')
160 #define	M_ALTNOT	META('^')
161 #define	M_ONE		META('?')
162 #define	M_RNG		META('-')
163 #define	M_SET		META('[')
164 #define	ismeta(c)	(((c)&M_META) != 0)
165 
166 #if defined(SOLARIS_DIRENT_ZERO) && !defined(SOLARIS_DIRENT_PATCH)
167 #  define SOLARIS_DIRENT_PATCH
168 #endif
169 
170 #ifdef SOLARIS_DIRENT_PATCH
171 struct  dirent {
172      ino_t            d_ino;
173      off_t            d_off;
174      unsigned short        d_reclen;
175      char             d_name[1];
176 };
177 #endif
178 
179 /*
180  * Need to dodge two kernel bugs:
181  * opendir("") != opendir(".")
182  * NAMEI_BUG: on plain files trailing slashes are ignored in some kernels.
183  *            POSIX specifies that they should be ignored in directories.
184  */
185 
186 static DIR *
Opendir(Char * str)187 Opendir(Char *str)
188 {
189     char    buf[MAXPATHLEN];
190     register char *dc = buf;
191 
192     if (!*str)
193 	return (opendir("."));
194     while ((*dc++ = *str++) != '\0')
195 	continue;
196     return (opendir(buf));
197 }
198 
199 #ifdef S_IFLNK
200 static int
Lstat(Char * fn,struct stat * sb)201 Lstat(Char *fn, struct stat *sb)
202 {
203     char    buf[MAXPATHLEN];
204     register char *dc = buf;
205 
206     while ((*dc++ = *fn++) != '\0')
207 	continue;
208 # ifdef NAMEI_BUG
209     {
210 	int     st;
211 
212 	st = lstat(buf, sb);
213 	if (*buf)
214 	    dc--;
215 	return (*--dc == '/' && !S_ISDIR(sb->st_mode) ? -1 : st);
216     }
217 # else
218     return (lstat(buf, sb));
219 # endif	/* NAMEI_BUG */
220 }
221 #else
222 #define Lstat Stat
223 #endif /* S_IFLNK */
224 
225 static int
Stat(Char * fn,struct stat * sb)226 Stat(Char *fn, struct stat *sb)
227 {
228     char    buf[MAXPATHLEN];
229     register char *dc = buf;
230 
231     while ((*dc++ = *fn++) != '\0')
232 	continue;
233 #ifdef NAMEI_BUG
234     {
235 	int     st;
236 
237 	st = stat(buf, sb);
238 	if (*buf)
239 	    dc--;
240 	return (*--dc == '/' && !S_ISDIR(sb->st_mode) ? -1 : st);
241     }
242 #else
243     return (stat(buf, sb));
244 #endif /* NAMEI_BUG */
245 }
246 
247 static Char *
Strchr(Char * str,int ch)248 Strchr(Char *str, int ch)
249 {
250     do
251 	if (*str == ch)
252 	    return (str);
253     while (*str++);
254     return (NULL);
255 }
256 
257 #ifdef DEBUG
258 static void
qprintf(Char * s)259 qprintf(Char *s)
260 {
261     Char *p;
262 
263     for (p = s; *p; p++)
264 	printf("%c", *p & 0xff);
265     printf("\n");
266     for (p = s; *p; p++)
267 	printf("%c", *p & M_PROTECT ? '"' : ' ');
268     printf("\n");
269     for (p = s; *p; p++)
270 	printf("%c", *p & M_META ? '_' : ' ');
271     printf("\n");
272 }
273 #endif /* DEBUG */
274 
275 static int
compare(const ptr_t p,const ptr_t q)276 compare(const ptr_t p, const ptr_t q)
277 {
278 #if defined(NLS) && !defined(NOSTRCOLL)
279 
280 #if 0
281     errno = 0;  /* strcoll sets errno, another brain-damage */
282 #endif
283 
284     return (g_sort_dir * strcoll(*(char **) p, *(char **) q));
285 #else
286     return (g_sort_dir * strcmp(*(char **) p, *(char **) q));
287 #endif /* NLS && !NOSTRCOLL */
288 }
289 
290 /*
291  * The main glob() routine: compiles the pattern (optionally processing
292  * quotes), calls glob1() to do the real pattern matching, and finally
293  * sorts the list (unless unsorted operation is requested).  Returns 0
294  * if things went well, nonzero if errors occurred.  It is not an error
295  * to find no matches.
296  */
297 int
glob(const char * pattern,int flags,int (* errfunc)(char *,int),glob_t * pglob)298 glob(const char *pattern, int flags, int(*errfunc)(char *,int), glob_t *pglob)
299 {
300     int     err, oldpathc;
301     Char *bufnext, *bufend, *compilebuf, m_not;
302     const unsigned char *compilepat, *patnext;
303     int     c, nnot;
304     Char patbuf[MAXPATHLEN + 1], *qpatnext;
305     int     no_match;
306 
307     patnext = (unsigned char *) pattern;
308     if (!(flags & GLOB_APPEND)) {
309 	pglob->gl_pathc = 0;
310 	pglob->gl_pathv = NULL;
311 	if (!(flags & GLOB_DOOFFS))
312 	    pglob->gl_offs = 0;
313     }
314     pglob->gl_flags = flags & ~GLOB_MAGCHAR;
315     pglob->gl_errfunc = errfunc;
316     oldpathc = pglob->gl_pathc;
317     pglob->gl_matchc = 0;
318 
319     if (pglob->gl_flags & GLOB_ALTNOT) {
320 	nnot = ALTNOT;
321 	m_not = M_ALTNOT;
322     }
323     else {
324 	nnot = NOT;
325 	m_not = M_NOT;
326     }
327 
328     bufnext = patbuf;
329     bufend = bufnext + MAXPATHLEN;
330     compilebuf = bufnext;
331     compilepat = patnext;
332 
333     no_match = *patnext == nnot;
334     if (no_match)
335 	patnext++;
336 
337     if (flags & GLOB_QUOTE) {
338 	/* Protect the quoted characters */
339 	while (bufnext < bufend && (c = *patnext++) != EOS)
340 	    if (c == QUOTE) {
341 		if ((c = *patnext++) == EOS) {
342 		    c = QUOTE;
343 		    --patnext;
344 		}
345 		*bufnext++ = (Char) (c | M_PROTECT);
346 	    }
347 	    else
348 		*bufnext++ = (Char) c;
349     }
350     else
351 	while (bufnext < bufend && (c = *patnext++) != EOS)
352 	    *bufnext++ = (Char) c;
353     *bufnext = EOS;
354 
355     bufnext = patbuf;
356     qpatnext = patbuf;
357     /* we don't need to check for buffer overflow any more */
358     while ((c = *qpatnext++) != EOS) {
359 	switch (c) {
360 	case LBRACKET:
361 	    c = *qpatnext;
362 	    if (c == nnot)
363 		++qpatnext;
364 	    if (*qpatnext == EOS ||
365 		Strchr(qpatnext + 1, RBRACKET) == NULL) {
366 		*bufnext++ = LBRACKET;
367 		if (c == nnot)
368 		    --qpatnext;
369 		break;
370 	    }
371 	    pglob->gl_flags |= GLOB_MAGCHAR;
372 	    *bufnext++ = M_SET;
373 	    if (c == nnot)
374 		*bufnext++ = m_not;
375 	    c = *qpatnext++;
376 	    do {
377 		*bufnext++ = CHAR(c);
378 		if (*qpatnext == RANGE &&
379 		    (c = qpatnext[1]) != RBRACKET) {
380 		    *bufnext++ = M_RNG;
381 		    *bufnext++ = CHAR(c);
382 		    qpatnext += 2;
383 		}
384 	    } while ((c = *qpatnext++) != RBRACKET);
385 	    *bufnext++ = M_END;
386 	    break;
387 	case QUESTION:
388 	    pglob->gl_flags |= GLOB_MAGCHAR;
389 	    *bufnext++ = M_ONE;
390 	    break;
391 	case STAR:
392 	    pglob->gl_flags |= GLOB_MAGCHAR;
393 	    /* collapse adjacent stars to one, to avoid
394 	     * exponential behavior
395 	     */
396 	    if (bufnext == patbuf || bufnext[-1] != M_ALL)
397 		*bufnext++ = M_ALL;
398 	    break;
399 	default:
400 	    *bufnext++ = CHAR(c);
401 	    break;
402 	}
403     }
404     *bufnext = EOS;
405 #ifdef DEBUG
406     qprintf(patbuf);
407 #endif
408 
409     if ((err = glob1(patbuf, pglob, no_match)) != 0)
410 	return (err);
411 
412     /*
413      * If there was no match we are going to append the pattern
414      * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
415      * and the pattern did not contain any magic characters
416      * GLOB_NOMAGIC is there just for compatibility with csh.
417      */
418     if (pglob->gl_pathc == oldpathc &&
419 	((flags & GLOB_NOCHECK) ||
420 	 ((flags & GLOB_NOMAGIC) && !(pglob->gl_flags & GLOB_MAGCHAR)))) {
421 	if (!(flags & GLOB_QUOTE)) {
422 	    Char *dp = compilebuf;
423 	    const unsigned char *sp = compilepat;
424 
425 	    while ((*dp++ = *sp++) != '\0')
426 		continue;
427 	}
428 	else {
429 	    /*
430 	     * copy pattern, interpreting quotes; this is slightly different
431 	     * than the interpretation of quotes above -- which should prevail?
432 	     */
433 	    while (*compilepat != EOS) {
434 		if (*compilepat == QUOTE) {
435 		    if (*++compilepat == EOS)
436 			--compilepat;
437 		}
438 		*compilebuf++ = (unsigned char) *compilepat++;
439 	    }
440 	    *compilebuf = EOS;
441 	}
442 	return (globextend(patbuf, pglob));
443     }
444     else if (!(flags & GLOB_NOSORT))
445 	qsort((char *) (pglob->gl_pathv + pglob->gl_offs + oldpathc),
446 	      pglob->gl_pathc - oldpathc, sizeof(char *),
447 	      (int (*) __P((const void *, const void *))) compare);
448     return (0);
449 }
450 
451 static int
glob1(Char * pattern,glob_t * pglob,int no_match)452 glob1(Char *pattern, glob_t *pglob, int no_match)
453 {
454     Char pathbuf[MAXPATHLEN + 1];
455 
456     /*
457      * a null pathname is invalid -- POSIX 1003.1 sect. 2.4.
458      */
459     if (*pattern == EOS)
460 	return (0);
461     return (glob2(pathbuf, pathbuf, pattern, pglob, no_match));
462 }
463 
464 /*
465  * functions glob2 and glob3 are mutually recursive; there is one level
466  * of recursion for each segment in the pattern that contains one or
467  * more meta characters.
468  */
469 static int
glob2(Char * pathbuf,Char * pathend,Char * pattern,glob_t * pglob,int no_match)470 glob2( Char *pathbuf,Char *pathend, Char *pattern, glob_t *pglob, int no_match)
471 {
472     struct stat sbuf;
473     int anymeta;
474     Char *p, *q;
475 
476     /*
477      * loop over pattern segments until end of pattern or until segment with
478      * meta character found.
479      */
480     anymeta = 0;
481     for (;;) {
482 	if (*pattern == EOS) {	/* end of pattern? */
483 	    *pathend = EOS;
484 
485 	    if (Lstat(pathbuf, &sbuf))
486 		return (0);
487 
488 	    if (((pglob->gl_flags & GLOB_MARK) &&
489 		 pathend[-1] != SEP) &&
490 		(S_ISDIR(sbuf.st_mode)
491 #ifdef S_IFLNK
492 		 || (S_ISLNK(sbuf.st_mode) &&
493 		     (Stat(pathbuf, &sbuf) == 0) &&
494 		     S_ISDIR(sbuf.st_mode))
495 #endif
496 		 )) {
497 		*pathend++ = SEP;
498 		*pathend = EOS;
499 	    }
500 	    ++pglob->gl_matchc;
501 	    return (globextend(pathbuf, pglob));
502 	}
503 
504 	/* find end of next segment, copy tentatively to pathend */
505 	q = pathend;
506 	p = pattern;
507 	while (*p != EOS && *p != SEP) {
508 	    if (ismeta(*p))
509 		anymeta = 1;
510 	    *q++ = *p++;
511 	}
512 
513 	if (!anymeta) {		/* no expansion, do next segment */
514 	    pathend = q;
515 	    pattern = p;
516 	    while (*pattern == SEP)
517 		*pathend++ = *pattern++;
518 	}
519 	else			/* need expansion, recurse */
520 	    return (glob3(pathbuf, pathend, pattern, p, pglob, no_match));
521     }
522     /* NOTREACHED */
523 }
524 
525 
526 static int
glob3(Char * pathbuf,Char * pathend,Char * pattern,Char * restpattern,glob_t * pglob,int no_match)527 glob3(Char *pathbuf, Char *pathend, Char *pattern, Char *restpattern, glob_t *pglob, int no_match)
528 {
529 #if 0
530     extern int errno;
531 #endif
532     DIR    *dirp;
533     struct dirent *dp;
534     int     err;
535     Char m_not = (pglob->gl_flags & GLOB_ALTNOT) ? M_ALTNOT : M_NOT;
536     char cpathbuf[MAXPATHLEN], *ptr;
537 #ifdef SOLARIS_DIRENT_PATCH
538     /* declaration of vars used in the solaris-patch */
539     char dname[255];
540     int ii;
541 #endif
542 
543     *pathend = EOS;
544 
545 #if 0
546     errno = 0;
547 #endif
548 
549     if (!(dirp = Opendir(pathbuf))) {
550 	/* todo: don't call for ENOENT or ENOTDIR? */
551 	for (ptr = cpathbuf; (*ptr++ = (char) *pathbuf++) != EOS;)
552 	    continue;
553 #if 0
554 	if ((pglob->gl_errfunc && (*pglob->gl_errfunc) (cpathbuf, errno)) ||
555 	    (pglob->gl_flags & GLOB_ERR))
556 #else
557 	if ( (pglob->gl_flags & GLOB_ERR))
558 #endif
559 	    return (GLOB_ABEND);
560 	else
561 	    return (0);
562     }
563 
564     err = 0;
565 
566     /* search directory for matching names */
567     while ((dp = readdir(dirp)) != NULL) {
568 	register unsigned char *sc;
569 	register Char *dc;
570 
571 #ifdef SOLARIS_DIRENT_PATCH
572 	/**********
573 	begin patch
574 	**********/
575 
576 #ifndef SOLARIS_DIRENT_ZERO
577 	for (ii = -2 ; dp->d_name[ii] != '\0' ; ++ii) {
578 	  dname[ii+2] = dp->d_name[ii];
579 	}
580         dname[ii+2] = '\0';
581 #else
582         strcpy(dname, dp->d_name); /* John Koger, March 1999 */
583 #endif
584 	/**********
585 	end patch
586 	now use dname for dp->d_name
587 	**********/
588 
589 	/* initial DOT must be matched literally */
590 	if (dname[0] == DOT && *pattern != DOT)
591 	    continue;
592 	for (sc = (unsigned char *) dname, dc = pathend;
593 #else
594 	if (dp->d_name[0] == DOT && *pattern != DOT)
595 	    continue;
596 	for (sc = (unsigned char *) dp->d_name, dc = pathend;
597 #endif
598 	     (*dc++ = *sc++) != '\0';)
599 	    continue;
600 	if (match(pathend, pattern, restpattern, (int) m_not) == no_match) {
601 	    *pathend = EOS;
602 	    continue;
603 	}
604 	err = glob2(pathbuf, --dc, restpattern, pglob, no_match);
605 	if (err)
606 	    break;
607     }
608     /* todo: check error from readdir? */
609     (void) closedir(dirp);
610     return (err);
611 }
612 
613 
614 /*
615  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
616  * add the new item, and update gl_pathc.
617  *
618  * This assumes the BSD realloc, which only copies the block when its size
619  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
620  * behavior.
621  *
622  * Return 0 if new item added, error code if memory couldn't be allocated.
623  *
624  * Invariant of the glob_t structure:
625  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
626  *	 gl_pathv points to (gl_offs + gl_pathc + 1) items.
627  */
628 static int
globextend(Char * path,glob_t * pglob)629 globextend(Char *path, glob_t *pglob)
630 {
631     register char **pathv;
632     register int i;
633     unsigned int newsize;
634     char   *copy;
635     Char *p;
636 
637     newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
638     pathv = (char **) (pglob->gl_pathv ?
639 		       xrealloc((ptr_t) pglob->gl_pathv, (size_t) newsize) :
640 		       xmalloc((size_t) newsize));
641     if (pathv == NULL)
642 	return (GLOB_NOSPACE);
643 
644     if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
645 	/* first time around -- clear initial gl_offs items */
646 	pathv += pglob->gl_offs;
647 	for (i = pglob->gl_offs; --i >= 0;)
648 	    *--pathv = NULL;
649     }
650     pglob->gl_pathv = pathv;
651 
652     for (p = path; *p++;)
653 	continue;
654     if ((copy = (char *) xmalloc((size_t) (p - path))) != NULL) {
655 	register char *dc = copy;
656 	register Char *sc = path;
657 
658 	while ((*dc++ = *sc++) != '\0')
659 	    continue;
660 	pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
661     }
662     pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
663     return ((copy == NULL) ? GLOB_NOSPACE : 0);
664 }
665 
666 
667 /*
668  * pattern matching function for filenames.  Each occurrence of the *
669  * pattern causes a recursion level.
670  */
671 static  int
match(Char * name,Char * pat,Char * patend,int m_not)672 match(Char *name, Char *pat, Char *patend, int m_not)
673 {
674     int ok, negate_range;
675     Char c, k;
676 
677     while (pat < patend) {
678 	c = *pat++;
679 	switch (c & M_MASK) {
680 	case M_ALL:
681 	    if (pat == patend)
682 		return (1);
683 	    do
684 		if (match(name, pat, patend, m_not))
685 		    return (1);
686 	    while (*name++ != EOS);
687 	    return (0);
688 	case M_ONE:
689 	    if (*name++ == EOS)
690 		return (0);
691 	    break;
692 	case M_SET:
693 	    ok = 0;
694 	    if ((k = *name++) == EOS)
695 		return (0);
696 	    if ((negate_range = ((*pat & M_MASK) == m_not)) != 0)
697 		++pat;
698 	    while (((c = *pat++) & M_MASK) != M_END) {
699 		if ((*pat & M_MASK) == M_RNG) {
700 		    if (c <= k && k <= pat[1])
701 			ok = 1;
702 		    pat += 2;
703 		}
704 		else if (c == k)
705 		    ok = 1;
706 	    }
707 	    if (ok == negate_range)
708 		return (0);
709 	    break;
710 	default:
711 	    k = *name++;
712 	    if (k != c)
713 		return (0);
714 	    break;
715 	}
716     }
717     return (*name == EOS);
718 }
719 
720 /* free allocated data belonging to a glob_t structure */
721 void
globfree(glob_t * pglob)722 globfree(glob_t *pglob)
723 {
724     register int i;
725     register char **pp;
726 
727     if (pglob->gl_pathv != NULL) {
728 	pp = pglob->gl_pathv + pglob->gl_offs;
729 	for (i = pglob->gl_pathc; i--; ++pp)
730 	    if (*pp)
731 		xfree((ptr_t) *pp), *pp = NULL;
732 	xfree((ptr_t) pglob->gl_pathv), pglob->gl_pathv = NULL;
733     }
734 }
735 
736 /*****************************************************************************
737    Major portions of this software are copyrighted by the Medical College
738    of Wisconsin, 1994-2000, and are released under the Gnu General Public
739    License, Version 2.  See the file README.Copyright for details.
740 ******************************************************************************/
741 
742 /*! set the direction of the sort (either small to large, or the reverse)    */
rglob_set_sort_dir(int dir)743 int rglob_set_sort_dir( int dir )                     /* 14 Feb 2005 [rickr] */
744 {
745    if ( dir == 1 )       g_sort_dir =  1;
746    else if ( dir == -1 ) g_sort_dir = -1;
747    else                  return 1;          /* else, ignore and signal error */
748 
749    return 0;
750 }
751 
752 
753 static int warn = 0 ;
MCW_warn_expand(int www)754 void MCW_warn_expand( int www ){ warn = www; return; }  /* 13 Jul 2001 */
755 
756 /*------------------------------------------------------------------------*/
757 /*! Routines that allows filename wildcarding to be handled inside
758     to3d.  The advantage: limitations of shell command line lengths.
759      - 29 July 1996:  Incorporated "glob" functions from tcsh-6.05, rather
760                        than rely on system supplying a library.
761      - 30 July 1996:  Extended routine to allow for 3D: type prefixes.
762      - 10 Feb  2000:  and for 3A: prefixes.
763 --------------------------------------------------------------------------*/
764 
MCW_file_expand(int nin,char ** fin,int * nout,char *** fout)765 void MCW_file_expand( int nin , char ** fin , int * nout , char *** fout )
766 {
767    glob_t gl ;
768    int    ii , gnum, gold , ilen ;
769    char ** gout ;
770    char *  fn ;
771    char prefix[4] , fpre[128] , fname[256] ;
772    int  b1,b2,b3,b4,b5 , ib,ig , lpre=0 ;
773 
774    if( nin <= 0 ){ *nout = 0 ; return ; }
775 
776    gnum = 0 ;
777    gout = NULL ;
778 
779    for( ii=0 ; ii < nin ; ii++ ){
780       fn = fin[ii] ;
781 
782       ig = 0 ;
783 
784       /** look for 3D: prefix **/
785 
786       if( strlen(fn) > 9 && fn[0] == '3' && fn[1] == 'D' ){
787          ib = 0 ;
788          prefix[ib++] = '3' ;
789          prefix[ib++] = 'D' ;
790          if( fn[2] == ':' ){ prefix[ib++] = '\0' ; }
791          else              { prefix[ib++] = fn[2] ; prefix[ib++] = '\0' ; }
792 
793          ig = sscanf( fn+ib , "%d:%d:%d:%d:%d:%s" ,     /* must scan all */
794                       &b1,&b2,&b3,&b4,&b5 , fname ) ;   /* six items OK  */
795 
796          /** if have all 6 3D: items, then make a 3D: prefix for output **/
797 
798          if( ig == 6 ){
799             sprintf(fpre , "%s:%d:%d:%d:%d:%d:" , prefix,b1,b2,b3,b4,b5) ;
800             lpre = strlen(fpre) ;
801          } else {
802             ig = 0 ;
803          }
804       }
805 
806       if( strlen(fn) > 9 && fn[0] == '3' && fn[1] == 'A' && fn[3] == ':' ){
807          ib = 0 ;
808          prefix[ib++] = '3' ;
809          prefix[ib++] = 'A' ;
810          prefix[ib++] = fn[2] ;
811          prefix[ib++] = '\0' ;
812 
813          ig = sscanf( fn+ib , "%d:%d:%d:%s" ,  /* must scan all */
814                       &b1,&b2,&b3, fname ) ;   /* four items OK */
815 
816          /** if have all 4 3A: items, then make a 3A: prefix for output **/
817 
818          if( ig == 4 ){
819             sprintf(fpre , "%s:%d:%d:%d:" , prefix,b1,b2,b3) ;
820             lpre = strlen(fpre) ;
821          } else {
822             ig = 0 ;
823          }
824       }
825 
826       if( ig > 0 ) (void) glob( fname , 0 , NULL ,  &gl ) ;  /* 3D: was OK */
827       else         (void) glob( fn    , 0 , NULL ,  &gl ) ;  /*     not OK */
828 
829       /** put each matched string into the output array **/
830 
831       if( gl.gl_pathc > 0 ){
832 
833          /** make space for output now **/
834          gold  = gnum ;
835          gnum += gl.gl_pathc ;
836          if( gout == NULL ) gout = (char **) malloc (      sizeof(char *)*gnum);
837          else               gout = (char **) realloc(gout, sizeof(char *)*gnum);
838 
839          for( ib=0 ; ib < gl.gl_pathc ; ib++ ){
840             ilen = strlen( gl.gl_pathv[ib] ) + 1 ;  /* length of this name */
841             if( ig > 0 ) ilen += lpre ;             /* plus 3D: prefix?    */
842 
843             gout[ib+gold] = (char *) malloc( sizeof(char) * ilen ) ; /* output! */
844 
845             if( ig > 0 ){
846                strcpy( gout[ib+gold] , fpre ) ;             /* 3D: prefix */
847                strcat( gout[ib+gold] , gl.gl_pathv[ib] ) ;  /* then name  */
848             }
849             else {
850                strcpy( gout[ib+gold] , gl.gl_pathv[ib] ) ;  /* just name */
851             }
852          }
853 
854       } else if( ig == 6 && strcmp(fname,"ALLZERO") == 0 ){ /* 06 Mar 2001 */
855 
856          gold = gnum ; gnum++ ;
857          if( gout == NULL ) gout = (char **) malloc (      sizeof(char *)*gnum);
858          else               gout = (char **) realloc(gout, sizeof(char *)*gnum);
859 
860          ilen = lpre + strlen(fname) + 1 ;
861          gout[gold] = (char *) malloc( sizeof(char) * ilen ) ; /* output! */
862          strcpy( gout[gold] , fpre ) ;
863          strcat( gout[gold] , fname ) ;
864 
865       } else {  /* 30 Apr 2001 */
866 
867          if( warn )  /* 13 Jul 2001 - print only if told to do so */
868            fprintf(stderr,"** Can't find file %s\n", (ig>0) ? fname : fn ) ;
869       }
870 
871       globfree( &gl ) ;
872    }
873 
874    *nout = gnum ; *fout = gout ; return ;
875 }
876 
877 /*-----------------------------------------------------------------------*/
878 /*! Simpler interface to MCW_file_expand().
879       - fnam = string of form "*.zork fred*.* ?a?b"; e.g., 1 or more
880                wildcards
881       - nout = pointer to output count
882       - fout = pointer to output list of strings.
883 
884     Sample usage:
885       int nfile ; char **flist ;
886       MCW_wildcards( "*.jpg *.JPG" , &nfile , &flist ) ;
887        ... do something with flist[0]..flist[nfile-1] if nfile > 0 ...
888       MCW_free_wildcards( nfile , flist ) ;
889 -------------------------------------------------------------------------*/
890 
MCW_wildcards(char * fnam,int * nout,char *** fout)891 void MCW_wildcards( char *fnam , int *nout , char ***fout )  /* 01 Dec 2003 */
892 {
893    char **fin=NULL, *fcop ;
894    int ii , nin , lf , ls ;
895 
896    if( fnam == NULL || *fnam == '\0' ){ *nout = 0 ; return ; }
897    fcop = strdup(fnam) ; lf = strlen(fcop) ;
898    ls = 1 ;
899    for( nin=ii=0 ; ii < lf ; ii++ ){
900      if( isspace(fcop[ii]) ){   /* This is a blank, so next */
901        ls = 1 ;                 /*  non-blank is a new word. */
902        fcop[ii] = '\0' ;        /* Set this char to NUL.      */
903 
904      } else {                   /* Not a blank. */
905 
906        if( ls ){                /* If last was a blank, is new name. */
907          fin = (char **) realloc( fin , sizeof(char *)*(nin+1) ) ;
908          fin[nin++] = fcop+ii ;
909        }
910        ls = 0 ;
911      }
912    }
913 
914    if( nin == 0 ){ *nout = 0 ; free(fcop) ; return ; }
915 
916    MCW_file_expand( nin , fin , nout , fout ) ;
917    free(fin) ; free(fcop) ; return ;
918 }
919 
920 /*-----------------------------------------------------------------------*/
921 
MCW_free_expand(int gnum,char ** gout)922 void MCW_free_expand( int gnum , char ** gout )
923 {
924    int ii ;
925 
926    if( gout == NULL ) return ;
927 
928    for( ii=0 ; ii < gnum ; ii++ ) free( gout[ii] ) ;
929    free( gout ) ;
930    return ;
931 }
932