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