blob: 26dd5215d976c44d63dbbf0bbd607a1d860d361e [file] [log] [blame]
Elliott Hughesfc0307d2016-02-02 15:26:47 -08001/* $OpenBSD: history.c,v 1.41 2015/09/01 13:12:31 tedu Exp $ */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07002/* $OpenBSD: trap.c,v 1.23 2010/05/19 17:36:08 jasper Exp $ */
3
4/*-
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00005 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
Elliott Hughesfc0307d2016-02-02 15:26:47 -08006 * 2011, 2012, 2014, 2015, 2016
7 * mirabilos <m@mirbsd.org>
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07008 *
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"
Geremy Condra03ebf062011-10-12 18:17:24 -070026#if HAVE_SYS_FILE_H
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070027#include <sys/file.h>
28#endif
29
Elliott Hughesa3c3f962017-04-12 16:52:30 -070030__RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.160 2017/04/08 01:07:16 tg Exp $");
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070031
Elliott Hughes96b43632015-07-17 11:39:41 -070032Trap sigtraps[ksh_NSIG + 1];
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070033static struct sigaction Sigact_ign;
34
35#if HAVE_PERSISTENT_HISTORY
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000036static int histload(Source *, unsigned char *, size_t);
37static int writehistline(int, int, const char *);
38static void writehistfile(int, const char *);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070039#endif
40
Elliott Hughes96b43632015-07-17 11:39:41 -070041static int hist_execute(char *, Area *);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070042static char **hist_get(const char *, bool, bool);
43static char **hist_get_oldest(void);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070044
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000045static bool hstarted; /* set after hist_init() called */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070046static Source *hist_source;
47
48#if HAVE_PERSISTENT_HISTORY
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000049/*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
Geremy Condra03ebf062011-10-12 18:17:24 -070066/* current history file: name, fd, size */
67static char *hname;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000068static int histfd = -1;
69static off_t histfsize;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070070#endif
71
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000072/* 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
Elliott Hughes96b43632015-07-17 11:39:41 -070081/* hidden option */
82#define HIST_DISCARD 5
83
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070084int
85c_fc(const char **wp)
86{
87 struct shf *shf;
88 struct temp *tf;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070089 bool gflag = false, lflag = false, nflag = false, rflag = false,
90 sflag = false;
91 int optc;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000092 const char *p, *first = NULL, *last = NULL;
93 char **hfirst, **hlast, **hp, *editor = NULL;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070094
95 if (!Flag(FTALKING_I)) {
Geremy Condra03ebf062011-10-12 18:17:24 -070096 bi_errorf("history %ss not available", Tfunction);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070097 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) {
Geremy Condra03ebf062011-10-12 18:17:24 -0700103
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700104 case 'e':
105 p = builtin_opt.optarg;
106 if (ksh_isdash(p))
107 sflag = true;
108 else {
109 size_t len = strlen(p);
Geremy Condra03ebf062011-10-12 18:17:24 -0700110
111 /* almost certainly not overflowing */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700112 editor = alloc(len + 4, ATEMP);
113 memcpy(editor, p, len);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000114 memcpy(editor + len, Tspdollaru, 4);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700115 }
116 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700117
118 /* non-AT&T ksh */
119 case 'g':
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700120 gflag = true;
121 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700122
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700123 case 'l':
124 lflag = true;
125 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700126
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700127 case 'n':
128 nflag = true;
129 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700130
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700131 case 'r':
132 rflag = true;
133 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700134
135 /* POSIX version of -e - */
136 case 's':
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700137 sflag = true;
138 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700139
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700140 /* 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 {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700150 bi_errorf(Ttoo_many_args);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700151 return (1);
152 }
153 break;
Geremy Condra03ebf062011-10-12 18:17:24 -0700154
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700155 case '?':
156 return (1);
157 }
158 wp += builtin_opt.optind;
159
160 /* Substitute and execute command */
161 if (sflag) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000162 char *pat = NULL, *rep = NULL, *line;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700163
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) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700180 bi_errorf(Ttoo_many_args);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700181 return (1);
182 }
183
184 hp = first ? hist_get(first, false, false) :
185 hist_get_newest(false);
186 if (!hp)
187 return (1);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000188 /* 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) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700214 bi_errorf(Tbadsubst);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000215 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 }
Elliott Hughes96b43632015-07-17 11:39:41 -0700223 return (hist_execute(line, ATEMP));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700224 }
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) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700236 bi_errorf(Ttoo_many_args);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700237 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 {
Geremy Condra03ebf062011-10-12 18:17:24 -0700247 /*
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.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700251 */
Geremy Condra03ebf062011-10-12 18:17:24 -0700252 hfirst = hist_get(first, tobool(lflag || last), lflag);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700253 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;
Geremy Condra03ebf062011-10-12 18:17:24 -0700264 /* POSIX */
265 rflag = !rflag;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700266 }
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)
Elliott Hughes77740fc2016-08-12 15:06:53 -0700275 shf_fprintf(shl_stdout, Tf_lu,
Elliott Hughesb27ce952015-04-21 13:39:18 -0700276 (unsigned long)hist_source->line -
277 (unsigned long)(histptr - hp));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700278 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 }
Elliott Hughes77740fc2016-08-12 15:06:53 -0700287 shf_fprintf(shl_stdout, Tf_sN, s);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700288 }
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)) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700297 bi_errorf(Tf_temp, Tcreate, tf->tffn, cstrerror(errno));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700298 return (1);
299 }
300 for (hp = rflag ? hlast : hfirst;
301 hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1)
Elliott Hughes77740fc2016-08-12 15:06:53 -0700302 shf_fprintf(shf, Tf_sN, *hp);
Elliott Hughes50012062015-03-10 22:22:24 -0700303 if (shf_close(shf) == -1) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700304 bi_errorf(Tf_temp, Twrite, tf->tffn, cstrerror(errno));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700305 return (1);
306 }
307
308 /* Ignore setstr errors here (arbitrary) */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000309 setstr(local("_", false), tf->tffn, KSH_RETURN_ERROR);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700310
Elliott Hughes77740fc2016-08-12 15:06:53 -0700311 if ((optc = command(editor ? editor : TFCEDIT_dollaru, 0)))
312 return (optc);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700313
314 {
315 struct stat statb;
316 XString xs;
317 char *xp;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000318 ssize_t n;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700319
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000320 if (!(shf = shf_open(tf->tffn, O_RDONLY, 0, 0))) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700321 bi_errorf(Tf_temp, Topen, tf->tffn, cstrerror(errno));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700322 return (1);
323 }
324
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000325 if (stat(tf->tffn, &statb) < 0)
Geremy Condra03ebf062011-10-12 18:17:24 -0700326 n = 128;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000327 else if ((off_t)statb.st_size > MKSH_MAXHISTFSIZE) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700328 bi_errorf(Tf_toolarge, Thistory,
329 Tfile, (unsigned long)statb.st_size);
Geremy Condra03ebf062011-10-12 18:17:24 -0700330 goto errout;
331 } else
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000332 n = (size_t)statb.st_size + 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700333 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) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700340 bi_errorf(Tf_temp, Tread, tf->tffn,
341 cstrerror(shf_errno(shf)));
Geremy Condra03ebf062011-10-12 18:17:24 -0700342 errout:
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700343 shf_close(shf);
344 return (1);
345 }
346 shf_close(shf);
347 *xp = '\0';
348 strip_nuls(Xstring(xs, xp), Xlength(xs, xp));
Elliott Hughes96b43632015-07-17 11:39:41 -0700349 return (hist_execute(Xstring(xs, xp), hist_source->areap));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700350 }
351}
352
Elliott Hughes96b43632015-07-17 11:39:41 -0700353/* save cmd in history, execute cmd (cmd gets afree’d) */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700354static int
Elliott Hughes96b43632015-07-17 11:39:41 -0700355hist_execute(char *cmd, Area *areap)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700356{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000357 static int last_line = -1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700358
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000359 /* 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 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700366
Elliott Hughes96b43632015-07-17 11:39:41 -0700367 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 */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700372 shellf(Tf_sN, cmd);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700373
Geremy Condra03ebf062011-10-12 18:17:24 -0700374 /*-
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700375 * 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 */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700381 return (command(cmd, 0));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700382}
383
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700384/*
385 * get pointer to history given pattern
386 * pattern is a number or string
387 */
388static char **
389hist_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));
Elliott Hughes50012062015-03-10 22:22:24 -0700396 if ((size_t)hp < (size_t)history) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700397 if (approx)
398 hp = hist_get_oldest();
399 else {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700400 bi_errorf(Tf_sD_s, str, Tnot_in_history);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700401 hp = NULL;
402 }
Elliott Hughes50012062015-03-10 22:22:24 -0700403 } else if ((size_t)hp > (size_t)histptr) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700404 if (approx)
405 hp = hist_get_newest(allow_cur);
406 else {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700407 bi_errorf(Tf_sD_s, str, Tnot_in_history);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700408 hp = NULL;
409 }
410 } else if (!allow_cur && hp == histptr) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700411 bi_errorf(Tf_sD_s, str, "invalid range");
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700412 hp = NULL;
413 }
414 } else {
Elliott Hughes737fdce2014-08-07 12:59:26 -0700415 bool anchored = *str == '?' ? (++str, false) : true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700416
417 /* the -1 is to avoid the current fc command */
418 if ((n = findhist(histptr - history - 1, 0, str, anchored)) < 0)
Elliott Hughes77740fc2016-08-12 15:06:53 -0700419 bi_errorf(Tf_sD_s, str, Tnot_in_history);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700420 else
421 hp = &history[n];
422 }
423 return (hp);
424}
425
426/* Return a pointer to the newest command in the history */
427char **
428hist_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 */
438static char **
439hist_get_oldest(void)
440{
441 if (histptr <= history) {
442 bi_errorf("no history (yet)");
443 return (NULL);
444 }
445 return (history);
446}
447
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000448#if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
449/* current position in history[] */
450static char **current;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700451
452/*
453 * Return the current position.
454 */
455char **
456histpos(void)
457{
458 return (current);
459}
460
461int
462histnum(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}
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000474#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700475
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 */
481int
Elliott Hughes737fdce2014-08-07 12:59:26 -0700482findhist(int start, int fwd, const char *str, bool anchored)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700483{
Geremy Condra03ebf062011-10-12 18:17:24 -0700484 char **hp;
485 int maxhist = histptr - history;
486 int incr = fwd ? 1 : -1;
487 size_t len = strlen(str);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700488
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
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700501/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000502 * set history; this means reallocating the dataspace
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700503 */
504void
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000505sethistsize(mksh_ari_t n)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700506{
507 if (n > 0 && n != histsize) {
508 int cursize = histptr - history;
509
510 /* save most recent history */
511 if (n < cursize) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000512 memmove(history, histptr - n + 1, n * sizeof(char *));
513 cursize = n - 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700514 }
515
Geremy Condra03ebf062011-10-12 18:17:24 -0700516 history = aresize2(history, n, sizeof(char *), APERM);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700517
518 histsize = n;
519 histptr = history + cursize;
520 }
521}
522
523#if HAVE_PERSISTENT_HISTORY
524/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000525 * set history file; this can mean reloading/resetting/starting
526 * history file maintenance
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700527 */
528void
529sethistfile(const char *name)
530{
531 /* if not started then nothing to do */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000532 if (hstarted == false)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700533 return;
534
535 /* if the name is the same as the name we have */
Elliott Hughesb27ce952015-04-21 13:39:18 -0700536 if (hname && name && !strcmp(hname, name))
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700537 return;
538
539 /*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000540 * it's a new name - possibly
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700541 */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000542 if (histfd != -1) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700543 /* yes the file is open */
544 (void)close(histfd);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000545 histfd = -1;
546 histfsize = 0;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700547 afree(hname, APERM);
548 hname = NULL;
549 /* let's reset the history */
Elliott Hughes96b43632015-07-17 11:39:41 -0700550 histsave(NULL, NULL, HIST_DISCARD, true);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700551 histptr = history - 1;
552 hist_source->line = 0;
553 }
554
Elliott Hughesb27ce952015-04-21 13:39:18 -0700555 if (name)
556 hist_init(hist_source);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700557}
558#endif
559
560/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000561 * initialise the history vector
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700562 */
563void
564init_histvec(void)
565{
566 if (history == (char **)NULL) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000567 histsize = MKSH_DEFHISTSIZE;
Geremy Condra03ebf062011-10-12 18:17:24 -0700568 history = alloc2(histsize, sizeof(char *), APERM);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700569 histptr = history - 1;
570 }
571}
572
573
574/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000575 * It turns out that there is a lot of ghastly hackery here
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700576 */
577
578#if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
579/* do not save command in history but possibly sync */
580bool
581histsync(void)
582{
583 bool changed = false;
584
Elliott Hughes96b43632015-07-17 11:39:41 -0700585 /* called by histsave(), may not HIST_DISCARD, caller should flush */
586
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000587 if (histfd != -1) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700588 int lno = hist_source->line;
589
590 hist_source->line++;
591 writehistfile(0, NULL);
592 hist_source->line--;
593
594 if (lno != hist_source->line)
595 changed = true;
596 }
597
598 return (changed);
599}
600#endif
601
602/*
603 * save command in history
604 */
605void
Elliott Hughes96b43632015-07-17 11:39:41 -0700606histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700607{
Elliott Hughes96b43632015-07-17 11:39:41 -0700608 static char *enqueued = NULL;
609 char **hp, *c;
610 const char *ccp;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700611
Elliott Hughes96b43632015-07-17 11:39:41 -0700612 if (svmode == HIST_DISCARD) {
613 afree(enqueued, APERM);
614 enqueued = NULL;
615 return;
616 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700617
Elliott Hughes96b43632015-07-17 11:39:41 -0700618 if (svmode == HIST_APPEND) {
619 if (!enqueued)
620 svmode = HIST_STORE;
621 } else if (enqueued) {
622 c = enqueued;
623 enqueued = NULL;
624 --*lnp;
625 histsave(lnp, c, HIST_STORE, true);
626 afree(c, APERM);
627 }
628
629 if (svmode == HIST_FLUSH)
630 return;
631
632 ccp = cmd + strlen(cmd);
633 while (ccp > cmd && ccp[-1] == '\n')
634 --ccp;
635 strndupx(c, cmd, ccp - cmd, APERM);
636
637 if (svmode != HIST_APPEND) {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700638 if (ignoredups &&
639 histptr >= history &&
640 !strcmp(c, *histptr)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700641#if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
Elliott Hughes96b43632015-07-17 11:39:41 -0700642 && !histsync()
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700643#endif
Elliott Hughes96b43632015-07-17 11:39:41 -0700644 ) {
645 afree(c, APERM);
646 return;
647 }
648 ++*lnp;
649 }
650
651#if HAVE_PERSISTENT_HISTORY
652 if (svmode == HIST_STORE && histfd != -1)
653 writehistfile(*lnp, c);
654#endif
655
656 if (svmode == HIST_QUEUE || svmode == HIST_APPEND) {
657 size_t nenq, ncmd;
658
659 if (!enqueued) {
660 if (*c)
661 enqueued = c;
662 else
663 afree(c, APERM);
664 return;
665 }
666
667 nenq = strlen(enqueued);
668 ncmd = strlen(c);
669 enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
670 enqueued[nenq] = '\n';
671 memcpy(enqueued + nenq + 1, c, ncmd + 1);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700672 afree(c, APERM);
673 return;
674 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700675
676 hp = histptr;
677
Geremy Condra03ebf062011-10-12 18:17:24 -0700678 if (++hp >= history + histsize) {
679 /* remove oldest command */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700680 afree(*history, APERM);
681 for (hp = history; hp < history + histsize - 1; hp++)
682 hp[0] = hp[1];
683 }
684 *hp = c;
685 histptr = hp;
686}
687
688/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000689 * Write history data to a file nominated by HISTFILE;
690 * if HISTFILE is unset then history still happens, but
691 * the data is not written to a file. All copies of ksh
692 * looking at the file will maintain the same history.
693 * This is ksh behaviour.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700694 *
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000695 * This stuff uses mmap()
696 *
697 * This stuff is so totally broken it must eventually be
698 * redesigned, without mmap, better checks, support for
699 * larger files, etc. and handle partially corrupted files
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700700 */
701
Geremy Condra03ebf062011-10-12 18:17:24 -0700702/*-
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000703 * Open a history file
704 * Format is:
705 * Bytes 1, 2:
706 * HMAGIC - just to check that we are dealing with the correct object
707 * Then follows a number of stored commands
708 * Each command is
709 * <command byte><command number(4 octets, big endian)><bytes><NUL>
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700710 */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000711#define HMAGIC1 0xAB
712#define HMAGIC2 0xCD
713#define COMMAND 0xFF
714
715#if HAVE_PERSISTENT_HISTORY
716static const unsigned char sprinkle[2] = { HMAGIC1, HMAGIC2 };
717#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700718
719void
720hist_init(Source *s)
721{
722#if HAVE_PERSISTENT_HISTORY
723 unsigned char *base;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000724 int lines, fd;
725 enum { hist_init_first, hist_init_retry, hist_init_restore } hs;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700726#endif
727
Elliott Hughes96b43632015-07-17 11:39:41 -0700728 histsave(NULL, NULL, HIST_DISCARD, true);
729
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700730 if (Flag(FTALKING) == 0)
731 return;
732
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000733 hstarted = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700734 hist_source = s;
735
736#if HAVE_PERSISTENT_HISTORY
Elliott Hughesb27ce952015-04-21 13:39:18 -0700737 if (((hname = str_val(global("HISTFILE"))) == NULL) || !*hname) {
738 hname = NULL;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700739 return;
Elliott Hughesb27ce952015-04-21 13:39:18 -0700740 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700741 strdupx(hname, hname, APERM);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000742 hs = hist_init_first;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700743
744 retry:
745 /* we have a file and are interactive */
Elliott Hughes96b43632015-07-17 11:39:41 -0700746 if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700747 return;
748
749 histfd = savefd(fd);
750 if (histfd != fd)
751 close(fd);
752
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000753 mksh_lockfd(histfd);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700754
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000755 histfsize = lseek(histfd, (off_t)0, SEEK_END);
756 if (histfsize > MKSH_MAXHISTFSIZE || hs == hist_init_restore) {
757 /* we ignore too large files but still append to them */
758 /* we also don't need to re-read after truncation */
759 goto hist_init_tail;
760 } else if (histfsize > 2) {
761 /* we have some data, check its validity */
762 base = (void *)mmap(NULL, (size_t)histfsize, PROT_READ,
763 MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
764 if (base == (unsigned char *)MAP_FAILED)
765 goto hist_init_fail;
766 if (base[0] != HMAGIC1 || base[1] != HMAGIC2) {
767 munmap(caddr_cast(base), (size_t)histfsize);
768 goto hist_init_fail;
769 }
770 /* load _all_ data */
771 lines = histload(hist_source, base + 2, (size_t)histfsize - 2);
772 munmap(caddr_cast(base), (size_t)histfsize);
773 /* check if the file needs to be truncated */
774 if (lines > histsize && histptr >= history) {
775 /* you're fucked up with the current code, trust me */
776 char *nhname, **hp;
777 struct stat sb;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700778
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000779 /* create temporary file */
780 nhname = shf_smprintf("%s.%d", hname, (int)procpid);
Elliott Hughes96b43632015-07-17 11:39:41 -0700781 if ((fd = binopen3(nhname, O_RDWR | O_CREAT | O_TRUNC |
782 O_EXCL, 0600)) < 0) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000783 /* just don't truncate then, meh. */
784 goto hist_trunc_dont;
785 }
786 if (fstat(histfd, &sb) >= 0 &&
787 chown(nhname, sb.st_uid, sb.st_gid)) {
788 /* abort the truncation then, meh. */
789 goto hist_trunc_abort;
790 }
791 /* we definitively want some magic in that file */
792 if (write(fd, sprinkle, 2) != 2)
793 goto hist_trunc_abort;
794 /* and of course the entries */
795 hp = history;
796 while (hp < histptr) {
797 if (!writehistline(fd,
798 s->line - (histptr - hp), *hp))
799 goto hist_trunc_abort;
800 ++hp;
801 }
802 /* now unlock, close both, rename, rinse, repeat */
803 close(fd);
804 fd = -1;
805 hist_finish();
806 if (rename(nhname, hname) < 0) {
807 hist_trunc_abort:
808 if (fd != -1)
809 close(fd);
810 unlink(nhname);
811 if (fd != -1)
812 goto hist_trunc_dont;
813 /* darn! restore histfd and pray */
814 }
815 hs = hist_init_restore;
816 hist_trunc_dont:
817 afree(nhname, ATEMP);
818 if (hs == hist_init_restore)
819 goto retry;
820 }
821 } else if (histfsize != 0) {
822 /* negative or too small... */
823 hist_init_fail:
824 /* ... or mmap failed or illegal */
825 hist_finish();
826 /* nuke the bogus file then retry, at most once */
827 if (!unlink(hname) && hs != hist_init_retry) {
828 hs = hist_init_retry;
829 goto retry;
830 }
831 if (hs != hist_init_retry)
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700832 bi_errorf(Tf_cant_ss_s,
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000833 "unlink HISTFILE", hname, cstrerror(errno));
834 histfsize = 0;
835 return;
836 } else {
837 /* size 0, add magic to the history file */
838 if (write(histfd, sprinkle, 2) != 2) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700839 hist_finish();
840 return;
841 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700842 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000843 histfsize = lseek(histfd, (off_t)0, SEEK_END);
844 hist_init_tail:
845 mksh_unlkfd(histfd);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700846#endif
847}
848
849#if HAVE_PERSISTENT_HISTORY
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700850/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000851 * load the history structure from the stored data
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700852 */
853static int
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000854histload(Source *s, unsigned char *base, size_t bytes)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700855{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000856 int lno = 0, lines = 0;
857 unsigned char *cp;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700858
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000859 histload_loop:
860 /* !bytes check as some systems (older FreeBSDs) have buggy memchr */
861 if (!bytes || (cp = memchr(base, COMMAND, bytes)) == NULL)
862 return (lines);
863 /* advance base pointer past COMMAND byte */
864 bytes -= ++cp - base;
865 base = cp;
866 /* if there is no full string left, don't bother with the rest */
867 if (bytes < 5 || (cp = memchr(base + 4, '\0', bytes - 4)) == NULL)
868 return (lines);
869 /* load the stored line number */
870 lno = ((base[0] & 0xFF) << 24) | ((base[1] & 0xFF) << 16) |
871 ((base[2] & 0xFF) << 8) | (base[3] & 0xFF);
872 /* store away the found line (@base[4]) */
873 ++lines;
874 if (histptr >= history && lno - 1 != s->line) {
875 /* a replacement? */
876 char **hp;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700877
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000878 if (lno >= s->line - (histptr - history) && lno <= s->line) {
879 hp = &histptr[lno - s->line];
Elliott Hughesfc0307d2016-02-02 15:26:47 -0800880 afree(*hp, APERM);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000881 strdupx(*hp, (char *)(base + 4), APERM);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700882 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000883 } else {
884 s->line = lno--;
Elliott Hughes96b43632015-07-17 11:39:41 -0700885 histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700886 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000887 /* advance base pointer past NUL */
888 bytes -= ++cp - base;
889 base = cp;
890 /* repeat until no more */
891 goto histload_loop;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700892}
893
894/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000895 * write a command to the end of the history file
896 *
897 * This *MAY* seem easy but it's also necessary to check
898 * that the history file has not changed in size.
899 * If it has - then some other shell has written to it and
900 * we should (re)read those commands to update our history
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700901 */
902static void
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000903writehistfile(int lno, const char *cmd)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700904{
Geremy Condra03ebf062011-10-12 18:17:24 -0700905 off_t sizenow;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000906 size_t bytes;
907 unsigned char *base, *news;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700908
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000909 mksh_lockfd(histfd);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700910 sizenow = lseek(histfd, (off_t)0, SEEK_END);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000911 if (sizenow < histfsize) {
912 /* the file has shrunk; give up */
913 goto bad;
914 }
915 if (
916 /* ignore changes when the file is too large */
917 sizenow <= MKSH_MAXHISTFSIZE
918 &&
919 /* the size has changed, we need to do read updates */
920 sizenow > histfsize
921 ) {
922 /* both sizenow and histfsize are <= MKSH_MAXHISTFSIZE */
923 bytes = (size_t)(sizenow - histfsize);
924 base = (void *)mmap(NULL, (size_t)sizenow, PROT_READ,
925 MAP_FILE | MAP_PRIVATE, histfd, (off_t)0);
926 if (base == (unsigned char *)MAP_FAILED)
927 goto bad;
928 news = base + (size_t)histfsize;
929 if (*news == COMMAND) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700930 hist_source->line--;
931 histload(hist_source, news, bytes);
932 hist_source->line++;
933 lno = hist_source->line;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000934 } else
935 bytes = 0;
936 munmap(caddr_cast(base), (size_t)sizenow);
937 if (!bytes)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700938 goto bad;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700939 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000940 if (cmd && !writehistline(histfd, lno, cmd)) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700941 bad:
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000942 hist_finish();
943 return;
944 }
945 histfsize = lseek(histfd, (off_t)0, SEEK_END);
946 mksh_unlkfd(histfd);
947}
948
949static int
950writehistline(int fd, int lno, const char *cmd)
951{
952 ssize_t n;
953 unsigned char hdr[5];
954
955 hdr[0] = COMMAND;
956 hdr[1] = (lno >> 24) & 0xFF;
957 hdr[2] = (lno >> 16) & 0xFF;
958 hdr[3] = (lno >> 8) & 0xFF;
959 hdr[4] = lno & 0xFF;
960 n = strlen(cmd) + 1;
961 return (write(fd, hdr, 5) == 5 && write(fd, cmd, n) == n);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700962}
963
964void
965hist_finish(void)
966{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000967 if (histfd >= 0) {
968 mksh_unlkfd(histfd);
969 (void)close(histfd);
970 }
971 histfd = -1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700972}
973#endif
974
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000975
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700976#if !HAVE_SYS_SIGNAME
977static const struct mksh_sigpair {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000978 const char * const name;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700979 int nr;
980} mksh_sigpairs[] = {
981#include "signames.inc"
982 { NULL, 0 }
983};
984#endif
985
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000986#if HAVE_SYS_SIGLIST
987#if !HAVE_SYS_SIGLIST_DECL
988extern const char * const sys_siglist[];
989#endif
990#endif
991
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700992void
993inittraps(void)
994{
995 int i;
996 const char *cs;
Elliott Hughes77740fc2016-08-12 15:06:53 -0700997#if !HAVE_SYS_SIGNAME
998 const struct mksh_sigpair *pair;
999#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001000
Geremy Condra03ebf062011-10-12 18:17:24 -07001001 trap_exstat = -1;
1002
Elliott Hughes77740fc2016-08-12 15:06:53 -07001003 /* populate sigtraps based on sys_signame and sys_siglist */
Elliott Hughes96b43632015-07-17 11:39:41 -07001004 for (i = 1; i < ksh_NSIG; i++) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001005 sigtraps[i].signal = i;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001006#if HAVE_SYS_SIGNAME
Elliott Hughes96b43632015-07-17 11:39:41 -07001007 cs = sys_signame[i];
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001008#else
Elliott Hughes77740fc2016-08-12 15:06:53 -07001009 pair = mksh_sigpairs;
Elliott Hughes96b43632015-07-17 11:39:41 -07001010 while ((pair->nr != i) && (pair->name != NULL))
1011 ++pair;
1012 cs = pair->name;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001013#endif
Elliott Hughes96b43632015-07-17 11:39:41 -07001014 if ((cs == NULL) ||
1015 (cs[0] == '\0'))
Elliott Hughes77740fc2016-08-12 15:06:53 -07001016 sigtraps[i].name = null;
Elliott Hughes96b43632015-07-17 11:39:41 -07001017 else {
1018 char *s;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001019
Elliott Hughes96b43632015-07-17 11:39:41 -07001020 /* this is not optimal, what about SIGSIG1? */
1021 if (ksh_eq(cs[0], 'S', 's') &&
1022 ksh_eq(cs[1], 'I', 'i') &&
1023 ksh_eq(cs[2], 'G', 'g') &&
1024 cs[3] != '\0') {
1025 /* skip leading "SIG" */
1026 cs += 3;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001027 }
Elliott Hughes96b43632015-07-17 11:39:41 -07001028 strdupx(s, cs, APERM);
1029 sigtraps[i].name = s;
1030 while ((*s = ksh_toupper(*s)))
1031 ++s;
Elliott Hughes77740fc2016-08-12 15:06:53 -07001032 /* check for reserved names */
1033 if (!strcmp(sigtraps[i].name, "EXIT") ||
1034 !strcmp(sigtraps[i].name, "ERR")) {
1035#ifndef MKSH_SMALL
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001036 internal_warningf(Tinvname, sigtraps[i].name,
1037 "signal");
Elliott Hughes77740fc2016-08-12 15:06:53 -07001038#endif
1039 sigtraps[i].name = null;
1040 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001041 }
Elliott Hughes77740fc2016-08-12 15:06:53 -07001042 if (sigtraps[i].name == null)
1043 sigtraps[i].name = shf_smprintf(Tf_d, i);
Elliott Hughes96b43632015-07-17 11:39:41 -07001044#if HAVE_SYS_SIGLIST
1045 sigtraps[i].mess = sys_siglist[i];
1046#elif HAVE_STRSIGNAL
1047 sigtraps[i].mess = strsignal(i);
1048#else
1049 sigtraps[i].mess = NULL;
1050#endif
1051 if ((sigtraps[i].mess == NULL) ||
1052 (sigtraps[i].mess[0] == '\0'))
Elliott Hughes77740fc2016-08-12 15:06:53 -07001053 sigtraps[i].mess = shf_smprintf(Tf_sd,
Elliott Hughes96b43632015-07-17 11:39:41 -07001054 "Signal", i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001055 }
Elliott Hughes96b43632015-07-17 11:39:41 -07001056 sigtraps[ksh_SIGEXIT].signal = ksh_SIGEXIT;
Geremy Condra03ebf062011-10-12 18:17:24 -07001057 sigtraps[ksh_SIGEXIT].name = "EXIT";
Elliott Hughes96b43632015-07-17 11:39:41 -07001058 sigtraps[ksh_SIGEXIT].mess = "Exit trap";
1059 sigtraps[ksh_SIGERR].signal = ksh_SIGERR;
1060 sigtraps[ksh_SIGERR].name = "ERR";
1061 sigtraps[ksh_SIGERR].mess = "Error handler";
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001062
1063 (void)sigemptyset(&Sigact_ign.sa_mask);
1064 Sigact_ign.sa_flags = 0; /* interruptible */
1065 Sigact_ign.sa_handler = SIG_IGN;
1066
1067 sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
1068 sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
Geremy Condra03ebf062011-10-12 18:17:24 -07001069 /* SIGTERM is not fatal for interactive */
1070 sigtraps[SIGTERM].flags |= TF_DFL_INTR;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001071 sigtraps[SIGHUP].flags |= TF_FATAL;
1072 sigtraps[SIGCHLD].flags |= TF_SHELL_USES;
1073
1074 /* these are always caught so we can clean up any temporary files. */
1075 setsig(&sigtraps[SIGINT], trapsig, SS_RESTORE_ORIG);
1076 setsig(&sigtraps[SIGQUIT], trapsig, SS_RESTORE_ORIG);
1077 setsig(&sigtraps[SIGTERM], trapsig, SS_RESTORE_ORIG);
1078 setsig(&sigtraps[SIGHUP], trapsig, SS_RESTORE_ORIG);
1079}
1080
1081static void alarm_catcher(int sig);
1082
1083void
1084alarm_init(void)
1085{
1086 sigtraps[SIGALRM].flags |= TF_SHELL_USES;
1087 setsig(&sigtraps[SIGALRM], alarm_catcher,
1088 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
1089}
1090
1091/* ARGSUSED */
1092static void
1093alarm_catcher(int sig MKSH_A_UNUSED)
1094{
1095 /* this runs inside interrupt context, with errno saved */
1096
1097 if (ksh_tmout_state == TMOUT_READING) {
1098 int left = alarm(0);
1099
1100 if (left == 0) {
1101 ksh_tmout_state = TMOUT_LEAVING;
1102 intrsig = 1;
1103 } else
1104 alarm(left);
1105 }
1106}
1107
1108Trap *
Elliott Hughes96b43632015-07-17 11:39:41 -07001109gettrap(const char *cs, bool igncase, bool allsigs)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001110{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001111 int i;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001112 Trap *p;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001113 char *as;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001114
Elliott Hughes96b43632015-07-17 11:39:41 -07001115 /* signal number (1..ksh_NSIG) or 0? */
1116
1117 if (ksh_isdigit(*cs))
1118 return ((getn(cs, &i) && 0 <= i && i < ksh_NSIG) ?
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001119 (&sigtraps[i]) : NULL);
Elliott Hughes96b43632015-07-17 11:39:41 -07001120
1121 /* do a lookup by name then */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001122
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001123 /* this breaks SIGSIG1, but we do that above anyway */
Elliott Hughes96b43632015-07-17 11:39:41 -07001124 if (ksh_eq(cs[0], 'S', 's') &&
1125 ksh_eq(cs[1], 'I', 'i') &&
1126 ksh_eq(cs[2], 'G', 'g') &&
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001127 cs[3] != '\0') {
1128 /* skip leading "SIG" */
1129 cs += 3;
1130 }
1131 if (igncase) {
1132 char *s;
1133
1134 strdupx(as, cs, ATEMP);
1135 cs = s = as;
1136 while ((*s = ksh_toupper(*s)))
1137 ++s;
1138 } else
1139 as = NULL;
1140
Elliott Hughes96b43632015-07-17 11:39:41 -07001141 /* this is idiotic, we really want a hashtable here */
1142
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001143 p = sigtraps;
Elliott Hughes96b43632015-07-17 11:39:41 -07001144 i = ksh_NSIG + 1;
1145 do {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001146 if (!strcmp(p->name, cs))
1147 goto found;
1148 ++p;
Elliott Hughes96b43632015-07-17 11:39:41 -07001149 } while (--i);
1150 goto notfound;
1151
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001152 found:
Elliott Hughes96b43632015-07-17 11:39:41 -07001153 if (!allsigs) {
1154 if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR) {
1155 notfound:
1156 p = NULL;
1157 }
1158 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001159 afree(as, ATEMP);
1160 return (p);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001161}
1162
1163/*
1164 * trap signal handler
1165 */
1166void
1167trapsig(int i)
1168{
1169 Trap *p = &sigtraps[i];
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001170 int eno = errno;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001171
1172 trap = p->set = 1;
1173 if (p->flags & TF_DFL_INTR)
1174 intrsig = 1;
1175 if ((p->flags & TF_FATAL) && !p->trap) {
1176 fatal_trap = 1;
1177 intrsig = 1;
1178 }
1179 if (p->shtrap)
1180 (*p->shtrap)(i);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001181 errno = eno;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001182}
1183
1184/*
1185 * called when we want to allow the user to ^C out of something - won't
1186 * work if user has trapped SIGINT.
1187 */
1188void
1189intrcheck(void)
1190{
1191 if (intrsig)
1192 runtraps(TF_DFL_INTR|TF_FATAL);
1193}
1194
1195/*
1196 * called after EINTR to check if a signal with normally causes process
1197 * termination has been received.
1198 */
1199int
1200fatal_trap_check(void)
1201{
Elliott Hughes96b43632015-07-17 11:39:41 -07001202 Trap *p = sigtraps;
1203 int i = ksh_NSIG + 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001204
1205 /* todo: should check if signal is fatal, not the TF_DFL_INTR flag */
Elliott Hughes96b43632015-07-17 11:39:41 -07001206 do {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001207 if (p->set && (p->flags & (TF_DFL_INTR|TF_FATAL)))
1208 /* return value is used as an exit code */
Elliott Hughesfc0307d2016-02-02 15:26:47 -08001209 return (ksh_sigmask(p->signal));
Elliott Hughes96b43632015-07-17 11:39:41 -07001210 ++p;
1211 } while (--i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001212 return (0);
1213}
1214
1215/*
1216 * Returns the signal number of any pending traps: ie, a signal which has
1217 * occurred for which a trap has been set or for which the TF_DFL_INTR flag
1218 * is set.
1219 */
1220int
1221trap_pending(void)
1222{
Elliott Hughes96b43632015-07-17 11:39:41 -07001223 Trap *p = sigtraps;
1224 int i = ksh_NSIG + 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001225
Elliott Hughes96b43632015-07-17 11:39:41 -07001226 do {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001227 if (p->set && ((p->trap && p->trap[0]) ||
1228 ((p->flags & (TF_DFL_INTR|TF_FATAL)) && !p->trap)))
1229 return (p->signal);
Elliott Hughes96b43632015-07-17 11:39:41 -07001230 ++p;
1231 } while (--i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001232 return (0);
1233}
1234
1235/*
1236 * run any pending traps. If intr is set, only run traps that
1237 * can interrupt commands.
1238 */
1239void
1240runtraps(int flag)
1241{
Elliott Hughes96b43632015-07-17 11:39:41 -07001242 Trap *p = sigtraps;
1243 int i = ksh_NSIG + 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001244
1245 if (ksh_tmout_state == TMOUT_LEAVING) {
1246 ksh_tmout_state = TMOUT_EXECUTING;
1247 warningf(false, "timed out waiting for input");
1248 unwind(LEXIT);
1249 } else
1250 /*
1251 * XXX: this means the alarm will have no effect if a trap
1252 * is caught after the alarm() was started...not good.
1253 */
1254 ksh_tmout_state = TMOUT_EXECUTING;
1255 if (!flag)
1256 trap = 0;
1257 if (flag & TF_DFL_INTR)
1258 intrsig = 0;
1259 if (flag & TF_FATAL)
1260 fatal_trap = 0;
Geremy Condra03ebf062011-10-12 18:17:24 -07001261 ++trap_nested;
Elliott Hughes96b43632015-07-17 11:39:41 -07001262 do {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001263 if (p->set && (!flag ||
1264 ((p->flags & flag) && p->trap == NULL)))
Geremy Condra03ebf062011-10-12 18:17:24 -07001265 runtrap(p, false);
Elliott Hughes96b43632015-07-17 11:39:41 -07001266 ++p;
1267 } while (--i);
Geremy Condra03ebf062011-10-12 18:17:24 -07001268 if (!--trap_nested)
1269 runtrap(NULL, true);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001270}
1271
1272void
Geremy Condra03ebf062011-10-12 18:17:24 -07001273runtrap(Trap *p, bool is_last)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001274{
Geremy Condra03ebf062011-10-12 18:17:24 -07001275 int old_changed = 0, i;
1276 char *trapstr;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001277
Geremy Condra03ebf062011-10-12 18:17:24 -07001278 if (p == NULL)
1279 /* just clean up, see runtraps() above */
1280 goto donetrap;
1281 i = p->signal;
1282 trapstr = p->trap;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001283 p->set = 0;
Geremy Condra03ebf062011-10-12 18:17:24 -07001284 if (trapstr == NULL) {
1285 /* SIG_DFL */
Elliott Hughes96b43632015-07-17 11:39:41 -07001286 if (p->flags & (TF_FATAL | TF_DFL_INTR)) {
1287 exstat = (int)(128U + (unsigned)i);
1288 if ((unsigned)exstat > 255U)
1289 exstat = 255;
1290 }
1291 /* e.g. SIGHUP */
1292 if (p->flags & TF_FATAL)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001293 unwind(LLEAVE);
Elliott Hughes96b43632015-07-17 11:39:41 -07001294 /* e.g. SIGINT, SIGQUIT, SIGTERM, etc. */
1295 if (p->flags & TF_DFL_INTR)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001296 unwind(LINTR);
Geremy Condra03ebf062011-10-12 18:17:24 -07001297 goto donetrap;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001298 }
Geremy Condra03ebf062011-10-12 18:17:24 -07001299 if (trapstr[0] == '\0')
1300 /* SIG_IGN */
1301 goto donetrap;
1302 if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
1303 /* avoid recursion on these */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001304 old_changed = p->flags & TF_CHANGED;
1305 p->flags &= ~TF_CHANGED;
1306 p->trap = NULL;
1307 }
Geremy Condra03ebf062011-10-12 18:17:24 -07001308 if (trap_exstat == -1)
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001309 trap_exstat = exstat & 0xFF;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001310 /*
1311 * Note: trapstr is fully parsed before anything is executed, thus
1312 * no problem with afree(p->trap) in settrap() while still in use.
1313 */
1314 command(trapstr, current_lineno);
Geremy Condra03ebf062011-10-12 18:17:24 -07001315 if (i == ksh_SIGEXIT || i == ksh_SIGERR) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001316 if (p->flags & TF_CHANGED)
1317 /* don't clear TF_CHANGED */
1318 afree(trapstr, APERM);
1319 else
1320 p->trap = trapstr;
1321 p->flags |= old_changed;
1322 }
Geremy Condra03ebf062011-10-12 18:17:24 -07001323
1324 donetrap:
1325 /* we're the last trap of a sequence executed */
1326 if (is_last && trap_exstat != -1) {
1327 exstat = trap_exstat;
1328 trap_exstat = -1;
1329 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001330}
1331
1332/* clear pending traps and reset user's trap handlers; used after fork(2) */
1333void
1334cleartraps(void)
1335{
Elliott Hughes96b43632015-07-17 11:39:41 -07001336 Trap *p = sigtraps;
1337 int i = ksh_NSIG + 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001338
1339 trap = 0;
1340 intrsig = 0;
1341 fatal_trap = 0;
Elliott Hughes96b43632015-07-17 11:39:41 -07001342
1343 do {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001344 p->set = 0;
1345 if ((p->flags & TF_USER_SET) && (p->trap && p->trap[0]))
1346 settrap(p, NULL);
Elliott Hughes96b43632015-07-17 11:39:41 -07001347 ++p;
1348 } while (--i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001349}
1350
1351/* restore signals just before an exec(2) */
1352void
1353restoresigs(void)
1354{
Elliott Hughes96b43632015-07-17 11:39:41 -07001355 Trap *p = sigtraps;
1356 int i = ksh_NSIG + 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001357
Elliott Hughes96b43632015-07-17 11:39:41 -07001358 do {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001359 if (p->flags & (TF_EXEC_IGN|TF_EXEC_DFL))
1360 setsig(p, (p->flags & TF_EXEC_IGN) ? SIG_IGN : SIG_DFL,
1361 SS_RESTORE_CURR|SS_FORCE);
Elliott Hughes96b43632015-07-17 11:39:41 -07001362 ++p;
1363 } while (--i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001364}
1365
1366void
1367settrap(Trap *p, const char *s)
1368{
1369 sig_t f;
1370
Elliott Hughesfc0307d2016-02-02 15:26:47 -08001371 afree(p->trap, APERM);
Geremy Condra03ebf062011-10-12 18:17:24 -07001372 /* handles s == NULL */
1373 strdupx(p->trap, s, APERM);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001374 p->flags |= TF_CHANGED;
1375 f = !s ? SIG_DFL : s[0] ? trapsig : SIG_IGN;
1376
1377 p->flags |= TF_USER_SET;
1378 if ((p->flags & (TF_DFL_INTR|TF_FATAL)) && f == SIG_DFL)
1379 f = trapsig;
1380 else if (p->flags & TF_SHELL_USES) {
1381 if (!(p->flags & TF_ORIG_IGN) || Flag(FTALKING)) {
1382 /* do what user wants at exec time */
1383 p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1384 if (f == SIG_IGN)
1385 p->flags |= TF_EXEC_IGN;
1386 else
1387 p->flags |= TF_EXEC_DFL;
1388 }
1389
1390 /*
1391 * assumes handler already set to what shell wants it
1392 * (normally trapsig, but could be j_sigchld() or SIG_IGN)
1393 */
1394 return;
1395 }
1396
1397 /* todo: should we let user know signal is ignored? how? */
1398 setsig(p, f, SS_RESTORE_CURR|SS_USER);
1399}
1400
1401/*
Elliott Hughes966dd552016-12-08 15:56:04 -08001402 * called by c_print() when writing to a co-process to ensure
1403 * SIGPIPE won't kill shell (unless user catches it and exits)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001404 */
Elliott Hughes966dd552016-12-08 15:56:04 -08001405bool
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001406block_pipe(void)
1407{
Elliott Hughes966dd552016-12-08 15:56:04 -08001408 bool restore_dfl = false;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001409 Trap *p = &sigtraps[SIGPIPE];
1410
1411 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1412 setsig(p, SIG_IGN, SS_RESTORE_CURR);
1413 if (p->flags & TF_ORIG_DFL)
Elliott Hughes966dd552016-12-08 15:56:04 -08001414 restore_dfl = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001415 } else if (p->cursig == SIG_DFL) {
1416 setsig(p, SIG_IGN, SS_RESTORE_CURR);
Geremy Condra03ebf062011-10-12 18:17:24 -07001417 /* restore to SIG_DFL */
Elliott Hughes966dd552016-12-08 15:56:04 -08001418 restore_dfl = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001419 }
1420 return (restore_dfl);
1421}
1422
Elliott Hughes966dd552016-12-08 15:56:04 -08001423/* called by c_print() to undo whatever block_pipe() did */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001424void
Elliott Hughes966dd552016-12-08 15:56:04 -08001425restore_pipe(void)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001426{
Elliott Hughes966dd552016-12-08 15:56:04 -08001427 setsig(&sigtraps[SIGPIPE], SIG_DFL, SS_RESTORE_CURR);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001428}
1429
1430/*
1431 * Set action for a signal. Action may not be set if original
1432 * action was SIG_IGN, depending on the value of flags and FTALKING.
1433 */
1434int
1435setsig(Trap *p, sig_t f, int flags)
1436{
1437 struct sigaction sigact;
1438
Geremy Condra03ebf062011-10-12 18:17:24 -07001439 if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001440 return (1);
1441
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001442 memset(&sigact, 0, sizeof(sigact));
1443
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001444 /*
1445 * First time setting this signal? If so, get and note the current
1446 * setting.
1447 */
1448 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
1449 sigaction(p->signal, &Sigact_ign, &sigact);
1450 p->flags |= sigact.sa_handler == SIG_IGN ?
1451 TF_ORIG_IGN : TF_ORIG_DFL;
1452 p->cursig = SIG_IGN;
1453 }
1454
1455 /*-
1456 * Generally, an ignored signal stays ignored, except if
1457 * - the user of an interactive shell wants to change it
1458 * - the shell wants for force a change
1459 */
1460 if ((p->flags & TF_ORIG_IGN) && !(flags & SS_FORCE) &&
1461 (!(flags & SS_USER) || !Flag(FTALKING)))
1462 return (0);
1463
1464 setexecsig(p, flags & SS_RESTORE_MASK);
1465
1466 /*
1467 * This is here 'cause there should be a way of clearing
1468 * shtraps, but don't know if this is a sane way of doing
1469 * it. At the moment, all users of shtrap are lifetime
1470 * users (SIGALRM, SIGCHLD, SIGWINCH).
1471 */
1472 if (!(flags & SS_USER))
1473 p->shtrap = (sig_t)NULL;
1474 if (flags & SS_SHTRAP) {
1475 p->shtrap = f;
1476 f = trapsig;
1477 }
1478
1479 if (p->cursig != f) {
1480 p->cursig = f;
1481 (void)sigemptyset(&sigact.sa_mask);
Geremy Condra03ebf062011-10-12 18:17:24 -07001482 /* interruptible */
1483 sigact.sa_flags = 0;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001484 sigact.sa_handler = f;
1485 sigaction(p->signal, &sigact, NULL);
1486 }
1487
1488 return (1);
1489}
1490
1491/* control what signal is set to before an exec() */
1492void
1493setexecsig(Trap *p, int restore)
1494{
1495 /* XXX debugging */
1496 if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
1497 internal_errorf("setexecsig: unset signal %d(%s)",
1498 p->signal, p->name);
1499
1500 /* restore original value for exec'd kids */
1501 p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
1502 switch (restore & SS_RESTORE_MASK) {
Geremy Condra03ebf062011-10-12 18:17:24 -07001503 case SS_RESTORE_CURR:
1504 /* leave things as they currently are */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001505 break;
1506 case SS_RESTORE_ORIG:
1507 p->flags |= p->flags & TF_ORIG_IGN ? TF_EXEC_IGN : TF_EXEC_DFL;
1508 break;
1509 case SS_RESTORE_DFL:
1510 p->flags |= TF_EXEC_DFL;
1511 break;
1512 case SS_RESTORE_IGN:
1513 p->flags |= TF_EXEC_IGN;
1514 break;
1515 }
1516}
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001517
1518#if HAVE_PERSISTENT_HISTORY || defined(DF)
1519/*
1520 * File descriptor locking and unlocking functions.
1521 * Could use some error handling, but hey, this is only
1522 * advisory locking anyway, will often not work over NFS,
1523 * and you are SOL if this fails...
1524 */
1525
1526void
1527mksh_lockfd(int fd)
1528{
1529#if defined(__OpenBSD__)
1530 /* flock is not interrupted by signals */
1531 (void)flock(fd, LOCK_EX);
1532#elif HAVE_FLOCK
1533 int rv;
1534
1535 /* e.g. on Linux */
1536 do {
1537 rv = flock(fd, LOCK_EX);
1538 } while (rv == 1 && errno == EINTR);
1539#elif HAVE_LOCK_FCNTL
1540 int rv;
1541 struct flock lks;
1542
1543 memset(&lks, 0, sizeof(lks));
1544 lks.l_type = F_WRLCK;
1545 do {
1546 rv = fcntl(fd, F_SETLKW, &lks);
1547 } while (rv == 1 && errno == EINTR);
1548#endif
1549}
1550
1551/* designed to not define mksh_unlkfd if none triggered */
1552#if HAVE_FLOCK
1553void
1554mksh_unlkfd(int fd)
1555{
1556 (void)flock(fd, LOCK_UN);
1557}
1558#elif HAVE_LOCK_FCNTL
1559void
1560mksh_unlkfd(int fd)
1561{
1562 struct flock lks;
1563
1564 memset(&lks, 0, sizeof(lks));
1565 lks.l_type = F_UNLCK;
1566 (void)fcntl(fd, F_SETLKW, &lks);
1567}
1568#endif
1569#endif