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.169 2019/09/16 21:10:33 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, 0, str, anchored)) < 0)
419 			bi_errorf(Tf_sD_s, str, Tnot_in_history);
420 		else
421 			hp = &history[n];
422 	}
423 	return (hp);
424 }
425 
426 /* Return a pointer to the newest command in the history */
427 char **
hist_get_newest(bool allow_cur)428 hist_get_newest(bool allow_cur)
429 {
430 	if (histptr < history || (!allow_cur && histptr == history)) {
431 		bi_errorf("no history (yet)");
432 		return (NULL);
433 	}
434 	return (allow_cur ? histptr : histptr - 1);
435 }
436 
437 /* Return a pointer to the oldest command in the history */
438 static char **
hist_get_oldest(void)439 hist_get_oldest(void)
440 {
441 	if (histptr <= history) {
442 		bi_errorf("no history (yet)");
443 		return (NULL);
444 	}
445 	return (history);
446 }
447 
448 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
449 /* current position in history[] */
450 static char **current;
451 
452 /*
453  * Return the current position.
454  */
455 char **
histpos(void)456 histpos(void)
457 {
458 	return (current);
459 }
460 
461 int
histnum(int n)462 histnum(int n)
463 {
464 	int last = histptr - history;
465 
466 	if (n < 0 || n >= last) {
467 		current = histptr;
468 		return (last);
469 	} else {
470 		current = &history[n];
471 		return (n);
472 	}
473 }
474 #endif
475 
476 /*
477  * This will become unnecessary if hist_get is modified to allow
478  * searching from positions other than the end, and in either
479  * direction.
480  */
481 int
findhist(int start,int fwd,const char * str,bool anchored)482 findhist(int start, int fwd, const char *str, bool anchored)
483 {
484 	char **hp;
485 	int maxhist = histptr - history;
486 	int incr = fwd ? 1 : -1;
487 	size_t len = strlen(str);
488 
489 	if (start < 0 || start >= maxhist)
490 		start = maxhist;
491 
492 	hp = &history[start];
493 	for (; hp >= history && hp <= histptr; hp += incr)
494 		if ((anchored && strncmp(*hp, str, len) == 0) ||
495 		    (!anchored && strstr(*hp, str)))
496 			return (hp - history);
497 
498 	return (-1);
499 }
500 
501 /*
502  * set history; this means reallocating the dataspace
503  */
504 void
sethistsize(mksh_ari_t n)505 sethistsize(mksh_ari_t n)
506 {
507 	if (n > 65535)
508 		n = 65535;
509 	if (n > 0 && n != histsize) {
510 		int cursize = histptr - history;
511 
512 		/* save most recent history */
513 		if (n < cursize) {
514 			memmove(history, histptr - n + 1, n * sizeof(char *));
515 			cursize = n - 1;
516 		}
517 
518 		history = aresize2(history, n, sizeof(char *), APERM);
519 
520 		histsize = n;
521 		histptr = history + cursize;
522 	}
523 }
524 
525 #if HAVE_PERSISTENT_HISTORY
526 /*
527  * set history file; this can mean reloading/resetting/starting
528  * history file maintenance
529  */
530 void
sethistfile(const char * name)531 sethistfile(const char *name)
532 {
533 	/* if not started then nothing to do */
534 	if (hstarted == false)
535 		return;
536 
537 	/* if the name is the same as the name we have */
538 	if (hname && name && !strcmp(hname, name))
539 		return;
540 
541 	/*
542 	 * it's a new name - possibly
543 	 */
544 	if (histfd != -1) {
545 		/* yes the file is open */
546 		(void)close(histfd);
547 		histfd = -1;
548 		histfsize = 0;
549 		afree(hname, APERM);
550 		hname = NULL;
551 		/* let's reset the history */
552 		histsave(NULL, NULL, HIST_DISCARD, true);
553 		histptr = history - 1;
554 		hist_source->line = 0;
555 	}
556 
557 	if (name)
558 		hist_init(hist_source);
559 }
560 #endif
561 
562 /*
563  * initialise the history vector
564  */
565 void
init_histvec(void)566 init_histvec(void)
567 {
568 	if (history == (char **)NULL) {
569 		histsize = MKSH_DEFHISTSIZE;
570 		history = alloc2(histsize, sizeof(char *), APERM);
571 		histptr = history - 1;
572 	}
573 }
574 
575 
576 /*
577  * It turns out that there is a lot of ghastly hackery here
578  */
579 
580 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
581 /* do not save command in history but possibly sync */
582 bool
histsync(void)583 histsync(void)
584 {
585 	bool changed = false;
586 
587 	/* called by histsave(), may not HIST_DISCARD, caller should flush */
588 
589 	if (histfd != -1) {
590 		int lno = hist_source->line;
591 
592 		hist_source->line++;
593 		writehistfile(0, NULL);
594 		hist_source->line--;
595 
596 		if (lno != hist_source->line)
597 			changed = true;
598 	}
599 
600 	return (changed);
601 }
602 #endif
603 
604 /*
605  * save command in history
606  */
607 void
histsave(int * lnp,const char * cmd,int svmode,bool ignoredups)608 histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
609 {
610 	static char *enqueued = NULL;
611 	char **hp, *c;
612 	const char *ccp;
613 
614 	if (svmode == HIST_DISCARD) {
615 		afree(enqueued, APERM);
616 		enqueued = NULL;
617 		return;
618 	}
619 
620 	if (svmode == HIST_APPEND) {
621 		if (!enqueued)
622 			svmode = HIST_STORE;
623 	} else if (enqueued) {
624 		c = enqueued;
625 		enqueued = NULL;
626 		--*lnp;
627 		histsave(lnp, c, HIST_STORE, true);
628 		afree(c, APERM);
629 	}
630 
631 	if (svmode == HIST_FLUSH)
632 		return;
633 
634 	ccp = strnul(cmd);
635 	while (ccp > cmd && ccp[-1] == '\n')
636 		--ccp;
637 	strndupx(c, cmd, ccp - cmd, APERM);
638 
639 	if (svmode != HIST_APPEND) {
640 		if (ignoredups &&
641 		    histptr >= history &&
642 		    !strcmp(c, *histptr)
643 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
644 		    && !histsync()
645 #endif
646 		    ) {
647 			afree(c, APERM);
648 			return;
649 		}
650 		++*lnp;
651 	}
652 
653 #if HAVE_PERSISTENT_HISTORY
654 	if (svmode == HIST_STORE && histfd != -1)
655 		writehistfile(*lnp, c);
656 #endif
657 
658 	if (svmode == HIST_QUEUE || svmode == HIST_APPEND) {
659 		size_t nenq, ncmd;
660 
661 		if (!enqueued) {
662 			if (*c)
663 				enqueued = c;
664 			else
665 				afree(c, APERM);
666 			return;
667 		}
668 
669 		nenq = strlen(enqueued);
670 		ncmd = strlen(c);
671 		enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
672 		enqueued[nenq] = '\n';
673 		memcpy(enqueued + nenq + 1, c, ncmd + 1);
674 		afree(c, APERM);
675 		return;
676 	}
677 
678 	hp = histptr;
679 
680 	if (++hp >= history + histsize) {
681 		/* remove oldest command */
682 		afree(*history, APERM);
683 		for (hp = history; hp < history + histsize - 1; hp++)
684 			hp[0] = hp[1];
685 	}
686 	*hp = c;
687 	histptr = hp;
688 }
689 
690 /*
691  * Write history data to a file nominated by HISTFILE;
692  * if HISTFILE is unset then history still happens, but
693  * the data is not written to a file. All copies of ksh
694  * looking at the file will maintain the same history.
695  * This is ksh behaviour.
696  *
697  * This stuff uses mmap()
698  *
699  * This stuff is so totally broken it must eventually be
700  * redesigned, without mmap, better checks, support for
701  * larger files, etc. and handle partially corrupted files
702  */
703 
704 /*-
705  * Open a history file
706  * Format is:
707  * Bytes 1, 2:
708  *	HMAGIC - just to check that we are dealing with the correct object
709  * Then follows a number of stored commands
710  * Each command is
711  *	<command byte><command number(4 octets, big endian)><bytes><NUL>
712  */
713 #define HMAGIC1		0xAB
714 #define HMAGIC2		0xCD
715 #define COMMAND		0xFF
716 
717 #if HAVE_PERSISTENT_HISTORY
718 static const unsigned char sprinkle[2] = { HMAGIC1, HMAGIC2 };
719 
720 static int
hist_persist_back(int srcfd)721 hist_persist_back(int srcfd)
722 {
723 	off_t tot, mis;
724 	ssize_t n, w;
725 	char *buf, *cp;
726 	int rv = 0;
727 #define MKSH_HS_BUFSIZ 4096
728 
729 	if ((tot = lseek(srcfd, (off_t)0, SEEK_END)) < 0 ||
730 	    lseek(srcfd, (off_t)0, SEEK_SET) < 0 ||
731 	    lseek(histfd, (off_t)0, SEEK_SET) < 0)
732 		return (1);
733 
734 	if ((buf = malloc_osfunc(MKSH_HS_BUFSIZ)) == NULL)
735 		return (1);
736 
737 	mis = tot;
738 	while (mis > 0) {
739 		if ((n = blocking_read(srcfd, (cp = buf),
740 		    MKSH_HS_BUFSIZ)) == -1) {
741 			if (errno == EINTR) {
742 				intrcheck();
743 				continue;
744 			}
745 			goto copy_error;
746 		}
747 		mis -= n;
748 		while (n) {
749 			if (intrsig)
750 				goto has_intrsig;
751 			if ((w = write(histfd, cp, n)) != -1) {
752 				n -= w;
753 				cp += w;
754 				continue;
755 			}
756 			if (errno == EINTR) {
757  has_intrsig:
758 				intrcheck();
759 				continue;
760 			}
761 			goto copy_error;
762 		}
763 	}
764 	if (ftruncate(histfd, tot)) {
765  copy_error:
766 		rv = 1;
767 	}
768 	free_osfunc(buf);
769 	return (rv);
770 }
771 
772 static void
hist_persist_init(void)773 hist_persist_init(void)
774 {
775 	unsigned char *base;
776 	int lines, fd;
777 	enum { hist_init_first, hist_init_retry, hist_use_it } hs;
778 
779 	if (((hname = str_val(global("HISTFILE"))) == NULL) || !*hname) {
780 		hname = NULL;
781 		return;
782 	}
783 	strdupx(hname, hname, APERM);
784 	hs = hist_init_first;
785 
786  retry:
787 	/* we have a file and are interactive */
788 	if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
789 		return;
790 	if ((histfd = savefd(fd)) < 0)
791 		return;
792 	if (histfd != fd)
793 		close(fd);
794 
795 	mksh_lockfd(histfd);
796 
797 	histfsize = lseek(histfd, (off_t)0, SEEK_END);
798 	if (histfsize > MKSH_MAXHISTFSIZE) {
799 		/* we ignore too large files but still append to them */
800 		goto hist_init_tail;
801 	} else if (histfsize > 2) {
802 		/* we have some data, check its validity */
803 		base = (void *)mmap(NULL, (size_t)histfsize, PROT_READ,
804 		    MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
805 		if (base == (unsigned char *)MAP_FAILED)
806 			goto hist_init_fail;
807 		if (base[0] != HMAGIC1 || base[1] != HMAGIC2) {
808 			munmap(caddr_cast(base), (size_t)histfsize);
809 			goto hist_init_fail;
810 		}
811 		/* load _all_ data */
812 		lines = histload(hist_source, base + 2, (size_t)histfsize - 2);
813 		munmap(caddr_cast(base), (size_t)histfsize);
814 		/* check if the file needs to be truncated */
815 		if (lines > histsize && histptr >= history) {
816 			/* you're fucked up with the current code, trust me */
817 			char *nhname, **hp;
818 			struct stat sb;
819 
820 			/* create temporary file */
821 			nhname = shf_smprintf("%s.%d", hname, (int)procpid);
822 			if ((fd = binopen3(nhname, O_RDWR | O_CREAT | O_TRUNC |
823 			    O_EXCL, 0600)) < 0) {
824 				/* just don't truncate then, meh. */
825 				hs = hist_use_it;
826 				goto hist_trunc_dont;
827 			}
828 			if (fstat(histfd, &sb) >= 0 &&
829 			    chown(nhname, sb.st_uid, sb.st_gid)) {
830 				/* abort the truncation then, meh. */
831 				goto hist_trunc_abort;
832 			}
833 			/* we definitively want some magic in that file */
834 			if (write(fd, sprinkle, 2) != 2)
835 				goto hist_trunc_abort;
836 			/* and of course the entries */
837 			hp = history;
838 			while (hp < histptr) {
839 				if (!writehistline(fd,
840 				    hist_source->line - (histptr - hp), *hp))
841 					goto hist_trunc_abort;
842 				++hp;
843 			}
844 			/* now transfer back */
845 			if (!hist_persist_back(fd)) {
846 				/* success! */
847 				hs = hist_use_it;
848 			}
849  hist_trunc_abort:
850 			/* remove temporary file */
851 			close(fd);
852 			fd = -1;
853 			unlink(nhname);
854 			/* use whatever is in the file now */
855  hist_trunc_dont:
856 			afree(nhname, ATEMP);
857 			if (hs == hist_use_it)
858 				goto hist_trunc_done;
859 			goto hist_init_fail;
860 		}
861 	} else if (histfsize != 0) {
862 		/* negative or too small... */
863  hist_init_fail:
864 		/* ... or mmap failed or illegal */
865 		hist_finish();
866 		/* nuke the bogus file then retry, at most once */
867 		if (!unlink(hname) && hs != hist_init_retry) {
868 			hs = hist_init_retry;
869 			goto retry;
870 		}
871 		if (hs != hist_init_retry)
872 			bi_errorf(Tf_cant_ss_s,
873 			    "unlink HISTFILE", hname, cstrerror(errno));
874 		histfsize = 0;
875 		return;
876 	} else {
877 		/* size 0, add magic to the history file */
878 		if (write(histfd, sprinkle, 2) != 2) {
879 			hist_finish();
880 			return;
881 		}
882 	}
883  hist_trunc_done:
884 	if ((histfsize = lseek(histfd, (off_t)0, SEEK_END)) < 0)
885 		goto hist_init_fail;
886  hist_init_tail:
887 	mksh_unlkfd(histfd);
888 }
889 #endif
890 
891 void
hist_init(Source * s)892 hist_init(Source *s)
893 {
894 	histsave(NULL, NULL, HIST_DISCARD, true);
895 
896 	if (Flag(FTALKING) == 0)
897 		return;
898 
899 	hstarted = true;
900 	hist_source = s;
901 
902 #if HAVE_PERSISTENT_HISTORY
903 	hist_persist_init();
904 #endif
905 }
906 
907 #if HAVE_PERSISTENT_HISTORY
908 /*
909  * load the history structure from the stored data
910  */
911 static int
histload(Source * s,unsigned char * base,size_t bytes)912 histload(Source *s, unsigned char *base, size_t bytes)
913 {
914 	int lno = 0, lines = 0;
915 	unsigned char *cp;
916 
917  histload_loop:
918 	/* !bytes check as some systems (older FreeBSDs) have buggy memchr */
919 	if (!bytes || (cp = memchr(base, COMMAND, bytes)) == NULL)
920 		return (lines);
921 	/* advance base pointer past COMMAND byte */
922 	bytes -= ++cp - base;
923 	base = cp;
924 	/* if there is no full string left, don't bother with the rest */
925 	if (bytes < 5 || (cp = memchr(base + 4, '\0', bytes - 4)) == NULL)
926 		return (lines);
927 	/* load the stored line number */
928 	lno = ((base[0] & 0xFF) << 24) | ((base[1] & 0xFF) << 16) |
929 	    ((base[2] & 0xFF) << 8) | (base[3] & 0xFF);
930 	/* store away the found line (@base[4]) */
931 	++lines;
932 	if (histptr >= history && lno - 1 != s->line) {
933 		/* a replacement? */
934 		char **hp;
935 
936 		if (lno >= s->line - (histptr - history) && lno <= s->line) {
937 			hp = &histptr[lno - s->line];
938 			afree(*hp, APERM);
939 			strdupx(*hp, (char *)(base + 4), APERM);
940 		}
941 	} else {
942 		s->line = lno--;
943 		histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
944 	}
945 	/* advance base pointer past NUL */
946 	bytes -= ++cp - base;
947 	base = cp;
948 	/* repeat until no more */
949 	goto histload_loop;
950 }
951 
952 /*
953  * write a command to the end of the history file
954  *
955  * This *MAY* seem easy but it's also necessary to check
956  * that the history file has not changed in size.
957  * If it has - then some other shell has written to it and
958  * we should (re)read those commands to update our history
959  */
960 static void
writehistfile(int lno,const char * cmd)961 writehistfile(int lno, const char *cmd)
962 {
963 	off_t sizenow;
964 	size_t bytes;
965 	unsigned char *base, *news;
966 
967 	mksh_lockfd(histfd);
968 	if ((sizenow = lseek(histfd, (off_t)0, SEEK_END)) < 0)
969 		goto bad;
970 	else if (sizenow < histfsize) {
971 		/* the file has shrunk; trust it just appending the new data */
972 		/* well, for now, anyway… since mksh strdups all into memory */
973 		/* we can use a nicer approach some time later… */
974 		;
975 	} else if (
976 		/* ignore changes when the file is too large */
977 		sizenow <= MKSH_MAXHISTFSIZE
978 	    &&
979 		/* the size has changed, we need to do read updates */
980 		sizenow > histfsize
981 	    ) {
982 		/* both sizenow and histfsize are <= MKSH_MAXHISTFSIZE */
983 		bytes = (size_t)(sizenow - histfsize);
984 		base = (void *)mmap(NULL, (size_t)sizenow, PROT_READ,
985 		    MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
986 		if (base == (unsigned char *)MAP_FAILED)
987 			goto bad;
988 		news = base + (size_t)histfsize;
989 		if (*news == COMMAND) {
990 			hist_source->line--;
991 			histload(hist_source, news, bytes);
992 			hist_source->line++;
993 			lno = hist_source->line;
994 		} else
995 			bytes = 0;
996 		munmap(caddr_cast(base), (size_t)sizenow);
997 		if (!bytes)
998 			goto bad;
999 	}
1000 	if (cmd && !writehistline(histfd, lno, cmd)) {
1001  bad:
1002 		hist_finish();
1003 		return;
1004 	}
1005 	if ((histfsize = lseek(histfd, (off_t)0, SEEK_END)) < 0)
1006 		goto bad;
1007 	mksh_unlkfd(histfd);
1008 }
1009 
1010 static int
writehistline(int fd,int lno,const char * cmd)1011 writehistline(int fd, int lno, const char *cmd)
1012 {
1013 	ssize_t n;
1014 	unsigned char hdr[5];
1015 
1016 	hdr[0] = COMMAND;
1017 	hdr[1] = (lno >> 24) & 0xFF;
1018 	hdr[2] = (lno >> 16) & 0xFF;
1019 	hdr[3] = (lno >> 8) & 0xFF;
1020 	hdr[4] = lno & 0xFF;
1021 	n = strlen(cmd) + 1;
1022 	return (write(fd, hdr, 5) == 5 && write(fd, cmd, n) == n);
1023 }
1024 
1025 void
hist_finish(void)1026 hist_finish(void)
1027 {
1028 	if (histfd >= 0) {
1029 		mksh_unlkfd(histfd);
1030 		(void)close(histfd);
1031 	}
1032 	histfd = -1;
1033 }
1034 #endif
1035 
1036 
1037 #if !HAVE_SYS_SIGNAME
1038 static const struct mksh_sigpair {
1039 	const char * const name;
1040 	int nr;
1041 } mksh_sigpairs[] = {
1042 #include "signames.inc"
1043 	{ NULL, 0 }
1044 };
1045 #endif
1046 
1047 #if HAVE_SYS_SIGLIST
1048 #if !HAVE_SYS_SIGLIST_DECL
1049 extern const char * const sys_siglist[];
1050 #endif
1051 #endif
1052 
1053 void
inittraps(void)1054 inittraps(void)
1055 {
1056 	int i;
1057 	const char *cs;
1058 #if !HAVE_SYS_SIGNAME
1059 	const struct mksh_sigpair *pair;
1060 #endif
1061 
1062 	trap_exstat = -1;
1063 
1064 	/* populate sigtraps based on sys_signame and sys_siglist */
1065 	for (i = 1; i < ksh_NSIG; i++) {
1066 		sigtraps[i].signal = i;
1067 #if HAVE_SYS_SIGNAME
1068 		cs = sys_signame[i];
1069 #else
1070 		pair = mksh_sigpairs;
1071 		while ((pair->nr != i) && (pair->name != NULL))
1072 			++pair;
1073 		cs = pair->name;
1074 #endif
1075 		if ((cs == NULL) ||
1076 		    (cs[0] == '\0'))
1077 			sigtraps[i].name = null;
1078 		else {
1079 			char *s;
1080 
1081 			/* this is not optimal, what about SIGSIG1? */
1082 			if (ksh_eq(cs[0], 'S', 's') &&
1083 			    ksh_eq(cs[1], 'I', 'i') &&
1084 			    ksh_eq(cs[2], 'G', 'g') &&
1085 			    cs[3] != '\0') {
1086 				/* skip leading "SIG" */
1087 				cs += 3;
1088 			}
1089 			strdupx(s, cs, APERM);
1090 			sigtraps[i].name = s;
1091 			while ((*s = ksh_toupper(*s)))
1092 				++s;
1093 			/* check for reserved names */
1094 			if (!strcmp(sigtraps[i].name, "EXIT") ||
1095 			    !strcmp(sigtraps[i].name, "ERR")) {
1096 #ifndef MKSH_SMALL
1097 				internal_warningf(Tinvname, sigtraps[i].name,
1098 				    "signal");
1099 #endif
1100 				sigtraps[i].name = null;
1101 			}
1102 		}
1103 		if (sigtraps[i].name == null)
1104 			sigtraps[i].name = shf_smprintf(Tf_d, i);
1105 #if HAVE_SYS_SIGLIST
1106 		sigtraps[i].mess = sys_siglist[i];
1107 #elif HAVE_STRSIGNAL
1108 		sigtraps[i].mess = strsignal(i);
1109 #else
1110 		sigtraps[i].mess = NULL;
1111 #endif
1112 		if ((sigtraps[i].mess == NULL) ||
1113 		    (sigtraps[i].mess[0] == '\0'))
1114 			sigtraps[i].mess = shf_smprintf(Tf_sd,
1115 			    "Signal", i);
1116 	}
1117 	sigtraps[ksh_SIGEXIT].signal = ksh_SIGEXIT;
1118 	sigtraps[ksh_SIGEXIT].name = "EXIT";
1119 	sigtraps[ksh_SIGEXIT].mess = "Exit trap";
1120 	sigtraps[ksh_SIGERR].signal = ksh_SIGERR;
1121 	sigtraps[ksh_SIGERR].name = "ERR";
1122 	sigtraps[ksh_SIGERR].mess = "Error handler";
1123 
1124 	(void)sigemptyset(&Sigact_ign.sa_mask);
1125 	Sigact_ign.sa_flags = 0; /* interruptible */
1126 	Sigact_ign.sa_handler = SIG_IGN;
1127 
1128 	sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1129 	sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1130 	/* SIGTERM is not fatal for interactive */
1131 	sigtraps[SIGTERM].flags |= TF_DFL_INTR;
1132 	sigtraps[SIGHUP].flags |= TF_FATAL;
1133 	sigtraps[SIGCHLD].flags |= TF_SHELL_USES;
1134 
1135 	/* these are always caught so we can clean up any temporary files. */
1136 	setsig(&sigtraps[SIGINT], trapsig, SS_RESTORE_ORIG);
1137 	setsig(&sigtraps[SIGQUIT], trapsig, SS_RESTORE_ORIG);
1138 	setsig(&sigtraps[SIGTERM], trapsig, SS_RESTORE_ORIG);
1139 	setsig(&sigtraps[SIGHUP], trapsig, SS_RESTORE_ORIG);
1140 }
1141 
1142 static void alarm_catcher(int sig);
1143 
1144 void
alarm_init(void)1145 alarm_init(void)
1146 {
1147 	sigtraps[SIGALRM].flags |= TF_SHELL_USES;
1148 	setsig(&sigtraps[SIGALRM], alarm_catcher,
1149 		SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
1150 }
1151 
1152 /* ARGSUSED */
1153 static void
alarm_catcher(int sig MKSH_A_UNUSED)1154 alarm_catcher(int sig MKSH_A_UNUSED)
1155 {
1156 	/* this runs inside interrupt context, with errno saved */
1157 
1158 	if (ksh_tmout_state == TMOUT_READING) {
1159 		int left = alarm(0);
1160 
1161 		if (left == 0) {
1162 			ksh_tmout_state = TMOUT_LEAVING;
1163 			intrsig = 1;
1164 		} else
1165 			alarm(left);
1166 	}
1167 }
1168 
1169 Trap *
gettrap(const char * cs,bool igncase,bool allsigs)1170 gettrap(const char *cs, bool igncase, bool allsigs)
1171 {
1172 	int i;
1173 	Trap *p;
1174 	char *as;
1175 
1176 	/* signal number (1..ksh_NSIG) or 0? */
1177 
1178 	if (ctype(*cs, C_DIGIT))
1179 		return ((getn(cs, &i) && 0 <= i && i < ksh_NSIG) ?
1180 		    (&sigtraps[i]) : NULL);
1181 
1182 	/* do a lookup by name then */
1183 
1184 	/* this breaks SIGSIG1, but we do that above anyway */
1185 	if (ksh_eq(cs[0], 'S', 's') &&
1186 	    ksh_eq(cs[1], 'I', 'i') &&
1187 	    ksh_eq(cs[2], 'G', 'g') &&
1188 	    cs[3] != '\0') {
1189 		/* skip leading "SIG" */
1190 		cs += 3;
1191 	}
1192 	if (igncase) {
1193 		char *s;
1194 
1195 		strdupx(as, cs, ATEMP);
1196 		cs = s = as;
1197 		while ((*s = ksh_toupper(*s)))
1198 			++s;
1199 	} else
1200 		as = NULL;
1201 
1202 	/* this is idiotic, we really want a hashtable here */
1203 
1204 	p = sigtraps;
1205 	i = ksh_NSIG + 1;
1206 	do {
1207 		if (!strcmp(p->name, cs))
1208 			goto found;
1209 		++p;
1210 	} while (--i);
1211 	goto notfound;
1212 
1213  found:
1214 	if (!allsigs) {
1215 		if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR) {
1216  notfound:
1217 			p = NULL;
1218 		}
1219 	}
1220 	afree(as, ATEMP);
1221 	return (p);
1222 }
1223 
1224 /*
1225  * trap signal handler
1226  */
1227 void
trapsig(int i)1228 trapsig(int i)
1229 {
1230 	Trap *p = &sigtraps[i];
1231 	int eno = errno;
1232 
1233 	trap = p->set = 1;
1234 	if (p->flags & TF_DFL_INTR)
1235 		intrsig = 1;
1236 	if ((p->flags & TF_FATAL) && !p->trap) {
1237 		fatal_trap = 1;
1238 		intrsig = 1;
1239 	}
1240 	if (p->shtrap)
1241 		(*p->shtrap)(i);
1242 	errno = eno;
1243 }
1244 
1245 /*
1246  * called when we want to allow the user to ^C out of something - won't
1247  * work if user has trapped SIGINT.
1248  */
1249 void
intrcheck(void)1250 intrcheck(void)
1251 {
1252 	if (intrsig)
1253 		runtraps(TF_DFL_INTR|TF_FATAL);
1254 }
1255 
1256 /*
1257  * called after EINTR to check if a signal with normally causes process
1258  * termination has been received.
1259  */
1260 int
fatal_trap_check(void)1261 fatal_trap_check(void)
1262 {
1263 	Trap *p = sigtraps;
1264 	int i = ksh_NSIG + 1;
1265 
1266 	/* todo: should check if signal is fatal, not the TF_DFL_INTR flag */
1267 	do {
1268 		if (p->set && (p->flags & (TF_DFL_INTR|TF_FATAL)))
1269 			/* return value is used as an exit code */
1270 			return (ksh_sigmask(p->signal));
1271 		++p;
1272 	} while (--i);
1273 	return (0);
1274 }
1275 
1276 /*
1277  * Returns the signal number of any pending traps: ie, a signal which has
1278  * occurred for which a trap has been set or for which the TF_DFL_INTR flag
1279  * is set.
1280  */
1281 int
trap_pending(void)1282 trap_pending(void)
1283 {
1284 	Trap *p = sigtraps;
1285 	int i = ksh_NSIG + 1;
1286 
1287 	do {
1288 		if (p->set && ((p->trap && p->trap[0]) ||
1289 		    ((p->flags & (TF_DFL_INTR|TF_FATAL)) && !p->trap)))
1290 			return (p->signal);
1291 		++p;
1292 	} while (--i);
1293 	return (0);
1294 }
1295 
1296 /*
1297  * run any pending traps. If intr is set, only run traps that
1298  * can interrupt commands.
1299  */
1300 void
runtraps(int flag)1301 runtraps(int flag)
1302 {
1303 	Trap *p = sigtraps;
1304 	int i = ksh_NSIG + 1;
1305 
1306 	if (ksh_tmout_state == TMOUT_LEAVING) {
1307 		ksh_tmout_state = TMOUT_EXECUTING;
1308 		warningf(false, "timed out waiting for input");
1309 		unwind(LEXIT);
1310 	} else
1311 		/*
1312 		 * XXX: this means the alarm will have no effect if a trap
1313 		 * is caught after the alarm() was started...not good.
1314 		 */
1315 		ksh_tmout_state = TMOUT_EXECUTING;
1316 	if (!flag)
1317 		trap = 0;
1318 	if (flag & TF_DFL_INTR)
1319 		intrsig = 0;
1320 	if (flag & TF_FATAL)
1321 		fatal_trap = 0;
1322 	++trap_nested;
1323 	do {
1324 		if (p->set && (!flag ||
1325 		    ((p->flags & flag) && p->trap == NULL)))
1326 			runtrap(p, false);
1327 		++p;
1328 	} while (--i);
1329 	if (!--trap_nested)
1330 		runtrap(NULL, true);
1331 }
1332 
1333 void
runtrap(Trap * p,bool is_last)1334 runtrap(Trap *p, bool is_last)
1335 {
1336 	int old_changed = 0, i;
1337 	char *trapstr;
1338 
1339 	if (p == NULL)
1340 		/* just clean up, see runtraps() above */
1341 		goto donetrap;
1342 	i = p->signal;
1343 	trapstr = p->trap;
1344 	p->set = 0;
1345 	if (trapstr == NULL) {
1346 		/* SIG_DFL */
1347 		if (p->flags & (TF_FATAL | TF_DFL_INTR)) {
1348 			exstat = (int)(128U + (unsigned)i);
1349 			if ((unsigned)exstat > 255U)
1350 				exstat = 255;
1351 		}
1352 		/* e.g. SIGHUP */
1353 		if (p->flags & TF_FATAL)
1354 			unwind(LLEAVE);
1355 		/* e.g. SIGINT, SIGQUIT, SIGTERM, etc. */
1356 		if (p->flags & TF_DFL_INTR)
1357 			unwind(LINTR);
1358 		goto donetrap;
1359 	}
1360 	if (trapstr[0] == '\0')
1361 		/* SIG_IGN */
1362 		goto donetrap;
1363 	if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1364 		/* avoid recursion on these */
1365 		old_changed = p->flags & TF_CHANGED;
1366 		p->flags &= ~TF_CHANGED;
1367 		p->trap = NULL;
1368 	}
1369 	if (trap_exstat == -1)
1370 		trap_exstat = exstat & 0xFF;
1371 	/*
1372 	 * Note: trapstr is fully parsed before anything is executed, thus
1373 	 * no problem with afree(p->trap) in settrap() while still in use.
1374 	 */
1375 	command(trapstr, current_lineno);
1376 	if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1377 		if (p->flags & TF_CHANGED)
1378 			/* don't clear TF_CHANGED */
1379 			afree(trapstr, APERM);
1380 		else
1381 			p->trap = trapstr;
1382 		p->flags |= old_changed;
1383 	}
1384 
1385  donetrap:
1386 	/* we're the last trap of a sequence executed */
1387 	if (is_last && trap_exstat != -1) {
1388 		exstat = trap_exstat;
1389 		trap_exstat = -1;
1390 	}
1391 }
1392 
1393 /* clear pending traps and reset user's trap handlers; used after fork(2) */
1394 void
cleartraps(void)1395 cleartraps(void)
1396 {
1397 	Trap *p = sigtraps;
1398 	int i = ksh_NSIG + 1;
1399 
1400 	trap = 0;
1401 	intrsig = 0;
1402 	fatal_trap = 0;
1403 
1404 	do {
1405 		p->set = 0;
1406 		if ((p->flags & TF_USER_SET) && (p->trap && p->trap[0]))
1407 			settrap(p, NULL);
1408 		++p;
1409 	} while (--i);
1410 }
1411 
1412 /* restore signals just before an exec(2) */
1413 void
restoresigs(void)1414 restoresigs(void)
1415 {
1416 	Trap *p = sigtraps;
1417 	int i = ksh_NSIG + 1;
1418 
1419 	do {
1420 		if (p->flags & (TF_EXEC_IGN|TF_EXEC_DFL))
1421 			setsig(p, (p->flags & TF_EXEC_IGN) ? SIG_IGN : SIG_DFL,
1422 			    SS_RESTORE_CURR|SS_FORCE);
1423 		++p;
1424 	} while (--i);
1425 }
1426 
1427 void
settrap(Trap * p,const char * s)1428 settrap(Trap *p, const char *s)
1429 {
1430 	sig_t f;
1431 
1432 	afree(p->trap, APERM);
1433 	/* handles s == NULL */
1434 	strdupx(p->trap, s, APERM);
1435 	p->flags |= TF_CHANGED;
1436 	f = !s ? SIG_DFL : s[0] ? trapsig : SIG_IGN;
1437 
1438 	p->flags |= TF_USER_SET;
1439 	if ((p->flags & (TF_DFL_INTR|TF_FATAL)) && f == SIG_DFL)
1440 		f = trapsig;
1441 	else if (p->flags & TF_SHELL_USES) {
1442 		if (!(p->flags & TF_ORIG_IGN) || Flag(FTALKING)) {
1443 			/* do what user wants at exec time */
1444 			p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1445 			if (f == SIG_IGN)
1446 				p->flags |= TF_EXEC_IGN;
1447 			else
1448 				p->flags |= TF_EXEC_DFL;
1449 		}
1450 
1451 		/*
1452 		 * assumes handler already set to what shell wants it
1453 		 * (normally trapsig, but could be j_sigchld() or SIG_IGN)
1454 		 */
1455 		return;
1456 	}
1457 
1458 	/* todo: should we let user know signal is ignored? how? */
1459 	setsig(p, f, SS_RESTORE_CURR|SS_USER);
1460 }
1461 
1462 /*
1463  * called by c_print() when writing to a co-process to ensure
1464  * SIGPIPE won't kill shell (unless user catches it and exits)
1465  */
1466 bool
block_pipe(void)1467 block_pipe(void)
1468 {
1469 	bool restore_dfl = false;
1470 	Trap *p = &sigtraps[SIGPIPE];
1471 
1472 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1473 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
1474 		if (p->flags & TF_ORIG_DFL)
1475 			restore_dfl = true;
1476 	} else if (p->cursig == SIG_DFL) {
1477 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
1478 		/* restore to SIG_DFL */
1479 		restore_dfl = true;
1480 	}
1481 	return (restore_dfl);
1482 }
1483 
1484 /* called by c_print() to undo whatever block_pipe() did */
1485 void
restore_pipe(void)1486 restore_pipe(void)
1487 {
1488 	setsig(&sigtraps[SIGPIPE], SIG_DFL, SS_RESTORE_CURR);
1489 }
1490 
1491 /*
1492  * Set action for a signal. Action may not be set if original
1493  * action was SIG_IGN, depending on the value of flags and FTALKING.
1494  */
1495 int
setsig(Trap * p,sig_t f,int flags)1496 setsig(Trap *p, sig_t f, int flags)
1497 {
1498 	struct sigaction sigact;
1499 
1500 	if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
1501 		return (1);
1502 
1503 	memset(&sigact, 0, sizeof(sigact));
1504 
1505 	/*
1506 	 * First time setting this signal? If so, get and note the current
1507 	 * setting.
1508 	 */
1509 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1510 		sigaction(p->signal, &Sigact_ign, &sigact);
1511 		p->flags |= sigact.sa_handler == SIG_IGN ?
1512 		    TF_ORIG_IGN : TF_ORIG_DFL;
1513 		p->cursig = SIG_IGN;
1514 	}
1515 
1516 	/*-
1517 	 * Generally, an ignored signal stays ignored, except if
1518 	 *	- the user of an interactive shell wants to change it
1519 	 *	- the shell wants for force a change
1520 	 */
1521 	if ((p->flags & TF_ORIG_IGN) && !(flags & SS_FORCE) &&
1522 	    (!(flags & SS_USER) || !Flag(FTALKING)))
1523 		return (0);
1524 
1525 	setexecsig(p, flags & SS_RESTORE_MASK);
1526 
1527 	/*
1528 	 * This is here 'cause there should be a way of clearing
1529 	 * shtraps, but don't know if this is a sane way of doing
1530 	 * it. At the moment, all users of shtrap are lifetime
1531 	 * users (SIGALRM, SIGCHLD, SIGWINCH).
1532 	 */
1533 	if (!(flags & SS_USER))
1534 		p->shtrap = (sig_t)NULL;
1535 	if (flags & SS_SHTRAP) {
1536 		p->shtrap = f;
1537 		f = trapsig;
1538 	}
1539 
1540 	if (p->cursig != f) {
1541 		p->cursig = f;
1542 		(void)sigemptyset(&sigact.sa_mask);
1543 		/* interruptible */
1544 		sigact.sa_flags = 0;
1545 		sigact.sa_handler = f;
1546 		sigaction(p->signal, &sigact, NULL);
1547 	}
1548 
1549 	return (1);
1550 }
1551 
1552 /* control what signal is set to before an exec() */
1553 void
setexecsig(Trap * p,int restore)1554 setexecsig(Trap *p, int restore)
1555 {
1556 	/* XXX debugging */
1557 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
1558 		internal_errorf("setexecsig: unset signal %d(%s)",
1559 		    p->signal, p->name);
1560 
1561 	/* restore original value for exec'd kids */
1562 	p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1563 	switch (restore & SS_RESTORE_MASK) {
1564 	case SS_RESTORE_CURR:
1565 		/* leave things as they currently are */
1566 		break;
1567 	case SS_RESTORE_ORIG:
1568 		p->flags |= p->flags & TF_ORIG_IGN ? TF_EXEC_IGN : TF_EXEC_DFL;
1569 		break;
1570 	case SS_RESTORE_DFL:
1571 		p->flags |= TF_EXEC_DFL;
1572 		break;
1573 	case SS_RESTORE_IGN:
1574 		p->flags |= TF_EXEC_IGN;
1575 		break;
1576 	}
1577 }
1578 
1579 #if HAVE_PERSISTENT_HISTORY || defined(DF)
1580 /*
1581  * File descriptor locking and unlocking functions.
1582  * Could use some error handling, but hey, this is only
1583  * advisory locking anyway, will often not work over NFS,
1584  * and you are SOL if this fails...
1585  */
1586 
1587 void
mksh_lockfd(int fd)1588 mksh_lockfd(int fd)
1589 {
1590 #if defined(__OpenBSD__)
1591 	/* flock is not interrupted by signals */
1592 	(void)flock(fd, LOCK_EX);
1593 #elif HAVE_FLOCK
1594 	int rv;
1595 
1596 	/* e.g. on Linux */
1597 	do {
1598 		rv = flock(fd, LOCK_EX);
1599 	} while (rv == 1 && errno == EINTR);
1600 #elif HAVE_LOCK_FCNTL
1601 	int rv;
1602 	struct flock lks;
1603 
1604 	memset(&lks, 0, sizeof(lks));
1605 	lks.l_type = F_WRLCK;
1606 	do {
1607 		rv = fcntl(fd, F_SETLKW, &lks);
1608 	} while (rv == 1 && errno == EINTR);
1609 #endif
1610 }
1611 
1612 /* designed to not define mksh_unlkfd if none triggered */
1613 #if HAVE_FLOCK
1614 void
mksh_unlkfd(int fd)1615 mksh_unlkfd(int fd)
1616 {
1617 	(void)flock(fd, LOCK_UN);
1618 }
1619 #elif HAVE_LOCK_FCNTL
1620 void
mksh_unlkfd(int fd)1621 mksh_unlkfd(int fd)
1622 {
1623 	struct flock lks;
1624 
1625 	memset(&lks, 0, sizeof(lks));
1626 	lks.l_type = F_UNLCK;
1627 	(void)fcntl(fd, F_SETLKW, &lks);
1628 }
1629 #endif
1630 #endif
1631