1 /*	$OpenBSD: main.c,v 1.54 2013/11/28 10:33:37 sobrado Exp $	*/
2 /*	$OpenBSD: tty.c,v 1.10 2014/08/10 02:44:26 guenther Exp $	*/
3 /*	$OpenBSD: io.c,v 1.25 2014/08/11 20:28:47 guenther Exp $	*/
4 /*	$OpenBSD: table.c,v 1.15 2012/02/19 07:52:30 otto Exp $	*/
5 
6 /*-
7  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
8  *		 2011, 2012, 2013, 2014
9  *	Thorsten Glaser <tg@mirbsd.org>
10  *
11  * Provided that these terms and disclaimer and all copyright notices
12  * are retained or reproduced in an accompanying document, permission
13  * is granted to deal in this work without restriction, including un-
14  * limited rights to use, publicly perform, distribute, sell, modify,
15  * merge, give away, or sublicence.
16  *
17  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
18  * the utmost extent permitted by applicable law, neither express nor
19  * implied; without malicious intent or gross negligence. In no event
20  * may a licensor, author or contributor be held liable for indirect,
21  * direct, other damage, loss, or other issues arising in any way out
22  * of dealing in the work, even if advised of the possibility of such
23  * damage or existence of a defect, except proven that it results out
24  * of said person's immediate fault when using the work as intended.
25  */
26 
27 #define EXTERN
28 #include "sh.h"
29 
30 #if HAVE_LANGINFO_CODESET
31 #include <langinfo.h>
32 #endif
33 #if HAVE_SETLOCALE_CTYPE
34 #include <locale.h>
35 #endif
36 
37 __RCSID("$MirOS: src/bin/mksh/main.c,v 1.281 2014/09/12 20:23:33 tg Exp $");
38 
39 extern char **environ;
40 
41 #ifndef MKSHRC_PATH
42 #define MKSHRC_PATH	"~/.mkshrc"
43 #endif
44 
45 #ifndef MKSH_DEFAULT_TMPDIR
46 #define MKSH_DEFAULT_TMPDIR	"/tmp"
47 #endif
48 
49 static uint8_t isuc(const char *);
50 static int main_init(int, const char *[], Source **, struct block **);
51 void chvt_reinit(void);
52 static void reclaim(void);
53 static void remove_temps(struct temp *);
54 static mksh_uari_t rndsetup(void);
55 #ifdef SIGWINCH
56 static void x_sigwinch(int);
57 #endif
58 
59 static const char initifs[] = "IFS= \t\n";
60 
61 static const char initsubs[] =
62     "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0} ${EPOCHREALTIME=}";
63 
64 static const char *initcoms[] = {
65 	Ttypeset, "-r", initvsn, NULL,
66 	Ttypeset, "-x", "HOME", "PATH", "RANDOM", "SHELL", NULL,
67 	Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
68 	Talias,
69 	"integer=typeset -i",
70 	Tlocal_typeset,
71 	/* not "alias -t --": hash -r needs to work */
72 	"hash=alias -t",
73 	"type=whence -v",
74 #if !defined(ANDROID) && !defined(MKSH_UNEMPLOYED)
75 	/* not in Android for political reasons */
76 	/* not in ARGE mksh due to no job control */
77 	"stop=kill -STOP",
78 #endif
79 	"autoload=typeset -fu",
80 	"functions=typeset -f",
81 	"history=fc -l",
82 	"nameref=typeset -n",
83 	"nohup=nohup ",
84 	Tr_fc_e_dash,
85 	"source=PATH=$PATH:. command .",
86 	"login=exec login",
87 	NULL,
88 	 /* this is what AT&T ksh seems to track, with the addition of emacs */
89 	Talias, "-tU",
90 	"cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
91 	"make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
92 	NULL
93 };
94 
95 static const char *restr_com[] = {
96 	Ttypeset, "-r", "PATH", "ENV", "SHELL", NULL
97 };
98 
99 static bool initio_done;
100 
101 /* top-level parsing and execution environment */
102 static struct env env;
103 struct env *e = &env;
104 
105 static mksh_uari_t
rndsetup(void)106 rndsetup(void)
107 {
108 	register uint32_t h;
109 	struct {
110 		ALLOC_ITEM alloc_INT;
111 		void *dataptr, *stkptr, *mallocptr;
112 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
113 		sigjmp_buf jbuf;
114 #endif
115 		struct timeval tv;
116 	} *bufptr;
117 	char *cp;
118 
119 	cp = alloc(sizeof(*bufptr) - ALLOC_SIZE, APERM);
120 #ifdef DEBUG
121 	/* clear the allocated space, for valgrind */
122 	memset(cp, 0, sizeof(*bufptr) - ALLOC_SIZE);
123 #endif
124 	/* undo what alloc() did to the malloc result address */
125 	bufptr = (void *)(cp - ALLOC_SIZE);
126 	/* PIE or something similar provides us with deltas here */
127 	bufptr->dataptr = &rndsetupstate;
128 	/* ASLR in at least Windows, Linux, some BSDs */
129 	bufptr->stkptr = &bufptr;
130 	/* randomised malloc in BSD (and possibly others) */
131 	bufptr->mallocptr = bufptr;
132 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
133 	/* glibc pointer guard */
134 	sigsetjmp(bufptr->jbuf, 1);
135 #endif
136 	/* introduce variation (and yes, second arg MBZ for portability) */
137 	mksh_TIME(bufptr->tv);
138 
139 	h = chvt_rndsetup(bufptr, sizeof(*bufptr));
140 
141 	afree(cp, APERM);
142 	return ((mksh_uari_t)h);
143 }
144 
145 void
chvt_reinit(void)146 chvt_reinit(void)
147 {
148 	kshpid = procpid = getpid();
149 	ksheuid = geteuid();
150 	kshpgrp = getpgrp();
151 	kshppid = getppid();
152 }
153 
154 static const char *empty_argv[] = {
155 	"mksh", NULL
156 };
157 
158 static uint8_t
isuc(const char * cx)159 isuc(const char *cx) {
160 	char *cp, *x;
161 	uint8_t rv = 0;
162 
163 	if (!cx || !*cx)
164 		return (0);
165 
166 	/* uppercase a string duplicate */
167 	strdupx(x, cx, ATEMP);
168 	cp = x;
169 	while ((*cp = ksh_toupper(*cp)))
170 		++cp;
171 
172 	/* check for UTF-8 */
173 	if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
174 		rv = 1;
175 
176 	/* free copy and out */
177 	afree(x, ATEMP);
178 	return (rv);
179 }
180 
181 static int
main_init(int argc,const char * argv[],Source ** sp,struct block ** lp)182 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
183 {
184 	int argi, i;
185 	Source *s = NULL;
186 	struct block *l;
187 	unsigned char restricted, errexit, utf_flag;
188 	char *cp;
189 	const char *ccp, **wp;
190 	struct tbl *vp;
191 	struct stat s_stdin;
192 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
193 	ssize_t k;
194 #endif
195 
196 	/* do things like getpgrp() et al. */
197 	chvt_reinit();
198 
199 	/* make sure argv[] is sane */
200 	if (!*argv) {
201 		argv = empty_argv;
202 		argc = 1;
203 	}
204 	kshname = argv[0];
205 
206 	/* initialise permanent Area */
207 	ainit(&aperm);
208 
209 	/* set up base environment */
210 	env.type = E_NONE;
211 	ainit(&env.area);
212 	/* set up global l->vars and l->funs */
213 	newblock();
214 
215 	/* Do this first so output routines (eg, errorf, shellf) can work */
216 	initio();
217 
218 	/* determine the basename (without '-' or path) of the executable */
219 	ccp = kshname;
220 	goto begin_parse_kshname;
221 	while ((i = ccp[argi++])) {
222 		if (i == '/') {
223 			ccp += argi;
224  begin_parse_kshname:
225 			argi = 0;
226 			if (*ccp == '-')
227 				++ccp;
228 		}
229 	}
230 	if (!*ccp)
231 		ccp = empty_argv[0];
232 
233 	/*
234 	 * Turn on nohup by default. (AT&T ksh does not have a nohup
235 	 * option - it always sends the hup).
236 	 */
237 	Flag(FNOHUP) = 1;
238 
239 	/*
240 	 * Turn on brace expansion by default. AT&T kshs that have
241 	 * alternation always have it on.
242 	 */
243 	Flag(FBRACEEXPAND) = 1;
244 
245 	/*
246 	 * Turn on "set -x" inheritance by default.
247 	 */
248 	Flag(FXTRACEREC) = 1;
249 
250 	/* define built-in commands and see if we were called as one */
251 	ktinit(APERM, &builtins,
252 	    /* currently up to 51 builtins: 75% of 128 = 2^7 */
253 	    7);
254 	for (i = 0; mkshbuiltins[i].name != NULL; i++)
255 		if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
256 		    mkshbuiltins[i].func)))
257 			Flag(FAS_BUILTIN) = 1;
258 
259 	if (!Flag(FAS_BUILTIN)) {
260 		/* check for -T option early */
261 		argi = parse_args(argv, OF_FIRSTTIME, NULL);
262 		if (argi < 0)
263 			return (1);
264 
265 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
266 		/* are we called as -sh or /bin/sh or so? */
267 		if (!strcmp(ccp, "sh")) {
268 			/* either also turns off braceexpand */
269 #ifdef MKSH_BINSHPOSIX
270 			/* enable better POSIX conformance */
271 			change_flag(FPOSIX, OF_FIRSTTIME, true);
272 #endif
273 #ifdef MKSH_BINSHREDUCED
274 			/* enable kludge/compat mode */
275 			change_flag(FSH, OF_FIRSTTIME, true);
276 #endif
277 		}
278 #endif
279 	}
280 
281 	initvar();
282 
283 	initctypes();
284 
285 	inittraps();
286 
287 	coproc_init();
288 
289 	/* set up variable and command dictionaries */
290 	ktinit(APERM, &taliases, 0);
291 	ktinit(APERM, &aliases, 0);
292 #ifndef MKSH_NOPWNAM
293 	ktinit(APERM, &homedirs, 0);
294 #endif
295 
296 	/* define shell keywords */
297 	initkeywords();
298 
299 	init_histvec();
300 
301 	/* initialise tty size before importing environment */
302 	change_winsz();
303 
304 #ifdef _PATH_DEFPATH
305 	def_path = _PATH_DEFPATH;
306 #else
307 #ifdef _CS_PATH
308 	if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
309 	    confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
310 		def_path = cp;
311 	else
312 #endif
313 		/*
314 		 * this is uniform across all OSes unless it
315 		 * breaks somewhere; don't try to optimise,
316 		 * e.g. add stuff for Interix or remove /usr
317 		 * for HURD, because e.g. Debian GNU/HURD is
318 		 * "keeping a regular /usr"; this is supposed
319 		 * to be a sane 'basic' default PATH
320 		 */
321 		def_path = "/bin:/usr/bin:/sbin:/usr/sbin";
322 #endif
323 
324 	/*
325 	 * Set PATH to def_path (will set the path global variable).
326 	 * (import of environment below will probably change this setting).
327 	 */
328 	vp = global("PATH");
329 	/* setstr can't fail here */
330 	setstr(vp, def_path, KSH_RETURN_ERROR);
331 
332 #ifndef MKSH_NO_CMDLINE_EDITING
333 	/*
334 	 * Set edit mode to emacs by default, may be overridden
335 	 * by the environment or the user. Also, we want tab completion
336 	 * on in vi by default.
337 	 */
338 	change_flag(FEMACS, OF_SPECIAL, true);
339 #if !MKSH_S_NOVI
340 	Flag(FVITABCOMPLETE) = 1;
341 #endif
342 #endif
343 
344 	/* import environment */
345 	if (environ != NULL) {
346 		wp = (const char **)environ;
347 		while (*wp != NULL) {
348 			rndpush(*wp);
349 			typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
350 			++wp;
351 		}
352 	}
353 
354 	/* for security */
355 	typeset(initifs, 0, 0, 0, 0);
356 
357 	/* assign default shell variable values */
358 	substitute(initsubs, 0);
359 
360 	/* Figure out the current working directory and set $PWD */
361 	vp = global("PWD");
362 	cp = str_val(vp);
363 	/* Try to use existing $PWD if it is valid */
364 	set_current_wd((cp[0] == '/' && test_eval(NULL, TO_FILEQ, cp, ".",
365 	    true)) ? cp : NULL);
366 	if (current_wd[0])
367 		simplify_path(current_wd);
368 	/* Only set pwd if we know where we are or if it had a bogus value */
369 	if (current_wd[0] || *cp)
370 		/* setstr can't fail here */
371 		setstr(vp, current_wd, KSH_RETURN_ERROR);
372 
373 	for (wp = initcoms; *wp != NULL; wp++) {
374 		shcomexec(wp);
375 		while (*wp != NULL)
376 			wp++;
377 	}
378 	setint_n(global("OPTIND"), 1, 10);
379 
380 	kshuid = getuid();
381 	kshgid = getgid();
382 	kshegid = getegid();
383 
384 	safe_prompt = ksheuid ? "$ " : "# ";
385 	vp = global("PS1");
386 	/* Set PS1 if unset or we are root and prompt doesn't contain a # */
387 	if (!(vp->flag & ISSET) ||
388 	    (!ksheuid && !strchr(str_val(vp), '#')))
389 		/* setstr can't fail here */
390 		setstr(vp, safe_prompt, KSH_RETURN_ERROR);
391 	setint_n((vp = global("BASHPID")), 0, 10);
392 	vp->flag |= INT_U;
393 	setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
394 	vp->flag |= INT_U;
395 	setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
396 	vp->flag |= INT_U;
397 	setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
398 	vp->flag |= INT_U;
399 	setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
400 	vp->flag |= INT_U;
401 	setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
402 	vp->flag |= INT_U;
403 	setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
404 	vp->flag |= INT_U;
405 	setint_n((vp = global("RANDOM")), rndsetup(), 10);
406 	vp->flag |= INT_U;
407 	setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
408 
409 	/* Set this before parsing arguments */
410 	Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
411 
412 	/* this to note if monitor is set on command line (see below) */
413 #ifndef MKSH_UNEMPLOYED
414 	Flag(FMONITOR) = 127;
415 #endif
416 	/* this to note if utf-8 mode is set on command line (see below) */
417 	UTFMODE = 2;
418 
419 	if (!Flag(FAS_BUILTIN)) {
420 		argi = parse_args(argv, OF_CMDLINE, NULL);
421 		if (argi < 0)
422 			return (1);
423 	}
424 
425 	/* process this later only, default to off (hysterical raisins) */
426 	utf_flag = UTFMODE;
427 	UTFMODE = 0;
428 
429 	if (Flag(FAS_BUILTIN)) {
430 		/* auto-detect from environment variables, always */
431 		utf_flag = 3;
432 	} else if (Flag(FCOMMAND)) {
433 		s = pushs(SSTRINGCMDLINE, ATEMP);
434 		if (!(s->start = s->str = argv[argi++]))
435 			errorf("%s %s", "-c", "requires an argument");
436 		while (*s->str) {
437 			if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
438 				break;
439 			s->str++;
440 		}
441 		if (!*s->str)
442 			s->flags |= SF_MAYEXEC;
443 		s->str = s->start;
444 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
445 		/* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
446 		if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
447 			++argi;
448 #endif
449 		if (argv[argi])
450 			kshname = argv[argi++];
451 	} else if (argi < argc && !Flag(FSTDIN)) {
452 		s = pushs(SFILE, ATEMP);
453 		s->file = argv[argi++];
454 		s->u.shf = shf_open(s->file, O_RDONLY, 0,
455 		    SHF_MAPHI | SHF_CLEXEC);
456 		if (s->u.shf == NULL) {
457 			shl_stdout_ok = false;
458 			warningf(true, "%s: %s", s->file, cstrerror(errno));
459 			/* mandated by SUSv4 */
460 			exstat = 127;
461 			unwind(LERROR);
462 		}
463 		kshname = s->file;
464 	} else {
465 		Flag(FSTDIN) = 1;
466 		s = pushs(SSTDIN, ATEMP);
467 		s->file = "<stdin>";
468 		s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
469 		    NULL);
470 		if (isatty(0) && isatty(2)) {
471 			Flag(FTALKING) = Flag(FTALKING_I) = 1;
472 			/* The following only if isatty(0) */
473 			s->flags |= SF_TTY;
474 			s->u.shf->flags |= SHF_INTERRUPT;
475 			s->file = NULL;
476 		}
477 	}
478 
479 	/* this bizarreness is mandated by POSIX */
480 	if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
481 	    Flag(FTALKING))
482 		reset_nonblock(0);
483 
484 	/* initialise job control */
485 	j_init();
486 	/* do this after j_init() which calls tty_init_state() */
487 	if (Flag(FTALKING)) {
488 		if (utf_flag == 2) {
489 #ifndef MKSH_ASSUME_UTF8
490 			/* auto-detect from locale or environment */
491 			utf_flag = 4;
492 #else /* this may not be an #elif */
493 #if MKSH_ASSUME_UTF8
494 			utf_flag = 1;
495 #else
496 			/* always disable UTF-8 (for interactive) */
497 			utf_flag = 0;
498 #endif
499 #endif
500 		}
501 #ifndef MKSH_NO_CMDLINE_EDITING
502 		x_init();
503 #endif
504 	}
505 
506 #ifdef SIGWINCH
507 	sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
508 	setsig(&sigtraps[SIGWINCH], x_sigwinch,
509 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
510 #endif
511 
512 	l = e->loc;
513 	if (Flag(FAS_BUILTIN)) {
514 		l->argc = argc;
515 		l->argv = argv;
516 		l->argv[0] = ccp;
517 	} else {
518 		l->argc = argc - argi;
519 		/*
520 		 * allocate a new array because otherwise, when we modify
521 		 * it in-place, ps(1) output changes; the meaning of argc
522 		 * here is slightly different as it excludes kshname, and
523 		 * we add a trailing NULL sentinel as well
524 		 */
525 		l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
526 		l->argv[0] = kshname;
527 		memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
528 		l->argv[l->argc + 1] = NULL;
529 		getopts_reset(1);
530 	}
531 
532 	/* divine the initial state of the utf8-mode Flag */
533 	ccp = null;
534 	switch (utf_flag) {
535 
536 	/* auto-detect from locale or environment */
537 	case 4:
538 #if HAVE_SETLOCALE_CTYPE
539 		ccp = setlocale(LC_CTYPE, "");
540 #if HAVE_LANGINFO_CODESET
541 		if (!isuc(ccp))
542 			ccp = nl_langinfo(CODESET);
543 #endif
544 		if (!isuc(ccp))
545 			ccp = null;
546 		/* FALLTHROUGH */
547 #endif
548 
549 	/* auto-detect from environment */
550 	case 3:
551 		/* these were imported from environ earlier */
552 		if (ccp == null)
553 			ccp = str_val(global("LC_ALL"));
554 		if (ccp == null)
555 			ccp = str_val(global("LC_CTYPE"));
556 		if (ccp == null)
557 			ccp = str_val(global("LANG"));
558 		UTFMODE = isuc(ccp);
559 		break;
560 
561 	/* not set on command line, not FTALKING */
562 	case 2:
563 	/* unknown values */
564 	default:
565 		utf_flag = 0;
566 		/* FALLTHROUGH */
567 
568 	/* known values */
569 	case 1:
570 	case 0:
571 		UTFMODE = utf_flag;
572 		break;
573 	}
574 
575 	/* Disable during .profile/ENV reading */
576 	restricted = Flag(FRESTRICTED);
577 	Flag(FRESTRICTED) = 0;
578 	errexit = Flag(FERREXIT);
579 	Flag(FERREXIT) = 0;
580 
581 	/*
582 	 * Do this before profile/$ENV so that if it causes problems in them,
583 	 * user will know why things broke.
584 	 */
585 	if (!current_wd[0] && Flag(FTALKING))
586 		warningf(false, "can't determine current directory");
587 
588 	if (Flag(FLOGIN))
589 		include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
590 	if (!Flag(FPRIVILEGED)) {
591 		if (Flag(FLOGIN))
592 			include(substitute("$HOME/.profile", 0), 0, NULL, true);
593 		if (Flag(FTALKING)) {
594 			cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
595 			    0), DOTILDE);
596 			if (cp[0] != '\0')
597 				include(cp, 0, NULL, true);
598 		}
599 	} else {
600 		include(MKSH_SUID_PROFILE, 0, NULL, true);
601 		/* turn off -p if not set explicitly */
602 		if (Flag(FPRIVILEGED) != 1)
603 			change_flag(FPRIVILEGED, OF_INTERNAL, false);
604 	}
605 
606 	if (restricted) {
607 		shcomexec(restr_com);
608 		/* After typeset command... */
609 		Flag(FRESTRICTED) = 1;
610 	}
611 	Flag(FERREXIT) = errexit;
612 
613 	if (Flag(FTALKING) && s)
614 		hist_init(s);
615 	else
616 		/* set after ENV */
617 		Flag(FTRACKALL) = 1;
618 
619 	alarm_init();
620 
621 	*sp = s;
622 	*lp = l;
623 	return (0);
624 }
625 
626 /* this indirection barrier reduces stack usage during normal operation */
627 
628 int
main(int argc,const char * argv[])629 main(int argc, const char *argv[])
630 {
631 	int rv;
632 	Source *s;
633 	struct block *l;
634 
635 	if ((rv = main_init(argc, argv, &s, &l)) == 0) {
636 		if (Flag(FAS_BUILTIN)) {
637 			rv = shcomexec(l->argv);
638 		} else {
639 			shell(s, true);
640 			/* NOTREACHED */
641 		}
642 	}
643 	return (rv);
644 }
645 
646 int
include(const char * name,int argc,const char ** argv,bool intr_ok)647 include(const char *name, int argc, const char **argv, bool intr_ok)
648 {
649 	Source *volatile s = NULL;
650 	struct shf *shf;
651 	const char **volatile old_argv;
652 	volatile int old_argc;
653 	int i;
654 
655 	shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
656 	if (shf == NULL)
657 		return (-1);
658 
659 	if (argv) {
660 		old_argv = e->loc->argv;
661 		old_argc = e->loc->argc;
662 	} else {
663 		old_argv = NULL;
664 		old_argc = 0;
665 	}
666 	newenv(E_INCL);
667 	if ((i = kshsetjmp(e->jbuf))) {
668 		quitenv(s ? s->u.shf : NULL);
669 		if (old_argv) {
670 			e->loc->argv = old_argv;
671 			e->loc->argc = old_argc;
672 		}
673 		switch (i) {
674 		case LRETURN:
675 		case LERROR:
676 			/* see below */
677 			return (exstat & 0xFF);
678 		case LINTR:
679 			/*
680 			 * intr_ok is set if we are including .profile or $ENV.
681 			 * If user ^Cs out, we don't want to kill the shell...
682 			 */
683 			if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
684 				return (1);
685 			/* FALLTHROUGH */
686 		case LEXIT:
687 		case LLEAVE:
688 		case LSHELL:
689 			unwind(i);
690 			/* NOTREACHED */
691 		default:
692 			internal_errorf("%s %d", "include", i);
693 			/* NOTREACHED */
694 		}
695 	}
696 	if (argv) {
697 		e->loc->argv = argv;
698 		e->loc->argc = argc;
699 	}
700 	s = pushs(SFILE, ATEMP);
701 	s->u.shf = shf;
702 	strdupx(s->file, name, ATEMP);
703 	i = shell(s, false);
704 	quitenv(s->u.shf);
705 	if (old_argv) {
706 		e->loc->argv = old_argv;
707 		e->loc->argc = old_argc;
708 	}
709 	/* & 0xff to ensure value not -1 */
710 	return (i & 0xFF);
711 }
712 
713 /* spawn a command into a shell optionally keeping track of the line number */
714 int
command(const char * comm,int line)715 command(const char *comm, int line)
716 {
717 	Source *s;
718 
719 	s = pushs(SSTRING, ATEMP);
720 	s->start = s->str = comm;
721 	s->line = line;
722 	return (shell(s, false));
723 }
724 
725 /*
726  * run the commands from the input source, returning status.
727  */
728 int
shell(Source * volatile s,volatile bool toplevel)729 shell(Source * volatile s, volatile bool toplevel)
730 {
731 	struct op *t;
732 	volatile bool wastty = tobool(s->flags & SF_TTY);
733 	volatile uint8_t attempts = 13;
734 	volatile bool interactive = Flag(FTALKING) && toplevel;
735 	volatile bool sfirst = true;
736 	Source *volatile old_source = source;
737 	int i;
738 
739 	newenv(E_PARSE);
740 	if (interactive)
741 		really_exit = false;
742 	switch ((i = kshsetjmp(e->jbuf))) {
743 	case 0:
744 		break;
745 	case LINTR:
746 		/* we get here if SIGINT not caught or ignored */
747 	case LERROR:
748 	case LSHELL:
749 		if (interactive) {
750 			if (i == LINTR)
751 				shellf("\n");
752 			/*
753 			 * Reset any eof that was read as part of a
754 			 * multiline command.
755 			 */
756 			if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
757 				s->type = SSTDIN;
758 			/*
759 			 * Used by exit command to get back to
760 			 * top level shell. Kind of strange since
761 			 * interactive is set if we are reading from
762 			 * a tty, but to have stopped jobs, one only
763 			 * needs FMONITOR set (not FTALKING/SF_TTY)...
764 			 */
765 			/* toss any input we have so far */
766 			yyrecursive_pop(true);
767 			s->start = s->str = null;
768 			retrace_info = NULL;
769 			herep = heres;
770 			break;
771 		}
772 		/* FALLTHROUGH */
773 	case LEXIT:
774 	case LLEAVE:
775 	case LRETURN:
776 		source = old_source;
777 		quitenv(NULL);
778 		/* keep on going */
779 		unwind(i);
780 		/* NOTREACHED */
781 	default:
782 		source = old_source;
783 		quitenv(NULL);
784 		internal_errorf("%s %d", "shell", i);
785 		/* NOTREACHED */
786 	}
787 	while (/* CONSTCOND */ 1) {
788 		if (trap)
789 			runtraps(0);
790 
791 		if (s->next == NULL) {
792 			if (Flag(FVERBOSE))
793 				s->flags |= SF_ECHO;
794 			else
795 				s->flags &= ~SF_ECHO;
796 		}
797 		if (interactive) {
798 			j_notify();
799 			set_prompt(PS1, s);
800 		}
801 		t = compile(s, sfirst);
802 		sfirst = false;
803 		if (!t)
804 			goto source_no_tree;
805 		if (t->type == TEOF) {
806 			if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
807 				shellf("Use 'exit' to leave mksh\n");
808 				s->type = SSTDIN;
809 			} else if (wastty && !really_exit &&
810 			    j_stopped_running()) {
811 				really_exit = true;
812 				s->type = SSTDIN;
813 			} else {
814 				/*
815 				 * this for POSIX which says EXIT traps
816 				 * shall be taken in the environment
817 				 * immediately after the last command
818 				 * executed.
819 				 */
820 				if (toplevel)
821 					unwind(LEXIT);
822 				break;
823 			}
824 		} else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
825 			t->u.evalflags |= DOTCOMEXEC;
826 		if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
827 			exstat = execute(t, 0, NULL) & 0xFF;
828 
829 		if (t->type != TEOF && interactive && really_exit)
830 			really_exit = false;
831 
832  source_no_tree:
833 		reclaim();
834 	}
835 	quitenv(NULL);
836 	source = old_source;
837 	return (exstat & 0xFF);
838 }
839 
840 /* return to closest error handler or shell(), exit if none found */
841 /* note: i MUST NOT be 0 */
842 void
unwind(int i)843 unwind(int i)
844 {
845 	/*
846 	 * This is a kludge. We need to restore everything that was
847 	 * changed in the new environment, see cid 1005090337C7A669439
848 	 * and 10050903386452ACBF1, but fail to even save things most of
849 	 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
850 	 * which needs to be restored thus (related to Debian #696823).
851 	 * We did not save the shell flags, so we use a special or'd
852 	 * value here... this is mostly to clean up behind *other*
853 	 * callers of unwind(LERROR) here; exec.c has the regular case.
854 	 */
855 	if (Flag(FERREXIT) & 0x80) {
856 		/* GNU bash does not run this trapsig */
857 		trapsig(ksh_SIGERR);
858 		Flag(FERREXIT) &= ~0x80;
859 	}
860 
861 	/* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
862 	if (i == LEXIT || ((i == LERROR || i == LINTR) &&
863 	    sigtraps[ksh_SIGEXIT].trap &&
864 	    (!Flag(FTALKING) || Flag(FERREXIT)))) {
865 		++trap_nested;
866 		runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
867 		--trap_nested;
868 		i = LLEAVE;
869 	} else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
870 		++trap_nested;
871 		runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
872 		--trap_nested;
873 		i = LLEAVE;
874 	}
875 
876 	while (/* CONSTCOND */ 1) {
877 		switch (e->type) {
878 		case E_PARSE:
879 		case E_FUNC:
880 		case E_INCL:
881 		case E_LOOP:
882 		case E_ERRH:
883 			kshlongjmp(e->jbuf, i);
884 			/* NOTREACHED */
885 		case E_NONE:
886 			if (i == LINTR)
887 				e->flags |= EF_FAKE_SIGDIE;
888 			/* FALLTHROUGH */
889 		default:
890 			quitenv(NULL);
891 		}
892 	}
893 }
894 
895 void
newenv(int type)896 newenv(int type)
897 {
898 	struct env *ep;
899 	char *cp;
900 
901 	/*
902 	 * struct env includes ALLOC_ITEM for alignment constraints
903 	 * so first get the actually used memory, then assign it
904 	 */
905 	cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
906 	/* undo what alloc() did to the malloc result address */
907 	ep = (void *)(cp - ALLOC_SIZE);
908 	/* initialise public members of struct env (not the ALLOC_ITEM) */
909 	ainit(&ep->area);
910 	ep->oenv = e;
911 	ep->loc = e->loc;
912 	ep->savefd = NULL;
913 	ep->temps = NULL;
914 	ep->yyrecursive_statep = NULL;
915 	ep->type = type;
916 	ep->flags = 0;
917 	/* jump buffer is invalid because flags == 0 */
918 	e = ep;
919 }
920 
921 void
quitenv(struct shf * shf)922 quitenv(struct shf *shf)
923 {
924 	struct env *ep = e;
925 	char *cp;
926 	int fd;
927 
928 	yyrecursive_pop(true);
929 	while (ep->oenv && ep->oenv->loc != ep->loc)
930 		popblock();
931 	if (ep->savefd != NULL) {
932 		for (fd = 0; fd < NUFILE; fd++)
933 			/* if ep->savefd[fd] < 0, means fd was closed */
934 			if (ep->savefd[fd])
935 				restfd(fd, ep->savefd[fd]);
936 		if (ep->savefd[2])
937 			/* Clear any write errors */
938 			shf_reopen(2, SHF_WR, shl_out);
939 	}
940 	/*
941 	 * Bottom of the stack.
942 	 * Either main shell is exiting or cleanup_parents_env() was called.
943 	 */
944 	if (ep->oenv == NULL) {
945 #ifdef DEBUG_LEAKS
946 		int i;
947 #endif
948 
949 		if (ep->type == E_NONE) {
950 			/* Main shell exiting? */
951 #if HAVE_PERSISTENT_HISTORY
952 			if (Flag(FTALKING))
953 				hist_finish();
954 #endif
955 			j_exit();
956 			if (ep->flags & EF_FAKE_SIGDIE) {
957 				int sig = (exstat & 0xFF) - 128;
958 
959 				/*
960 				 * ham up our death a bit (AT&T ksh
961 				 * only seems to do this for SIGTERM)
962 				 * Don't do it for SIGQUIT, since we'd
963 				 * dump a core..
964 				 */
965 				if ((sig == SIGINT || sig == SIGTERM) &&
966 				    (kshpgrp == kshpid)) {
967 					setsig(&sigtraps[sig], SIG_DFL,
968 					    SS_RESTORE_CURR | SS_FORCE);
969 					kill(0, sig);
970 				}
971 			}
972 		}
973 		if (shf)
974 			shf_close(shf);
975 		reclaim();
976 #ifdef DEBUG_LEAKS
977 #ifndef MKSH_NO_CMDLINE_EDITING
978 		x_done();
979 #endif
980 #ifndef MKSH_NOPROSPECTOFWORK
981 		/* block at least SIGCHLD during/after afreeall */
982 		sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
983 #endif
984 		afreeall(APERM);
985 		for (fd = 3; fd < NUFILE; fd++)
986 			if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
987 			    (i & FD_CLOEXEC))
988 				close(fd);
989 		close(2);
990 		close(1);
991 		close(0);
992 #endif
993 		exit(exstat & 0xFF);
994 	}
995 	if (shf)
996 		shf_close(shf);
997 	reclaim();
998 
999 	e = e->oenv;
1000 
1001 	/* free the struct env - tricky due to the ALLOC_ITEM inside */
1002 	cp = (void *)ep;
1003 	afree(cp + ALLOC_SIZE, ATEMP);
1004 }
1005 
1006 /* Called after a fork to cleanup stuff left over from parents environment */
1007 void
cleanup_parents_env(void)1008 cleanup_parents_env(void)
1009 {
1010 	struct env *ep;
1011 	int fd;
1012 
1013 	mkssert(e != NULL);
1014 
1015 	/*
1016 	 * Don't clean up temporary files - parent will probably need them.
1017 	 * Also, can't easily reclaim memory since variables, etc. could be
1018 	 * anywhere.
1019 	 */
1020 
1021 	/* close all file descriptors hiding in savefd */
1022 	for (ep = e; ep; ep = ep->oenv) {
1023 		if (ep->savefd) {
1024 			for (fd = 0; fd < NUFILE; fd++)
1025 				if (ep->savefd[fd] > 0)
1026 					close(ep->savefd[fd]);
1027 			afree(ep->savefd, &ep->area);
1028 			ep->savefd = NULL;
1029 		}
1030 #ifdef DEBUG_LEAKS
1031 		if (ep->type != E_NONE)
1032 			ep->type = E_GONE;
1033 #endif
1034 	}
1035 #ifndef DEBUG_LEAKS
1036 	e->oenv = NULL;
1037 #endif
1038 }
1039 
1040 /* Called just before an execve cleanup stuff temporary files */
1041 void
cleanup_proc_env(void)1042 cleanup_proc_env(void)
1043 {
1044 	struct env *ep;
1045 
1046 	for (ep = e; ep; ep = ep->oenv)
1047 		remove_temps(ep->temps);
1048 }
1049 
1050 /* remove temp files and free ATEMP Area */
1051 static void
reclaim(void)1052 reclaim(void)
1053 {
1054 	struct block *l;
1055 
1056 	while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1057 		e->loc = l->next;
1058 		afreeall(&l->area);
1059 	}
1060 
1061 	remove_temps(e->temps);
1062 	e->temps = NULL;
1063 	afreeall(&e->area);
1064 }
1065 
1066 static void
remove_temps(struct temp * tp)1067 remove_temps(struct temp *tp)
1068 {
1069 	for (; tp != NULL; tp = tp->next)
1070 		if (tp->pid == procpid)
1071 			unlink(tp->tffn);
1072 }
1073 
1074 /*
1075  * Initialise tty_fd. Used for tracking the size of the terminal,
1076  * saving/resetting tty modes upon forground job completion, and
1077  * for setting up the tty process group. Return values:
1078  *	0 = got controlling tty
1079  *	1 = got terminal but no controlling tty
1080  *	2 = cannot find a terminal
1081  *	3 = cannot dup fd
1082  *	4 = cannot make fd close-on-exec
1083  * An existing tty_fd is cached if no "better" one could be found,
1084  * i.e. if tty_devtty was already set or the new would not set it.
1085  */
1086 int
tty_init_fd(void)1087 tty_init_fd(void)
1088 {
1089 	int fd, rv, eno = 0;
1090 	bool do_close = false, is_devtty = true;
1091 
1092 	if (tty_devtty) {
1093 		/* already got a tty which is /dev/tty */
1094 		return (0);
1095 	}
1096 
1097 #ifdef _UWIN
1098 	/*XXX imake style */
1099 	if (isatty(3)) {
1100 		/* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1101 		fd = 3;
1102 		goto got_fd;
1103 	}
1104 #endif
1105 	if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
1106 		do_close = true;
1107 		goto got_fd;
1108 	}
1109 	eno = errno;
1110 
1111 	if (tty_fd >= 0) {
1112 		/* already got a non-devtty one */
1113 		rv = 1;
1114 		goto out;
1115 	}
1116 	is_devtty = false;
1117 
1118 	if (isatty((fd = 0)) || isatty((fd = 2)))
1119 		goto got_fd;
1120 	/* cannot find one */
1121 	rv = 2;
1122 	/* assert: do_close == false */
1123 	goto out;
1124 
1125  got_fd:
1126 	if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1127 		eno = errno;
1128 		rv = 3;
1129 		goto out;
1130 	}
1131 	if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1132 		eno = errno;
1133 		close(rv);
1134 		rv = 4;
1135 		goto out;
1136 	}
1137 	tty_fd = rv;
1138 	tty_devtty = is_devtty;
1139 	rv = eno = 0;
1140  out:
1141 	if (do_close)
1142 		close(fd);
1143 	errno = eno;
1144 	return (rv);
1145 }
1146 
1147 /* A shell error occurred (eg, syntax error, etc.) */
1148 
1149 #define VWARNINGF_ERRORPREFIX	1
1150 #define VWARNINGF_FILELINE	2
1151 #define VWARNINGF_BUILTIN	4
1152 #define VWARNINGF_INTERNAL	8
1153 
1154 static void vwarningf(unsigned int, const char *, va_list)
1155     MKSH_A_FORMAT(__printf__, 2, 0);
1156 
1157 static void
vwarningf(unsigned int flags,const char * fmt,va_list ap)1158 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1159 {
1160 	if (fmt) {
1161 		if (flags & VWARNINGF_INTERNAL)
1162 			shf_fprintf(shl_out, "internal error: ");
1163 		if (flags & VWARNINGF_ERRORPREFIX)
1164 			error_prefix(tobool(flags & VWARNINGF_FILELINE));
1165 		if ((flags & VWARNINGF_BUILTIN) &&
1166 		    /* not set when main() calls parse_args() */
1167 		    builtin_argv0 && builtin_argv0 != kshname)
1168 			shf_fprintf(shl_out, "%s: ", builtin_argv0);
1169 		shf_vfprintf(shl_out, fmt, ap);
1170 		shf_putchar('\n', shl_out);
1171 	}
1172 	shf_flush(shl_out);
1173 }
1174 
1175 void
errorfx(int rc,const char * fmt,...)1176 errorfx(int rc, const char *fmt, ...)
1177 {
1178 	va_list va;
1179 
1180 	exstat = rc;
1181 
1182 	/* debugging: note that stdout not valid */
1183 	shl_stdout_ok = false;
1184 
1185 	va_start(va, fmt);
1186 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1187 	va_end(va);
1188 	unwind(LERROR);
1189 }
1190 
1191 void
errorf(const char * fmt,...)1192 errorf(const char *fmt, ...)
1193 {
1194 	va_list va;
1195 
1196 	exstat = 1;
1197 
1198 	/* debugging: note that stdout not valid */
1199 	shl_stdout_ok = false;
1200 
1201 	va_start(va, fmt);
1202 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1203 	va_end(va);
1204 	unwind(LERROR);
1205 }
1206 
1207 /* like errorf(), but no unwind is done */
1208 void
warningf(bool fileline,const char * fmt,...)1209 warningf(bool fileline, const char *fmt, ...)
1210 {
1211 	va_list va;
1212 
1213 	va_start(va, fmt);
1214 	vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1215 	    fmt, va);
1216 	va_end(va);
1217 }
1218 
1219 /*
1220  * Used by built-in utilities to prefix shell and utility name to message
1221  * (also unwinds environments for special builtins).
1222  */
1223 void
bi_errorf(const char * fmt,...)1224 bi_errorf(const char *fmt, ...)
1225 {
1226 	va_list va;
1227 
1228 	/* debugging: note that stdout not valid */
1229 	shl_stdout_ok = false;
1230 
1231 	exstat = 1;
1232 
1233 	va_start(va, fmt);
1234 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1235 	    VWARNINGF_BUILTIN, fmt, va);
1236 	va_end(va);
1237 
1238 	/*
1239 	 * POSIX special builtins and ksh special builtins cause
1240 	 * non-interactive shells to exit.
1241 	 * XXX odd use of KEEPASN; also may not want LERROR here
1242 	 */
1243 	if (builtin_flag & SPEC_BI) {
1244 		builtin_argv0 = NULL;
1245 		unwind(LERROR);
1246 	}
1247 }
1248 
1249 /* Called when something that shouldn't happen does */
1250 void
internal_errorf(const char * fmt,...)1251 internal_errorf(const char *fmt, ...)
1252 {
1253 	va_list va;
1254 
1255 	va_start(va, fmt);
1256 	vwarningf(VWARNINGF_INTERNAL, fmt, va);
1257 	va_end(va);
1258 	unwind(LERROR);
1259 }
1260 
1261 void
internal_warningf(const char * fmt,...)1262 internal_warningf(const char *fmt, ...)
1263 {
1264 	va_list va;
1265 
1266 	va_start(va, fmt);
1267 	vwarningf(VWARNINGF_INTERNAL, fmt, va);
1268 	va_end(va);
1269 }
1270 
1271 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1272 void
error_prefix(bool fileline)1273 error_prefix(bool fileline)
1274 {
1275 	/* Avoid foo: foo[2]: ... */
1276 	if (!fileline || !source || !source->file ||
1277 	    strcmp(source->file, kshname) != 0)
1278 		shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1279 	if (fileline && source && source->file != NULL) {
1280 		shf_fprintf(shl_out, "%s[%d]: ", source->file,
1281 		    source->errline > 0 ? source->errline : source->line);
1282 		source->errline = 0;
1283 	}
1284 }
1285 
1286 /* printf to shl_out (stderr) with flush */
1287 void
shellf(const char * fmt,...)1288 shellf(const char *fmt, ...)
1289 {
1290 	va_list va;
1291 
1292 	if (!initio_done)
1293 		/* shl_out may not be set up yet... */
1294 		return;
1295 	va_start(va, fmt);
1296 	shf_vfprintf(shl_out, fmt, va);
1297 	va_end(va);
1298 	shf_flush(shl_out);
1299 }
1300 
1301 /* printf to shl_stdout (stdout) */
1302 void
shprintf(const char * fmt,...)1303 shprintf(const char *fmt, ...)
1304 {
1305 	va_list va;
1306 
1307 	if (!shl_stdout_ok)
1308 		internal_errorf("shl_stdout not valid");
1309 	va_start(va, fmt);
1310 	shf_vfprintf(shl_stdout, fmt, va);
1311 	va_end(va);
1312 }
1313 
1314 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1315 int
can_seek(int fd)1316 can_seek(int fd)
1317 {
1318 	struct stat statb;
1319 
1320 	return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1321 	    SHF_UNBUF : 0);
1322 }
1323 
1324 #ifdef DF
1325 int shl_dbg_fd;
1326 #define NSHF_IOB 4
1327 #else
1328 #define NSHF_IOB 3
1329 #endif
1330 struct shf shf_iob[NSHF_IOB];
1331 
1332 void
initio(void)1333 initio(void)
1334 {
1335 #ifdef DF
1336 	const char *lfp;
1337 #endif
1338 
1339 	/* force buffer allocation */
1340 	shf_fdopen(1, SHF_WR, shl_stdout);
1341 	shf_fdopen(2, SHF_WR, shl_out);
1342 	shf_fdopen(2, SHF_WR, shl_xtrace);
1343 #ifdef DF
1344 	if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1345 		if ((lfp = getenv("HOME")) == NULL || *lfp != '/')
1346 			errorf("cannot get home directory");
1347 		lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
1348 	}
1349 
1350 	if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1351 		errorf("cannot open debug output file %s", lfp);
1352 	if (shl_dbg_fd < FDBASE) {
1353 		int nfd;
1354 
1355 		nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1356 		close(shl_dbg_fd);
1357 		if ((shl_dbg_fd = nfd) == -1)
1358 			errorf("cannot dup debug output file");
1359 	}
1360 	fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1361 	shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1362 	DF("=== open ===");
1363 #endif
1364 	initio_done = true;
1365 }
1366 
1367 /* A dup2() with error checking */
1368 int
ksh_dup2(int ofd,int nfd,bool errok)1369 ksh_dup2(int ofd, int nfd, bool errok)
1370 {
1371 	int rv;
1372 
1373 	if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1374 		errorf("too many files open in shell");
1375 
1376 #ifdef __ultrix
1377 	/*XXX imake style */
1378 	if (rv >= 0)
1379 		fcntl(nfd, F_SETFD, 0);
1380 #endif
1381 
1382 	return (rv);
1383 }
1384 
1385 /*
1386  * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1387  * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1388  */
1389 short
savefd(int fd)1390 savefd(int fd)
1391 {
1392 	int nfd = fd;
1393 
1394 	if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1395 	    errno == EBADF)
1396 		return (-1);
1397 	if (nfd < 0 || nfd > SHRT_MAX)
1398 		errorf("too many files open in shell");
1399 	fcntl(nfd, F_SETFD, FD_CLOEXEC);
1400 	return ((short)nfd);
1401 }
1402 
1403 void
restfd(int fd,int ofd)1404 restfd(int fd, int ofd)
1405 {
1406 	if (fd == 2)
1407 		shf_flush(&shf_iob[/* fd */ 2]);
1408 	if (ofd < 0)
1409 		/* original fd closed */
1410 		close(fd);
1411 	else if (fd != ofd) {
1412 		/*XXX: what to do if this dup fails? */
1413 		ksh_dup2(ofd, fd, true);
1414 		close(ofd);
1415 	}
1416 }
1417 
1418 void
openpipe(int * pv)1419 openpipe(int *pv)
1420 {
1421 	int lpv[2];
1422 
1423 	if (pipe(lpv) < 0)
1424 		errorf("can't create pipe - try again");
1425 	pv[0] = savefd(lpv[0]);
1426 	if (pv[0] != lpv[0])
1427 		close(lpv[0]);
1428 	pv[1] = savefd(lpv[1]);
1429 	if (pv[1] != lpv[1])
1430 		close(lpv[1]);
1431 }
1432 
1433 void
closepipe(int * pv)1434 closepipe(int *pv)
1435 {
1436 	close(pv[0]);
1437 	close(pv[1]);
1438 }
1439 
1440 /*
1441  * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1442  * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1443  */
1444 int
check_fd(const char * name,int mode,const char ** emsgp)1445 check_fd(const char *name, int mode, const char **emsgp)
1446 {
1447 	int fd, fl;
1448 
1449 	if (name[0] == 'p' && !name[1])
1450 		return (coproc_getfd(mode, emsgp));
1451 	for (fd = 0; ksh_isdigit(*name); ++name)
1452 		fd = (fd * 10) + *name - '0';
1453 	if (*name || fd >= FDBASE) {
1454 		if (emsgp)
1455 			*emsgp = "illegal file descriptor name";
1456 		return (-1);
1457 	}
1458 	if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1459 		if (emsgp)
1460 			*emsgp = "bad file descriptor";
1461 		return (-1);
1462 	}
1463 	fl &= O_ACCMODE;
1464 	/*
1465 	 * X_OK is a kludge to disable this check for dups (x<&1):
1466 	 * historical shells never did this check (XXX don't know what
1467 	 * POSIX has to say).
1468 	 */
1469 	if (!(mode & X_OK) && fl != O_RDWR && (
1470 	    ((mode & R_OK) && fl != O_RDONLY) ||
1471 	    ((mode & W_OK) && fl != O_WRONLY))) {
1472 		if (emsgp)
1473 			*emsgp = (fl == O_WRONLY) ?
1474 			    "fd not open for reading" :
1475 			    "fd not open for writing";
1476 		return (-1);
1477 	}
1478 	return (fd);
1479 }
1480 
1481 /* Called once from main */
1482 void
coproc_init(void)1483 coproc_init(void)
1484 {
1485 	coproc.read = coproc.readw = coproc.write = -1;
1486 	coproc.njobs = 0;
1487 	coproc.id = 0;
1488 }
1489 
1490 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1491 void
coproc_read_close(int fd)1492 coproc_read_close(int fd)
1493 {
1494 	if (coproc.read >= 0 && fd == coproc.read) {
1495 		coproc_readw_close(fd);
1496 		close(coproc.read);
1497 		coproc.read = -1;
1498 	}
1499 }
1500 
1501 /*
1502  * Called by c_read() and by iosetup() to close the other side of the
1503  * read pipe, so reads will actually terminate.
1504  */
1505 void
coproc_readw_close(int fd)1506 coproc_readw_close(int fd)
1507 {
1508 	if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1509 		close(coproc.readw);
1510 		coproc.readw = -1;
1511 	}
1512 }
1513 
1514 /*
1515  * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1516  * when co-process input is dup'd
1517  */
1518 void
coproc_write_close(int fd)1519 coproc_write_close(int fd)
1520 {
1521 	if (coproc.write >= 0 && fd == coproc.write) {
1522 		close(coproc.write);
1523 		coproc.write = -1;
1524 	}
1525 }
1526 
1527 /*
1528  * Called to check for existence of/value of the co-process file descriptor.
1529  * (Used by check_fd() and by c_read/c_print to deal with -p option).
1530  */
1531 int
coproc_getfd(int mode,const char ** emsgp)1532 coproc_getfd(int mode, const char **emsgp)
1533 {
1534 	int fd = (mode & R_OK) ? coproc.read : coproc.write;
1535 
1536 	if (fd >= 0)
1537 		return (fd);
1538 	if (emsgp)
1539 		*emsgp = "no coprocess";
1540 	return (-1);
1541 }
1542 
1543 /*
1544  * called to close file descriptors related to the coprocess (if any)
1545  * Should be called with SIGCHLD blocked.
1546  */
1547 void
coproc_cleanup(int reuse)1548 coproc_cleanup(int reuse)
1549 {
1550 	/* This to allow co-processes to share output pipe */
1551 	if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1552 		if (coproc.read >= 0) {
1553 			close(coproc.read);
1554 			coproc.read = -1;
1555 		}
1556 		if (coproc.readw >= 0) {
1557 			close(coproc.readw);
1558 			coproc.readw = -1;
1559 		}
1560 	}
1561 	if (coproc.write >= 0) {
1562 		close(coproc.write);
1563 		coproc.write = -1;
1564 	}
1565 }
1566 
1567 struct temp *
maketemp(Area * ap,Temp_type type,struct temp ** tlist)1568 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1569 {
1570 	char *cp;
1571 	size_t len;
1572 	int i, j;
1573 	struct temp *tp;
1574 	const char *dir;
1575 	struct stat sb;
1576 
1577 	dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1578 	/* add "/shXXXXXX.tmp" plus NUL */
1579 	len = strlen(dir);
1580 	checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1581 	tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1582 
1583 	tp->shf = NULL;
1584 	tp->pid = procpid;
1585 	tp->type = type;
1586 
1587 	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1588 		tp->tffn[0] = '\0';
1589 		goto maketemp_out;
1590 	}
1591 
1592 	cp = (void *)tp;
1593 	cp += offsetof(struct temp, tffn[0]);
1594 	memcpy(cp, dir, len);
1595 	cp += len;
1596 	memcpy(cp, "/shXXXXXX.tmp", 14);
1597 	/* point to the first of six Xes */
1598 	cp += 3;
1599 	/* generate random part of filename */
1600 	len = -1;
1601 	do {
1602 		i = rndget() % 36;
1603 		cp[++len] = i < 26 ? 'a' + i : '0' + i - 26;
1604 	} while (len < 5);
1605 
1606 	/* cyclically attempt to open a temporary file */
1607 	while ((i = open(tp->tffn, O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1608 	    0600)) < 0) {
1609 		if (errno != EEXIST)
1610 			goto maketemp_out;
1611 		/* count down from z to a then from 9 to 0 */
1612 		while (cp[len] == '0')
1613 			if (!len--)
1614 				goto maketemp_out;
1615 		if (cp[len] == 'a')
1616 			cp[len] = '9';
1617 		else
1618 			--cp[len];
1619 		/* do another cycle */
1620 	}
1621 
1622 	if (type == TT_FUNSUB) {
1623 		/* map us high and mark as close-on-exec */
1624 		if ((j = savefd(i)) != i) {
1625 			close(i);
1626 			i = j;
1627 		}
1628 
1629 		/* operation mode for the shf */
1630 		j = SHF_RD;
1631 	} else
1632 		j = SHF_WR;
1633 
1634 	/* shf_fdopen cannot fail, so no fd leak */
1635 	tp->shf = shf_fdopen(i, j, NULL);
1636 
1637  maketemp_out:
1638 	tp->next = *tlist;
1639 	*tlist = tp;
1640 	return (tp);
1641 }
1642 
1643 /*
1644  * We use a similar collision resolution algorithm as Python 2.5.4
1645  * but with a slightly tweaked implementation written from scratch.
1646  */
1647 
1648 #define	INIT_TBLSHIFT	3	/* initial table shift (2^3 = 8) */
1649 #define PERTURB_SHIFT	5	/* see Python 2.5.4 Objects/dictobject.c */
1650 
1651 static void tgrow(struct table *);
1652 static int tnamecmp(const void *, const void *);
1653 
1654 static void
tgrow(struct table * tp)1655 tgrow(struct table *tp)
1656 {
1657 	size_t i, j, osize, mask, perturb;
1658 	struct tbl *tblp, **pp;
1659 	struct tbl **ntblp, **otblp = tp->tbls;
1660 
1661 	if (tp->tshift > 29)
1662 		internal_errorf("hash table size limit reached");
1663 
1664 	/* calculate old size, new shift and new size */
1665 	osize = (size_t)1 << (tp->tshift++);
1666 	i = osize << 1;
1667 
1668 	ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1669 	/* multiplication cannot overflow: alloc2 checked that */
1670 	memset(ntblp, 0, i * sizeof(struct tbl *));
1671 
1672 	/* table can get very full when reaching its size limit */
1673 	tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1674 	    /* but otherwise, only 75% */
1675 	    ((i * 3) / 4);
1676 	tp->tbls = ntblp;
1677 	if (otblp == NULL)
1678 		return;
1679 
1680 	mask = i - 1;
1681 	for (i = 0; i < osize; i++)
1682 		if ((tblp = otblp[i]) != NULL) {
1683 			if ((tblp->flag & DEFINED)) {
1684 				/* search for free hash table slot */
1685 				j = perturb = tblp->ua.hval;
1686 				goto find_first_empty_slot;
1687  find_next_empty_slot:
1688 				j = (j << 2) + j + perturb + 1;
1689 				perturb >>= PERTURB_SHIFT;
1690  find_first_empty_slot:
1691 				pp = &ntblp[j & mask];
1692 				if (*pp != NULL)
1693 					goto find_next_empty_slot;
1694 				/* found an empty hash table slot */
1695 				*pp = tblp;
1696 				tp->nfree--;
1697 			} else if (!(tblp->flag & FINUSE)) {
1698 				afree(tblp, tp->areap);
1699 			}
1700 		}
1701 	afree(otblp, tp->areap);
1702 }
1703 
1704 void
ktinit(Area * ap,struct table * tp,uint8_t initshift)1705 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1706 {
1707 	tp->areap = ap;
1708 	tp->tbls = NULL;
1709 	tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1710 	    initshift : INIT_TBLSHIFT) - 1;
1711 	tgrow(tp);
1712 }
1713 
1714 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1715 struct tbl *
ktscan(struct table * tp,const char * name,uint32_t h,struct tbl *** ppp)1716 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1717 {
1718 	size_t j, perturb, mask;
1719 	struct tbl **pp, *p;
1720 
1721 	mask = ((size_t)1 << (tp->tshift)) - 1;
1722 	/* search for hash table slot matching name */
1723 	j = perturb = h;
1724 	goto find_first_slot;
1725  find_next_slot:
1726 	j = (j << 2) + j + perturb + 1;
1727 	perturb >>= PERTURB_SHIFT;
1728  find_first_slot:
1729 	pp = &tp->tbls[j & mask];
1730 	if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1731 	    strcmp(p->name, name)))
1732 		goto find_next_slot;
1733 	/* p == NULL if not found, correct found entry otherwise */
1734 	if (ppp)
1735 		*ppp = pp;
1736 	return (p);
1737 }
1738 
1739 /* table, name (key) to enter, hash(n) */
1740 struct tbl *
ktenter(struct table * tp,const char * n,uint32_t h)1741 ktenter(struct table *tp, const char *n, uint32_t h)
1742 {
1743 	struct tbl **pp, *p;
1744 	size_t len;
1745 
1746  Search:
1747 	if ((p = ktscan(tp, n, h, &pp)))
1748 		return (p);
1749 
1750 	if (tp->nfree == 0) {
1751 		/* too full */
1752 		tgrow(tp);
1753 		goto Search;
1754 	}
1755 
1756 	/* create new tbl entry */
1757 	len = strlen(n);
1758 	checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1759 	p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1760 	p->flag = 0;
1761 	p->type = 0;
1762 	p->areap = tp->areap;
1763 	p->ua.hval = h;
1764 	p->u2.field = 0;
1765 	p->u.array = NULL;
1766 	memcpy(p->name, n, len);
1767 
1768 	/* enter in tp->tbls */
1769 	tp->nfree--;
1770 	*pp = p;
1771 	return (p);
1772 }
1773 
1774 void
ktwalk(struct tstate * ts,struct table * tp)1775 ktwalk(struct tstate *ts, struct table *tp)
1776 {
1777 	ts->left = (size_t)1 << (tp->tshift);
1778 	ts->next = tp->tbls;
1779 }
1780 
1781 struct tbl *
ktnext(struct tstate * ts)1782 ktnext(struct tstate *ts)
1783 {
1784 	while (--ts->left >= 0) {
1785 		struct tbl *p = *ts->next++;
1786 		if (p != NULL && (p->flag & DEFINED))
1787 			return (p);
1788 	}
1789 	return (NULL);
1790 }
1791 
1792 static int
tnamecmp(const void * p1,const void * p2)1793 tnamecmp(const void *p1, const void *p2)
1794 {
1795 	const struct tbl *a = *((const struct tbl * const *)p1);
1796 	const struct tbl *b = *((const struct tbl * const *)p2);
1797 
1798 	return (strcmp(a->name, b->name));
1799 }
1800 
1801 struct tbl **
ktsort(struct table * tp)1802 ktsort(struct table *tp)
1803 {
1804 	size_t i;
1805 	struct tbl **p, **sp, **dp;
1806 
1807 	/*
1808 	 * since the table is never entirely full, no need to reserve
1809 	 * additional space for the trailing NULL appended below
1810 	 */
1811 	i = (size_t)1 << (tp->tshift);
1812 	p = alloc2(i, sizeof(struct tbl *), ATEMP);
1813 	sp = tp->tbls;		/* source */
1814 	dp = p;			/* dest */
1815 	while (i--)
1816 		if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1817 		    ((*dp)->flag & ARRAY)))
1818 			dp++;
1819 	qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1820 	p[i] = NULL;
1821 	return (p);
1822 }
1823 
1824 #ifdef SIGWINCH
1825 static void
x_sigwinch(int sig MKSH_A_UNUSED)1826 x_sigwinch(int sig MKSH_A_UNUSED)
1827 {
1828 	/* this runs inside interrupt context, with errno saved */
1829 
1830 	got_winch = 1;
1831 }
1832 #endif
1833 
1834 #ifdef DF
1835 void
DF(const char * fmt,...)1836 DF(const char *fmt, ...)
1837 {
1838 	va_list args;
1839 	struct timeval tv;
1840 	mirtime_mjd mjd;
1841 
1842 	mksh_lockfd(shl_dbg_fd);
1843 	mksh_TIME(tv);
1844 	timet2mjd(&mjd, tv.tv_sec);
1845 	shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1846 	    (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1847 	    (unsigned)mjd.sec % 60, (unsigned)getpid(),
1848 	    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1849 	va_start(args, fmt);
1850 	shf_vfprintf(shl_dbg, fmt, args);
1851 	va_end(args);
1852 	shf_putc('\n', shl_dbg);
1853 	shf_flush(shl_dbg);
1854 	mksh_unlkfd(shl_dbg_fd);
1855 }
1856 #endif
1857 
1858 void
x_mkraw(int fd,mksh_ttyst * ocb,bool forread)1859 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1860 {
1861 	mksh_ttyst cb;
1862 
1863 	if (ocb)
1864 		mksh_tcget(fd, ocb);
1865 	else
1866 		ocb = &tty_state;
1867 
1868 	cb = *ocb;
1869 	if (forread) {
1870 		cb.c_iflag &= ~(ISTRIP);
1871 		cb.c_lflag &= ~(ICANON) | ECHO;
1872 	} else {
1873 		cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1874 		cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1875 	}
1876 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1877 	/* OSF/1 processes lnext when ~icanon */
1878 	cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1879 #endif
1880 	/* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1881 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1882 	cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1883 #endif
1884 	cb.c_cc[VTIME] = 0;
1885 	cb.c_cc[VMIN] = 1;
1886 
1887 	mksh_tcset(fd, &cb);
1888 }
1889