1 /****************************************************************************
2  * Copyright (c) 1998-2009,2010 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 #if SVR4_ACTION && !defined(_POSIX_SOURCE)
46 #define _POSIX_SOURCE
47 #endif
48 
49 MODULE_ID("$Id: lib_tstp.c,v 1.41 2010/05/15 21:31:12 tom Exp $")
50 
51 #if defined(SIGTSTP) && (HAVE_SIGACTION || HAVE_SIGVEC)
52 #define USE_SIGTSTP 1
53 #else
54 #define USE_SIGTSTP 0
55 #endif
56 
57 #ifdef TRACE
58 static const char *
59 signal_name(int sig)
60 {
61     switch (sig) {
62 #ifdef SIGALRM
63     case SIGALRM:
64 	return "SIGALRM";
65 #endif
66 #ifdef SIGCONT
67     case SIGCONT:
68 	return "SIGCONT";
69 #endif
70     case SIGINT:
71 	return "SIGINT";
72 #ifdef SIGQUIT
73     case SIGQUIT:
74 	return "SIGQUIT";
75 #endif
76     case SIGTERM:
77 	return "SIGTERM";
78 #ifdef SIGTSTP
79     case SIGTSTP:
80 	return "SIGTSTP";
81 #endif
82 #ifdef SIGTTOU
83     case SIGTTOU:
84 	return "SIGTTOU";
85 #endif
86 #ifdef SIGWINCH
87     case SIGWINCH:
88 	return "SIGWINCH";
89 #endif
90     default:
91 	return "unknown signal";
92     }
93 }
94 #endif
95 
96 /*
97  * Note: This code is fragile!  Its problem is that different OSs
98  * handle restart of system calls interrupted by signals differently.
99  * The ncurses code needs signal-call restart to happen -- otherwise,
100  * interrupted wgetch() calls will return FAIL, probably making the
101  * application think the input stream has ended and it should
102  * terminate.  In particular, you know you have this problem if, when
103  * you suspend an ncurses-using lynx with ^Z and resume, it dies
104  * immediately.
105  *
106  * Default behavior of POSIX sigaction(2) is not to restart
107  * interrupted system calls, but Linux's sigaction does it anyway (at
108  * least, on and after the 1.1.47 I (esr) use).  Thus this code works
109  * OK under Linux.  The 4.4BSD sigaction(2) supports a (non-portable)
110  * SA_RESTART flag that forces the right behavior.  Thus, this code
111  * should work OK under BSD/OS, NetBSD, and FreeBSD (let us know if it
112  * does not).
113  *
114  * Stock System Vs (and anything else using a strict-POSIX
115  * sigaction(2) without SA_RESTART) may have a problem.  Possible
116  * solutions:
117  *
118  *    sigvec      restarts by default (SV_INTERRUPT flag to not restart)
119  *    signal      restarts by default in SVr4 (assuming you link with -lucb)
120  *                and BSD, but not SVr3.
121  *    sigset      restarts, but is only available under SVr4/Solaris.
122  *
123  * The signal(3) call is mandated by the ANSI standard, and its
124  * interaction with sigaction(2) is described in the POSIX standard
125  * (3.3.4.2, page 72,line 934).  According to section 8.1, page 191,
126  * however, signal(3) itself is not required by POSIX.1.  And POSIX is
127  * silent on whether it is required to restart signals.
128  *
129  * So.  The present situation is, we use sigaction(2) with no
130  * guarantee of restart anywhere but on Linux and BSD.  We could
131  * switch to signal(3) and collar Linux, BSD, and SVr4.  Any way
132  * we slice it, System V UNIXes older than SVr4 will probably lose
133  * (this may include XENIX).
134  *
135  * This implementation will probably be changed to use signal(3) in
136  * the future.  If nothing else, it's simpler...
137  */
138 
139 #if USE_SIGTSTP
140 static void
141 tstp(int dummy GCC_UNUSED)
142 {
143     SCREEN *sp = CURRENT_SCREEN;
144     sigset_t mask, omask;
145     sigaction_t act, oact;
146 
147 #ifdef SIGTTOU
148     int sigttou_blocked;
149 #endif
150 
151     T(("tstp() called"));
152 
153     /*
154      * The user may have changed the prog_mode tty bits, so save them.
155      *
156      * But first try to detect whether we still are in the foreground
157      * process group - if not, an interactive shell may already have
158      * taken ownership of the tty and modified the settings when our
159      * parent was stopped before us, and we would likely pick up the
160      * settings already modified by the shell.
161      */
162     if (sp != 0 && !sp->_endwin)	/* don't do this if we're not in curses */
163 #if HAVE_TCGETPGRP
164 	if (tcgetpgrp(STDIN_FILENO) == getpgrp())
165 #endif
166 	    NCURSES_SP_NAME(def_prog_mode) (NCURSES_SP_ARG);
167 
168     /*
169      * Block window change and timer signals.  The latter
170      * is because applications use timers to decide when
171      * to repaint the screen.
172      */
173     (void) sigemptyset(&mask);
174 #ifdef SIGALRM
175     (void) sigaddset(&mask, SIGALRM);
176 #endif
177 #if USE_SIGWINCH
178     (void) sigaddset(&mask, SIGWINCH);
179 #endif
180     (void) sigprocmask(SIG_BLOCK, &mask, &omask);
181 
182 #ifdef SIGTTOU
183     sigttou_blocked = sigismember(&omask, SIGTTOU);
184     if (!sigttou_blocked) {
185 	(void) sigemptyset(&mask);
186 	(void) sigaddset(&mask, SIGTTOU);
187 	(void) sigprocmask(SIG_BLOCK, &mask, NULL);
188     }
189 #endif
190 
191     /*
192      * End window mode, which also resets the terminal state to the
193      * original (pre-curses) modes.
194      */
195     NCURSES_SP_NAME(endwin) (NCURSES_SP_ARG);
196 
197     /* Unblock SIGTSTP. */
198     (void) sigemptyset(&mask);
199     (void) sigaddset(&mask, SIGTSTP);
200 #ifdef SIGTTOU
201     if (!sigttou_blocked) {
202 	/* Unblock this too if it wasn't blocked on entry */
203 	(void) sigaddset(&mask, SIGTTOU);
204     }
205 #endif
206     (void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
207 
208     /* Now we want to resend SIGSTP to this process and suspend it */
209     act.sa_handler = SIG_DFL;
210     sigemptyset(&act.sa_mask);
211     act.sa_flags = 0;
212 #ifdef SA_RESTART
213     act.sa_flags |= SA_RESTART;
214 #endif /* SA_RESTART */
215     sigaction(SIGTSTP, &act, &oact);
216     kill(getpid(), SIGTSTP);
217 
218     /* Process gets suspended...time passes...process resumes */
219 
220     T(("SIGCONT received"));
221     sigaction(SIGTSTP, &oact, NULL);
222     NCURSES_SP_NAME(flushinp) (NCURSES_SP_ARG);
223 
224     /*
225      * If the user modified the tty state while suspended, he wants
226      * those changes to stick.  So save the new "default" terminal state.
227      */
228     NCURSES_SP_NAME(def_shell_mode) (NCURSES_SP_ARG);
229 
230     /*
231      * This relies on the fact that doupdate() will restore the
232      * program-mode tty state, and issue enter_ca_mode if need be.
233      */
234     NCURSES_SP_NAME(doupdate) (NCURSES_SP_ARG);
235 
236     /* Reset the signals. */
237     (void) sigprocmask(SIG_SETMASK, &omask, NULL);
238 }
239 #endif /* USE_SIGTSTP */
240 
241 static void
242 cleanup(int sig)
243 {
244     SCREEN *sp = CURRENT_SCREEN;
245 
246     /*
247      * Actually, doing any sort of I/O from within an signal handler is
248      * "unsafe".  But we'll _try_ to clean up the screen and terminal
249      * settings on the way out.
250      */
251     if (!_nc_globals.cleanup_nested++
252 	&& (sig == SIGINT
253 #ifdef SIGQUIT
254 	    || sig == SIGQUIT
255 #endif
256 	)) {
257 #if HAVE_SIGACTION || HAVE_SIGVEC
258 	sigaction_t act;
259 	sigemptyset(&act.sa_mask);
260 	act.sa_flags = 0;
261 	act.sa_handler = SIG_IGN;
262 	if (sigaction(sig, &act, NULL) == 0)
263 #else
264 	if (signal(sig, SIG_IGN) != SIG_ERR)
265 #endif
266 	{
267 	    SCREEN *scan;
268 	    for (each_screen(scan)) {
269 		if (scan->_ofp != 0
270 		    && isatty(fileno(scan->_ofp))) {
271 		    scan->_cleanup = TRUE;
272 		    scan->_outch = NCURSES_SP_NAME(_nc_outch);
273 		}
274 		set_term(scan);
275 		NCURSES_SP_NAME(endwin) (NCURSES_SP_ARG);
276 		if (sp)
277 		    sp->_endwin = FALSE;	/* in case we have an atexit! */
278 	    }
279 	}
280     }
281     exit(EXIT_FAILURE);
282 }
283 
284 #if USE_SIGWINCH
285 static void
286 sigwinch(int sig GCC_UNUSED)
287 {
288     _nc_globals.have_sigwinch = 1;
289 # if USE_PTHREADS_EINTR
290     if (_nc_globals.read_thread) {
291 	if (!pthread_equal(pthread_self(), _nc_globals.read_thread))
292 	    pthread_kill(_nc_globals.read_thread, SIGWINCH);
293 	_nc_globals.read_thread = 0;
294     }
295 # endif
296 }
297 #endif /* USE_SIGWINCH */
298 
299 /*
300  * If the given signal is still in its default state, set it to the given
301  * handler.
302  */
303 static int
304 CatchIfDefault(int sig, RETSIGTYPE (*handler) (int))
305 {
306     int result;
307 #if HAVE_SIGACTION || HAVE_SIGVEC
308     sigaction_t old_act;
309     sigaction_t new_act;
310 
311     memset(&new_act, 0, sizeof(new_act));
312     sigemptyset(&new_act.sa_mask);
313 #ifdef SA_RESTART
314 #ifdef SIGWINCH
315     if (sig != SIGWINCH)
316 #endif
317 	new_act.sa_flags |= SA_RESTART;
318 #endif /* SA_RESTART */
319     new_act.sa_handler = handler;
320 
321     if (sigaction(sig, NULL, &old_act) == 0
322 	&& (old_act.sa_handler == SIG_DFL
323 	    || old_act.sa_handler == handler
324 #if USE_SIGWINCH
325 	    || (sig == SIGWINCH && old_act.sa_handler == SIG_IGN)
326 #endif
327 	)) {
328 	(void) sigaction(sig, &new_act, NULL);
329 	result = TRUE;
330     } else {
331 	result = FALSE;
332     }
333 #else /* !HAVE_SIGACTION */
334     RETSIGTYPE (*ohandler) (int);
335 
336     ohandler = signal(sig, SIG_IGN);
337     if (ohandler == SIG_DFL
338 	|| ohandler == handler
339 #if USE_SIGWINCH
340 	|| (sig == SIGWINCH && ohandler == SIG_IGN)
341 #endif
342 	) {
343 	signal(sig, handler);
344 	result = TRUE;
345     } else {
346 	signal(sig, ohandler);
347 	result = FALSE;
348     }
349 #endif
350     T(("CatchIfDefault - will %scatch %s",
351        result ? "" : "not ", signal_name(sig)));
352     return result;
353 }
354 
355 /*
356  * This is invoked once at the beginning (e.g., from 'initscr()'), to
357  * initialize the signal catchers, and thereafter when spawning a shell (and
358  * returning) to disable/enable the SIGTSTP (i.e., ^Z) catcher.
359  *
360  * If the application has already set one of the signals, we'll not modify it
361  * (during initialization).
362  *
363  * The XSI document implies that we shouldn't keep the SIGTSTP handler if
364  * the caller later changes its mind, but that doesn't seem correct.
365  */
366 NCURSES_EXPORT(void)
367 _nc_signal_handler(bool enable)
368 {
369     T((T_CALLED("_nc_signal_handler(%d)"), enable));
370 #if USE_SIGTSTP			/* Xenix 2.x doesn't have SIGTSTP, for example */
371     {
372 	static bool ignore_tstp = FALSE;
373 
374 	if (!ignore_tstp) {
375 	    static sigaction_t new_sigaction, old_sigaction;
376 
377 	    if (!enable) {
378 		new_sigaction.sa_handler = SIG_IGN;
379 		sigaction(SIGTSTP, &new_sigaction, &old_sigaction);
380 	    } else if (new_sigaction.sa_handler != SIG_DFL) {
381 		sigaction(SIGTSTP, &old_sigaction, NULL);
382 	    } else if (sigaction(SIGTSTP, NULL, &old_sigaction) == 0
383 		       && (old_sigaction.sa_handler == SIG_DFL)) {
384 		sigemptyset(&new_sigaction.sa_mask);
385 #ifdef SA_RESTART
386 		new_sigaction.sa_flags |= SA_RESTART;
387 #endif /* SA_RESTART */
388 		new_sigaction.sa_handler = tstp;
389 		(void) sigaction(SIGTSTP, &new_sigaction, NULL);
390 	    } else {
391 		ignore_tstp = TRUE;
392 	    }
393 	}
394     }
395 #endif /* !USE_SIGTSTP */
396 
397     if (!_nc_globals.init_signals) {
398 	if (enable) {
399 	    CatchIfDefault(SIGINT, cleanup);
400 	    CatchIfDefault(SIGTERM, cleanup);
401 #if USE_SIGWINCH
402 	    CatchIfDefault(SIGWINCH, sigwinch);
403 #endif
404 	    _nc_globals.init_signals = TRUE;
405 	}
406     }
407     returnVoid;
408 }
409