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