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.
This commit is contained in:
Wez Furlong committed 2019-08-06 15:03:25 -07:00
1 parent 073615ef39
commit 786a4c8551
6 files changed
+95 -82

No files matched your search

+77 -6
View File
@@ -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<S: AsRef<OsStr>>(&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<std::process::Command> {
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<String> {
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<String> {
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<u16>, Vec<u16>), Error> {
let mut cmdline = Vec::<u16>::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
+6 -2
View File
@@ -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<dyn Child> = Box::new(SshChild {
pty: self.pty.clone(),
+1 -1
View File
@@ -94,7 +94,7 @@ fn cloexec(fd: RawFd) -> Result<(), Error> {
impl SlavePty for UnixSlavePty {
fn spawn_command(&self, builder: CommandBuilder) -> Result<Box<dyn Child>, Error> {
let mut cmd = builder.as_command();
let mut cmd = builder.as_command()?;
unsafe {
cmd.stdin(self.as_stdio()?)
+9 -42
View File
@@ -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<Vec<String>, 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<Vec<String>, 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<Vec<&OsStr>>) -> Result<CommandBuilder, Error> {
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()
}
}
};
+1 -30
View File
@@ -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<String, Error> {
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<String, Error> {
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);
// !=
+1 -1
View File
@@ -256,7 +256,7 @@ impl Domain for RemoteSshDomain {
) -> Result<Rc<dyn Tab>, 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)?;