xref: /openbsd-src/bin/ksh/misc.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: misc.c,v 1.16 2003/04/16 23:11:52 tdeval Exp $	*/
2 
3 /*
4  * Miscellaneous functions
5  */
6 
7 #include "sh.h"
8 #include <ctype.h>	/* for FILECHCONV */
9 #ifdef HAVE_LIMITS_H
10 # include <limits.h>
11 #endif
12 
13 #ifndef UCHAR_MAX
14 # define UCHAR_MAX	0xFF
15 #endif
16 
17 short ctypes [UCHAR_MAX+1];	/* type bits for unsigned char */
18 
19 static int	do_gmatch ARGS((const unsigned char *s, const unsigned char *p,
20 			const unsigned char *se, const unsigned char *pe,
21 			int isfile));
22 static const unsigned char *cclass ARGS((const unsigned char *p, int sub));
23 
24 /*
25  * Fast character classes
26  */
27 void
28 setctypes(s, t)
29 	register const char *s;
30 	register int t;
31 {
32 	register int i;
33 
34 	if (t & C_IFS) {
35 		for (i = 0; i < UCHAR_MAX+1; i++)
36 			ctypes[i] &= ~C_IFS;
37 		ctypes[0] |= C_IFS; /* include \0 in C_IFS */
38 	}
39 	while (*s != 0)
40 		ctypes[(unsigned char) *s++] |= t;
41 }
42 
43 void
44 initctypes()
45 {
46 	register int c;
47 
48 	for (c = 'a'; c <= 'z'; c++)
49 		ctypes[c] |= C_ALPHA;
50 	for (c = 'A'; c <= 'Z'; c++)
51 		ctypes[c] |= C_ALPHA;
52 	ctypes['_'] |= C_ALPHA;
53 	setctypes("0123456789", C_DIGIT);
54 	setctypes(" \t\n|&;<>()", C_LEX1); /* \0 added automatically */
55 	setctypes("*@#!$-?", C_VAR1);
56 	setctypes(" \t\n", C_IFSWS);
57 	setctypes("=-+?", C_SUBOP1);
58 	setctypes("#%", C_SUBOP2);
59 	setctypes(" \n\t\"#$&'()*;<>?[\\`|", C_QUOTE);
60 }
61 
62 /* convert unsigned long to base N string */
63 
64 char *
65 ulton(n, base)
66 	register unsigned long n;
67 	int base;
68 {
69 	register char *p;
70 	static char buf [20];
71 
72 	p = &buf[sizeof(buf)];
73 	*--p = '\0';
74 	do {
75 		*--p = "0123456789ABCDEF"[n%base];
76 		n /= base;
77 	} while (n != 0);
78 	return p;
79 }
80 
81 char *
82 str_save(s, ap)
83 	register const char *s;
84 	Area *ap;
85 {
86 	size_t len;
87 	char *p;
88 
89 	if (!s)
90 		return NULL;
91 	len = strlen(s)+1;
92 	p = alloc(len, ap);
93 	if (!p)
94 		return NULL;
95 	strlcpy(p, s, len+1);
96 	return (p);
97 }
98 
99 /* Allocate a string of size n+1 and copy upto n characters from the possibly
100  * null terminated string s into it.  Always returns a null terminated string
101  * (unless n < 0).
102  */
103 char *
104 str_nsave(s, n, ap)
105 	register const char *s;
106 	int n;
107 	Area *ap;
108 {
109 	char *ns;
110 
111 	if (n < 0)
112 		return 0;
113 	ns = alloc(n + 1, ap);
114 	ns[0] = '\0';
115 	return strncat(ns, s, n);
116 }
117 
118 /* called from expand.h:XcheckN() to grow buffer */
119 char *
120 Xcheck_grow_(xsp, xp, more)
121 	XString *xsp;
122 	char *xp;
123 	int more;
124 {
125 	char *old_beg = xsp->beg;
126 
127 	xsp->len += more > xsp->len ? more : xsp->len;
128 	xsp->beg = aresize(xsp->beg, xsp->len + 8, xsp->areap);
129 	xsp->end = xsp->beg + xsp->len;
130 	return xsp->beg + (xp - old_beg);
131 }
132 
133 const struct option options[] = {
134 	/* Special cases (see parse_args()): -A, -o, -s.
135 	 * Options are sorted by their longnames - the order of these
136 	 * entries MUST match the order of sh_flag F* enumerations in sh.h.
137 	 */
138 	{ "allexport",	'a',		OF_ANY },
139 #ifdef BRACE_EXPAND
140 	{ "braceexpand",  0,		OF_ANY }, /* non-standard */
141 #endif
142 	{ "bgnice",	  0,		OF_ANY },
143 	{ (char *) 0, 	'c',	    OF_CMDLINE },
144 #ifdef EMACS
145 	{ "emacs",	  0,		OF_ANY },
146 #endif
147 	{ "errexit",	'e',		OF_ANY },
148 #ifdef EMACS
149 	{ "gmacs",	  0,		OF_ANY },
150 #endif
151 	{ "ignoreeof",	  0,		OF_ANY },
152 	{ "interactive",'i',	    OF_CMDLINE },
153 	{ "keyword",	'k',		OF_ANY },
154 	{ "login",	'l',	    OF_CMDLINE },
155 	{ "markdirs",	'X',		OF_ANY },
156 #ifdef JOBS
157 	{ "monitor",	'm',		OF_ANY },
158 #else /* JOBS */
159 	{ (char *) 0,	'm',		     0 }, /* so FMONITOR not ifdef'd */
160 #endif /* JOBS */
161 	{ "noclobber",	'C',		OF_ANY },
162 	{ "noexec",	'n',		OF_ANY },
163 	{ "noglob",	'f',		OF_ANY },
164 	{ "nohup",	  0,		OF_ANY },
165 	{ "nolog",	  0,		OF_ANY }, /* no effect */
166 #ifdef	JOBS
167 	{ "notify",	'b',		OF_ANY },
168 #endif	/* JOBS */
169 	{ "nounset",	'u',		OF_ANY },
170 	{ "physical",	  0,		OF_ANY }, /* non-standard */
171 	{ "posix",	  0,		OF_ANY }, /* non-standard */
172 	{ "privileged",	'p',		OF_ANY },
173 	{ "restricted",	'r',	    OF_CMDLINE },
174 	{ "sh",		  0,		OF_ANY }, /* non-standard */
175 	{ "stdin",	's',	    OF_CMDLINE }, /* pseudo non-standard */
176 	{ "trackall",	'h',		OF_ANY },
177 	{ "verbose",	'v',		OF_ANY },
178 #ifdef VI
179 	{ "vi",		  0,		OF_ANY },
180 	{ "viraw",	  0,		OF_ANY }, /* no effect */
181 	{ "vi-show8",	  0,		OF_ANY }, /* non-standard */
182 	{ "vi-tabcomplete",  0, 	OF_ANY }, /* non-standard */
183 	{ "vi-esccomplete",  0, 	OF_ANY }, /* non-standard */
184 #endif
185 	{ "xtrace",	'x',		OF_ANY },
186 	/* Anonymous flags: used internally by shell only
187 	 * (not visable to user)
188 	 */
189 	{ (char *) 0,	0,		OF_INTERNAL }, /* FTALKING_I */
190 };
191 
192 /*
193  * translate -o option into F* constant (also used for test -o option)
194  */
195 int
196 option(n)
197 	const char *n;
198 {
199 	int i;
200 
201 	for (i = 0; i < NELEM(options); i++)
202 		if (options[i].name && strcmp(options[i].name, n) == 0)
203 			return i;
204 
205 	return -1;
206 }
207 
208 struct options_info {
209 	int opt_width;
210 	struct {
211 		const char *name;
212 		int	flag;
213 	} opts[NELEM(options)];
214 };
215 
216 static char *options_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
217 static void printoptions ARGS((int verbose));
218 
219 /* format a single select menu item */
220 static char *
221 options_fmt_entry(arg, i, buf, buflen)
222 	void *arg;
223 	int i;
224 	char *buf;
225 	int buflen;
226 {
227 	struct options_info *oi = (struct options_info *) arg;
228 
229 	shf_snprintf(buf, buflen, "%-*s %s",
230 		oi->opt_width, oi->opts[i].name,
231 		Flag(oi->opts[i].flag) ? "on" : "off");
232 	return buf;
233 }
234 
235 static void
236 printoptions(verbose)
237 	int verbose;
238 {
239 	int i;
240 
241 	if (verbose) {
242 		struct options_info oi;
243 		int n, len;
244 
245 		/* verbose version */
246 		shprintf("Current option settings\n");
247 
248 		for (i = n = oi.opt_width = 0; i < NELEM(options); i++)
249 			if (options[i].name) {
250 				len = strlen(options[i].name);
251 				oi.opts[n].name = options[i].name;
252 				oi.opts[n++].flag = i;
253 				if (len > oi.opt_width)
254 					oi.opt_width = len;
255 			}
256 		print_columns(shl_stdout, n, options_fmt_entry, &oi,
257 			      oi.opt_width + 5, 1);
258 	} else {
259 		/* short version ala ksh93 */
260 		shprintf("set");
261 		for (i = 0; i < NELEM(options); i++)
262 			if (Flag(i) && options[i].name)
263 				shprintf(" -o %s", options[i].name);
264 		shprintf(newline);
265 	}
266 }
267 
268 char *
269 getoptions()
270 {
271 	int i;
272 	char m[(int) FNFLAGS + 1];
273 	register char *cp = m;
274 
275 	for (i = 0; i < NELEM(options); i++)
276 		if (options[i].c && Flag(i))
277 			*cp++ = options[i].c;
278 	*cp = 0;
279 	return str_save(m, ATEMP);
280 }
281 
282 /* change a Flag(*) value; takes care of special actions */
283 void
284 change_flag(f, what, newval)
285 	enum sh_flag f;	/* flag to change */
286 	int what;	/* what is changing the flag (command line vs set) */
287 	int newval;
288 {
289 	int oldval;
290 
291 	oldval = Flag(f);
292 	Flag(f) = newval;
293 #ifdef JOBS
294 	if (f == FMONITOR) {
295 		if (what != OF_CMDLINE && newval != oldval)
296 			j_change();
297 	} else
298 #endif /* JOBS */
299 #ifdef EDIT
300 	if (0
301 # ifdef VI
302 	    || f == FVI
303 # endif /* VI */
304 # ifdef EMACS
305 	    || f == FEMACS || f == FGMACS
306 # endif /* EMACS */
307 	   )
308 	{
309 		if (newval) {
310 # ifdef VI
311 			Flag(FVI) = 0;
312 # endif /* VI */
313 # ifdef EMACS
314 			Flag(FEMACS) = Flag(FGMACS) = 0;
315 # endif /* EMACS */
316 			Flag(f) = newval;
317 		}
318 	} else
319 #endif /* EDIT */
320 	/* Turning off -p? */
321 	if (f == FPRIVILEGED && oldval && !newval) {
322 #ifdef OS2
323 		;
324 #else /* OS2 */
325 		seteuid(ksheuid = getuid());
326 		setuid(ksheuid);
327 		setegid(getgid());
328 		setgid(getgid());
329 #endif /* OS2 */
330 	} else if (f == FPOSIX && newval) {
331 #ifdef BRACE_EXPAND
332 		Flag(FBRACEEXPAND) = 0
333 #endif /* BRACE_EXPAND */
334 		;
335 	}
336 	/* Changing interactive flag? */
337 	if (f == FTALKING) {
338 		if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
339 			Flag(FTALKING_I) = newval;
340 	}
341 }
342 
343 /* parse command line & set command arguments.  returns the index of
344  * non-option arguments, -1 if there is an error.
345  */
346 int
347 parse_args(argv, what, setargsp)
348 	char **argv;
349 	int	what;		/* OF_CMDLINE or OF_SET */
350 	int	*setargsp;
351 {
352 	static char cmd_opts[NELEM(options) + 3]; /* o:\0 */
353 	static char set_opts[NELEM(options) + 5]; /* Ao;s\0 */
354 	char *opts;
355 	char *array = (char *) 0;
356 	Getopt go;
357 	int i, optc, set, sortargs = 0, arrayset = 0;
358 
359 	/* First call?  Build option strings... */
360 	if (cmd_opts[0] == '\0') {
361 		char *p, *q;
362 
363 		/* see cmd_opts[] declaration */
364 		strlcpy(cmd_opts, "o:", sizeof cmd_opts);
365 		p = cmd_opts + strlen(cmd_opts);
366 		/* see set_opts[] declaration */
367 		strlcpy(set_opts, "A:o;s", sizeof set_opts);
368 		q = set_opts + strlen(set_opts);
369 		for (i = 0; i < NELEM(options); i++) {
370 			if (options[i].c) {
371 				if (options[i].flags & OF_CMDLINE)
372 					*p++ = options[i].c;
373 				if (options[i].flags & OF_SET)
374 					*q++ = options[i].c;
375 			}
376 		}
377 		*p = '\0';
378 		*q = '\0';
379 	}
380 
381 	if (what == OF_CMDLINE) {
382 		char *p;
383 		/* Set FLOGIN before parsing options so user can clear
384 		 * flag using +l.
385 		 */
386 		Flag(FLOGIN) = (argv[0][0] == '-'
387 				|| ((p = ksh_strrchr_dirsep(argv[0]))
388 				     && *++p == '-'));
389 		opts = cmd_opts;
390 	} else
391 		opts = set_opts;
392 	ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
393 	while ((optc = ksh_getopt(argv, &go, opts)) != EOF) {
394 		set = (go.info & GI_PLUS) ? 0 : 1;
395 		switch (optc) {
396 		  case 'A':
397 			arrayset = set ? 1 : -1;
398 			array = go.optarg;
399 			break;
400 
401 		  case 'o':
402 			if (go.optarg == (char *) 0) {
403 				/* lone -o: print options
404 				 *
405 				 * Note that on the command line, -o requires
406 				 * an option (ie, can't get here if what is
407 				 * OF_CMDLINE).
408 				 */
409 				printoptions(set);
410 				break;
411 			}
412 			i = option(go.optarg);
413 			if (i >= 0 && set == Flag(i))
414 				/* Don't check the context if the flag
415 				 * isn't changing - makes "set -o interactive"
416 				 * work if you're already interactive.  Needed
417 				 * if the output of "set +o" is to be used.
418 				 */
419 				;
420 			else if (i >= 0 && (options[i].flags & what))
421 				change_flag((enum sh_flag) i, what, set);
422 			else {
423 				bi_errorf("%s: bad option", go.optarg);
424 				return -1;
425 			}
426 			break;
427 
428 		  case '?':
429 			return -1;
430 
431 		  default:
432 			/* -s: sort positional params (at&t ksh stupidity) */
433 			if (what == OF_SET && optc == 's') {
434 				sortargs = 1;
435 				break;
436 			}
437 			for (i = 0; i < NELEM(options); i++)
438 				if (optc == options[i].c
439 				    && (what & options[i].flags))
440 				{
441 					change_flag((enum sh_flag) i, what,
442 						    set);
443 					break;
444 				}
445 			if (i == NELEM(options)) {
446 				internal_errorf(1, "parse_args: `%c'", optc);
447 				return -1; /* not reached */
448 			}
449 		}
450 	}
451 	if (!(go.info & GI_MINUSMINUS) && argv[go.optind]
452 	    && (argv[go.optind][0] == '-' || argv[go.optind][0] == '+')
453 	    && argv[go.optind][1] == '\0')
454 	{
455 		/* lone - clears -v and -x flags */
456 		if (argv[go.optind][0] == '-' && !Flag(FPOSIX))
457 			Flag(FVERBOSE) = Flag(FXTRACE) = 0;
458 		/* set skips lone - or + option */
459 		go.optind++;
460 	}
461 	if (setargsp)
462 		/* -- means set $#/$* even if there are no arguments */
463 		*setargsp = !arrayset && ((go.info & GI_MINUSMINUS)
464 					  || argv[go.optind]);
465 
466 	if (arrayset && (!*array || *skip_varname(array, FALSE))) {
467 		bi_errorf("%s: is not an identifier", array);
468 		return -1;
469 	}
470 	if (sortargs) {
471 		for (i = go.optind; argv[i]; i++)
472 			;
473 		qsortp((void **) &argv[go.optind], (size_t) (i - go.optind),
474 			xstrcmp);
475 	}
476 	if (arrayset) {
477 		set_array(array, arrayset, argv + go.optind);
478 		for (; argv[go.optind]; go.optind++)
479 			;
480 	}
481 
482 	return go.optind;
483 }
484 
485 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
486 int
487 getn(as, ai)
488 	const char *as;
489 	int *ai;
490 {
491 	char *p;
492 	long n;
493 
494 	n = strtol(as, &p, 10);
495 
496 	if (!*as || *p || INT_MIN >= n || n >= INT_MAX)
497 		return 0;
498 
499 	*ai = (int)n;
500 	return 1;
501 }
502 
503 /* getn() that prints error */
504 int
505 bi_getn(as, ai)
506 	const char *as;
507 	int *ai;
508 {
509 	int rv = getn(as, ai);
510 
511 	if (!rv)
512 		bi_errorf("%s: bad number", as);
513 	return rv;
514 }
515 
516 /* -------- gmatch.c -------- */
517 
518 /*
519  * int gmatch(string, pattern)
520  * char *string, *pattern;
521  *
522  * Match a pattern as in sh(1).
523  * pattern character are prefixed with MAGIC by expand.
524  */
525 
526 int
527 gmatch(s, p, isfile)
528 	const char *s, *p;
529 	int isfile;
530 {
531 	const char *se, *pe;
532 
533 	if (s == NULL || p == NULL)
534 		return 0;
535 	se = s + strlen(s);
536 	pe = p + strlen(p);
537 	/* isfile is false iff no syntax check has been done on
538 	 * the pattern.  If check fails, just to a strcmp().
539 	 */
540 	if (!isfile && !has_globbing(p, pe)) {
541 		int len = pe - p + 1;
542 		char tbuf[64];
543 		char *t = len <= sizeof(tbuf) ? tbuf
544 				: (char *) alloc(len, ATEMP);
545 		debunk(t, p, len);
546 		return !strcmp(t, s);
547 	}
548 	return do_gmatch((const unsigned char *) s, (const unsigned char *) se,
549 			 (const unsigned char *) p, (const unsigned char *) pe,
550 			 isfile);
551 }
552 
553 /* Returns if p is a syntacticly correct globbing pattern, false
554  * if it contains no pattern characters or if there is a syntax error.
555  * Syntax errors are:
556  *	- [ with no closing ]
557  *	- imbalanced $(...) expression
558  *	- [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
559  */
560 /*XXX
561 - if no magic,
562 	if dest given, copy to dst
563 	return ?
564 - if magic && (no globbing || syntax error)
565 	debunk to dst
566 	return ?
567 - return ?
568 */
569 int
570 has_globbing(xp, xpe)
571 	const char *xp, *xpe;
572 {
573 	const unsigned char *p = (const unsigned char *) xp;
574 	const unsigned char *pe = (const unsigned char *) xpe;
575 	int c;
576 	int nest = 0, bnest = 0;
577 	int saw_glob = 0;
578 	int in_bracket = 0; /* inside [...] */
579 
580 	for (; p < pe; p++) {
581 		if (!ISMAGIC(*p))
582 			continue;
583 		if ((c = *++p) == '*' || c == '?')
584 			saw_glob = 1;
585 		else if (c == '[') {
586 			if (!in_bracket) {
587 				saw_glob = 1;
588 				in_bracket = 1;
589 				if (ISMAGIC(p[1]) && p[2] == NOT)
590 					p += 2;
591 				if (ISMAGIC(p[1]) && p[2] == ']')
592 					p += 2;
593 			}
594 			/* XXX Do we need to check ranges here? POSIX Q */
595 		} else if (c == ']') {
596 			if (in_bracket) {
597 				if (bnest)		/* [a*(b]) */
598 					return 0;
599 				in_bracket = 0;
600 			}
601 		} else if ((c & 0x80) && strchr("*+?@! ", c & 0x7f)) {
602 			saw_glob = 1;
603 			if (in_bracket)
604 				bnest++;
605 			else
606 				nest++;
607 		} else if (c == '|') {
608 			if (in_bracket && !bnest)	/* *(a[foo|bar]) */
609 				return 0;
610 		} else if (c == /*(*/ ')') {
611 			if (in_bracket) {
612 				if (!bnest--)		/* *(a[b)c] */
613 					return 0;
614 			} else if (nest)
615 				nest--;
616 		}
617 		/* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
618 			 MAGIC-{, MAGIC-,, MAGIC-} */
619 	}
620 	return saw_glob && !in_bracket && !nest;
621 }
622 
623 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
624 static int
625 do_gmatch(s, se, p, pe, isfile)
626 	const unsigned char *s, *p;
627 	const unsigned char *se, *pe;
628 	int isfile;
629 {
630 	register int sc, pc;
631 	const unsigned char *prest, *psub, *pnext;
632 	const unsigned char *srest;
633 
634 	if (s == NULL || p == NULL)
635 		return 0;
636 	while (p < pe) {
637 		pc = *p++;
638 		sc = s < se ? *s : '\0';
639 		s++;
640 		if (isfile) {
641 			sc = FILECHCONV(sc);
642 			pc = FILECHCONV(pc);
643 		}
644 		if (!ISMAGIC(pc)) {
645 			if (sc != pc)
646 				return 0;
647 			continue;
648 		}
649 		switch (*p++) {
650 		  case '[':
651 			if (sc == 0 || (p = cclass(p, sc)) == NULL)
652 				return 0;
653 			break;
654 
655 		  case '?':
656 			if (sc == 0)
657 				return 0;
658 			break;
659 
660 		  case '*':
661 			if (p == pe)
662 				return 1;
663 			s--;
664 			do {
665 				if (do_gmatch(s, se, p, pe, isfile))
666 					return 1;
667 			} while (s++ < se);
668 			return 0;
669 
670 		  /*
671 		   * [*+?@!](pattern|pattern|..)
672 		   *
673 		   * Not ifdef'd KSH as this is needed for ${..%..}, etc.
674 		   */
675 		  case 0x80|'+': /* matches one or more times */
676 		  case 0x80|'*': /* matches zero or more times */
677 			if (!(prest = pat_scan(p, pe, 0)))
678 				return 0;
679 			s--;
680 			/* take care of zero matches */
681 			if (p[-1] == (0x80 | '*')
682 			    && do_gmatch(s, se, prest, pe, isfile))
683 				return 1;
684 			for (psub = p; ; psub = pnext) {
685 				pnext = pat_scan(psub, pe, 1);
686 				for (srest = s; srest <= se; srest++) {
687 					if (do_gmatch(s, srest,
688 						psub, pnext - 2, isfile)
689 					    && (do_gmatch(srest, se,
690 							  prest, pe, isfile)
691 						|| (s != srest
692 						    && do_gmatch(srest, se,
693 							p - 2, pe, isfile))))
694 						return 1;
695 				}
696 				if (pnext == prest)
697 					break;
698 			}
699 			return 0;
700 
701 		  case 0x80|'?': /* matches zero or once */
702 		  case 0x80|'@': /* matches one of the patterns */
703 		  case 0x80|' ': /* simile for @ */
704 			if (!(prest = pat_scan(p, pe, 0)))
705 				return 0;
706 			s--;
707 			/* Take care of zero matches */
708 			if (p[-1] == (0x80 | '?')
709 			    && do_gmatch(s, se, prest, pe, isfile))
710 				return 1;
711 			for (psub = p; ; psub = pnext) {
712 				pnext = pat_scan(psub, pe, 1);
713 				srest = prest == pe ? se : s;
714 				for (; srest <= se; srest++) {
715 					if (do_gmatch(s, srest,
716 						      psub, pnext - 2, isfile)
717 					    && do_gmatch(srest, se,
718 							 prest, pe, isfile))
719 						return 1;
720 				}
721 				if (pnext == prest)
722 					break;
723 			}
724 			return 0;
725 
726 		  case 0x80|'!': /* matches none of the patterns */
727 			if (!(prest = pat_scan(p, pe, 0)))
728 				return 0;
729 			s--;
730 			for (srest = s; srest <= se; srest++) {
731 				int matched = 0;
732 
733 				for (psub = p; ; psub = pnext) {
734 					pnext = pat_scan(psub, pe, 1);
735 					if (do_gmatch(s, srest,
736 						      psub, pnext - 2, isfile))
737 					{
738 						matched = 1;
739 						break;
740 					}
741 					if (pnext == prest)
742 						break;
743 				}
744 				if (!matched && do_gmatch(srest, se,
745 							  prest, pe, isfile))
746 					return 1;
747 			}
748 			return 0;
749 
750 		  default:
751 			if (sc != p[-1])
752 				return 0;
753 			break;
754 		}
755 	}
756 	return s == se;
757 }
758 
759 static const unsigned char *
760 cclass(p, sub)
761 	const unsigned char *p;
762 	register int sub;
763 {
764 	register int c, d, not, found = 0;
765 	const unsigned char *orig_p = p;
766 
767 	if ((not = (ISMAGIC(*p) && *++p == NOT)))
768 		p++;
769 	do {
770 		c = *p++;
771 		if (ISMAGIC(c)) {
772 			c = *p++;
773 			if ((c & 0x80) && !ISMAGIC(c)) {
774 				c &= 0x7f;/* extended pattern matching: *+?@! */
775 				/* XXX the ( char isn't handled as part of [] */
776 				if (c == ' ') /* simile for @: plain (..) */
777 					c = '(' /*)*/;
778 			}
779 		}
780 		if (c == '\0')
781 			/* No closing ] - act as if the opening [ was quoted */
782 			return sub == '[' ? orig_p : NULL;
783 		if (ISMAGIC(p[0]) && p[1] == '-'
784 		    && (!ISMAGIC(p[2]) || p[3] != ']'))
785 		{
786 			p += 2; /* MAGIC- */
787 			d = *p++;
788 			if (ISMAGIC(d)) {
789 				d = *p++;
790 				if ((d & 0x80) && !ISMAGIC(d))
791 					d &= 0x7f;
792 			}
793 			/* POSIX says this is an invalid expression */
794 			if (c > d)
795 				return NULL;
796 		} else
797 			d = c;
798 		if (c == sub || (c <= sub && sub <= d))
799 			found = 1;
800 	} while (!(ISMAGIC(p[0]) && p[1] == ']'));
801 
802 	return (found != not) ? p+2 : NULL;
803 }
804 
805 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
806 const unsigned char *
807 pat_scan(p, pe, match_sep)
808 	const unsigned char *p;
809 	const unsigned char *pe;
810 	int match_sep;
811 {
812 	int nest = 0;
813 
814 	for (; p < pe; p++) {
815 		if (!ISMAGIC(*p))
816 			continue;
817 		if ((*++p == /*(*/ ')' && nest-- == 0)
818 		    || (*p == '|' && match_sep && nest == 0))
819 			return ++p;
820 		if ((*p & 0x80) && strchr("*+?@! ", *p & 0x7f))
821 			nest++;
822 	}
823 	return (const unsigned char *) 0;
824 }
825 
826 
827 /* -------- qsort.c -------- */
828 
829 /*
830  * quick sort of array of generic pointers to objects.
831  */
832 static void qsort1 ARGS((void **base, void **lim, int (*f)(void *, void *)));
833 
834 void
835 qsortp(base, n, f)
836 	void **base;				/* base address */
837 	size_t n;				/* elements */
838 	int (*f) ARGS((void *, void *));	/* compare function */
839 {
840 	qsort1(base, base + n, f);
841 }
842 
843 #define	swap2(a, b)	{\
844 	register void *t; t = *(a); *(a) = *(b); *(b) = t;\
845 }
846 #define	swap3(a, b, c)	{\
847 	register void *t; t = *(a); *(a) = *(c); *(c) = *(b); *(b) = t;\
848 }
849 
850 static void
851 qsort1(base, lim, f)
852 	void **base, **lim;
853 	int (*f) ARGS((void *, void *));
854 {
855 	register void **i, **j;
856 	register void **lptr, **hptr;
857 	size_t n;
858 	int c;
859 
860   top:
861 	n = (lim - base) / 2;
862 	if (n == 0)
863 		return;
864 	hptr = lptr = base+n;
865 	i = base;
866 	j = lim - 1;
867 
868 	for (;;) {
869 		if (i < lptr) {
870 			if ((c = (*f)(*i, *lptr)) == 0) {
871 				lptr --;
872 				swap2(i, lptr);
873 				continue;
874 			}
875 			if (c < 0) {
876 				i += 1;
877 				continue;
878 			}
879 		}
880 
881 	  begin:
882 		if (j > hptr) {
883 			if ((c = (*f)(*hptr, *j)) == 0) {
884 				hptr ++;
885 				swap2(hptr, j);
886 				goto begin;
887 			}
888 			if (c > 0) {
889 				if (i == lptr) {
890 					hptr ++;
891 					swap3(i, hptr, j);
892 					i = lptr += 1;
893 					goto begin;
894 				}
895 				swap2(i, j);
896 				j -= 1;
897 				i += 1;
898 				continue;
899 			}
900 			j -= 1;
901 			goto begin;
902 		}
903 
904 		if (i == lptr) {
905 			if (lptr-base >= lim-hptr) {
906 				qsort1(hptr+1, lim, f);
907 				lim = lptr;
908 			} else {
909 				qsort1(base, lptr, f);
910 				base = hptr+1;
911 			}
912 			goto top;
913 		}
914 
915 		lptr -= 1;
916 		swap3(j, lptr, i);
917 		j = hptr -= 1;
918 	}
919 }
920 
921 int
922 xstrcmp(p1, p2)
923 	void *p1, *p2;
924 {
925 	return (strcmp((char *)p1, (char *)p2));
926 }
927 
928 /* Initialize a Getopt structure */
929 void
930 ksh_getopt_reset(go, flags)
931 	Getopt *go;
932 	int flags;
933 {
934 	go->optind = 1;
935 	go->optarg = (char *) 0;
936 	go->p = 0;
937 	go->flags = flags;
938 	go->info = 0;
939 	go->buf[1] = '\0';
940 }
941 
942 
943 /* getopt() used for shell built-in commands, the getopts command, and
944  * command line options.
945  * A leading ':' in options means don't print errors, instead return '?'
946  * or ':' and set go->optarg to the offending option character.
947  * If GF_ERROR is set (and option doesn't start with :), errors result in
948  * a call to bi_errorf().
949  *
950  * Non-standard features:
951  *	- ';' is like ':' in options, except the argument is optional
952  *	  (if it isn't present, optarg is set to 0).
953  *	  Used for 'set -o'.
954  *	- ',' is like ':' in options, except the argument always immediately
955  *	  follows the option character (optarg is set to the null string if
956  *	  the option is missing).
957  *	  Used for 'read -u2', 'print -u2' and fc -40.
958  *	- '#' is like ':' in options, expect that the argument is optional
959  *	  and must start with a digit.  If the argument doesn't start with a
960  *	  digit, it is assumed to be missing and normal option processing
961  *	  continues (optarg is set to 0 if the option is missing).
962  *	  Used for 'typeset -LZ4'.
963  *	- accepts +c as well as -c IF the GF_PLUSOPT flag is present.  If an
964  *	  option starting with + is accepted, the GI_PLUS flag will be set
965  *	  in go->info.
966  */
967 int
968 ksh_getopt(argv, go, options)
969 	char **argv;
970 	Getopt *go;
971 	const char *options;
972 {
973 	char c;
974 	char *o;
975 
976 	if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
977 		char *arg = argv[go->optind], flag = arg ? *arg : '\0';
978 
979 		go->p = 1;
980 		if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
981 			go->optind++;
982 			go->p = 0;
983 			go->info |= GI_MINUSMINUS;
984 			return EOF;
985 		}
986 		if (arg == (char *) 0
987 		    || ((flag != '-' ) /* neither a - nor a + (if + allowed) */
988 			&& (!(go->flags & GF_PLUSOPT) || flag != '+'))
989 		    || (c = arg[1]) == '\0')
990 		{
991 			go->p = 0;
992 			return EOF;
993 		}
994 		go->optind++;
995 		go->info &= ~(GI_MINUS|GI_PLUS);
996 		go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
997 	}
998 	go->p++;
999 	if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#'
1000 	    || !(o = strchr(options, c)))
1001 	{
1002 		if (options[0] == ':') {
1003 			go->buf[0] = c;
1004 			go->optarg = go->buf;
1005 		} else {
1006 			warningf(TRUE, "%s%s-%c: unknown option",
1007 				(go->flags & GF_NONAME) ? "" : argv[0],
1008 				(go->flags & GF_NONAME) ? "" : ": ", c);
1009 			if (go->flags & GF_ERROR)
1010 				bi_errorf(null);
1011 		}
1012 		return '?';
1013 	}
1014 	/* : means argument must be present, may be part of option argument
1015 	 *   or the next argument
1016 	 * ; same as : but argument may be missing
1017 	 * , means argument is part of option argument, and may be null.
1018 	 */
1019 	if (*++o == ':' || *o == ';') {
1020 		if (argv[go->optind - 1][go->p])
1021 			go->optarg = argv[go->optind - 1] + go->p;
1022 		else if (argv[go->optind])
1023 			go->optarg = argv[go->optind++];
1024 		else if (*o == ';')
1025 			go->optarg = (char *) 0;
1026 		else {
1027 			if (options[0] == ':') {
1028 				go->buf[0] = c;
1029 				go->optarg = go->buf;
1030 				return ':';
1031 			}
1032 			warningf(TRUE, "%s%s-`%c' requires argument",
1033 				(go->flags & GF_NONAME) ? "" : argv[0],
1034 				(go->flags & GF_NONAME) ? "" : ": ", c);
1035 			if (go->flags & GF_ERROR)
1036 				bi_errorf(null);
1037 			return '?';
1038 		}
1039 		go->p = 0;
1040 	} else if (*o == ',') {
1041 		/* argument is attached to option character, even if null */
1042 		go->optarg = argv[go->optind - 1] + go->p;
1043 		go->p = 0;
1044 	} else if (*o == '#') {
1045 		/* argument is optional and may be attached or unattached
1046 		 * but must start with a digit.  optarg is set to 0 if the
1047 		 * argument is missing.
1048 		 */
1049 		if (argv[go->optind - 1][go->p]) {
1050 			if (digit(argv[go->optind - 1][go->p])) {
1051 				go->optarg = argv[go->optind - 1] + go->p;
1052 				go->p = 0;
1053 			} else
1054 				go->optarg = (char *) 0;;
1055 		} else {
1056 			if (argv[go->optind] && digit(argv[go->optind][0])) {
1057 				go->optarg = argv[go->optind++];
1058 				go->p = 0;
1059 			} else
1060 				go->optarg = (char *) 0;;
1061 		}
1062 	}
1063 	return c;
1064 }
1065 
1066 /* print variable/alias value using necessary quotes
1067  * (POSIX says they should be suitable for re-entry...)
1068  * No trailing newline is printed.
1069  */
1070 void
1071 print_value_quoted(s)
1072 	const char *s;
1073 {
1074 	const char *p;
1075 	int inquote = 0;
1076 
1077 	/* Test if any quotes are needed */
1078 	for (p = s; *p; p++)
1079 		if (ctype(*p, C_QUOTE))
1080 			break;
1081 	if (!*p) {
1082 		shprintf("%s", s);
1083 		return;
1084 	}
1085 	for (p = s; *p; p++) {
1086 		if (*p == '\'') {
1087 			shprintf("'\\'" + 1 - inquote);
1088 			inquote = 0;
1089 		} else {
1090 			if (!inquote) {
1091 				shprintf("'");
1092 				inquote = 1;
1093 			}
1094 			shf_putc(*p, shl_stdout);
1095 		}
1096 	}
1097 	if (inquote)
1098 		shprintf("'");
1099 }
1100 
1101 /* Print things in columns and rows - func() is called to format the ith
1102  * element
1103  */
1104 void
1105 print_columns(shf, n, func, arg, max_width, prefcol)
1106 	struct shf *shf;
1107 	int n;
1108 	char *(*func) ARGS((void *, int, char *, int));
1109 	void *arg;
1110 	int max_width;
1111 	int prefcol;
1112 {
1113 	char *str = (char *) alloc(max_width + 1, ATEMP);
1114 	int i;
1115 	int r, c;
1116 	int rows, cols;
1117 	int nspace;
1118 
1119 	/* max_width + 1 for the space.  Note that no space
1120 	 * is printed after the last column to avoid problems
1121 	 * with terminals that have auto-wrap.
1122 	 */
1123 	cols = x_cols / (max_width + 1);
1124 	if (!cols)
1125 		cols = 1;
1126 	rows = (n + cols - 1) / cols;
1127 	if (prefcol && n && cols > rows) {
1128 		int tmp = rows;
1129 
1130 		rows = cols;
1131 		cols = tmp;
1132 		if (rows > n)
1133 			rows = n;
1134 	}
1135 
1136 	nspace = (x_cols - max_width * cols) / cols;
1137 	if (nspace <= 0)
1138 		nspace = 1;
1139 	for (r = 0; r < rows; r++) {
1140 		for (c = 0; c < cols; c++) {
1141 			i = c * rows + r;
1142 			if (i < n) {
1143 				shf_fprintf(shf, "%-*s",
1144 					max_width,
1145 					(*func)(arg, i, str, max_width + 1));
1146 				if (c + 1 < cols)
1147 					shf_fprintf(shf, "%*s", nspace, null);
1148 			}
1149 		}
1150 		shf_putchar('\n', shf);
1151 	}
1152 	afree(str, ATEMP);
1153 }
1154 
1155 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
1156 int
1157 strip_nuls(buf, nbytes)
1158 	char *buf;
1159 	int nbytes;
1160 {
1161 	char *dst;
1162 
1163 	/* nbytes check because some systems (older freebsd's) have a buggy
1164 	 * memchr()
1165 	 */
1166 	if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
1167 		char *end = buf + nbytes;
1168 		char *p, *q;
1169 
1170 		for (p = dst; p < end; p = q) {
1171 			/* skip a block of nulls */
1172 			while (++p < end && *p == '\0')
1173 				;
1174 			/* find end of non-null block */
1175 			if (!(q = memchr(p, '\0', end - p)))
1176 				q = end;
1177 			memmove(dst, p, q - p);
1178 			dst += q - p;
1179 		}
1180 		*dst = '\0';
1181 		return dst - buf;
1182 	}
1183 	return nbytes;
1184 }
1185 
1186 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
1187  * Returns dst.
1188  */
1189 char *
1190 str_zcpy(dst, src, dsize)
1191 	char *dst;
1192 	const char *src;
1193 	int dsize;
1194 {
1195 	if (dsize > 0) {
1196 		int len = strlen(src);
1197 
1198 		if (len >= dsize)
1199 			len = dsize - 1;
1200 		memcpy(dst, src, len);
1201 		dst[len] = '\0';
1202 	}
1203 	return dst;
1204 }
1205 
1206 /* Like read(2), but if read fails due to non-blocking flag, resets flag
1207  * and restarts read.
1208  */
1209 int
1210 blocking_read(fd, buf, nbytes)
1211 	int fd;
1212 	char *buf;
1213 	int nbytes;
1214 {
1215 	int ret;
1216 	int tried_reset = 0;
1217 
1218 	while ((ret = read(fd, buf, nbytes)) < 0) {
1219 		if (!tried_reset && (errno == EAGAIN
1220 #ifdef EWOULDBLOCK
1221 				     || errno == EWOULDBLOCK
1222 #endif /* EWOULDBLOCK */
1223 				    ))
1224 		{
1225 			int oerrno = errno;
1226 			if (reset_nonblock(fd) > 0) {
1227 				tried_reset = 1;
1228 				continue;
1229 			}
1230 			errno = oerrno;
1231 		}
1232 		break;
1233 	}
1234 	return ret;
1235 }
1236 
1237 /* Reset the non-blocking flag on the specified file descriptor.
1238  * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1239  * 1 if it was.
1240  */
1241 int
1242 reset_nonblock(fd)
1243 	int fd;
1244 {
1245 	int flags;
1246 	int blocking_flags;
1247 
1248 	if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1249 		return -1;
1250 	/* With luck, the C compiler will reduce this to a constant */
1251 	blocking_flags = 0;
1252 #ifdef O_NONBLOCK
1253 	blocking_flags |= O_NONBLOCK;
1254 #endif /* O_NONBLOCK */
1255 #ifdef O_NDELAY
1256 	blocking_flags |= O_NDELAY;
1257 #else /* O_NDELAY */
1258 # ifndef O_NONBLOCK
1259 	blocking_flags |= FNDELAY; /* hope this exists... */
1260 # endif /* O_NONBLOCK */
1261 #endif /* O_NDELAY */
1262 	if (!(flags & blocking_flags))
1263 		return 0;
1264 	flags &= ~blocking_flags;
1265 	if (fcntl(fd, F_SETFL, flags) < 0)
1266 		return -1;
1267 	return 1;
1268 }
1269 
1270 
1271 #ifdef HAVE_SYS_PARAM_H
1272 # include <sys/param.h>
1273 #endif /* HAVE_SYS_PARAM_H */
1274 #ifndef MAXPATHLEN
1275 # define MAXPATHLEN PATH
1276 #endif /* MAXPATHLEN */
1277 
1278 #ifdef HPUX_GETWD_BUG
1279 # include "ksh_dir.h"
1280 
1281 /*
1282  * Work around bug in hpux 10.x C library - getwd/getcwd dump core
1283  * if current directory is not readable.  Done in macro 'cause code
1284  * is needed in GETWD and GETCWD cases.
1285  */
1286 # define HPUX_GETWD_BUG_CODE \
1287 	{ \
1288 	    DIR *d = ksh_opendir("."); \
1289 	    if (!d) \
1290 		return (char *) 0; \
1291 	    closedir(d); \
1292 	}
1293 #else /* HPUX_GETWD_BUG */
1294 # define HPUX_GETWD_BUG_CODE
1295 #endif /* HPUX_GETWD_BUG */
1296 
1297 /* Like getcwd(), except bsize is ignored if buf is 0 (MAXPATHLEN is used) */
1298 char *
1299 ksh_get_wd(buf, bsize)
1300 	char *buf;
1301 	int bsize;
1302 {
1303 #ifdef HAVE_GETCWD
1304 	char *b;
1305 	char *ret;
1306 
1307 	/* Before memory allocated */
1308 	HPUX_GETWD_BUG_CODE
1309 
1310 	/* Assume getcwd() available */
1311 	if (!buf) {
1312 		bsize = MAXPATHLEN;
1313 		b = alloc(MAXPATHLEN + 1, ATEMP);
1314 	} else
1315 		b = buf;
1316 
1317 	ret = getcwd(b, bsize);
1318 
1319 	if (!buf) {
1320 		if (ret)
1321 			ret = aresize(b, strlen(b) + 1, ATEMP);
1322 		else
1323 			afree(b, ATEMP);
1324 	}
1325 
1326 	return ret;
1327 #else /* HAVE_GETCWD */
1328 	extern char *getwd ARGS((char *));
1329 	char *b;
1330 	int len;
1331 
1332 	/* Before memory allocated */
1333 	HPUX_GETWD_BUG_CODE
1334 
1335 	if (buf && bsize > MAXPATHLEN)
1336 		b = buf;
1337 	else
1338 		b = alloc(MAXPATHLEN + 1, ATEMP);
1339 	if (!getwd(b)) {
1340 		errno = EACCES;
1341 		if (b != buf)
1342 			afree(b, ATEMP);
1343 		return (char *) 0;
1344 	}
1345 	len = strlen(b) + 1;
1346 	if (!buf)
1347 		b = aresize(b, len, ATEMP);
1348 	else if (buf != b) {
1349 		if (len > bsize) {
1350 			errno = ERANGE;
1351 			return (char *) 0;
1352 		}
1353 		memcpy(buf, b, len);
1354 		afree(b, ATEMP);
1355 		b = buf;
1356 	}
1357 
1358 	return b;
1359 #endif /* HAVE_GETCWD */
1360 }
1361