]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tty/lib_tstp.c
ncurses 6.0 - patch 20170909
[ncurses.git] / ncurses / tty / lib_tstp.c
1 /****************************************************************************
2  * Copyright (c) 1998-2014,2017 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1995-on                 *
33  ****************************************************************************/
34
35 /*
36 **      lib_tstp.c
37 **
38 **      The routine _nc_signal_handler().
39 **
40 */
41 #include <curses.priv.h>
42
43 #include <SigAction.h>
44
45 MODULE_ID("$Id: lib_tstp.c,v 1.49 2017/07/22 23:29:58 tom Exp $")
46
47 #if defined(SIGTSTP) && (HAVE_SIGACTION || HAVE_SIGVEC)
48 #define USE_SIGTSTP 1
49 #else
50 #define USE_SIGTSTP 0
51 #endif
52
53 #ifdef TRACE
54 static const char *
55 signal_name(int sig)
56 {
57     switch (sig) {
58 #ifdef SIGALRM
59     case SIGALRM:
60         return "SIGALRM";
61 #endif
62 #ifdef SIGCONT
63     case SIGCONT:
64         return "SIGCONT";
65 #endif
66     case SIGINT:
67         return "SIGINT";
68 #ifdef SIGQUIT
69     case SIGQUIT:
70         return "SIGQUIT";
71 #endif
72     case SIGTERM:
73         return "SIGTERM";
74 #ifdef SIGTSTP
75     case SIGTSTP:
76         return "SIGTSTP";
77 #endif
78 #ifdef SIGTTOU
79     case SIGTTOU:
80         return "SIGTTOU";
81 #endif
82 #ifdef SIGWINCH
83     case SIGWINCH:
84         return "SIGWINCH";
85 #endif
86     default:
87         return "unknown signal";
88     }
89 }
90 #endif
91
92 /*
93  * Note: This code is fragile!  Its problem is that different OSs
94  * handle restart of system calls interrupted by signals differently.
95  * The ncurses code needs signal-call restart to happen -- otherwise,
96  * interrupted wgetch() calls will return FAIL, probably making the
97  * application think the input stream has ended and it should
98  * terminate.  In particular, you know you have this problem if, when
99  * you suspend an ncurses-using lynx with ^Z and resume, it dies
100  * immediately.
101  *
102  * Default behavior of POSIX sigaction(2) is not to restart
103  * interrupted system calls, but Linux's sigaction does it anyway (at
104  * least, on and after the 1.1.47 I (esr) use).  Thus this code works
105  * OK under Linux.  The 4.4BSD sigaction(2) supports a (non-portable)
106  * SA_RESTART flag that forces the right behavior.  Thus, this code
107  * should work OK under BSD/OS, NetBSD, and FreeBSD (let us know if it
108  * does not).
109  *
110  * Stock System Vs (and anything else using a strict-POSIX
111  * sigaction(2) without SA_RESTART) may have a problem.  Possible
112  * solutions:
113  *
114  *    sigvec      restarts by default (SV_INTERRUPT flag to not restart)
115  *    signal      restarts by default in SVr4 (assuming you link with -lucb)
116  *                and BSD, but not SVr3.
117  *    sigset      restarts, but is only available under SVr4/Solaris.
118  *
119  * The signal(3) call is mandated by the ANSI standard, and its
120  * interaction with sigaction(2) is described in the POSIX standard
121  * (3.3.4.2, page 72,line 934).  According to section 8.1, page 191,
122  * however, signal(3) itself is not required by POSIX.1.  And POSIX is
123  * silent on whether it is required to restart signals.
124  *
125  * So.  The present situation is, we use sigaction(2) with no
126  * guarantee of restart anywhere but on Linux and BSD.  We could
127  * switch to signal(3) and collar Linux, BSD, and SVr4.  Any way
128  * we slice it, System V UNIXes older than SVr4 will probably lose
129  * (this may include XENIX).
130  *
131  * This implementation will probably be changed to use signal(3) in
132  * the future.  If nothing else, it's simpler...
133  */
134
135 #if USE_SIGTSTP
136 static void
137 handle_SIGTSTP(int dummy GCC_UNUSED)
138 {
139     SCREEN *sp = CURRENT_SCREEN;
140     sigset_t mask, omask;
141     sigaction_t act, oact;
142
143 #ifdef SIGTTOU
144     int sigttou_blocked;
145 #endif
146
147     _nc_globals.have_sigtstp = 1;
148     T(("handle_SIGTSTP() called"));
149
150     /*
151      * The user may have changed the prog_mode tty bits, so save them.
152      *
153      * But first try to detect whether we still are in the foreground
154      * process group - if not, an interactive shell may already have
155      * taken ownership of the tty and modified the settings when our
156      * parent was stopped before us, and we would likely pick up the
157      * settings already modified by the shell.
158      *
159      * Don't do this if we're not in curses -
160      */
161     if (sp != 0 && (sp->_endwin == ewRunning))
162 #if HAVE_TCGETPGRP
163         if (tcgetpgrp(STDIN_FILENO) == getpgrp())
164 #endif
165             NCURSES_SP_NAME(def_prog_mode) (NCURSES_SP_ARG);
166
167     /*
168      * Block window change and timer signals.  The latter
169      * is because applications use timers to decide when
170      * to repaint the screen.
171      */
172     (void) sigemptyset(&mask);
173 #ifdef SIGALRM
174     (void) sigaddset(&mask, SIGALRM);
175 #endif
176 #if USE_SIGWINCH
177     (void) sigaddset(&mask, SIGWINCH);
178 #endif
179     (void) sigprocmask(SIG_BLOCK, &mask, &omask);
180
181 #ifdef SIGTTOU
182     sigttou_blocked = sigismember(&omask, SIGTTOU);
183     if (!sigttou_blocked) {
184         (void) sigemptyset(&mask);
185         (void) sigaddset(&mask, SIGTTOU);
186         (void) sigprocmask(SIG_BLOCK, &mask, NULL);
187     }
188 #endif
189
190     /*
191      * End window mode, which also resets the terminal state to the
192      * original (pre-curses) modes.
193      */
194     NCURSES_SP_NAME(endwin) (NCURSES_SP_ARG);
195
196     /* Unblock SIGTSTP. */
197     (void) sigemptyset(&mask);
198     (void) sigaddset(&mask, SIGTSTP);
199 #ifdef SIGTTOU
200     if (!sigttou_blocked) {
201         /* Unblock this too if it wasn't blocked on entry */
202         (void) sigaddset(&mask, SIGTTOU);
203     }
204 #endif
205     (void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
206
207     /* Now we want to resend SIGSTP to this process and suspend it */
208     act.sa_handler = SIG_DFL;
209     sigemptyset(&act.sa_mask);
210     act.sa_flags = 0;
211 #ifdef SA_RESTART
212     act.sa_flags |= SA_RESTART;
213 #endif /* SA_RESTART */
214     sigaction(SIGTSTP, &act, &oact);
215     kill(getpid(), SIGTSTP);
216
217     /* Process gets suspended...time passes...process resumes */
218
219     T(("SIGCONT received"));
220     sigaction(SIGTSTP, &oact, NULL);
221     NCURSES_SP_NAME(flushinp) (NCURSES_SP_ARG);
222
223     /*
224      * If the user modified the tty state while suspended, he wants
225      * those changes to stick.  So save the new "default" terminal state.
226      */
227     NCURSES_SP_NAME(def_shell_mode) (NCURSES_SP_ARG);
228
229     /*
230      * This relies on the fact that doupdate() will restore the
231      * program-mode tty state, and issue enter_ca_mode if need be.
232      */
233     NCURSES_SP_NAME(doupdate) (NCURSES_SP_ARG);
234
235     /* Reset the signals. */
236     (void) sigprocmask(SIG_SETMASK, &omask, NULL);
237 }
238 #endif /* USE_SIGTSTP */
239
240 static void
241 handle_SIGINT(int sig)
242 {
243     SCREEN *sp = CURRENT_SCREEN;
244
245     /*
246      * Much of this is unsafe from a signal handler.  But we'll _try_ to clean
247      * up the screen and terminal settings on the way out.
248      *
249      * There are at least the following problems:
250      * 1) Walking the SCREEN list is unsafe, since all list management
251      *    is done without any signal blocking.
252      * 2) On systems which have REENTRANT turned on, set_term() uses
253      *    _nc_lock_global() which could deadlock or misbehave in other ways.
254      * 3) endwin() calls all sorts of stuff, many of which use stdio or
255      *    other library functions which are clearly unsafe.
256      */
257     if (!_nc_globals.cleanup_nested++
258         && (sig == SIGINT || sig == SIGTERM)) {
259 #if HAVE_SIGACTION || HAVE_SIGVEC
260         sigaction_t act;
261         sigemptyset(&act.sa_mask);
262         act.sa_flags = 0;
263         act.sa_handler = SIG_IGN;
264         if (sigaction(sig, &act, NULL) == 0)
265 #else
266         if (signal(sig, SIG_IGN) != SIG_ERR)
267 #endif
268         {
269             SCREEN *scan;
270             for (each_screen(scan)) {
271                 if (scan->_ofp != 0
272                     && NC_ISATTY(fileno(scan->_ofp))) {
273                     scan->_outch = NCURSES_SP_NAME(_nc_outch);
274                 }
275                 set_term(scan);
276                 NCURSES_SP_NAME(endwin) (NCURSES_SP_ARG);
277                 if (sp)
278                     sp->_endwin = ewInitial;    /* in case of reuse */
279             }
280         }
281     }
282     _exit(EXIT_FAILURE);
283 }
284
285 #if USE_SIGWINCH
286 static void
287 handle_SIGWINCH(int sig GCC_UNUSED)
288 {
289     _nc_globals.have_sigwinch = 1;
290 # if USE_PTHREADS_EINTR
291     if (_nc_globals.read_thread) {
292         if (!pthread_equal(pthread_self(), _nc_globals.read_thread))
293             pthread_kill(_nc_globals.read_thread, SIGWINCH);
294         _nc_globals.read_thread = 0;
295     }
296 # endif
297 }
298 #endif /* USE_SIGWINCH */
299
300 /*
301  * If the given signal is still in its default state, set it to the given
302  * handler.
303  */
304 static int
305 CatchIfDefault(int sig, void (*handler) (int))
306 {
307     int result;
308 #if HAVE_SIGACTION || HAVE_SIGVEC
309     sigaction_t old_act;
310     sigaction_t new_act;
311
312     memset(&new_act, 0, sizeof(new_act));
313     sigemptyset(&new_act.sa_mask);
314 #ifdef SA_RESTART
315 #ifdef SIGWINCH
316     if (sig != SIGWINCH)
317 #endif
318         new_act.sa_flags |= SA_RESTART;
319 #endif /* SA_RESTART */
320     new_act.sa_handler = handler;
321
322     if (sigaction(sig, NULL, &old_act) == 0
323         && (old_act.sa_handler == SIG_DFL
324             || old_act.sa_handler == handler
325 #if USE_SIGWINCH
326             || (sig == SIGWINCH && old_act.sa_handler == SIG_IGN)
327 #endif
328         )) {
329         (void) sigaction(sig, &new_act, NULL);
330         result = TRUE;
331     } else {
332         result = FALSE;
333     }
334 #else /* !HAVE_SIGACTION */
335     void (*ohandler) (int);
336
337     ohandler = signal(sig, SIG_IGN);
338     if (ohandler == SIG_DFL
339         || ohandler == handler
340 #if USE_SIGWINCH
341         || (sig == SIGWINCH && ohandler == SIG_IGN)
342 #endif
343         ) {
344         signal(sig, handler);
345         result = TRUE;
346     } else {
347         signal(sig, ohandler);
348         result = FALSE;
349     }
350 #endif
351     T(("CatchIfDefault - will %scatch %s",
352        result ? "" : "not ", signal_name(sig)));
353     return result;
354 }
355
356 /*
357  * This is invoked once at the beginning (e.g., from 'initscr()'), to
358  * initialize the signal catchers, and thereafter when spawning a shell (and
359  * returning) to disable/enable the SIGTSTP (i.e., ^Z) catcher.
360  *
361  * If the application has already set one of the signals, we'll not modify it
362  * (during initialization).
363  *
364  * The XSI document implies that we shouldn't keep the SIGTSTP handler if
365  * the caller later changes its mind, but that doesn't seem correct.
366  */
367 NCURSES_EXPORT(void)
368 _nc_signal_handler(int enable)
369 {
370     T((T_CALLED("_nc_signal_handler(%d)"), enable));
371 #if USE_SIGTSTP                 /* Xenix 2.x doesn't have SIGTSTP, for example */
372     {
373         static bool ignore_tstp = FALSE;
374
375         if (!ignore_tstp) {
376             static sigaction_t new_sigaction, old_sigaction;
377
378             if (!enable) {
379                 new_sigaction.sa_handler = SIG_IGN;
380                 sigaction(SIGTSTP, &new_sigaction, &old_sigaction);
381             } else if (new_sigaction.sa_handler != SIG_DFL) {
382                 sigaction(SIGTSTP, &old_sigaction, NULL);
383             } else if (sigaction(SIGTSTP, NULL, &old_sigaction) == 0
384                        && (old_sigaction.sa_handler == SIG_DFL)) {
385                 sigemptyset(&new_sigaction.sa_mask);
386 #ifdef SA_RESTART
387                 new_sigaction.sa_flags |= SA_RESTART;
388 #endif /* SA_RESTART */
389                 new_sigaction.sa_handler = handle_SIGTSTP;
390                 (void) sigaction(SIGTSTP, &new_sigaction, NULL);
391             } else {
392                 ignore_tstp = TRUE;
393             }
394         }
395     }
396 #endif /* !USE_SIGTSTP */
397
398     if (!_nc_globals.init_signals) {
399         if (enable) {
400             CatchIfDefault(SIGINT, handle_SIGINT);
401             CatchIfDefault(SIGTERM, handle_SIGINT);
402 #if USE_SIGWINCH
403             CatchIfDefault(SIGWINCH, handle_SIGWINCH);
404 #endif
405             _nc_globals.init_signals = TRUE;
406         }
407     }
408     returnVoid;
409 }