Prevent init(8) from using the tty when a daemon uses it.

This commit is contained in:
Jonas 'Sortie' Termansen 2024-06-16 19:57:02 +00:00
parent e90e2077e7
commit 5d18d8be30

View file

@ -314,6 +314,7 @@ struct communication
static pid_t main_pid;
static pid_t forward_signal_pid = -1;
static int tty_fd;
static bool tty_gifted;
static volatile sig_atomic_t caught_exit_signal = -1;
static sigset_t handled_signals;
@ -937,6 +938,8 @@ static void log_status(const char* status, const char* format, ...)
strcmp(status, "failed") != 0 &&
strcmp(status, "timeout") != 0) )
return;
if ( tty_gifted )
return;
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
struct tm tm;
@ -981,6 +984,7 @@ static void log_status(const char* status, const char* format, ...)
__attribute__((format(printf, 1, 2)))
noreturn static void fatal(const char* format, ...)
{
// TODO: Reclaim tty? Avoid potenteial SIGTTOU.
va_list ap;
va_start(ap, format);
fprintf(stderr, "%s: fatal: ", program_invocation_name);
@ -1004,12 +1008,15 @@ __attribute__((format(printf, 1, 2)))
static void warning(const char* format, ...)
{
va_list ap;
va_start(ap, format);
fprintf(stderr, "%s: warning: ", program_invocation_name);
vfprintf(stderr, format, ap);
fprintf(stderr, "\n");
fflush(stderr);
va_end(ap);
if ( !tty_gifted )
{
va_start(ap, format);
fprintf(stderr, "%s: warning: ", program_invocation_name);
vfprintf(stderr, format, ap);
fprintf(stderr, "\n");
fflush(stderr);
va_end(ap);
}
if ( getpid() == main_pid )
{
va_start(ap, format);
@ -1023,12 +1030,15 @@ __attribute__((format(printf, 1, 2)))
static void note(const char* format, ...)
{
va_list ap;
va_start(ap, format);
fprintf(stderr, "%s: ", program_invocation_name);
vfprintf(stderr, format, ap);
fprintf(stderr, "\n");
fflush(stderr);
va_end(ap);
if ( !tty_gifted )
{
va_start(ap, format);
fprintf(stderr, "%s: ", program_invocation_name);
vfprintf(stderr, format, ap);
fprintf(stderr, "\n");
fflush(stderr);
va_end(ap);
}
if ( getpid() == main_pid )
{
va_start(ap, format);
@ -2541,6 +2551,8 @@ static void daemon_start(struct daemon* daemon)
int errfds[2];
if ( pipe2(errfds, O_CLOEXEC) < 0 )
fatal("pipe");
if ( daemon->need_tty )
tty_gifted = true;
daemon->pid = daemon->log.pid = fork();
if ( daemon->pid < 0 )
fatal("fork: %m");
@ -2719,8 +2731,10 @@ static void daemon_on_exit(struct daemon* daemon, int exit_code)
sigprocmask(SIG_BLOCK, &sigttou, &oldset);
if ( tcsetattr(tty_fd, TCSAFLUSH, &daemon->oldtio) )
fatal("tcsetattr: %m");
// TODO: Do this in niht too?
if ( ioctl(tty_fd, TIOCSCTTY, 1) < 0 )
fatal("TIOCSCTTY: %m");
tty_gifted = false;
sigprocmask(SIG_SETMASK, &oldset, NULL);
}
daemon_on_finished(daemon);