#include <config.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include "sudo.h"
#include "sudo_exec.h"
int signal_pipe[2];
static struct signal_state {
int signo;
int restore;
sigaction_t sa;
} saved_signals[] = {
{ SIGALRM },
{ SIGCHLD },
{ SIGCONT },
{ SIGHUP },
{ SIGINT },
{ SIGPIPE },
{ SIGQUIT },
{ SIGTERM },
{ SIGTSTP },
{ SIGTTIN },
{ SIGTTOU },
{ SIGUSR1 },
{ SIGUSR2 },
{ -1 }
};
void
save_signals(void)
{
struct signal_state *ss;
debug_decl(save_signals, SUDO_DEBUG_MAIN)
for (ss = saved_signals; ss->signo != -1; ss++) {
if (sigaction(ss->signo, NULL, &ss->sa) != 0)
sudo_warn(U_("unable to save handler for signal %d"), ss->signo);
}
debug_return;
}
void
restore_signals(void)
{
struct signal_state *ss;
debug_decl(restore_signals, SUDO_DEBUG_MAIN)
for (ss = saved_signals; ss->signo != -1; ss++) {
if (ss->restore) {
if (sigaction(ss->signo, &ss->sa, NULL) != 0) {
sudo_warn(U_("unable to restore handler for signal %d"),
ss->signo);
}
}
}
debug_return;
}
static void
sudo_handler(int s)
{
unsigned char signo = (unsigned char)s;
while (write(signal_pipe[1], &signo, sizeof(signo)) == -1) {
if (errno != EINTR)
break;
}
}
void
init_signals(void)
{
struct sigaction sa;
struct signal_state *ss;
debug_decl(init_signals, SUDO_DEBUG_MAIN)
if (pipe_nonblock(signal_pipe) != 0)
sudo_fatal(U_("unable to create pipe"));
memset(&sa, 0, sizeof(sa));
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = sudo_handler;
for (ss = saved_signals; ss->signo > 0; ss++) {
switch (ss->signo) {
case SIGCHLD:
case SIGCONT:
case SIGPIPE:
case SIGTTIN:
case SIGTTOU:
break;
default:
if (ss->sa.sa_handler != SIG_IGN) {
if (sigaction(ss->signo, &sa, NULL) != 0) {
sudo_warn(U_("unable to set handler for signal %d"),
ss->signo);
}
}
break;
}
}
if (saved_signals[SAVED_SIGPIPE].sa.sa_handler != SIG_IGN) {
sa.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &sa, NULL) != 0)
sudo_warn(U_("unable to set handler for signal %d"), SIGPIPE);
}
debug_return;
}
int
sudo_sigaction(int signo, struct sigaction *sa, struct sigaction *osa)
{
struct signal_state *ss;
int rval;
debug_decl(sudo_sigaction, SUDO_DEBUG_MAIN)
for (ss = saved_signals; ss->signo > 0; ss++) {
if (ss->signo == signo) {
if (ss->sa.sa_handler == SIG_IGN || sa->sa_handler == SIG_IGN) {
sudo_debug_printf(SUDO_DEBUG_INFO,
"will restore signal %d on exec", signo);
ss->restore = true;
}
break;
}
}
rval = sigaction(signo, sa, osa);
debug_return_int(rval);
}