1 /*	$OpenBSD: history.c,v 1.41 2015/09/01 13:12:31 tedu Exp $	*/
2 /*	$OpenBSD: trap.c,v 1.23 2010/05/19 17:36:08 jasper Exp $	*/
3 
4 /*-
5  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
6  *		 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019
7  *	mirabilos <m@mirbsd.org>
8  *
9  * Provided that these terms and disclaimer and all copyright notices
10  * are retained or reproduced in an accompanying document, permission
11  * is granted to deal in this work without restriction, including un-
12  * limited rights to use, publicly perform, distribute, sell, modify,
13  * merge, give away, or sublicence.
14  *
15  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
16  * the utmost extent permitted by applicable law, neither express nor
17  * implied; without malicious intent or gross negligence. In no event
18  * may a licensor, author or contributor be held liable for indirect,
19  * direct, other damage, loss, or other issues arising in any way out
20  * of dealing in the work, even if advised of the possibility of such
21  * damage or existence of a defect, except proven that it results out
22  * of said person's immediate fault when using the work as intended.
23  */
24 
25 #include "sh.h"
26 #if HAVE_SYS_FILE_H
27 #include <sys/file.h>
28 #endif
29 
30 __RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.170 2020/10/01 22:53:20 tg Exp $");
31 
32 Trap sigtraps[ksh_NSIG + 1];
33 static struct sigaction Sigact_ign;
34 
35 #if HAVE_PERSISTENT_HISTORY
36 static int histload(Source *, unsigned char *, size_t);
37 static int writehistline(int, int, const char *);
38 static void writehistfile(int, const char *);
39 #endif
40 
41 static int hist_execute(char *, Area *);
42 static char **hist_get(const char *, bool, bool);
43 static char **hist_get_oldest(void);
44 
45 static bool hstarted;		/* set after hist_init() called */
46 static Source *hist_source;
47 
48 #if HAVE_PERSISTENT_HISTORY
49 /*XXX imake style */
50 #if defined(__linux)
51 #define caddr_cast(x)	((void *)(x))
52 #else
53 #define caddr_cast(x)	((caddr_t)(x))
54 #endif
55 
56 /* several OEs do not have these constants */
57 #ifndef MAP_FAILED
58 #define MAP_FAILED	caddr_cast(-1)
59 #endif
60 
61 /* some OEs need the default mapping type specified */
62 #ifndef MAP_FILE
63 #define MAP_FILE	0
64 #endif
65 
66 /* current history file: name, fd, size */
67 static char *hname;
68 static int histfd = -1;
69 static off_t histfsize;
70 #endif
71 
72 /* HISTSIZE default: size of saved history, persistent or standard */
73 #ifdef MKSH_SMALL
74 #define MKSH_DEFHISTSIZE	255
75 #else
76 #define MKSH_DEFHISTSIZE	2047
77 #endif
78 /* maximum considered size of persistent history file */
79 #define MKSH_MAXHISTFSIZE	((off_t)1048576 * 96)
80 
81 /* hidden option */
82 #define HIST_DISCARD		5
83 
84 int
c_fc(const char ** wp)85 c_fc(const char **wp)
86 {
87 	struct shf *shf;
88 	struct temp *tf;
89 	bool gflag = false, lflag = false, nflag = false, rflag = false,
90 	    sflag = false;
91 	int optc;
92 	const char *p, *first = NULL, *last = NULL;
93 	char **hfirst, **hlast, **hp, *editor = NULL;
94 
95 	if (!Flag(FTALKING_I)) {
96 		bi_errorf("history %ss not available", Tfunction);
97 		return (1);
98 	}
99 
100 	while ((optc = ksh_getopt(wp, &builtin_opt,
101 	    "e:glnrs0,1,2,3,4,5,6,7,8,9,")) != -1)
102 		switch (optc) {
103 
104 		case 'e':
105 			p = builtin_opt.optarg;
106 			if (ksh_isdash(p))
107 				sflag = true;
108 			else {
109 				size_t len = strlen(p);
110 
111 				/* almost certainly not overflowing */
112 				editor = alloc(len + 4, ATEMP);
113 				memcpy(editor, p, len);
114 				memcpy(editor + len, Tspdollaru, 4);
115 			}
116 			break;
117 
118 		/* non-AT&T ksh */
119 		case 'g':
120 			gflag = true;
121 			break;
122 
123 		case 'l':
124 			lflag = true;
125 			break;
126 
127 		case 'n':
128 			nflag = true;
129 			break;
130 
131 		case 'r':
132 			rflag = true;
133 			break;
134 
135 		/* POSIX version of -e - */
136 		case 's':
137 			sflag = true;
138 			break;
139 
140 		/* kludge city - accept -num as -- -num (kind of) */
141 		case '0': case '1': case '2': case '3': case '4':
142 		case '5': case '6': case '7': case '8': case '9':
143 			p = shf_smprintf("-%c%s",
144 					optc, builtin_opt.optarg);
145 			if (!first)
146 				first = p;
147 			else if (!last)
148 				last = p;
149 			else {
150 				bi_errorf(Ttoo_many_args);
151 				return (1);
152 			}
153 			break;
154 
155 		case '?':
156 			return (1);
157 		}
158 	wp += builtin_opt.optind;
159 
160 	/* Substitute and execute command */
161 	if (sflag) {
162 		char *pat = NULL, *rep = NULL, *line;
163 
164 		if (editor || lflag || nflag || rflag) {
165 			bi_errorf("can't use -e, -l, -n, -r with -s (-e -)");
166 			return (1);
167 		}
168 
169 		/* Check for pattern replacement argument */
170 		if (*wp && **wp && (p = cstrchr(*wp + 1, '='))) {
171 			strdupx(pat, *wp, ATEMP);
172 			rep = pat + (p - *wp);
173 			*rep++ = '\0';
174 			wp++;
175 		}
176 		/* Check for search prefix */
177 		if (!first && (first = *wp))
178 			wp++;
179 		if (last || *wp) {
180 			bi_errorf(Ttoo_many_args);
181 			return (1);
182 		}
183 
184 		hp = first ? hist_get(first, false, false) :
185 		    hist_get_newest(false);
186 		if (!hp)
187 			return (1);
188 		/* hist_replace */
189 		if (!pat)
190 			strdupx(line, *hp, ATEMP);
191 		else {
192 			char *s, *s1;
193 			size_t len, pat_len, rep_len;
194 			XString xs;
195 			char *xp;
196 			bool any_subst = false;
197 
198 			pat_len = strlen(pat);
199 			rep_len = strlen(rep);
200 			Xinit(xs, xp, 128, ATEMP);
201 			for (s = *hp; (s1 = strstr(s, pat)) &&
202 			    (!any_subst || gflag); s = s1 + pat_len) {
203 				any_subst = true;
204 				len = s1 - s;
205 				XcheckN(xs, xp, len + rep_len);
206 				/*; first part */
207 				memcpy(xp, s, len);
208 				xp += len;
209 				/* replacement */
210 				memcpy(xp, rep, rep_len);
211 				xp += rep_len;
212 			}
213 			if (!any_subst) {
214 				bi_errorf(Tbadsubst);
215 				return (1);
216 			}
217 			len = strlen(s) + 1;
218 			XcheckN(xs, xp, len);
219 			memcpy(xp, s, len);
220 			xp += len;
221 			line = Xclose(xs, xp);
222 		}
223 		return (hist_execute(line, ATEMP));
224 	}
225 
226 	if (editor && (lflag || nflag)) {
227 		bi_errorf("can't use -l, -n with -e");
228 		return (1);
229 	}
230 
231 	if (!first && (first = *wp))
232 		wp++;
233 	if (!last && (last = *wp))
234 		wp++;
235 	if (*wp) {
236 		bi_errorf(Ttoo_many_args);
237 		return (1);
238 	}
239 	if (!first) {
240 		hfirst = lflag ? hist_get("-16", true, true) :
241 		    hist_get_newest(false);
242 		if (!hfirst)
243 			return (1);
244 		/* can't fail if hfirst didn't fail */
245 		hlast = hist_get_newest(false);
246 	} else {
247 		/*
248 		 * POSIX says not an error if first/last out of bounds
249 		 * when range is specified; AT&T ksh and pdksh allow out
250 		 * of bounds for -l as well.
251 		 */
252 		hfirst = hist_get(first, tobool(lflag || last), lflag);
253 		if (!hfirst)
254 			return (1);
255 		hlast = last ? hist_get(last, true, lflag) :
256 		    (lflag ? hist_get_newest(false) : hfirst);
257 		if (!hlast)
258 			return (1);
259 	}
260 	if (hfirst > hlast) {
261 		char **temp;
262 
263 		temp = hfirst; hfirst = hlast; hlast = temp;
264 		/* POSIX */
265 		rflag = !rflag;
266 	}
267 
268 	/* List history */
269 	if (lflag) {
270 		char *s, *t;
271 
272 		for (hp = rflag ? hlast : hfirst;
273 		    hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1) {
274 			if (!nflag)
275 				shf_fprintf(shl_stdout, Tf_lu,
276 				    (unsigned long)hist_source->line -
277 				    (unsigned long)(histptr - hp));
278 			shf_putc('\t', shl_stdout);
279 			/* print multi-line commands correctly */
280 			s = *hp;
281 			while ((t = strchr(s, '\n'))) {
282 				*t = '\0';
283 				shf_fprintf(shl_stdout, "%s\n\t", s);
284 				*t++ = '\n';
285 				s = t;
286 			}
287 			shf_fprintf(shl_stdout, Tf_sN, s);
288 		}
289 		shf_flush(shl_stdout);
290 		return (0);
291 	}
292 
293 	/* Run editor on selected lines, then run resulting commands */
294 
295 	tf = maketemp(ATEMP, TT_HIST_EDIT, &e->temps);
296 	if (!(shf = tf->shf)) {
297 		bi_errorf(Tf_temp, Tcreate, tf->tffn, cstrerror(errno));
298 		return (1);
299 	}
300 	for (hp = rflag ? hlast : hfirst;
301 	    hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1)
302 		shf_fprintf(shf, Tf_sN, *hp);
303 	if (shf_close(shf) == -1) {
304 		bi_errorf(Tf_temp, Twrite, tf->tffn, cstrerror(errno));
305 		return (1);
306 	}
307 
308 	/* Ignore setstr errors here (arbitrary) */
309 	setstr(local("_", false), tf->tffn, KSH_RETURN_ERROR);
310 
311 	if ((optc = command(editor ? editor : TFCEDIT_dollaru, 0)))
312 		return (optc);
313 
314 	{
315 		struct stat statb;
316 		XString xs;
317 		char *xp;
318 		ssize_t n;
319 
320 		if (!(shf = shf_open(tf->tffn, O_RDONLY, 0, 0))) {
321 			bi_errorf(Tf_temp, Topen, tf->tffn, cstrerror(errno));
322 			return (1);
323 		}
324 
325 		if (stat(tf->tffn, &statb) < 0)
326 			n = 128;
327 		else if ((off_t)statb.st_size > MKSH_MAXHISTFSIZE) {
328 			bi_errorf(Tf_toolarge, Thistory,
329 			    Tfile, (unsigned long)statb.st_size);
330 			goto errout;
331 		} else
332 			n = (size_t)statb.st_size + 1;
333 		Xinit(xs, xp, n, hist_source->areap);
334 		while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
335 			xp += n;
336 			if (Xnleft(xs, xp) <= 0)
337 				XcheckN(xs, xp, Xlength(xs, xp));
338 		}
339 		if (n < 0) {
340 			bi_errorf(Tf_temp, Tread, tf->tffn,
341 			    cstrerror(shf_errno(shf)));
342  errout:
343 			shf_close(shf);
344 			return (1);
345 		}
346 		shf_close(shf);
347 		*xp = '\0';
348 		strip_nuls(Xstring(xs, xp), Xlength(xs, xp));
349 		return (hist_execute(Xstring(xs, xp), hist_source->areap));
350 	}
351 }
352 
353 /* save cmd in history, execute cmd (cmd gets afree’d) */
354 static int
hist_execute(char * cmd,Area * areap)355 hist_execute(char *cmd, Area *areap)
356 {
357 	static int last_line = -1;
358 
359 	/* Back up over last histsave */
360 	if (histptr >= history && last_line != hist_source->line) {
361 		hist_source->line--;
362 		afree(*histptr, APERM);
363 		histptr--;
364 		last_line = hist_source->line;
365 	}
366 
367 	histsave(&hist_source->line, cmd, HIST_STORE, true);
368 	/* now *histptr == cmd without all trailing newlines */
369 	afree(cmd, areap);
370 	cmd = *histptr;
371 	/* pdksh says POSIX doesn’t say this is done, testsuite needs it */
372 	shellf(Tf_sN, cmd);
373 
374 	/*-
375 	 * Commands are executed here instead of pushing them onto the
376 	 * input 'cause POSIX says the redirection and variable assignments
377 	 * in
378 	 *	X=y fc -e - 42 2> /dev/null
379 	 * are to effect the repeated commands environment.
380 	 */
381 	return (command(cmd, 0));
382 }
383 
384 /*
385  * get pointer to history given pattern
386  * pattern is a number or string
387  */
388 static char **
hist_get(const char * str,bool approx,bool allow_cur)389 hist_get(const char *str, bool approx, bool allow_cur)
390 {
391 	char **hp = NULL;
392 	int n;
393 
394 	if (getn(str, &n)) {
395 		hp = histptr + (n < 0 ? n : (n - hist_source->line));
396 		if ((size_t)hp < (size_t)history) {
397 			if (approx)
398 				hp = hist_get_oldest();
399 			else {
400 				bi_errorf(Tf_sD_s, str, Tnot_in_history);
401 				hp = NULL;
402 			}
403 		} else if ((size_t)hp > (size_t)histptr) {
404 			if (approx)
405 				hp = hist_get_newest(allow_cur);
406 			else {
407 				bi_errorf(Tf_sD_s, str, Tnot_in_history);
408 				hp = NULL;
409 			}
410 		} else if (!allow_cur && hp == histptr) {
411 			bi_errorf(Tf_sD_s, str, "invalid range");
412 			hp = NULL;
413 		}
414 	} else {
415 		bool anchored = *str == '?' ? (++str, false) : true;
416 
417 		/* the -1 is to avoid the current fc command */
418 		if ((n = findhist(histptr - history - 1, str, false,
419 		    anchored)) < 0)
420 			bi_errorf(Tf_sD_s, str, Tnot_in_history);
421 		else
422 			hp = &history[n];
423 	}
424 	return (hp);
425 }
426 
427 /* Return a pointer to the newest command in the history */
428 char **
hist_get_newest(bool allow_cur)429 hist_get_newest(bool allow_cur)
430 {
431 	if (histptr < history || (!allow_cur && histptr == history)) {
432 		bi_errorf("no history (yet)");
433 		return (NULL);
434 	}
435 	return (allow_cur ? histptr : histptr - 1);
436 }
437 
438 /* Return a pointer to the oldest command in the history */
439 static char **
hist_get_oldest(void)440 hist_get_oldest(void)
441 {
442 	if (histptr <= history) {
443 		bi_errorf("no history (yet)");
444 		return (NULL);
445 	}
446 	return (history);
447 }
448 
449 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
450 /* current position in history[] */
451 static char **current;
452 
453 /*
454  * Return the current position.
455  */
456 char **
histpos(void)457 histpos(void)
458 {
459 	return (current);
460 }
461 
462 int
histnum(int n)463 histnum(int n)
464 {
465 	int last = histptr - history;
466 
467 	if (n < 0 || n >= last) {
468 		current = histptr;
469 		return (last);
470 	} else {
471 		current = &history[n];
472 		return (n);
473 	}
474 }
475 #endif
476 
477 /*
478  * This will become unnecessary if hist_get is modified to allow
479  * searching from positions other than the end, and in either
480  * direction.
481  */
482 int
findhist(int start,const char * str,bool fwd,bool anchored)483 findhist(int start, const char *str, bool fwd, bool anchored)
484 {
485 	char **hp;
486 	int maxhist = histptr - history;
487 	int incr = fwd ? 1 : -1;
488 	size_t len = strlen(str);
489 
490 	if (start < 0 || start >= maxhist)
491 		start = maxhist;
492 
493 	hp = &history[start];
494 	for (; hp >= history && hp <= histptr; hp += incr)
495 		if ((anchored && strncmp(*hp, str, len) == 0) ||
496 		    (!anchored && strstr(*hp, str)))
497 			return (hp - history);
498 
499 	return (-1);
500 }
501 
502 /*
503  * set history; this means reallocating the dataspace
504  */
505 void
sethistsize(mksh_ari_t n)506 sethistsize(mksh_ari_t n)
507 {
508 	if (n > 65535)
509 		n = 65535;
510 	if (n > 0 && n != histsize) {
511 		int cursize = histptr - history;
512 
513 		/* save most recent history */
514 		if (n < cursize) {
515 			memmove(history, histptr - n + 1, n * sizeof(char *));
516 			cursize = n - 1;
517 		}
518 
519 		history = aresize2(history, n, sizeof(char *), APERM);
520 
521 		histsize = n;
522 		histptr = history + cursize;
523 	}
524 }
525 
526 #if HAVE_PERSISTENT_HISTORY
527 /*
528  * set history file; this can mean reloading/resetting/starting
529  * history file maintenance
530  */
531 void
sethistfile(const char * name)532 sethistfile(const char *name)
533 {
534 	/* if not started then nothing to do */
535 	if (hstarted == false)
536 		return;
537 
538 	/* if the name is the same as the name we have */
539 	if (hname && name && !strcmp(hname, name))
540 		return;
541 
542 	/*
543 	 * it's a new name - possibly
544 	 */
545 	if (histfd != -1) {
546 		/* yes the file is open */
547 		(void)close(histfd);
548 		histfd = -1;
549 		histfsize = 0;
550 		afree(hname, APERM);
551 		hname = NULL;
552 		/* let's reset the history */
553 		histsave(NULL, NULL, HIST_DISCARD, true);
554 		histptr = history - 1;
555 		hist_source->line = 0;
556 	}
557 
558 	if (name)
559 		hist_init(hist_source);
560 }
561 #endif
562 
563 /*
564  * initialise the history vector
565  */
566 void
init_histvec(void)567 init_histvec(void)
568 {
569 	if (history == (char **)NULL) {
570 		histsize = MKSH_DEFHISTSIZE;
571 		history = alloc2(histsize, sizeof(char *), APERM);
572 		histptr = history - 1;
573 	}
574 }
575 
576 
577 /*
578  * It turns out that there is a lot of ghastly hackery here
579  */
580 
581 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
582 /* do not save command in history but possibly sync */
583 bool
histsync(void)584 histsync(void)
585 {
586 	bool changed = false;
587 
588 	/* called by histsave(), may not HIST_DISCARD, caller should flush */
589 
590 	if (histfd != -1) {
591 		int lno = hist_source->line;
592 
593 		hist_source->line++;
594 		writehistfile(0, NULL);
595 		hist_source->line--;
596 
597 		if (lno != hist_source->line)
598 			changed = true;
599 	}
600 
601 	return (changed);
602 }
603 #endif
604 
605 /*
606  * save command in history
607  */
608 void
histsave(int * lnp,const char * cmd,int svmode,bool ignoredups)609 histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
610 {
611 	static char *enqueued = NULL;
612 	char **hp, *c;
613 	const char *ccp;
614 
615 	if (svmode == HIST_DISCARD) {
616 		afree(enqueued, APERM);
617 		enqueued = NULL;
618 		return;
619 	}
620 
621 	if (svmode == HIST_APPEND) {
622 		if (!enqueued)
623 			svmode = HIST_STORE;
624 	} else if (enqueued) {
625 		c = enqueued;
626 		enqueued = NULL;
627 		--*lnp;
628 		histsave(lnp, c, HIST_STORE, true);
629 		afree(c, APERM);
630 	}
631 
632 	if (svmode == HIST_FLUSH)
633 		return;
634 
635 	ccp = strnul(cmd);
636 	while (ccp > cmd && ccp[-1] == '\n')
637 		--ccp;
638 	strndupx(c, cmd, ccp - cmd, APERM);
639 
640 	if (svmode != HIST_APPEND) {
641 		if (ignoredups &&
642 		    histptr >= history &&
643 		    !strcmp(c, *histptr)
644 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
645 		    && !histsync()
646 #endif
647 		    ) {
648 			afree(c, APERM);
649 			return;
650 		}
651 		++*lnp;
652 	}
653 
654 #if HAVE_PERSISTENT_HISTORY
655 	if (svmode == HIST_STORE && histfd != -1)
656 		writehistfile(*lnp, c);
657 #endif
658 
659 	if (svmode == HIST_QUEUE || svmode == HIST_APPEND) {
660 		size_t nenq, ncmd;
661 
662 		if (!enqueued) {
663 			if (*c)
664 				enqueued = c;
665 			else
666 				afree(c, APERM);
667 			return;
668 		}
669 
670 		nenq = strlen(enqueued);
671 		ncmd = strlen(c);
672 		enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
673 		enqueued[nenq] = '\n';
674 		memcpy(enqueued + nenq + 1, c, ncmd + 1);
675 		afree(c, APERM);
676 		return;
677 	}
678 
679 	hp = histptr;
680 
681 	if (++hp >= history + histsize) {
682 		/* remove oldest command */
683 		afree(*history, APERM);
684 		for (hp = history; hp < history + histsize - 1; hp++)
685 			hp[0] = hp[1];
686 	}
687 	*hp = c;
688 	histptr = hp;
689 }
690 
691 /*
692  * Write history data to a file nominated by HISTFILE;
693  * if HISTFILE is unset then history still happens, but
694  * the data is not written to a file. All copies of ksh
695  * looking at the file will maintain the same history.
696  * This is ksh behaviour.
697  *
698  * This stuff uses mmap()
699  *
700  * This stuff is so totally broken it must eventually be
701  * redesigned, without mmap, better checks, support for
702  * larger files, etc. and handle partially corrupted files
703  */
704 
705 /*-
706  * Open a history file
707  * Format is:
708  * Bytes 1, 2:
709  *	HMAGIC - just to check that we are dealing with the correct object
710  * Then follows a number of stored commands
711  * Each command is
712  *	<command byte><command number(4 octets, big endian)><bytes><NUL>
713  */
714 #define HMAGIC1		0xAB
715 #define HMAGIC2		0xCD
716 #define COMMAND		0xFF
717 
718 #if HAVE_PERSISTENT_HISTORY
719 static const unsigned char sprinkle[2] = { HMAGIC1, HMAGIC2 };
720 
721 static int
hist_persist_back(int srcfd)722 hist_persist_back(int srcfd)
723 {
724 	off_t tot, mis;
725 	ssize_t n, w;
726 	char *buf, *cp;
727 	int rv = 0;
728 #define MKSH_HS_BUFSIZ 4096
729 
730 	if ((tot = lseek(srcfd, (off_t)0, SEEK_END)) < 0 ||
731 	    lseek(srcfd, (off_t)0, SEEK_SET) < 0 ||
732 	    lseek(histfd, (off_t)0, SEEK_SET) < 0)
733 		return (1);
734 
735 	if ((buf = malloc_osfunc(MKSH_HS_BUFSIZ)) == NULL)
736 		return (1);
737 
738 	mis = tot;
739 	while (mis > 0) {
740 		if ((n = blocking_read(srcfd, (cp = buf),
741 		    MKSH_HS_BUFSIZ)) == -1) {
742 			if (errno == EINTR) {
743 				intrcheck();
744 				continue;
745 			}
746 			goto copy_error;
747 		}
748 		mis -= n;
749 		while (n) {
750 			if (intrsig)
751 				goto has_intrsig;
752 			if ((w = write(histfd, cp, n)) != -1) {
753 				n -= w;
754 				cp += w;
755 				continue;
756 			}
757 			if (errno == EINTR) {
758  has_intrsig:
759 				intrcheck();
760 				continue;
761 			}
762 			goto copy_error;
763 		}
764 	}
765 	if (ftruncate(histfd, tot)) {
766  copy_error:
767 		rv = 1;
768 	}
769 	free_osfunc(buf);
770 	return (rv);
771 }
772 
773 static void
hist_persist_init(void)774 hist_persist_init(void)
775 {
776 	unsigned char *base;
777 	int lines, fd;
778 	enum { hist_init_first, hist_init_retry, hist_use_it } hs;
779 
780 	if (((hname = str_val(global("HISTFILE"))) == NULL) || !*hname) {
781 		hname = NULL;
782 		return;
783 	}
784 	strdupx(hname, hname, APERM);
785 	hs = hist_init_first;
786 
787  retry:
788 	/* we have a file and are interactive */
789 	if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
790 		return;
791 	if ((histfd = savefd(fd)) < 0)
792 		return;
793 	if (histfd != fd)
794 		close(fd);
795 
796 	mksh_lockfd(histfd);
797 
798 	histfsize = lseek(histfd, (off_t)0, SEEK_END);
799 	if (histfsize > MKSH_MAXHISTFSIZE) {
800 		/* we ignore too large files but still append to them */
801 		goto hist_init_tail;
802 	} else if (histfsize > 2) {
803 		/* we have some data, check its validity */
804 		base = (void *)mmap(NULL, (size_t)histfsize, PROT_READ,
805 		    MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
806 		if (base == (unsigned char *)MAP_FAILED)
807 			goto hist_init_fail;
808 		if (base[0] != HMAGIC1 || base[1] != HMAGIC2) {
809 			munmap(caddr_cast(base), (size_t)histfsize);
810 			goto hist_init_fail;
811 		}
812 		/* load _all_ data */
813 		lines = histload(hist_source, base + 2, (size_t)histfsize - 2);
814 		munmap(caddr_cast(base), (size_t)histfsize);
815 		/* check if the file needs to be truncated */
816 		if (lines > histsize && histptr >= history) {
817 			/* you're fucked up with the current code, trust me */
818 			char *nhname, **hp;
819 			struct stat sb;
820 
821 			/* create temporary file */
822 			nhname = shf_smprintf("%s.%d", hname, (int)procpid);
823 			if ((fd = binopen3(nhname, O_RDWR | O_CREAT | O_TRUNC |
824 			    O_EXCL, 0600)) < 0) {
825 				/* just don't truncate then, meh. */
826 				hs = hist_use_it;
827 				goto hist_trunc_dont;
828 			}
829 			if (fstat(histfd, &sb) >= 0 &&
830 			    chown(nhname, sb.st_uid, sb.st_gid)) {
831 				/* abort the truncation then, meh. */
832 				goto hist_trunc_abort;
833 			}
834 			/* we definitively want some magic in that file */
835 			if (write(fd, sprinkle, 2) != 2)
836 				goto hist_trunc_abort;
837 			/* and of course the entries */
838 			hp = history;
839 			while (hp < histptr) {
840 				if (!writehistline(fd,
841 				    hist_source->line - (histptr - hp), *hp))
842 					goto hist_trunc_abort;
843 				++hp;
844 			}
845 			/* now transfer back */
846 			if (!hist_persist_back(fd)) {
847 				/* success! */
848 				hs = hist_use_it;
849 			}
850  hist_trunc_abort:
851 			/* remove temporary file */
852 			close(fd);
853 			fd = -1;
854 			unlink(nhname);
855 			/* use whatever is in the file now */
856  hist_trunc_dont:
857 			afree(nhname, ATEMP);
858 			if (hs == hist_use_it)
859 				goto hist_trunc_done;
860 			goto hist_init_fail;
861 		}
862 	} else if (histfsize != 0) {
863 		/* negative or too small... */
864  hist_init_fail:
865 		/* ... or mmap failed or illegal */
866 		hist_finish();
867 		/* nuke the bogus file then retry, at most once */
868 		if (!unlink(hname) && hs != hist_init_retry) {
869 			hs = hist_init_retry;
870 			goto retry;
871 		}
872 		if (hs != hist_init_retry)
873 			bi_errorf(Tf_cant_ss_s,
874 			    "unlink HISTFILE", hname, cstrerror(errno));
875 		histfsize = 0;
876 		return;
877 	} else {
878 		/* size 0, add magic to the history file */
879 		if (write(histfd, sprinkle, 2) != 2) {
880 			hist_finish();
881 			return;
882 		}
883 	}
884  hist_trunc_done:
885 	if ((histfsize = lseek(histfd, (off_t)0, SEEK_END)) < 0)
886 		goto hist_init_fail;
887  hist_init_tail:
888 	mksh_unlkfd(histfd);
889 }
890 #endif
891 
892 void
hist_init(Source * s)893 hist_init(Source *s)
894 {
895 	histsave(NULL, NULL, HIST_DISCARD, true);
896 
897 	if (Flag(FTALKING) == 0)
898 		return;
899 
900 	hstarted = true;
901 	hist_source = s;
902 
903 #if HAVE_PERSISTENT_HISTORY
904 	hist_persist_init();
905 #endif
906 }
907 
908 #if HAVE_PERSISTENT_HISTORY
909 /*
910  * load the history structure from the stored data
911  */
912 static int
histload(Source * s,unsigned char * base,size_t bytes)913 histload(Source *s, unsigned char *base, size_t bytes)
914 {
915 	int lno = 0, lines = 0;
916 	unsigned char *cp;
917 
918  histload_loop:
919 	/* !bytes check as some systems (older FreeBSDs) have buggy memchr */
920 	if (!bytes || (cp = memchr(base, COMMAND, bytes)) == NULL)
921 		return (lines);
922 	/* advance base pointer past COMMAND byte */
923 	bytes -= ++cp - base;
924 	base = cp;
925 	/* if there is no full string left, don't bother with the rest */
926 	if (bytes < 5 || (cp = memchr(base + 4, '\0', bytes - 4)) == NULL)
927 		return (lines);
928 	/* load the stored line number */
929 	lno = ((base[0] & 0xFF) << 24) | ((base[1] & 0xFF) << 16) |
930 	    ((base[2] & 0xFF) << 8) | (base[3] & 0xFF);
931 	/* store away the found line (@base[4]) */
932 	++lines;
933 	if (histptr >= history && lno - 1 != s->line) {
934 		/* a replacement? */
935 		char **hp;
936 
937 		if (lno >= s->line - (histptr - history) && lno <= s->line) {
938 			hp = &histptr[lno - s->line];
939 			afree(*hp, APERM);
940 			strdupx(*hp, (char *)(base + 4), APERM);
941 		}
942 	} else {
943 		s->line = lno--;
944 		histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
945 	}
946 	/* advance base pointer past NUL */
947 	bytes -= ++cp - base;
948 	base = cp;
949 	/* repeat until no more */
950 	goto histload_loop;
951 }
952 
953 /*
954  * write a command to the end of the history file
955  *
956  * This *MAY* seem easy but it's also necessary to check
957  * that the history file has not changed in size.
958  * If it has - then some other shell has written to it and
959  * we should (re)read those commands to update our history
960  */
961 static void
writehistfile(int lno,const char * cmd)962 writehistfile(int lno, const char *cmd)
963 {
964 	off_t sizenow;
965 	size_t bytes;
966 	unsigned char *base, *news;
967 
968 	mksh_lockfd(histfd);
969 	if ((sizenow = lseek(histfd, (off_t)0, SEEK_END)) < 0)
970 		goto bad;
971 	else if (sizenow < histfsize) {
972 		/* the file has shrunk; trust it just appending the new data */
973 		/* well, for now, anyway… since mksh strdups all into memory */
974 		/* we can use a nicer approach some time later… */
975 		;
976 	} else if (
977 		/* ignore changes when the file is too large */
978 		sizenow <= MKSH_MAXHISTFSIZE
979 	    &&
980 		/* the size has changed, we need to do read updates */
981 		sizenow > histfsize
982 	    ) {
983 		/* both sizenow and histfsize are <= MKSH_MAXHISTFSIZE */
984 		bytes = (size_t)(sizenow - histfsize);
985 		base = (void *)mmap(NULL, (size_t)sizenow, PROT_READ,
986 		    MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
987 		if (base == (unsigned char *)MAP_FAILED)
988 			goto bad;
989 		news = base + (size_t)histfsize;
990 		if (*news == COMMAND) {
991 			hist_source->line--;
992 			histload(hist_source, news, bytes);
993 			hist_source->line++;
994 			lno = hist_source->line;
995 		} else
996 			bytes = 0;
997 		munmap(caddr_cast(base), (size_t)sizenow);
998 		if (!bytes)
999 			goto bad;
1000 	}
1001 	if (cmd && !writehistline(histfd, lno, cmd)) {
1002  bad:
1003 		hist_finish();
1004 		return;
1005 	}
1006 	if ((histfsize = lseek(histfd, (off_t)0, SEEK_END)) < 0)
1007 		goto bad;
1008 	mksh_unlkfd(histfd);
1009 }
1010 
1011 static int
writehistline(int fd,int lno,const char * cmd)1012 writehistline(int fd, int lno, const char *cmd)
1013 {
1014 	ssize_t n;
1015 	unsigned char hdr[5];
1016 
1017 	hdr[0] = COMMAND;
1018 	hdr[1] = (lno >> 24) & 0xFF;
1019 	hdr[2] = (lno >> 16) & 0xFF;
1020 	hdr[3] = (lno >> 8) & 0xFF;
1021 	hdr[4] = lno & 0xFF;
1022 	n = strlen(cmd) + 1;
1023 	return (write(fd, hdr, 5) == 5 && write(fd, cmd, n) == n);
1024 }
1025 
1026 void
hist_finish(void)1027 hist_finish(void)
1028 {
1029 	if (histfd >= 0) {
1030 		mksh_unlkfd(histfd);
1031 		(void)close(histfd);
1032 	}
1033 	histfd = -1;
1034 }
1035 #endif
1036 
1037 
1038 #if !HAVE_SYS_SIGNAME
1039 static const struct mksh_sigpair {
1040 	const char * const name;
1041 	int nr;
1042 } mksh_sigpairs[] = {
1043 #include "signames.inc"
1044 	{ NULL, 0 }
1045 };
1046 #endif
1047 
1048 #if HAVE_SYS_SIGLIST
1049 #if !HAVE_SYS_SIGLIST_DECL
1050 extern const char * const sys_siglist[];
1051 #endif
1052 #endif
1053 
1054 void
inittraps(void)1055 inittraps(void)
1056 {
1057 	int i;
1058 	const char *cs;
1059 #if !HAVE_SYS_SIGNAME
1060 	const struct mksh_sigpair *pair;
1061 #endif
1062 
1063 	trap_exstat = -1;
1064 
1065 	/* populate sigtraps based on sys_signame and sys_siglist */
1066 	for (i = 1; i < ksh_NSIG; i++) {
1067 		sigtraps[i].signal = i;
1068 #if HAVE_SYS_SIGNAME
1069 		cs = sys_signame[i];
1070 #else
1071 		pair = mksh_sigpairs;
1072 		while ((pair->nr != i) && (pair->name != NULL))
1073 			++pair;
1074 		cs = pair->name;
1075 #endif
1076 		if ((cs == NULL) ||
1077 		    (cs[0] == '\0'))
1078 			sigtraps[i].name = null;
1079 		else {
1080 			char *s;
1081 
1082 			/* this is not optimal, what about SIGSIG1? */
1083 			if (ksh_eq(cs[0], 'S', 's') &&
1084 			    ksh_eq(cs[1], 'I', 'i') &&
1085 			    ksh_eq(cs[2], 'G', 'g') &&
1086 			    cs[3] != '\0') {
1087 				/* skip leading "SIG" */
1088 				cs += 3;
1089 			}
1090 			strdupx(s, cs, APERM);
1091 			sigtraps[i].name = s;
1092 			while ((*s = ksh_toupper(*s)))
1093 				++s;
1094 			/* check for reserved names */
1095 			if (!strcmp(sigtraps[i].name, "EXIT") ||
1096 			    !strcmp(sigtraps[i].name, "ERR")) {
1097 #ifndef MKSH_SMALL
1098 				internal_warningf(Tinvname, sigtraps[i].name,
1099 				    "signal");
1100 #endif
1101 				sigtraps[i].name = null;
1102 			}
1103 		}
1104 		if (sigtraps[i].name == null)
1105 			sigtraps[i].name = shf_smprintf(Tf_d, i);
1106 #if HAVE_SYS_SIGLIST
1107 		sigtraps[i].mess = sys_siglist[i];
1108 #elif HAVE_STRSIGNAL
1109 		sigtraps[i].mess = strsignal(i);
1110 #else
1111 		sigtraps[i].mess = NULL;
1112 #endif
1113 		if ((sigtraps[i].mess == NULL) ||
1114 		    (sigtraps[i].mess[0] == '\0'))
1115 			sigtraps[i].mess = shf_smprintf(Tf_sd,
1116 			    "Signal", i);
1117 	}
1118 	sigtraps[ksh_SIGEXIT].signal = ksh_SIGEXIT;
1119 	sigtraps[ksh_SIGEXIT].name = "EXIT";
1120 	sigtraps[ksh_SIGEXIT].mess = "Exit trap";
1121 	sigtraps[ksh_SIGERR].signal = ksh_SIGERR;
1122 	sigtraps[ksh_SIGERR].name = "ERR";
1123 	sigtraps[ksh_SIGERR].mess = "Error handler";
1124 
1125 	(void)sigemptyset(&Sigact_ign.sa_mask);
1126 	Sigact_ign.sa_flags = 0; /* interruptible */
1127 	Sigact_ign.sa_handler = SIG_IGN;
1128 
1129 	sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1130 	sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1131 	/* SIGTERM is not fatal for interactive */
1132 	sigtraps[SIGTERM].flags |= TF_DFL_INTR;
1133 	sigtraps[SIGHUP].flags |= TF_FATAL;
1134 	sigtraps[SIGCHLD].flags |= TF_SHELL_USES;
1135 
1136 	/* these are always caught so we can clean up any temporary files. */
1137 	setsig(&sigtraps[SIGINT], trapsig, SS_RESTORE_ORIG);
1138 	setsig(&sigtraps[SIGQUIT], trapsig, SS_RESTORE_ORIG);
1139 	setsig(&sigtraps[SIGTERM], trapsig, SS_RESTORE_ORIG);
1140 	setsig(&sigtraps[SIGHUP], trapsig, SS_RESTORE_ORIG);
1141 }
1142 
1143 static void alarm_catcher(int sig);
1144 
1145 void
alarm_init(void)1146 alarm_init(void)
1147 {
1148 	sigtraps[SIGALRM].flags |= TF_SHELL_USES;
1149 	setsig(&sigtraps[SIGALRM], alarm_catcher,
1150 		SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
1151 }
1152 
1153 /* ARGSUSED */
1154 static void
alarm_catcher(int sig MKSH_A_UNUSED)1155 alarm_catcher(int sig MKSH_A_UNUSED)
1156 {
1157 	/* this runs inside interrupt context, with errno saved */
1158 
1159 	if (ksh_tmout_state == TMOUT_READING) {
1160 		int left = alarm(0);
1161 
1162 		if (left == 0) {
1163 			ksh_tmout_state = TMOUT_LEAVING;
1164 			intrsig = 1;
1165 		} else
1166 			alarm(left);
1167 	}
1168 }
1169 
1170 Trap *
gettrap(const char * cs,bool igncase,bool allsigs)1171 gettrap(const char *cs, bool igncase, bool allsigs)
1172 {
1173 	int i;
1174 	Trap *p;
1175 	char *as;
1176 
1177 	/* signal number (1..ksh_NSIG) or 0? */
1178 
1179 	if (ctype(*cs, C_DIGIT))
1180 		return ((getn(cs, &i) && 0 <= i && i < ksh_NSIG) ?
1181 		    (&sigtraps[i]) : NULL);
1182 
1183 	/* do a lookup by name then */
1184 
1185 	/* this breaks SIGSIG1, but we do that above anyway */
1186 	if (ksh_eq(cs[0], 'S', 's') &&
1187 	    ksh_eq(cs[1], 'I', 'i') &&
1188 	    ksh_eq(cs[2], 'G', 'g') &&
1189 	    cs[3] != '\0') {
1190 		/* skip leading "SIG" */
1191 		cs += 3;
1192 	}
1193 	if (igncase) {
1194 		char *s;
1195 
1196 		strdupx(as, cs, ATEMP);
1197 		cs = s = as;
1198 		while ((*s = ksh_toupper(*s)))
1199 			++s;
1200 	} else
1201 		as = NULL;
1202 
1203 	/* this is idiotic, we really want a hashtable here */
1204 
1205 	p = sigtraps;
1206 	i = ksh_NSIG + 1;
1207 	do {
1208 		if (!strcmp(p->name, cs))
1209 			goto found;
1210 		++p;
1211 	} while (--i);
1212 	goto notfound;
1213 
1214  found:
1215 	if (!allsigs) {
1216 		if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR) {
1217  notfound:
1218 			p = NULL;
1219 		}
1220 	}
1221 	afree(as, ATEMP);
1222 	return (p);
1223 }
1224 
1225 /*
1226  * trap signal handler
1227  */
1228 void
trapsig(int i)1229 trapsig(int i)
1230 {
1231 	Trap *p = &sigtraps[i];
1232 	int eno = errno;
1233 
1234 	trap = p->set = 1;
1235 	if (p->flags & TF_DFL_INTR)
1236 		intrsig = 1;
1237 	if ((p->flags & TF_FATAL) && !p->trap) {
1238 		fatal_trap = 1;
1239 		intrsig = 1;
1240 	}
1241 	if (p->shtrap)
1242 		(*p->shtrap)(i);
1243 	errno = eno;
1244 }
1245 
1246 /*
1247  * called when we want to allow the user to ^C out of something - won't
1248  * work if user has trapped SIGINT.
1249  */
1250 void
intrcheck(void)1251 intrcheck(void)
1252 {
1253 	if (intrsig)
1254 		runtraps(TF_DFL_INTR|TF_FATAL);
1255 }
1256 
1257 /*
1258  * called after EINTR to check if a signal with normally causes process
1259  * termination has been received.
1260  */
1261 int
fatal_trap_check(void)1262 fatal_trap_check(void)
1263 {
1264 	Trap *p = sigtraps;
1265 	int i = ksh_NSIG + 1;
1266 
1267 	/* todo: should check if signal is fatal, not the TF_DFL_INTR flag */
1268 	do {
1269 		if (p->set && (p->flags & (TF_DFL_INTR|TF_FATAL)))
1270 			/* return value is used as an exit code */
1271 			return (ksh_sigmask(p->signal));
1272 		++p;
1273 	} while (--i);
1274 	return (0);
1275 }
1276 
1277 /*
1278  * Returns the signal number of any pending traps: ie, a signal which has
1279  * occurred for which a trap has been set or for which the TF_DFL_INTR flag
1280  * is set.
1281  */
1282 int
trap_pending(void)1283 trap_pending(void)
1284 {
1285 	Trap *p = sigtraps;
1286 	int i = ksh_NSIG + 1;
1287 
1288 	do {
1289 		if (p->set && ((p->trap && p->trap[0]) ||
1290 		    ((p->flags & (TF_DFL_INTR|TF_FATAL)) && !p->trap)))
1291 			return (p->signal);
1292 		++p;
1293 	} while (--i);
1294 	return (0);
1295 }
1296 
1297 /*
1298  * run any pending traps. If intr is set, only run traps that
1299  * can interrupt commands.
1300  */
1301 void
runtraps(int flag)1302 runtraps(int flag)
1303 {
1304 	Trap *p = sigtraps;
1305 	int i = ksh_NSIG + 1;
1306 
1307 	if (ksh_tmout_state == TMOUT_LEAVING) {
1308 		ksh_tmout_state = TMOUT_EXECUTING;
1309 		warningf(false, "timed out waiting for input");
1310 		unwind(LEXIT);
1311 	} else
1312 		/*
1313 		 * XXX: this means the alarm will have no effect if a trap
1314 		 * is caught after the alarm() was started...not good.
1315 		 */
1316 		ksh_tmout_state = TMOUT_EXECUTING;
1317 	if (!flag)
1318 		trap = 0;
1319 	if (flag & TF_DFL_INTR)
1320 		intrsig = 0;
1321 	if (flag & TF_FATAL)
1322 		fatal_trap = 0;
1323 	++trap_nested;
1324 	do {
1325 		if (p->set && (!flag ||
1326 		    ((p->flags & flag) && p->trap == NULL)))
1327 			runtrap(p, false);
1328 		++p;
1329 	} while (--i);
1330 	if (!--trap_nested)
1331 		runtrap(NULL, true);
1332 }
1333 
1334 void
runtrap(Trap * p,bool is_last)1335 runtrap(Trap *p, bool is_last)
1336 {
1337 	int old_changed = 0, i;
1338 	char *trapstr;
1339 
1340 	if (p == NULL)
1341 		/* just clean up, see runtraps() above */
1342 		goto donetrap;
1343 	i = p->signal;
1344 	trapstr = p->trap;
1345 	p->set = 0;
1346 	if (trapstr == NULL) {
1347 		/* SIG_DFL */
1348 		if (p->flags & (TF_FATAL | TF_DFL_INTR)) {
1349 			exstat = (int)(128U + (unsigned)i);
1350 			if ((unsigned)exstat > 255U)
1351 				exstat = 255;
1352 		}
1353 		/* e.g. SIGHUP */
1354 		if (p->flags & TF_FATAL)
1355 			unwind(LLEAVE);
1356 		/* e.g. SIGINT, SIGQUIT, SIGTERM, etc. */
1357 		if (p->flags & TF_DFL_INTR)
1358 			unwind(LINTR);
1359 		goto donetrap;
1360 	}
1361 	if (trapstr[0] == '\0')
1362 		/* SIG_IGN */
1363 		goto donetrap;
1364 	if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1365 		/* avoid recursion on these */
1366 		old_changed = p->flags & TF_CHANGED;
1367 		p->flags &= ~TF_CHANGED;
1368 		p->trap = NULL;
1369 	}
1370 	if (trap_exstat == -1)
1371 		trap_exstat = exstat & 0xFF;
1372 	/*
1373 	 * Note: trapstr is fully parsed before anything is executed, thus
1374 	 * no problem with afree(p->trap) in settrap() while still in use.
1375 	 */
1376 	command(trapstr, current_lineno);
1377 	if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1378 		if (p->flags & TF_CHANGED)
1379 			/* don't clear TF_CHANGED */
1380 			afree(trapstr, APERM);
1381 		else
1382 			p->trap = trapstr;
1383 		p->flags |= old_changed;
1384 	}
1385 
1386  donetrap:
1387 	/* we're the last trap of a sequence executed */
1388 	if (is_last && trap_exstat != -1) {
1389 		exstat = trap_exstat;
1390 		trap_exstat = -1;
1391 	}
1392 }
1393 
1394 /* clear pending traps and reset user's trap handlers; used after fork(2) */
1395 void
cleartraps(void)1396 cleartraps(void)
1397 {
1398 	Trap *p = sigtraps;
1399 	int i = ksh_NSIG + 1;
1400 
1401 	trap = 0;
1402 	intrsig = 0;
1403 	fatal_trap = 0;
1404 
1405 	do {
1406 		p->set = 0;
1407 		if ((p->flags & TF_USER_SET) && (p->trap && p->trap[0]))
1408 			settrap(p, NULL);
1409 		++p;
1410 	} while (--i);
1411 }
1412 
1413 /* restore signals just before an exec(2) */
1414 void
restoresigs(void)1415 restoresigs(void)
1416 {
1417 	Trap *p = sigtraps;
1418 	int i = ksh_NSIG + 1;
1419 
1420 	do {
1421 		if (p->flags & (TF_EXEC_IGN|TF_EXEC_DFL))
1422 			setsig(p, (p->flags & TF_EXEC_IGN) ? SIG_IGN : SIG_DFL,
1423 			    SS_RESTORE_CURR|SS_FORCE);
1424 		++p;
1425 	} while (--i);
1426 }
1427 
1428 void
settrap(Trap * p,const char * s)1429 settrap(Trap *p, const char *s)
1430 {
1431 	sig_t f;
1432 
1433 	afree(p->trap, APERM);
1434 	/* handles s == NULL */
1435 	strdupx(p->trap, s, APERM);
1436 	p->flags |= TF_CHANGED;
1437 	f = !s ? SIG_DFL : s[0] ? trapsig : SIG_IGN;
1438 
1439 	p->flags |= TF_USER_SET;
1440 	if ((p->flags & (TF_DFL_INTR|TF_FATAL)) && f == SIG_DFL)
1441 		f = trapsig;
1442 	else if (p->flags & TF_SHELL_USES) {
1443 		if (!(p->flags & TF_ORIG_IGN) || Flag(FTALKING)) {
1444 			/* do what user wants at exec time */
1445 			p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1446 			if (f == SIG_IGN)
1447 				p->flags |= TF_EXEC_IGN;
1448 			else
1449 				p->flags |= TF_EXEC_DFL;
1450 		}
1451 
1452 		/*
1453 		 * assumes handler already set to what shell wants it
1454 		 * (normally trapsig, but could be j_sigchld() or SIG_IGN)
1455 		 */
1456 		return;
1457 	}
1458 
1459 	/* todo: should we let user know signal is ignored? how? */
1460 	setsig(p, f, SS_RESTORE_CURR|SS_USER);
1461 }
1462 
1463 /*
1464  * called by c_print() when writing to a co-process to ensure
1465  * SIGPIPE won't kill shell (unless user catches it and exits)
1466  */
1467 bool
block_pipe(void)1468 block_pipe(void)
1469 {
1470 	bool restore_dfl = false;
1471 	Trap *p = &sigtraps[SIGPIPE];
1472 
1473 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1474 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
1475 		if (p->flags & TF_ORIG_DFL)
1476 			restore_dfl = true;
1477 	} else if (p->cursig == SIG_DFL) {
1478 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
1479 		/* restore to SIG_DFL */
1480 		restore_dfl = true;
1481 	}
1482 	return (restore_dfl);
1483 }
1484 
1485 /* called by c_print() to undo whatever block_pipe() did */
1486 void
restore_pipe(void)1487 restore_pipe(void)
1488 {
1489 	setsig(&sigtraps[SIGPIPE], SIG_DFL, SS_RESTORE_CURR);
1490 }
1491 
1492 /*
1493  * Set action for a signal. Action may not be set if original
1494  * action was SIG_IGN, depending on the value of flags and FTALKING.
1495  */
1496 int
setsig(Trap * p,sig_t f,int flags)1497 setsig(Trap *p, sig_t f, int flags)
1498 {
1499 	struct sigaction sigact;
1500 
1501 	if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
1502 		return (1);
1503 
1504 	memset(&sigact, 0, sizeof(sigact));
1505 
1506 	/*
1507 	 * First time setting this signal? If so, get and note the current
1508 	 * setting.
1509 	 */
1510 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1511 		sigaction(p->signal, &Sigact_ign, &sigact);
1512 		p->flags |= sigact.sa_handler == SIG_IGN ?
1513 		    TF_ORIG_IGN : TF_ORIG_DFL;
1514 		p->cursig = SIG_IGN;
1515 	}
1516 
1517 	/*-
1518 	 * Generally, an ignored signal stays ignored, except if
1519 	 *	- the user of an interactive shell wants to change it
1520 	 *	- the shell wants for force a change
1521 	 */
1522 	if ((p->flags & TF_ORIG_IGN) && !(flags & SS_FORCE) &&
1523 	    (!(flags & SS_USER) || !Flag(FTALKING)))
1524 		return (0);
1525 
1526 	setexecsig(p, flags & SS_RESTORE_MASK);
1527 
1528 	/*
1529 	 * This is here 'cause there should be a way of clearing
1530 	 * shtraps, but don't know if this is a sane way of doing
1531 	 * it. At the moment, all users of shtrap are lifetime
1532 	 * users (SIGALRM, SIGCHLD, SIGWINCH).
1533 	 */
1534 	if (!(flags & SS_USER))
1535 		p->shtrap = (sig_t)NULL;
1536 	if (flags & SS_SHTRAP) {
1537 		p->shtrap = f;
1538 		f = trapsig;
1539 	}
1540 
1541 	if (p->cursig != f) {
1542 		p->cursig = f;
1543 		(void)sigemptyset(&sigact.sa_mask);
1544 		/* interruptible */
1545 		sigact.sa_flags = 0;
1546 		sigact.sa_handler = f;
1547 		sigaction(p->signal, &sigact, NULL);
1548 	}
1549 
1550 	return (1);
1551 }
1552 
1553 /* control what signal is set to before an exec() */
1554 void
setexecsig(Trap * p,int restore)1555 setexecsig(Trap *p, int restore)
1556 {
1557 	/* XXX debugging */
1558 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
1559 		internal_errorf("setexecsig: unset signal %d(%s)",
1560 		    p->signal, p->name);
1561 
1562 	/* restore original value for exec'd kids */
1563 	p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1564 	switch (restore & SS_RESTORE_MASK) {
1565 	case SS_RESTORE_CURR:
1566 		/* leave things as they currently are */
1567 		break;
1568 	case SS_RESTORE_ORIG:
1569 		p->flags |= p->flags & TF_ORIG_IGN ? TF_EXEC_IGN : TF_EXEC_DFL;
1570 		break;
1571 	case SS_RESTORE_DFL:
1572 		p->flags |= TF_EXEC_DFL;
1573 		break;
1574 	case SS_RESTORE_IGN:
1575 		p->flags |= TF_EXEC_IGN;
1576 		break;
1577 	}
1578 }
1579 
1580 #if HAVE_PERSISTENT_HISTORY || defined(DF)
1581 /*
1582  * File descriptor locking and unlocking functions.
1583  * Could use some error handling, but hey, this is only
1584  * advisory locking anyway, will often not work over NFS,
1585  * and you are SOL if this fails...
1586  */
1587 
1588 void
mksh_lockfd(int fd)1589 mksh_lockfd(int fd)
1590 {
1591 #if defined(__OpenBSD__)
1592 	/* flock is not interrupted by signals */
1593 	(void)flock(fd, LOCK_EX);
1594 #elif HAVE_FLOCK
1595 	int rv;
1596 
1597 	/* e.g. on Linux */
1598 	do {
1599 		rv = flock(fd, LOCK_EX);
1600 	} while (rv == 1 && errno == EINTR);
1601 #elif HAVE_LOCK_FCNTL
1602 	int rv;
1603 	struct flock lks;
1604 
1605 	memset(&lks, 0, sizeof(lks));
1606 	lks.l_type = F_WRLCK;
1607 	do {
1608 		rv = fcntl(fd, F_SETLKW, &lks);
1609 	} while (rv == 1 && errno == EINTR);
1610 #endif
1611 }
1612 
1613 /* designed to not define mksh_unlkfd if none triggered */
1614 #if HAVE_FLOCK
1615 void
mksh_unlkfd(int fd)1616 mksh_unlkfd(int fd)
1617 {
1618 	(void)flock(fd, LOCK_UN);
1619 }
1620 #elif HAVE_LOCK_FCNTL
1621 void
mksh_unlkfd(int fd)1622 mksh_unlkfd(int fd)
1623 {
1624 	struct flock lks;
1625 
1626 	memset(&lks, 0, sizeof(lks));
1627 	lks.l_type = F_UNLCK;
1628 	(void)fcntl(fd, F_SETLKW, &lks);
1629 }
1630 #endif
1631 #endif
1632