From fe23507043d5d476e382d364270fcc9419475958 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Mon, 25 May 2020 21:37:07 -0400 Subject: fix finding the active tty name apparently $TTY is a shell builtin variable, and not set in the actual environment --- src/bin/rbw/actions.rs | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/bin/rbw/actions.rs b/src/bin/rbw/actions.rs index 035ebe6..8eabdd6 100644 --- a/src/bin/rbw/actions.rs +++ b/src/bin/rbw/actions.rs @@ -25,7 +25,7 @@ pub fn quit() -> anyhow::Result<()> { std::fs::File::open(pidfile)?.read_to_string(&mut pid)?; let pid = nix::unistd::Pid::from_raw(pid.parse()?); sock.send(&rbw::protocol::Request { - tty: std::env::var("TTY").ok(), + tty: ttyname(), action: rbw::protocol::Action::Quit, })?; wait_for_exit(pid)?; @@ -48,7 +48,7 @@ pub fn decrypt( let mut sock = crate::sock::Sock::connect() .context("failed to connect to rbw-agent")?; sock.send(&rbw::protocol::Request { - tty: std::env::var("TTY").ok(), + tty: ttyname(), action: rbw::protocol::Action::Decrypt { cipherstring: cipherstring.to_string(), org_id: org_id.map(std::string::ToString::to_string), @@ -72,7 +72,7 @@ pub fn encrypt( let mut sock = crate::sock::Sock::connect() .context("failed to connect to rbw-agent")?; sock.send(&rbw::protocol::Request { - tty: std::env::var("TTY").ok(), + tty: ttyname(), action: rbw::protocol::Action::Encrypt { plaintext: plaintext.to_string(), org_id: org_id.map(std::string::ToString::to_string), @@ -93,7 +93,7 @@ pub fn version() -> anyhow::Result { let mut sock = crate::sock::Sock::connect() .context("failed to connect to rbw-agent")?; sock.send(&rbw::protocol::Request { - tty: std::env::var("TTY").ok(), + tty: ttyname(), action: rbw::protocol::Action::Version, })?; @@ -112,7 +112,7 @@ fn simple_action(action: rbw::protocol::Action) -> anyhow::Result<()> { .context("failed to connect to rbw-agent")?; sock.send(&rbw::protocol::Request { - tty: std::env::var("TTY").ok(), + tty: ttyname(), action, })?; @@ -126,6 +126,27 @@ fn simple_action(action: rbw::protocol::Action) -> anyhow::Result<()> { } } +// TODO: it'd be great if ttyname_r was exposed via nix, so i didn't have to +// manually deal with unsafe here +fn ttyname() -> Option { + const PATH_MAX: usize = libc::PATH_MAX as usize; + let mut buf = [0_u8; PATH_MAX]; + let c_buf = buf.as_mut_ptr() as *mut libc::c_char; + + let ret = unsafe { libc::ttyname_r(0, c_buf, PATH_MAX) }; + if ret != 0 { + return None; + } + + let nul = memchr::memchr(b'\0', &buf)?; + if nul == 0 { + return None; + } + + let s = std::str::from_utf8(&buf[..nul]).ok()?; + Some(s.to_string()) +} + fn wait_for_exit(pid: nix::unistd::Pid) -> anyhow::Result<()> { loop { if nix::sys::signal::kill(pid, None).is_err() { -- cgit v1.2.3-54-g00ecf