Skip to content

Commit

Permalink
Don't eagerly close tty fd in read_secure
Browse files Browse the repository at this point in the history
The tcsetattr was failing because the fd was closed in the if statement
before, where it was moved out.
  • Loading branch information
Noratrieb authored and djc committed Dec 16, 2024
1 parent ddc83cd commit 3055c33
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/unix_term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub fn terminal_size(out: &Term) -> Option<(u16, u16)> {
}

pub fn read_secure() -> io::Result<String> {
let f_tty;
let mut f_tty;
let fd = unsafe {
if libc::isatty(libc::STDIN_FILENO) == 1 {
f_tty = None;
Expand All @@ -91,14 +91,17 @@ pub fn read_secure() -> io::Result<String> {
c_result(|| unsafe { libc::tcsetattr(fd, libc::TCSAFLUSH, &termios) })?;
let mut rv = String::new();

let read_rv = if let Some(mut f) = f_tty {
let read_rv = if let Some(f) = &mut f_tty {
f.read_line(&mut rv)
} else {
io::stdin().read_line(&mut rv)
};

c_result(|| unsafe { libc::tcsetattr(fd, libc::TCSAFLUSH, &original) })?;

// Ensure the fd is only closed after everything has been restored.
drop(f_tty);

read_rv.map(|_| {
let len = rv.trim_end_matches(&['\r', '\n'][..]).len();
rv.truncate(len);
Expand Down

0 comments on commit 3055c33

Please sign in to comment.