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