oksh-noxz

[fork] Portable OpenBSD ksh, based on the Public Domain Korn Shell (pdksh).
git clone https://noxz.tech/git/oksh-noxz.git
Log | Files | Tags

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