Skip to content

Commit

Permalink
terminal: teach save_term to fail when not foreground
Browse files Browse the repository at this point in the history
e22b245 (terminal: teach git how to save/restore its terminal
settings, 2021-10-05) allows external calls to the termios code,
but kept the assumption that all operations were done with
foreground processes, which was proven incorrect.

Add a check to validate that the current process is indeed in the
foreground and in control of the terminal and fail early if not the
case.

To avoid changing behaviour from the other users of save_term() the
full_duplex parameter has been overloaded to restrict the new check
to only future callers, as it is set to 0 for all current users.

The detection is done in a helper function so it can be reused by
all other functions that might benefit from it later, and once that
is done that overloading might be unnecessary and cleaned up, but
doing so has been punted from this series as it is not needed and
might require backward incompatible changes.

Helped-by: Phillip Wood <[email protected]>
Signed-off-by: Carlo Marcelo Arenas Belón <[email protected]>
  • Loading branch information
carenas committed Nov 30, 2021
1 parent abe6bb3 commit 4438e93
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion compat/terminal.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,31 @@ void restore_term(void)
return;

tcsetattr(term_fd, TCSAFLUSH, &old_term);

close(term_fd);
term_fd = -1;
}

static int is_controlling_terminal(int fd)
{
return (getpgid(0) == tcgetpgrp(fd));
}

int save_term(int full_duplex)
{
if (term_fd < 0)
term_fd = open("/dev/tty", O_RDWR);

return (term_fd < 0) ? -1 : tcgetattr(term_fd, &old_term);
if (term_fd < 0)
return -1;

if (full_duplex && !is_controlling_terminal(term_fd)) {
close(term_fd);
term_fd = -1;
return -1;
}

return tcgetattr(term_fd, &old_term);
}

static int disable_bits(tcflag_t bits)
Expand Down

0 comments on commit 4438e93

Please sign in to comment.