From 786a4c85515abd2bab9bfb93b886b0f13a969360 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 6 Aug 2019 15:03:25 -0700 Subject: [PATCH] pty: add concept of "default prog" to the pty layer Previously we had the logic for this in wezterm itself; it would know how to figure out which shell to run, or whether we should run a different program by default (the `default_prog` setting). This was OK, but when I added support for ssh we hit a conceptual issue: the local side of the ssh session doesn't have any information about the shell that should be invoked on the remote side and instead needs to ask the remote to figure that out. The interfaces defined in the code didn't allow for this. This commit formalizes the concept of a default program and allows it to be carried through to the pty layer, including over ssh sessions. Since we now have enough smarts to figure out the local shell and the local home dir, I've removed the logic that run `login -pf` on macos by default; this should make the terminal startup very slightly faster on macos, but since I'm currently on a windows system, I can only test linux and windows on this side of this commit. I'll follow up on macos later. --- pty/src/cmdbuilder.rs | 83 +++++++++++++++++++++++++++++++++++++++---- pty/src/ssh.rs | 8 +++-- pty/src/unix.rs | 2 +- src/config.rs | 51 +++++--------------------- src/main.rs | 31 +--------------- src/ssh.rs | 2 +- 6 files changed, 95 insertions(+), 82 deletions(-) diff --git a/pty/src/cmdbuilder.rs b/pty/src/cmdbuilder.rs index e5ef5714b..5b5a2a4d4 100644 --- a/pty/src/cmdbuilder.rs +++ b/pty/src/cmdbuilder.rs @@ -1,5 +1,7 @@ #[cfg(windows)] use failure::{ensure, Error}; +#[cfg(unix)] +use failure::{format_err, Fallible}; #[cfg(feature = "serde_support")] use serde_derive::*; use std::ffi::{OsStr, OsString}; @@ -25,8 +27,26 @@ impl CommandBuilder { } } - /// Append an argument to the current command line + /// Create a new builder instance that will run some idea of a default + /// program. Such a builder will panic if `arg` is called on it. + pub fn new_default_prog() -> Self { + Self { + args: vec![], + envs: vec![], + } + } + + /// Returns true if this builder was created via `new_default_prog` + pub fn is_default_prog(&self) -> bool { + self.args.is_empty() + } + + /// Append an argument to the current command line. + /// Will panic if called on a builder created via `new_default_prog`. pub fn arg>(&mut self, arg: S) { + if self.is_default_prog() { + panic!("attempted to add args to a default_prog builder"); + } self.args.push(arg.as_ref().to_owned()); } @@ -76,14 +96,60 @@ impl CommandBuilder { #[cfg(unix)] impl CommandBuilder { /// Convert the CommandBuilder to a `std::process::Command` instance. - pub(crate) fn as_command(&self) -> std::process::Command { - let mut cmd = std::process::Command::new(&self.args[0]); - cmd.args(&self.args[1..]); + pub(crate) fn as_command(&self) -> Fallible { + let mut cmd = if self.is_default_prog() { + let mut cmd = std::process::Command::new(&Self::get_shell()?); + cmd.current_dir(Self::get_home_dir()?); + cmd + } else { + let mut cmd = std::process::Command::new(&self.args[0]); + cmd.args(&self.args[1..]); + cmd + }; + for (key, val) in &self.envs { cmd.env(key, val); } - cmd + Ok(cmd) + } + + /// Determine which shell to run. + /// We take the contents of the $SHELL env var first, then + /// fall back to looking it up from the password database. + fn get_shell() -> Fallible { + std::env::var("SHELL").or_else(|_| { + let ent = unsafe { libc::getpwuid(libc::getuid()) }; + + if ent.is_null() { + Ok("/bin/sh".into()) + } else { + use std::ffi::CStr; + use std::str; + let shell = unsafe { CStr::from_ptr((*ent).pw_shell) }; + shell + .to_str() + .map(str::to_owned) + .map_err(|e| format_err!("failed to resolve shell: {:?}", e)) + } + }) + } + + fn get_home_dir() -> Fallible { + std::env::var("HOME").or_else(|_| { + let ent = unsafe { libc::getpwuid(libc::getuid()) }; + + if ent.is_null() { + Ok("/".into()) + } else { + use std::ffi::CStr; + use std::str; + let home = unsafe { CStr::from_ptr((*ent).pw_dir) }; + home.to_str() + .map(str::to_owned) + .map_err(|e| format_err!("failed to resolve home dir: {:?}", e)) + } + }) } } @@ -148,7 +214,12 @@ impl CommandBuilder { pub(crate) fn cmdline(&self) -> Result<(Vec, Vec), Error> { let mut cmdline = Vec::::new(); - let exe = Self::search_path(&self.args[0]); + let exe = if self.is_default_prog() { + std::env::var_os("ComSpec").unwrap_or("cmd.exe".into()) + } else { + Self::search_path(&self.args[0]) + }; + Self::append_quoted(&exe, &mut cmdline); // Ensure that we nul terminate the module name, otherwise we'll diff --git a/pty/src/ssh.rs b/pty/src/ssh.rs index db4d33fb0..b0f6381ac 100644 --- a/pty/src/ssh.rs +++ b/pty/src/ssh.rs @@ -191,8 +191,12 @@ impl SlavePty for SshSlave { .map_err(|e| format_err!("ssh: setenv {}={} failed: {}", key, val, e))?; } - let command = cmd.as_unix_command_line()?; - channel.exec(&command)?; + if cmd.is_default_prog() { + channel.shell()?; + } else { + let command = cmd.as_unix_command_line()?; + channel.exec(&command)?; + } let child: Box = Box::new(SshChild { pty: self.pty.clone(), diff --git a/pty/src/unix.rs b/pty/src/unix.rs index 62b429bfb..dcc564a5f 100644 --- a/pty/src/unix.rs +++ b/pty/src/unix.rs @@ -94,7 +94,7 @@ fn cloexec(fd: RawFd) -> Result<(), Error> { impl SlavePty for UnixSlavePty { fn spawn_command(&self, builder: CommandBuilder) -> Result, Error> { - let mut cmd = builder.as_command(); + let mut cmd = builder.as_command()?; unsafe { cmd.stdin(self.as_stdio()?) diff --git a/src/config.rs b/src/config.rs index 053d3a9af..18e6462de 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,10 +1,10 @@ //! Configuration for the gui portion of the terminal +use crate::create_user_owned_dirs; use crate::font::FontSystemSelection; use crate::frontend::guicommon::host::KeyAssignment; use crate::frontend::guicommon::window::SpawnTabDomain; use crate::frontend::FrontEndSelection; -use crate::{create_user_owned_dirs, get_shell}; use failure::{bail, err_msg, format_err, Error, Fallible}; use lazy_static::lazy_static; use portable_pty::{CommandBuilder, PtySystemSelection}; @@ -890,42 +890,6 @@ impl Config { cfg } - /// On macOS, we get launched from: eg: spotlight or alfred - /// or the finder with whatever SHELL was set to at login time - /// (which have been subsequently changed via `chsh`) and with - /// a cwd=/. - /// That feels a bit broken, so we follow the lead of - /// Terminal.app and use `login -pf $USER` as the default - /// program to run. - /// This function computes and returns that command. - /// We don't do this on Linux because the linux `login` - /// program refuses to run except when started by root. - #[cfg(target_os = "macos")] - fn macos_login() -> Result, Error> { - let ent = unsafe { libc::getpwuid(libc::getuid()) }; - if ent.is_null() { - bail!("unable to resolve my own uid"); - } else { - let name = unsafe { std::ffi::CStr::from_ptr((*ent).pw_name) }; - let name = name.to_str().map(str::to_owned)?; - Ok(vec!["login".to_owned(), "-pf".to_owned(), name]) - } - } - - pub fn default_prog(&self) -> Result, Error> { - if let Some(prog) = self.default_prog.as_ref() { - Ok(prog.clone()) - } else { - #[cfg(target_os = "macos")] - { - if let Ok(login) = Self::macos_login() { - return Ok(login); - } - } - Ok(vec![get_shell()?]) - } - } - pub fn build_prog(&self, prog: Option>) -> Result { let mut cmd = match prog { Some(args) => { @@ -935,11 +899,14 @@ impl Config { cmd } None => { - let prog = self.default_prog()?; - let mut args = prog.iter(); - let mut cmd = CommandBuilder::new(args.next().expect("executable name")); - cmd.args(args); - cmd + if let Some(prog) = self.default_prog.as_ref() { + let mut args = prog.iter(); + let mut cmd = CommandBuilder::new(args.next().expect("executable name")); + cmd.args(args); + cmd + } else { + CommandBuilder::new_default_prog() + } } }; diff --git a/src/main.rs b/src/main.rs index 0a808b8fe..827d85d7d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,40 +28,11 @@ use crate::mux::Mux; use crate::server::client::{unix_connect_with_retry, Client}; use crate::server::domain::{ClientDomain, ClientDomainConfig}; use portable_pty::cmdbuilder::CommandBuilder; +use portable_pty::PtySize; mod font; use crate::font::{FontConfiguration, FontSystemSelection}; -use portable_pty::PtySize; -use std::env; - -/// Determine which shell to run. -/// We take the contents of the $SHELL env var first, then -/// fall back to looking it up from the password database. -#[cfg(unix)] -fn get_shell() -> Result { - env::var("SHELL").or_else(|_| { - let ent = unsafe { libc::getpwuid(libc::getuid()) }; - - if ent.is_null() { - Ok("/bin/sh".into()) - } else { - use std::ffi::CStr; - use std::str; - let shell = unsafe { CStr::from_ptr((*ent).pw_shell) }; - shell - .to_str() - .map(str::to_owned) - .map_err(|e| format_err!("failed to resolve shell: {:?}", e)) - } - }) -} - -#[cfg(windows)] -fn get_shell() -> Result { - Ok(env::var("ComSpec").unwrap_or("cmd.exe".into())) -} - // let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m."; // terminal.advance_bytes(message); // != diff --git a/src/ssh.rs b/src/ssh.rs index 55c2ec8d7..9d08976d1 100644 --- a/src/ssh.rs +++ b/src/ssh.rs @@ -256,7 +256,7 @@ impl Domain for RemoteSshDomain { ) -> Result, Error> { let cmd = match command { Some(c) => c, - None => CommandBuilder::new("bash"), + None => CommandBuilder::new_default_prog(), }; let pair = self.pty_system.openpty(size)?; let child = pair.slave.spawn_command(cmd)?;