Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 80e922957e | |||
| 1dcb33550e | |||
| 2c5b9ab30d |
Generated
+1
-1
@@ -436,7 +436,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dosh"
|
name = "dosh"
|
||||||
version = "1.0.0-rc26"
|
version = "1.0.0-rc29"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dosh"
|
name = "dosh"
|
||||||
version = "1.0.0-rc26"
|
version = "1.0.0-rc29"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
|
|||||||
@@ -68,6 +68,18 @@ dosh restart HOST
|
|||||||
Agent forwarding is opt-in with `-A` and must also be enabled on the server.
|
Agent forwarding is opt-in with `-A` and must also be enabled on the server.
|
||||||
File copy must be enabled by the server config.
|
File copy must be enabled by the server config.
|
||||||
|
|
||||||
|
## Tracing
|
||||||
|
|
||||||
|
For terminal/reconnect bugs, run a client with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
DOSH_TRACE=/tmp/dosh-client.log DOSH_TRACE_BYTES=1 dosh HOST
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `DOSH_TRACE=/tmp/dosh-server.log` on `dosh-server` for matching server
|
||||||
|
events. `DOSH_TRACE_BYTES=1` records byte prefixes, so use it only for short
|
||||||
|
reproductions.
|
||||||
|
|
||||||
## VS Code
|
## VS Code
|
||||||
|
|
||||||
Dosh can carry VS Code Remote-SSH through its transport:
|
Dosh can carry VS Code Remote-SSH through its transport:
|
||||||
|
|||||||
+565
-61
@@ -1866,6 +1866,30 @@ impl FileServiceClient {
|
|||||||
other => bail!("unexpected mkdir response: {other:?}"),
|
other => bail!("unexpected mkdir response: {other:?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn readlink(&mut self, path: &str) -> Result<String> {
|
||||||
|
self.send(FileRequest::Readlink {
|
||||||
|
path: path.to_string(),
|
||||||
|
})?;
|
||||||
|
match self.recv()? {
|
||||||
|
FileResponse::LinkTarget { target } => Ok(target),
|
||||||
|
FileResponse::Error { message } => Err(anyhow!(message)),
|
||||||
|
other => bail!("unexpected readlink response: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn symlink(&mut self, path: &str, target: &str, overwrite: bool) -> Result<()> {
|
||||||
|
self.send(FileRequest::Symlink {
|
||||||
|
path: path.to_string(),
|
||||||
|
target: target.to_string(),
|
||||||
|
overwrite,
|
||||||
|
})?;
|
||||||
|
match self.recv()? {
|
||||||
|
FileResponse::Ok => Ok(()),
|
||||||
|
FileResponse::Error { message } => Err(anyhow!(message)),
|
||||||
|
other => bail!("unexpected symlink response: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_cp_command(_config: &dosh::config::ClientConfig, args: &Args) -> Result<()> {
|
fn run_cp_command(_config: &dosh::config::ClientConfig, args: &Args) -> Result<()> {
|
||||||
@@ -2197,6 +2221,18 @@ fn upload_path(
|
|||||||
let metadata =
|
let metadata =
|
||||||
fs::symlink_metadata(local).with_context(|| format!("stat {}", local.display()))?;
|
fs::symlink_metadata(local).with_context(|| format!("stat {}", local.display()))?;
|
||||||
let remote = upload_destination(client, local, remote, metadata.is_dir())?;
|
let remote = upload_destination(client, local, remote, metadata.is_dir())?;
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
let target =
|
||||||
|
fs::read_link(local).with_context(|| format!("readlink {}", local.display()))?;
|
||||||
|
let target = target
|
||||||
|
.to_str()
|
||||||
|
.ok_or_else(|| anyhow!("symlink target is not valid UTF-8: {}", local.display()))?;
|
||||||
|
client.symlink(&remote, target, opts.overwrite)?;
|
||||||
|
if opts.progress {
|
||||||
|
eprintln!("linked {} -> {}", remote, target);
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
if metadata.is_dir() {
|
if metadata.is_dir() {
|
||||||
anyhow::ensure!(
|
anyhow::ensure!(
|
||||||
opts.recursive,
|
opts.recursive,
|
||||||
@@ -2343,8 +2379,9 @@ fn download_path(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
FileKind::File => download_file(client, remote, &destination, &meta, opts),
|
FileKind::File => download_file(client, remote, &destination, &meta, opts),
|
||||||
|
FileKind::Symlink => download_symlink(client, remote, &destination, opts),
|
||||||
_ => Err(anyhow!(
|
_ => Err(anyhow!(
|
||||||
"remote path is not a regular file or directory: {remote}"
|
"remote path is not a regular file, directory, or symlink: {remote}"
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2377,8 +2414,16 @@ fn copy_remote_path(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
FileKind::File => copy_remote_file(src_client, dst_client, src, &dst, &meta, opts),
|
FileKind::File => copy_remote_file(src_client, dst_client, src, &dst, &meta, opts),
|
||||||
|
FileKind::Symlink => {
|
||||||
|
let target = src_client.readlink(src)?;
|
||||||
|
dst_client.symlink(&dst, &target, opts.overwrite)?;
|
||||||
|
if opts.progress {
|
||||||
|
eprintln!("linked {dst} -> {target}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
_ => Err(anyhow!(
|
_ => Err(anyhow!(
|
||||||
"remote path is not a regular file or directory: {src}"
|
"remote path is not a regular file, directory, or symlink: {src}"
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2609,6 +2654,45 @@ fn download_file(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn download_symlink(
|
||||||
|
client: &mut FileServiceClient,
|
||||||
|
remote: &str,
|
||||||
|
local: &Path,
|
||||||
|
opts: &CpOptions,
|
||||||
|
) -> Result<()> {
|
||||||
|
if let Some(parent) = local.parent()
|
||||||
|
&& !parent.as_os_str().is_empty()
|
||||||
|
{
|
||||||
|
fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
|
||||||
|
}
|
||||||
|
let target = client.readlink(remote)?;
|
||||||
|
create_local_symlink(local, &target, opts.overwrite)?;
|
||||||
|
if opts.progress {
|
||||||
|
eprintln!("linked {} -> {}", local.display(), target);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn create_local_symlink(path: &Path, target: &str, overwrite: bool) -> Result<()> {
|
||||||
|
if let Ok(metadata) = fs::symlink_metadata(path) {
|
||||||
|
anyhow::ensure!(overwrite, "destination exists: {}", path.display());
|
||||||
|
anyhow::ensure!(
|
||||||
|
!metadata.is_dir(),
|
||||||
|
"destination is a directory: {}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
fs::remove_file(path).with_context(|| format!("remove {}", path.display()))?;
|
||||||
|
}
|
||||||
|
std::os::unix::fs::symlink(target, path)
|
||||||
|
.with_context(|| format!("symlink {} -> {}", path.display(), target))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn create_local_symlink(_path: &Path, _target: &str, _overwrite: bool) -> Result<()> {
|
||||||
|
bail!("symlink creation is not supported on this client platform")
|
||||||
|
}
|
||||||
|
|
||||||
fn hash_prefix(file: &mut fs::File, bytes: u64, hasher: &mut Sha256) -> Result<()> {
|
fn hash_prefix(file: &mut fs::File, bytes: u64, hasher: &mut Sha256) -> Result<()> {
|
||||||
file.seek(std::io::SeekFrom::Start(0))?;
|
file.seek(std::io::SeekFrom::Start(0))?;
|
||||||
let mut remaining = bytes;
|
let mut remaining = bytes;
|
||||||
@@ -3948,7 +4032,7 @@ async fn try_native_auth(
|
|||||||
let auth = sign_native_user_auth(
|
let auth = sign_native_user_auth(
|
||||||
config,
|
config,
|
||||||
cli_identity,
|
cli_identity,
|
||||||
ssh_config,
|
&NativeIdentityContext::new(server, ssh_port, ssh_config),
|
||||||
&hello,
|
&hello,
|
||||||
&server_hello.hello,
|
&server_hello.hello,
|
||||||
requested_forwardings,
|
requested_forwardings,
|
||||||
@@ -4099,7 +4183,7 @@ async fn try_native_auth_check(
|
|||||||
let auth = sign_native_user_auth(
|
let auth = sign_native_user_auth(
|
||||||
config,
|
config,
|
||||||
cli_identity,
|
cli_identity,
|
||||||
ssh_config,
|
&NativeIdentityContext::new(server, ssh_port, ssh_config),
|
||||||
&hello,
|
&hello,
|
||||||
&server_hello.hello,
|
&server_hello.hello,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@@ -4134,13 +4218,14 @@ async fn try_native_auth_check(
|
|||||||
fn sign_native_user_auth(
|
fn sign_native_user_auth(
|
||||||
config: &dosh::config::ClientConfig,
|
config: &dosh::config::ClientConfig,
|
||||||
cli_identity: Option<&Path>,
|
cli_identity: Option<&Path>,
|
||||||
ssh_config: &SshConfig,
|
identity_context: &NativeIdentityContext<'_>,
|
||||||
hello: &dosh::native::NativeClientHello,
|
hello: &dosh::native::NativeClientHello,
|
||||||
server_hello: &dosh::native::NativeServerHello,
|
server_hello: &dosh::native::NativeServerHello,
|
||||||
requested_forwardings: Vec<ForwardingRequest>,
|
requested_forwardings: Vec<ForwardingRequest>,
|
||||||
allow_passphrase_prompt: bool,
|
allow_passphrase_prompt: bool,
|
||||||
) -> Result<dosh::native::NativeUserAuth> {
|
) -> Result<dosh::native::NativeUserAuth> {
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
|
let ssh_config = identity_context.ssh_config;
|
||||||
if config.use_ssh_agent && !ssh_config.identities_only {
|
if config.use_ssh_agent && !ssh_config.identities_only {
|
||||||
match ssh_agent::sign_user_auth_with_agent(
|
match ssh_agent::sign_user_auth_with_agent(
|
||||||
hello,
|
hello,
|
||||||
@@ -4155,9 +4240,9 @@ fn sign_native_user_auth(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let identity = if allow_passphrase_prompt {
|
let identity = if allow_passphrase_prompt {
|
||||||
load_first_native_identity(config, cli_identity, ssh_config)
|
load_first_native_identity(config, cli_identity, identity_context)
|
||||||
} else {
|
} else {
|
||||||
load_first_native_identity_noninteractive(config, cli_identity, ssh_config)
|
load_first_native_identity_noninteractive(config, cli_identity, identity_context)
|
||||||
};
|
};
|
||||||
match identity {
|
match identity {
|
||||||
Ok(identity) => {
|
Ok(identity) => {
|
||||||
@@ -4176,12 +4261,12 @@ fn sign_native_user_auth(
|
|||||||
fn load_first_native_identity(
|
fn load_first_native_identity(
|
||||||
config: &dosh::config::ClientConfig,
|
config: &dosh::config::ClientConfig,
|
||||||
cli_identity: Option<&Path>,
|
cli_identity: Option<&Path>,
|
||||||
ssh_config: &SshConfig,
|
identity_context: &NativeIdentityContext<'_>,
|
||||||
) -> Result<ssh_key::PrivateKey> {
|
) -> Result<ssh_key::PrivateKey> {
|
||||||
load_first_native_identity_with_prompt(
|
load_first_native_identity_with_prompt(
|
||||||
config,
|
config,
|
||||||
cli_identity,
|
cli_identity,
|
||||||
ssh_config,
|
identity_context,
|
||||||
prompt_identity_passphrase,
|
prompt_identity_passphrase,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -4189,9 +4274,9 @@ fn load_first_native_identity(
|
|||||||
fn load_first_native_identity_noninteractive(
|
fn load_first_native_identity_noninteractive(
|
||||||
config: &dosh::config::ClientConfig,
|
config: &dosh::config::ClientConfig,
|
||||||
cli_identity: Option<&Path>,
|
cli_identity: Option<&Path>,
|
||||||
ssh_config: &SshConfig,
|
identity_context: &NativeIdentityContext<'_>,
|
||||||
) -> Result<ssh_key::PrivateKey> {
|
) -> Result<ssh_key::PrivateKey> {
|
||||||
load_first_native_identity_with_prompt(config, cli_identity, ssh_config, |path| {
|
load_first_native_identity_with_prompt(config, cli_identity, identity_context, |path| {
|
||||||
Err(anyhow!(
|
Err(anyhow!(
|
||||||
"{} is encrypted; unlock it in ssh-agent or use an unencrypted key for proxy-stdio",
|
"{} is encrypted; unlock it in ssh-agent or use an unencrypted key for proxy-stdio",
|
||||||
path.display()
|
path.display()
|
||||||
@@ -4202,22 +4287,30 @@ fn load_first_native_identity_noninteractive(
|
|||||||
fn load_first_native_identity_with_prompt<F>(
|
fn load_first_native_identity_with_prompt<F>(
|
||||||
config: &dosh::config::ClientConfig,
|
config: &dosh::config::ClientConfig,
|
||||||
cli_identity: Option<&Path>,
|
cli_identity: Option<&Path>,
|
||||||
ssh_config: &SshConfig,
|
identity_context: &NativeIdentityContext<'_>,
|
||||||
mut prompt: F,
|
mut prompt: F,
|
||||||
) -> Result<ssh_key::PrivateKey>
|
) -> Result<ssh_key::PrivateKey>
|
||||||
where
|
where
|
||||||
F: FnMut(&Path) -> Result<String>,
|
F: FnMut(&Path) -> Result<String>,
|
||||||
{
|
{
|
||||||
|
let ssh_config = identity_context.ssh_config;
|
||||||
|
let token_context = &identity_context.path_tokens;
|
||||||
let mut paths = Vec::new();
|
let mut paths = Vec::new();
|
||||||
if let Some(path) = cli_identity {
|
if let Some(path) = cli_identity {
|
||||||
push_identity_path(&mut paths, path.to_path_buf());
|
push_identity_path(&mut paths, path.to_path_buf());
|
||||||
}
|
}
|
||||||
for path in &ssh_config.identity_files {
|
for path in &ssh_config.identity_files {
|
||||||
push_identity_path(&mut paths, expand_tilde(path));
|
push_identity_path(
|
||||||
|
&mut paths,
|
||||||
|
expand_tilde(&expand_ssh_path_tokens(path, token_context)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if !ssh_config.identities_only {
|
if !ssh_config.identities_only {
|
||||||
for path in &config.identity_files {
|
for path in &config.identity_files {
|
||||||
push_identity_path(&mut paths, expand_tilde(path));
|
push_identity_path(
|
||||||
|
&mut paths,
|
||||||
|
expand_tilde(&expand_ssh_path_tokens(path, token_context)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4255,6 +4348,98 @@ fn push_identity_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct SshPathTokenContext {
|
||||||
|
original_host: String,
|
||||||
|
hostname: String,
|
||||||
|
port: u16,
|
||||||
|
remote_user: String,
|
||||||
|
local_user: String,
|
||||||
|
home_dir: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct NativeIdentityContext<'a> {
|
||||||
|
ssh_config: &'a SshConfig,
|
||||||
|
path_tokens: SshPathTokenContext,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> NativeIdentityContext<'a> {
|
||||||
|
fn new(server: &str, ssh_port: Option<u16>, ssh_config: &'a SshConfig) -> Self {
|
||||||
|
Self {
|
||||||
|
ssh_config,
|
||||||
|
path_tokens: ssh_path_token_context(server, ssh_port, ssh_config),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ssh_path_token_context(
|
||||||
|
server: &str,
|
||||||
|
ssh_port: Option<u16>,
|
||||||
|
ssh_config: &SshConfig,
|
||||||
|
) -> SshPathTokenContext {
|
||||||
|
let original_host = ssh_destination_host(server);
|
||||||
|
let hostname = ssh_config
|
||||||
|
.hostname
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| original_host.clone());
|
||||||
|
let port = ssh_config.port.or(ssh_port).unwrap_or(22);
|
||||||
|
let remote_user = ssh_username(server)
|
||||||
|
.or(ssh_config.user.clone())
|
||||||
|
.unwrap_or_else(local_username);
|
||||||
|
let local_user = local_username();
|
||||||
|
let home_dir = dirs::home_dir().map(|path| path.to_string_lossy().to_string());
|
||||||
|
SshPathTokenContext {
|
||||||
|
original_host,
|
||||||
|
hostname,
|
||||||
|
port,
|
||||||
|
remote_user,
|
||||||
|
local_user,
|
||||||
|
home_dir,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_username() -> String {
|
||||||
|
std::env::var("USER")
|
||||||
|
.or_else(|_| std::env::var("USERNAME"))
|
||||||
|
.unwrap_or_else(|_| "unknown".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expand_ssh_path_tokens(path: &str, context: &SshPathTokenContext) -> String {
|
||||||
|
let mut out = String::with_capacity(path.len());
|
||||||
|
let mut chars = path.chars();
|
||||||
|
while let Some(ch) = chars.next() {
|
||||||
|
if ch != '%' {
|
||||||
|
out.push(ch);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(token) = chars.next() else {
|
||||||
|
out.push('%');
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
match token {
|
||||||
|
'%' => out.push('%'),
|
||||||
|
'd' => {
|
||||||
|
if let Some(home_dir) = &context.home_dir {
|
||||||
|
out.push_str(home_dir);
|
||||||
|
} else {
|
||||||
|
out.push('%');
|
||||||
|
out.push(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'h' => out.push_str(&context.hostname),
|
||||||
|
'n' => out.push_str(&context.original_host),
|
||||||
|
'p' => out.push_str(&context.port.to_string()),
|
||||||
|
'r' => out.push_str(&context.remote_user),
|
||||||
|
'u' => out.push_str(&context.local_user),
|
||||||
|
other => {
|
||||||
|
out.push('%');
|
||||||
|
out.push(other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
fn prompt_identity_passphrase(path: &Path) -> Result<String> {
|
fn prompt_identity_passphrase(path: &Path) -> Result<String> {
|
||||||
rpassword::prompt_password(format!("Enter passphrase for {}: ", path.display()))
|
rpassword::prompt_password(format!("Enter passphrase for {}: ", path.display()))
|
||||||
.with_context(|| format!("read passphrase for {}", path.display()))
|
.with_context(|| format!("read passphrase for {}", path.display()))
|
||||||
@@ -4693,7 +4878,12 @@ async fn run_terminal(
|
|||||||
stdin_msg = stdin_rx.recv() => {
|
stdin_msg = stdin_rx.recv() => {
|
||||||
match stdin_msg {
|
match stdin_msg {
|
||||||
Some(mut bytes) => {
|
Some(mut bytes) => {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.stdin",
|
||||||
|
&[("bytes", dosh::trace::bytes_summary(&bytes))],
|
||||||
|
);
|
||||||
if input_matches_escape(&bytes, escape_key.as_deref()) {
|
if input_matches_escape(&bytes, escape_key.as_deref()) {
|
||||||
|
dosh::trace::event("client.escape", &[]);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
let saw_focus_in = input_contains_focus_in(&bytes);
|
let saw_focus_in = input_contains_focus_in(&bytes);
|
||||||
@@ -4701,6 +4891,10 @@ async fn run_terminal(
|
|||||||
&& saw_focus_in
|
&& saw_focus_in
|
||||||
&& last_focus_repaint_at.elapsed() >= FOCUS_REPAINT_COOLDOWN
|
&& last_focus_repaint_at.elapsed() >= FOCUS_REPAINT_COOLDOWN
|
||||||
{
|
{
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.focus_reconnect_start",
|
||||||
|
&[("silent_ms", last_packet_at.elapsed().as_millis().to_string())],
|
||||||
|
);
|
||||||
last_focus_repaint_at = Instant::now();
|
last_focus_repaint_at = Instant::now();
|
||||||
if let Some(frame) = reconnect(
|
if let Some(frame) = reconnect(
|
||||||
&socket,
|
&socket,
|
||||||
@@ -4712,6 +4906,13 @@ async fn run_terminal(
|
|||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.focus_reconnect_ok",
|
||||||
|
&[
|
||||||
|
("output_seq", frame.output_seq.to_string()),
|
||||||
|
("bytes", frame.bytes.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
arm_stale_terminal_input_suppression(
|
arm_stale_terminal_input_suppression(
|
||||||
&mut stale_terminal_input_suppress_until,
|
&mut stale_terminal_input_suppress_until,
|
||||||
@@ -4732,15 +4933,60 @@ async fn run_terminal(
|
|||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let before_focus_strip = bytes.len();
|
||||||
bytes = strip_terminal_focus_reports(&bytes);
|
bytes = strip_terminal_focus_reports(&bytes);
|
||||||
|
if before_focus_strip != bytes.len() {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.focus_stripped",
|
||||||
|
&[
|
||||||
|
("before", before_focus_strip.to_string()),
|
||||||
|
("after", bytes.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
if bytes.is_empty() {
|
if bytes.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if should_strip_unowned_terminal_reports(
|
||||||
|
predictor.alternate_screen,
|
||||||
|
predictor.mouse_tracking,
|
||||||
|
) {
|
||||||
|
let before_mouse_strip = bytes.len();
|
||||||
|
bytes = strip_stale_mouse_reports(&bytes);
|
||||||
|
if before_mouse_strip != bytes.len() {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.unowned_mouse_stripped",
|
||||||
|
&[
|
||||||
|
("before", before_mouse_strip.to_string()),
|
||||||
|
("after", bytes.len().to_string()),
|
||||||
|
("summary", dosh::trace::bytes_summary(&bytes)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if bytes.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
if should_strip_stale_terminal_reports(
|
if should_strip_stale_terminal_reports(
|
||||||
last_packet_at.elapsed(),
|
last_packet_at.elapsed(),
|
||||||
stale_terminal_input_suppress_until,
|
stale_terminal_input_suppress_until,
|
||||||
) {
|
) {
|
||||||
|
let before_mouse_strip = bytes.len();
|
||||||
bytes = strip_stale_mouse_reports(&bytes);
|
bytes = strip_stale_mouse_reports(&bytes);
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.stale_strip",
|
||||||
|
&[
|
||||||
|
("before", before_mouse_strip.to_string()),
|
||||||
|
("after", bytes.len().to_string()),
|
||||||
|
("silent_ms", last_packet_at.elapsed().as_millis().to_string()),
|
||||||
|
(
|
||||||
|
"grace",
|
||||||
|
stale_terminal_input_suppress_until
|
||||||
|
.is_some_and(|deadline| Instant::now() < deadline)
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
if bytes.is_empty() {
|
if bytes.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -4755,6 +5001,13 @@ async fn run_terminal(
|
|||||||
&bytes,
|
&bytes,
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.queue_startup_gate",
|
||||||
|
&[
|
||||||
|
("bytes", dosh::trace::bytes_summary(&bytes)),
|
||||||
|
("pending", pending_user_input.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
queue_pending_user_input(
|
queue_pending_user_input(
|
||||||
&mut pending_user_input,
|
&mut pending_user_input,
|
||||||
&mut pending_user_input_bytes,
|
&mut pending_user_input_bytes,
|
||||||
@@ -4782,6 +5035,10 @@ async fn run_terminal(
|
|||||||
if send_input(&socket, addr, &cred, &mut send_seq, send_now.clone()).await? {
|
if send_input(&socket, addr, &cred, &mut send_seq, send_now.clone()).await? {
|
||||||
predictor.observe_input(&send_now)?;
|
predictor.observe_input(&send_now)?;
|
||||||
} else {
|
} else {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.queue_send_now_stale",
|
||||||
|
&[("bytes", dosh::trace::bytes_summary(&send_now))],
|
||||||
|
);
|
||||||
queue_stale_pending_user_input(
|
queue_stale_pending_user_input(
|
||||||
&mut pending_user_input,
|
&mut pending_user_input,
|
||||||
&mut pending_user_input_bytes,
|
&mut pending_user_input_bytes,
|
||||||
@@ -4799,6 +5056,16 @@ async fn run_terminal(
|
|||||||
StartupGateMode::HoldAll
|
StartupGateMode::HoldAll
|
||||||
};
|
};
|
||||||
if should_hold_post_submit_input(&hold_for_later) {
|
if should_hold_post_submit_input(&hold_for_later) {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.queue_post_submit_control",
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"bytes",
|
||||||
|
dosh::trace::bytes_summary(&hold_for_later),
|
||||||
|
),
|
||||||
|
("pending", pending_user_input.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
queue_pending_user_input(
|
queue_pending_user_input(
|
||||||
&mut pending_user_input,
|
&mut pending_user_input,
|
||||||
&mut pending_user_input_bytes,
|
&mut pending_user_input_bytes,
|
||||||
@@ -4817,6 +5084,13 @@ async fn run_terminal(
|
|||||||
if sent {
|
if sent {
|
||||||
predictor.observe_input(&hold_for_later)?;
|
predictor.observe_input(&hold_for_later)?;
|
||||||
} else {
|
} else {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.queue_post_submit_stale",
|
||||||
|
&[(
|
||||||
|
"bytes",
|
||||||
|
dosh::trace::bytes_summary(&hold_for_later),
|
||||||
|
)],
|
||||||
|
);
|
||||||
queue_stale_pending_user_input(
|
queue_stale_pending_user_input(
|
||||||
&mut pending_user_input,
|
&mut pending_user_input,
|
||||||
&mut pending_user_input_bytes,
|
&mut pending_user_input_bytes,
|
||||||
@@ -4827,6 +5101,13 @@ async fn run_terminal(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if last_packet_at.elapsed() >= Duration::from_secs(2) {
|
if last_packet_at.elapsed() >= Duration::from_secs(2) {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.queue_disconnected",
|
||||||
|
&[
|
||||||
|
("bytes", dosh::trace::bytes_summary(&bytes)),
|
||||||
|
("silent_ms", last_packet_at.elapsed().as_millis().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
queue_stale_pending_user_input(
|
queue_stale_pending_user_input(
|
||||||
&mut pending_user_input,
|
&mut pending_user_input,
|
||||||
&mut pending_user_input_bytes,
|
&mut pending_user_input_bytes,
|
||||||
@@ -4842,6 +5123,13 @@ async fn run_terminal(
|
|||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.disconnected_reconnect_ok",
|
||||||
|
&[
|
||||||
|
("output_seq", frame.output_seq.to_string()),
|
||||||
|
("bytes", frame.bytes.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
arm_stale_terminal_input_suppression(
|
arm_stale_terminal_input_suppression(
|
||||||
&mut stale_terminal_input_suppress_until,
|
&mut stale_terminal_input_suppress_until,
|
||||||
@@ -4867,6 +5155,10 @@ async fn run_terminal(
|
|||||||
if send_input(&socket, addr, &cred, &mut send_seq, bytes.clone()).await? {
|
if send_input(&socket, addr, &cred, &mut send_seq, bytes.clone()).await? {
|
||||||
predictor.observe_input(&bytes)?;
|
predictor.observe_input(&bytes)?;
|
||||||
} else {
|
} else {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.queue_transient_send",
|
||||||
|
&[("bytes", dosh::trace::bytes_summary(&bytes))],
|
||||||
|
);
|
||||||
queue_stale_pending_user_input(
|
queue_stale_pending_user_input(
|
||||||
&mut pending_user_input,
|
&mut pending_user_input,
|
||||||
&mut pending_user_input_bytes,
|
&mut pending_user_input_bytes,
|
||||||
@@ -5829,6 +6121,14 @@ async fn reconnect(
|
|||||||
frame_buffer: &mut FrameBuffer,
|
frame_buffer: &mut FrameBuffer,
|
||||||
predictor: &mut Predictor,
|
predictor: &mut Predictor,
|
||||||
) -> Result<Option<Frame>> {
|
) -> Result<Option<Frame>> {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.reconnect_start",
|
||||||
|
&[
|
||||||
|
("session", cred.session.clone()),
|
||||||
|
("mode", cred.mode.clone()),
|
||||||
|
("last_rendered_seq", cred.last_rendered_seq.to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
if let Ok((frame, next)) = try_live_resume(socket, cred, send_seq, size.0, size.1).await {
|
if let Ok((frame, next)) = try_live_resume(socket, cred, send_seq, size.0, size.1).await {
|
||||||
*cred = next;
|
*cred = next;
|
||||||
frame_buffer.clear();
|
frame_buffer.clear();
|
||||||
@@ -5841,11 +6141,19 @@ async fn reconnect(
|
|||||||
send_seq,
|
send_seq,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.reconnect_live_ok",
|
||||||
|
&[
|
||||||
|
("output_seq", frame.output_seq.to_string()),
|
||||||
|
("bytes", frame.bytes.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
return Ok(Some(frame));
|
return Ok(Some(frame));
|
||||||
}
|
}
|
||||||
|
|
||||||
let Ok((frame, next)) = try_ticket_attach(socket, cred, size.0, size.1, Vec::new()).await
|
let Ok((frame, next)) = try_ticket_attach(socket, cred, size.0, size.1, Vec::new()).await
|
||||||
else {
|
else {
|
||||||
|
dosh::trace::event("client.reconnect_none", &[]);
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
*cred = next;
|
*cred = next;
|
||||||
@@ -5860,6 +6168,13 @@ async fn reconnect(
|
|||||||
send_seq,
|
send_seq,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.reconnect_ticket_ok",
|
||||||
|
&[
|
||||||
|
("output_seq", frame.output_seq.to_string()),
|
||||||
|
("bytes", frame.bytes.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
Ok(Some(frame))
|
Ok(Some(frame))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5977,6 +6292,10 @@ fn should_strip_stale_terminal_reports(
|
|||||||
|| suppress_until.is_some_and(|deadline| Instant::now() < deadline)
|
|| suppress_until.is_some_and(|deadline| Instant::now() < deadline)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn should_strip_unowned_terminal_reports(alternate_screen: bool, mouse_tracking: bool) -> bool {
|
||||||
|
!alternate_screen && !mouse_tracking
|
||||||
|
}
|
||||||
|
|
||||||
fn input_contains_focus_in(bytes: &[u8]) -> bool {
|
fn input_contains_focus_in(bytes: &[u8]) -> bool {
|
||||||
contains_bytes(bytes, b"\x1b[I") || contains_bytes(bytes, b"\x9bI")
|
contains_bytes(bytes, b"\x1b[I") || contains_bytes(bytes, b"\x9bI")
|
||||||
}
|
}
|
||||||
@@ -6025,23 +6344,44 @@ async fn flush_pending_user_input(
|
|||||||
pending: &mut VecDeque<PendingUserInput>,
|
pending: &mut VecDeque<PendingUserInput>,
|
||||||
pending_bytes: &mut usize,
|
pending_bytes: &mut usize,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.pending_flush_start",
|
||||||
|
&[
|
||||||
|
("items", pending.len().to_string()),
|
||||||
|
("bytes", pending_bytes.to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
while let Some(input) = pending.pop_front() {
|
while let Some(input) = pending.pop_front() {
|
||||||
let PendingUserInput {
|
let PendingUserInput {
|
||||||
bytes,
|
bytes,
|
||||||
strip_mouse_reports,
|
strip_mouse_reports,
|
||||||
} = input;
|
} = input;
|
||||||
*pending_bytes = pending_bytes.saturating_sub(bytes.len());
|
*pending_bytes = pending_bytes.saturating_sub(bytes.len());
|
||||||
|
let before_filter_len = bytes.len();
|
||||||
let bytes = if strip_mouse_reports {
|
let bytes = if strip_mouse_reports {
|
||||||
strip_stale_mouse_reports(&bytes)
|
strip_stale_mouse_reports(&bytes)
|
||||||
} else {
|
} else {
|
||||||
bytes
|
bytes
|
||||||
};
|
};
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.pending_flush_item",
|
||||||
|
&[
|
||||||
|
("before", before_filter_len.to_string()),
|
||||||
|
("after", bytes.len().to_string()),
|
||||||
|
("strip_mouse", strip_mouse_reports.to_string()),
|
||||||
|
("summary", dosh::trace::bytes_summary(&bytes)),
|
||||||
|
],
|
||||||
|
);
|
||||||
if bytes.is_empty() {
|
if bytes.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if send_input(socket, addr, cred, send_seq, bytes.clone()).await? {
|
if send_input(socket, addr, cred, send_seq, bytes.clone()).await? {
|
||||||
predictor.observe_input(&bytes)?;
|
predictor.observe_input(&bytes)?;
|
||||||
} else {
|
} else {
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.pending_flush_requeue",
|
||||||
|
&[("bytes", dosh::trace::bytes_summary(&bytes))],
|
||||||
|
);
|
||||||
requeue_pending_user_input_front(
|
requeue_pending_user_input_front(
|
||||||
pending,
|
pending,
|
||||||
pending_bytes,
|
pending_bytes,
|
||||||
@@ -6212,6 +6552,8 @@ async fn send_input(
|
|||||||
send_seq: &mut u64,
|
send_seq: &mut u64,
|
||||||
bytes: Vec<u8>,
|
bytes: Vec<u8>,
|
||||||
) -> Result<bool> {
|
) -> Result<bool> {
|
||||||
|
let seq = *send_seq;
|
||||||
|
let bytes_summary = dosh::trace::bytes_summary(&bytes);
|
||||||
let body = protocol::to_body(&Input { bytes })?;
|
let body = protocol::to_body(&Input { bytes })?;
|
||||||
let packet = protocol::encode_encrypted(
|
let packet = protocol::encode_encrypted(
|
||||||
PacketKind::Input,
|
PacketKind::Input,
|
||||||
@@ -6223,7 +6565,17 @@ async fn send_input(
|
|||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
*send_seq += 1;
|
*send_seq += 1;
|
||||||
send_terminal_udp(socket, &packet, addr).await
|
let sent = send_terminal_udp(socket, &packet, addr).await?;
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.input_send",
|
||||||
|
&[
|
||||||
|
("seq", seq.to_string()),
|
||||||
|
("ack", cred.last_rendered_seq.to_string()),
|
||||||
|
("sent", sent.to_string()),
|
||||||
|
("summary", bytes_summary),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
Ok(sent)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_stream_open(
|
async fn send_stream_open(
|
||||||
@@ -6738,22 +7090,44 @@ const GLITCH_FORCE_MS: u128 = 250;
|
|||||||
/// without retaining arbitrary terminal output.
|
/// without retaining arbitrary terminal output.
|
||||||
const TERMINAL_OUTPUT_PARSE_TAIL: usize = 64;
|
const TERMINAL_OUTPUT_PARSE_TAIL: usize = 64;
|
||||||
|
|
||||||
fn alternate_screen_after_output(mut active: bool, bytes: &[u8]) -> bool {
|
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||||
|
struct TerminalModeChanges {
|
||||||
|
alternate_screen: Option<bool>,
|
||||||
|
mouse_tracking: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terminal_modes_after_output(
|
||||||
|
mut alternate_screen: bool,
|
||||||
|
mut mouse_tracking: bool,
|
||||||
|
bytes: &[u8],
|
||||||
|
) -> (bool, bool) {
|
||||||
let mut offset = 0usize;
|
let mut offset = 0usize;
|
||||||
while offset < bytes.len() {
|
while offset < bytes.len() {
|
||||||
let Some((next, transition)) = terminal_private_mode_transition(bytes, offset) else {
|
let Some((next, changes)) = terminal_private_mode_changes(bytes, offset) else {
|
||||||
offset += 1;
|
offset += 1;
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if let Some(enable) = transition {
|
if let Some(enable) = changes.alternate_screen {
|
||||||
active = enable;
|
alternate_screen = enable;
|
||||||
|
}
|
||||||
|
if let Some(enable) = changes.mouse_tracking {
|
||||||
|
mouse_tracking = enable;
|
||||||
}
|
}
|
||||||
offset = next.max(offset + 1);
|
offset = next.max(offset + 1);
|
||||||
}
|
}
|
||||||
active
|
(alternate_screen, mouse_tracking)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
fn terminal_private_mode_transition(bytes: &[u8], offset: usize) -> Option<(usize, Option<bool>)> {
|
fn terminal_private_mode_transition(bytes: &[u8], offset: usize) -> Option<(usize, Option<bool>)> {
|
||||||
|
terminal_private_mode_changes(bytes, offset)
|
||||||
|
.map(|(next, changes)| (next, changes.alternate_screen))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terminal_private_mode_changes(
|
||||||
|
bytes: &[u8],
|
||||||
|
offset: usize,
|
||||||
|
) -> Option<(usize, TerminalModeChanges)> {
|
||||||
let mut cursor = offset;
|
let mut cursor = offset;
|
||||||
match bytes.get(cursor).copied()? {
|
match bytes.get(cursor).copied()? {
|
||||||
0x1b if bytes.get(cursor + 1) == Some(&b'[') => cursor += 2,
|
0x1b if bytes.get(cursor + 1) == Some(&b'[') => cursor += 2,
|
||||||
@@ -6772,10 +7146,18 @@ fn terminal_private_mode_transition(bytes: &[u8], offset: usize) -> Option<(usiz
|
|||||||
b'0'..=b'9' | b';' | b':' => cursor += 1,
|
b'0'..=b'9' | b';' | b':' => cursor += 1,
|
||||||
b'h' | b'l' => {
|
b'h' | b'l' => {
|
||||||
let params = &bytes[params_start..cursor];
|
let params = &bytes[params_start..cursor];
|
||||||
let touches_alt = terminal_private_params_include_alt_screen(params);
|
let enable = byte == b'h';
|
||||||
return Some((cursor + 1, touches_alt.then_some(byte == b'h')));
|
return Some((
|
||||||
|
cursor + 1,
|
||||||
|
TerminalModeChanges {
|
||||||
|
alternate_screen: terminal_private_params_include_alt_screen(params)
|
||||||
|
.then_some(enable),
|
||||||
|
mouse_tracking: terminal_private_params_include_mouse_tracking(params)
|
||||||
|
.then_some(enable),
|
||||||
|
},
|
||||||
|
));
|
||||||
}
|
}
|
||||||
0x40..=0x7e => return Some((cursor + 1, None)),
|
0x40..=0x7e => return Some((cursor + 1, TerminalModeChanges::default())),
|
||||||
_ => return None,
|
_ => return None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6788,6 +7170,17 @@ fn terminal_private_params_include_alt_screen(params: &[u8]) -> bool {
|
|||||||
.any(|param| matches!(param, b"47" | b"1047" | b"1049"))
|
.any(|param| matches!(param, b"47" | b"1047" | b"1049"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn terminal_private_params_include_mouse_tracking(params: &[u8]) -> bool {
|
||||||
|
params
|
||||||
|
.split(|byte| matches!(byte, b';' | b':'))
|
||||||
|
.any(|param| {
|
||||||
|
matches!(
|
||||||
|
param,
|
||||||
|
b"1000" | b"1001" | b"1002" | b"1003" | b"1005" | b"1006" | b"1015"
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// One speculatively-echoed character on the current line.
|
/// One speculatively-echoed character on the current line.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
struct PredictedCell {
|
struct PredictedCell {
|
||||||
@@ -6805,6 +7198,10 @@ struct Predictor {
|
|||||||
/// as vim/htop); we never speculate there because we cannot model arbitrary
|
/// as vim/htop); we never speculate there because we cannot model arbitrary
|
||||||
/// cursor addressing safely.
|
/// cursor addressing safely.
|
||||||
alternate_screen: bool,
|
alternate_screen: bool,
|
||||||
|
/// True while the server-side program has requested terminal mouse reports.
|
||||||
|
/// When false, SGR mouse bytes from the local terminal are stale UI noise and
|
||||||
|
/// must not be forwarded into the shell prompt.
|
||||||
|
mouse_tracking: bool,
|
||||||
/// Tail of recent terminal output, retained so alternate-screen transitions
|
/// Tail of recent terminal output, retained so alternate-screen transitions
|
||||||
/// split across UDP frames are still detected.
|
/// split across UDP frames are still detected.
|
||||||
output_parse_tail: Vec<u8>,
|
output_parse_tail: Vec<u8>,
|
||||||
@@ -6854,6 +7251,7 @@ impl Predictor {
|
|||||||
mode,
|
mode,
|
||||||
enabled: enabled && mode != PredictMode::Off,
|
enabled: enabled && mode != PredictMode::Off,
|
||||||
alternate_screen: false,
|
alternate_screen: false,
|
||||||
|
mouse_tracking: false,
|
||||||
output_parse_tail: Vec::new(),
|
output_parse_tail: Vec::new(),
|
||||||
cells: Vec::new(),
|
cells: Vec::new(),
|
||||||
cursor: 0,
|
cursor: 0,
|
||||||
@@ -6877,6 +7275,7 @@ impl Predictor {
|
|||||||
self.epoch += 1;
|
self.epoch += 1;
|
||||||
self.confirmed_epoch = self.epoch - 1;
|
self.confirmed_epoch = self.epoch - 1;
|
||||||
self.alternate_screen = false;
|
self.alternate_screen = false;
|
||||||
|
self.mouse_tracking = false;
|
||||||
self.output_parse_tail.clear();
|
self.output_parse_tail.clear();
|
||||||
self.oldest_pending_at = None;
|
self.oldest_pending_at = None;
|
||||||
}
|
}
|
||||||
@@ -7038,11 +7437,27 @@ impl Predictor {
|
|||||||
parse.extend_from_slice(&self.output_parse_tail);
|
parse.extend_from_slice(&self.output_parse_tail);
|
||||||
parse.extend_from_slice(bytes);
|
parse.extend_from_slice(bytes);
|
||||||
|
|
||||||
let before = self.alternate_screen;
|
let before_alternate_screen = self.alternate_screen;
|
||||||
self.alternate_screen = alternate_screen_after_output(self.alternate_screen, &parse);
|
let before_mouse_tracking = self.mouse_tracking;
|
||||||
if self.alternate_screen != before {
|
let (alternate_screen, mouse_tracking) =
|
||||||
|
terminal_modes_after_output(self.alternate_screen, self.mouse_tracking, &parse);
|
||||||
|
self.alternate_screen = alternate_screen;
|
||||||
|
self.mouse_tracking = mouse_tracking;
|
||||||
|
if self.alternate_screen != before_alternate_screen {
|
||||||
let _ = self.discard_all();
|
let _ = self.discard_all();
|
||||||
}
|
}
|
||||||
|
if self.alternate_screen != before_alternate_screen
|
||||||
|
|| self.mouse_tracking != before_mouse_tracking
|
||||||
|
{
|
||||||
|
dosh::trace::event(
|
||||||
|
"client.terminal_modes",
|
||||||
|
&[
|
||||||
|
("alt", self.alternate_screen.to_string()),
|
||||||
|
("mouse", self.mouse_tracking.to_string()),
|
||||||
|
("bytes", dosh::trace::bytes_summary(bytes)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
self.output_parse_tail.clear();
|
self.output_parse_tail.clear();
|
||||||
let keep = parse.len().min(TERMINAL_OUTPUT_PARSE_TAIL);
|
let keep = parse.len().min(TERMINAL_OUTPUT_PARSE_TAIL);
|
||||||
@@ -7857,22 +8272,23 @@ mod tests {
|
|||||||
use super::{
|
use super::{
|
||||||
ALT_SCREEN_IDLE_REPAINT_AFTER, CachedCredential, DisconnectStatus, DynamicForward,
|
ALT_SCREEN_IDLE_REPAINT_AFTER, CachedCredential, DisconnectStatus, DynamicForward,
|
||||||
FRAME_GAP_RESYNC_AFTER_MS, FrameBuffer, LocalForward, MAX_PENDING_USER_INPUT_BYTES,
|
FRAME_GAP_RESYNC_AFTER_MS, FrameBuffer, LocalForward, MAX_PENDING_USER_INPUT_BYTES,
|
||||||
POST_SUBMIT_ALL_INPUT_HOLD, PendingStreamOpen, PredictMode, Predictor,
|
NativeIdentityContext, POST_SUBMIT_ALL_INPUT_HOLD, PendingStreamOpen, PredictMode,
|
||||||
RESTART_STATUS_SCRIPT, RemoteForward, STARTUP_INPUT_HOLD, SshConfig, StartupGateMode,
|
Predictor, RESTART_STATUS_SCRIPT, RemoteForward, STARTUP_INPUT_HOLD, SshConfig,
|
||||||
StatusAction, UpdateOptions, UpdateRole, auth_allows, cache_key, cache_server_prefix,
|
SshPathTokenContext, StartupGateMode, StatusAction, UpdateOptions, UpdateRole, auth_allows,
|
||||||
cleanup_stream_state, clear_cached_credentials, ensure_tui_safe_status_overlay,
|
cache_key, cache_server_prefix, cleanup_stream_state, clear_cached_credentials,
|
||||||
input_contains_focus_in, input_matches_escape, is_local_status_target,
|
ensure_tui_safe_status_overlay, expand_ssh_path_tokens, input_contains_focus_in,
|
||||||
is_resume_response_for_client, latest_release_download_url,
|
input_matches_escape, is_local_status_target, is_resume_response_for_client,
|
||||||
load_first_native_identity_with_prompt, native_proxy_udp_warning, parse_dynamic_forward,
|
latest_release_download_url, load_first_native_identity_with_prompt,
|
||||||
parse_escape_key, parse_local_forward, parse_remote_forward, parse_ssh_config,
|
native_proxy_udp_warning, parse_dynamic_forward, parse_escape_key, parse_local_forward,
|
||||||
parse_update_options, post_submit_hold_duration, queue_pending_user_input,
|
parse_remote_forward, parse_ssh_config, parse_update_options, post_submit_hold_duration,
|
||||||
raw_contains_host_table, recv_response_until, refresh_live_addr, release_tag_download_url,
|
queue_pending_user_input, raw_contains_host_table, recv_response_until, refresh_live_addr,
|
||||||
release_tag_from_effective_url, release_version_from_tag, render_status_clear,
|
release_tag_download_url, release_tag_from_effective_url, release_version_from_tag,
|
||||||
render_status_overlay, requested_env, resolved_startup_command, retire_stream_state,
|
render_status_clear, render_status_overlay, requested_env, resolved_startup_command,
|
||||||
retransmit_stream_opens, rewrite_forward_command, selected_predict_mode, selected_udp_host,
|
retire_stream_state, retransmit_stream_opens, rewrite_forward_command,
|
||||||
server_version_mismatch, should_flush_terminal_input_after_contact,
|
selected_predict_mode, selected_udp_host, server_version_mismatch,
|
||||||
should_hold_during_startup_gate, should_hold_post_submit_input,
|
should_flush_terminal_input_after_contact, should_hold_during_startup_gate,
|
||||||
should_repaint_idle_alternate_screen, split_after_command_submit, ssh_command_target,
|
should_hold_post_submit_input, should_repaint_idle_alternate_screen,
|
||||||
|
should_strip_unowned_terminal_reports, split_after_command_submit, ssh_command_target,
|
||||||
ssh_config_uses_proxy, ssh_destination_host, ssh_username, ssh_with_user, startup_command,
|
ssh_config_uses_proxy, ssh_destination_host, ssh_username, ssh_with_user, startup_command,
|
||||||
status_ssh_target, strip_stale_mouse_reports, strip_terminal_focus_reports,
|
status_ssh_target, strip_stale_mouse_reports, strip_terminal_focus_reports,
|
||||||
terminal_private_mode_transition, toml_bare_key_or_quoted, unix_update_script,
|
terminal_private_mode_transition, toml_bare_key_or_quoted, unix_update_script,
|
||||||
@@ -8262,6 +8678,26 @@ mod tests {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ssh_identity_paths_expand_common_openssh_tokens() {
|
||||||
|
let context = SshPathTokenContext {
|
||||||
|
original_host: "prod".to_string(),
|
||||||
|
hostname: "10.0.0.5".to_string(),
|
||||||
|
port: 2222,
|
||||||
|
remote_user: "deploy".to_string(),
|
||||||
|
local_user: "palav".to_string(),
|
||||||
|
home_dir: Some("/home/palav".to_string()),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
expand_ssh_path_tokens("~/.ssh/%r@%h:%p-%n-%u-%%-%x", &context),
|
||||||
|
"~/.ssh/deploy@10.0.0.5:2222-prod-palav-%-%x"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
expand_ssh_path_tokens("%d/.ssh/%r_%h", &context),
|
||||||
|
"/home/palav/.ssh/deploy_10.0.0.5"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn native_proxy_udp_warning_requires_missing_explicit_dosh_host() {
|
fn native_proxy_udp_warning_requires_missing_explicit_dosh_host() {
|
||||||
let proxied = SshConfig {
|
let proxied = SshConfig {
|
||||||
@@ -8319,13 +8755,14 @@ mod tests {
|
|||||||
write_encrypted_identity(&path, &signing, "let-me-in");
|
write_encrypted_identity(&path, &signing, "let-me-in");
|
||||||
let mut config = ClientConfig::default();
|
let mut config = ClientConfig::default();
|
||||||
config.identity_files.clear();
|
config.identity_files.clear();
|
||||||
let loaded = load_first_native_identity_with_prompt(
|
let ssh_config = SshConfig::default();
|
||||||
&config,
|
let identity_context =
|
||||||
Some(&path),
|
NativeIdentityContext::new("alice@example.com", Some(2222), &ssh_config);
|
||||||
&SshConfig::default(),
|
let loaded =
|
||||||
|_| Ok("let-me-in".to_string()),
|
load_first_native_identity_with_prompt(&config, Some(&path), &identity_context, |_| {
|
||||||
)
|
Ok("let-me-in".to_string())
|
||||||
.unwrap();
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded.public_key().key_data().ed25519().unwrap().as_ref(),
|
loaded.public_key().key_data().ed25519().unwrap().as_ref(),
|
||||||
@@ -8341,13 +8778,14 @@ mod tests {
|
|||||||
write_encrypted_identity(&path, &signing, "correct");
|
write_encrypted_identity(&path, &signing, "correct");
|
||||||
let mut config = ClientConfig::default();
|
let mut config = ClientConfig::default();
|
||||||
config.identity_files.clear();
|
config.identity_files.clear();
|
||||||
let err = load_first_native_identity_with_prompt(
|
let ssh_config = SshConfig::default();
|
||||||
&config,
|
let identity_context =
|
||||||
Some(&path),
|
NativeIdentityContext::new("alice@example.com", Some(2222), &ssh_config);
|
||||||
&SshConfig::default(),
|
let err =
|
||||||
|_| Ok("wrong".to_string()),
|
load_first_native_identity_with_prompt(&config, Some(&path), &identity_context, |_| {
|
||||||
)
|
Ok("wrong".to_string())
|
||||||
.unwrap_err();
|
})
|
||||||
|
.unwrap_err();
|
||||||
|
|
||||||
assert!(err.to_string().contains("no usable native identity"));
|
assert!(err.to_string().contains("no usable native identity"));
|
||||||
}
|
}
|
||||||
@@ -8366,7 +8804,9 @@ mod tests {
|
|||||||
identities_only: true,
|
identities_only: true,
|
||||||
..SshConfig::default()
|
..SshConfig::default()
|
||||||
};
|
};
|
||||||
let err = load_first_native_identity_with_prompt(&config, None, &ssh_config, |_| {
|
let identity_context =
|
||||||
|
NativeIdentityContext::new("alice@example.com", Some(2222), &ssh_config);
|
||||||
|
let err = load_first_native_identity_with_prompt(&config, None, &identity_context, |_| {
|
||||||
unreachable!("unencrypted key should not prompt")
|
unreachable!("unencrypted key should not prompt")
|
||||||
})
|
})
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
@@ -8387,10 +8827,41 @@ mod tests {
|
|||||||
identities_only: true,
|
identities_only: true,
|
||||||
..SshConfig::default()
|
..SshConfig::default()
|
||||||
};
|
};
|
||||||
let loaded = load_first_native_identity_with_prompt(&config, None, &ssh_config, |_| {
|
let identity_context =
|
||||||
unreachable!("unencrypted key should not prompt")
|
NativeIdentityContext::new("alice@example.com", Some(2222), &ssh_config);
|
||||||
})
|
let loaded =
|
||||||
.unwrap();
|
load_first_native_identity_with_prompt(&config, None, &identity_context, |_| {
|
||||||
|
unreachable!("unencrypted key should not prompt")
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
loaded.public_key().key_data().ed25519().unwrap().as_ref(),
|
||||||
|
VerifyingKey::from(&signing).as_bytes()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ssh_config_identity_file_tokens_are_expanded_for_native_auth() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("deploy_10.0.0.5_2222");
|
||||||
|
let signing = SigningKey::from_bytes(&[65u8; 32]);
|
||||||
|
write_identity(&path, &signing);
|
||||||
|
let mut config = ClientConfig::default();
|
||||||
|
config.identity_files.clear();
|
||||||
|
let ssh_config = SshConfig {
|
||||||
|
hostname: Some("10.0.0.5".to_string()),
|
||||||
|
identity_files: vec![format!("{}/%r_%h_%p", dir.path().display())],
|
||||||
|
identities_only: true,
|
||||||
|
port: Some(2222),
|
||||||
|
..SshConfig::default()
|
||||||
|
};
|
||||||
|
let identity_context = NativeIdentityContext::new("deploy@prod", None, &ssh_config);
|
||||||
|
let loaded =
|
||||||
|
load_first_native_identity_with_prompt(&config, None, &identity_context, |_| {
|
||||||
|
unreachable!("unencrypted key should not prompt")
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
loaded.public_key().key_data().ed25519().unwrap().as_ref(),
|
loaded.public_key().key_data().ed25519().unwrap().as_ref(),
|
||||||
@@ -8592,6 +9063,33 @@ mod tests {
|
|||||||
assert!(!predictor.alternate_screen);
|
assert!(!predictor.alternate_screen);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn predictor_tracks_mouse_tracking_modes_separately_from_alternate_screen() {
|
||||||
|
let mut predictor = Predictor::new(true);
|
||||||
|
|
||||||
|
predictor.observe_output(b"\x1b[?1000;1006h");
|
||||||
|
assert!(!predictor.alternate_screen);
|
||||||
|
assert!(predictor.mouse_tracking);
|
||||||
|
|
||||||
|
predictor.observe_output(b"\x1b[?1006;1000l");
|
||||||
|
assert!(!predictor.mouse_tracking);
|
||||||
|
|
||||||
|
predictor.observe_output(b"\x1b[?1000;1049h");
|
||||||
|
assert!(predictor.alternate_screen);
|
||||||
|
assert!(predictor.mouse_tracking);
|
||||||
|
|
||||||
|
predictor.observe_output(b"\x1b[?1049l");
|
||||||
|
assert!(!predictor.alternate_screen);
|
||||||
|
assert!(predictor.mouse_tracking);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unowned_mouse_reports_are_stripped_only_outside_terminal_mouse_mode() {
|
||||||
|
assert!(should_strip_unowned_terminal_reports(false, false));
|
||||||
|
assert!(!should_strip_unowned_terminal_reports(false, true));
|
||||||
|
assert!(!should_strip_unowned_terminal_reports(true, false));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn predictor_tracks_alternate_screen_split_across_frames() {
|
fn predictor_tracks_alternate_screen_split_across_frames() {
|
||||||
let mut predictor = Predictor::new(true);
|
let mut predictor = Predictor::new(true);
|
||||||
@@ -9500,6 +9998,12 @@ mod tests {
|
|||||||
assert_eq!(strip_stale_mouse_reports(b"152;1Mls\r"), b"ls\r");
|
assert_eq!(strip_stale_mouse_reports(b"152;1Mls\r"), b"ls\r");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn long_orphan_mouse_spam_is_stripped_from_pending_input() {
|
||||||
|
let input = b"35;152;1M35;149;1M35;147;1M35;144;2M35;141;3M0;107;10m35;106;10Mtm\r";
|
||||||
|
assert_eq!(strip_stale_mouse_reports(input), b"tm\r");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn split_stale_mouse_suffixes_are_stripped_from_pending_input() {
|
fn split_stale_mouse_suffixes_are_stripped_from_pending_input() {
|
||||||
assert_eq!(strip_stale_mouse_reports(b"1M35;149;1Mls\r"), b"ls\r");
|
assert_eq!(strip_stale_mouse_reports(b"1M35;149;1Mls\r"), b"ls\r");
|
||||||
|
|||||||
@@ -67,6 +67,15 @@ static AGENT_SOCK_COUNTER: AtomicU64 = AtomicU64::new(0);
|
|||||||
/// before it is swept by the cleanup task.
|
/// before it is swept by the cleanup task.
|
||||||
const NATIVE_HANDSHAKE_TTL_SECS: u64 = 30;
|
const NATIVE_HANDSHAKE_TTL_SECS: u64 = 30;
|
||||||
|
|
||||||
|
fn hex_id(id: [u8; 16]) -> String {
|
||||||
|
let mut out = String::with_capacity(32);
|
||||||
|
for byte in id {
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
let _ = write!(&mut out, "{byte:02x}");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Parser)]
|
#[derive(Debug, Parser)]
|
||||||
#[command(
|
#[command(
|
||||||
name = "dosh-server",
|
name = "dosh-server",
|
||||||
@@ -1602,9 +1611,22 @@ async fn handle_resume(
|
|||||||
peer: SocketAddr,
|
peer: SocketAddr,
|
||||||
packet: &protocol::Packet,
|
packet: &protocol::Packet,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.resume_start",
|
||||||
|
&[
|
||||||
|
("peer", peer.to_string()),
|
||||||
|
("client", hex_id(packet.header.conn_id)),
|
||||||
|
("seq", packet.header.seq.to_string()),
|
||||||
|
("ack", packet.header.ack.to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
let (key, session_name) = match find_client_decrypt_key(state, &packet.header) {
|
let (key, session_name) = match find_client_decrypt_key(state, &packet.header) {
|
||||||
Ok(found) => found,
|
Ok(found) => found,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.resume_unknown_client",
|
||||||
|
&[("client", hex_id(packet.header.conn_id))],
|
||||||
|
);
|
||||||
return send_reject_to_client(socket, peer, packet.header.conn_id, "unknown client")
|
return send_reject_to_client(socket, peer, packet.header.conn_id, "unknown client")
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
@@ -1623,8 +1645,25 @@ async fn handle_resume(
|
|||||||
.get_mut(&packet.header.conn_id)
|
.get_mut(&packet.header.conn_id)
|
||||||
.ok_or_else(|| anyhow!("unknown client"))?;
|
.ok_or_else(|| anyhow!("unknown client"))?;
|
||||||
if !client.replay.accept(packet.header.seq) {
|
if !client.replay.accept(packet.header.seq) {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.resume_replay_drop",
|
||||||
|
&[
|
||||||
|
("session", req.session.clone()),
|
||||||
|
("seq", packet.header.seq.to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
if client.endpoint != peer {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.resume_roam",
|
||||||
|
&[
|
||||||
|
("session", req.session.clone()),
|
||||||
|
("from", client.endpoint.to_string()),
|
||||||
|
("to", peer.to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
client.endpoint = peer;
|
client.endpoint = peer;
|
||||||
client.last_acked = req.last_rendered_seq;
|
client.last_acked = req.last_rendered_seq;
|
||||||
client.cols = req.cols;
|
client.cols = req.cols;
|
||||||
@@ -1662,6 +1701,14 @@ async fn handle_resume(
|
|||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
let _ = send_udp(socket, &out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.resume_ok",
|
||||||
|
&[
|
||||||
|
("session", frame.session),
|
||||||
|
("output_seq", frame.output_seq.to_string()),
|
||||||
|
("bytes", frame.bytes.len().to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1673,6 +1720,7 @@ async fn handle_input(
|
|||||||
let (key, session_name) = find_client_decrypt_key(state, &packet.header)?;
|
let (key, session_name) = find_client_decrypt_key(state, &packet.header)?;
|
||||||
let body = protocol::decrypt_body(packet, &key, CLIENT_TO_SERVER)?;
|
let body = protocol::decrypt_body(packet, &key, CLIENT_TO_SERVER)?;
|
||||||
let input: Input = protocol::from_body(&body)?;
|
let input: Input = protocol::from_body(&body)?;
|
||||||
|
let input_summary = dosh::trace::bytes_summary(&input.bytes);
|
||||||
let mut locked = state.lock().expect("server state poisoned");
|
let mut locked = state.lock().expect("server state poisoned");
|
||||||
let session = locked
|
let session = locked
|
||||||
.sessions
|
.sessions
|
||||||
@@ -1683,13 +1731,37 @@ async fn handle_input(
|
|||||||
.get_mut(&packet.header.conn_id)
|
.get_mut(&packet.header.conn_id)
|
||||||
.ok_or_else(|| anyhow!("unknown client"))?;
|
.ok_or_else(|| anyhow!("unknown client"))?;
|
||||||
if !client.replay.accept(packet.header.seq) {
|
if !client.replay.accept(packet.header.seq) {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.input_replay_drop",
|
||||||
|
&[
|
||||||
|
("session", session_name.clone()),
|
||||||
|
("seq", packet.header.seq.to_string()),
|
||||||
|
("summary", input_summary),
|
||||||
|
],
|
||||||
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if client.endpoint != peer {
|
if client.endpoint != peer {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.input_roam",
|
||||||
|
&[
|
||||||
|
("session", session_name.clone()),
|
||||||
|
("from", client.endpoint.to_string()),
|
||||||
|
("to", peer.to_string()),
|
||||||
|
],
|
||||||
|
);
|
||||||
client.endpoint = peer;
|
client.endpoint = peer;
|
||||||
}
|
}
|
||||||
client.last_seen = Instant::now();
|
client.last_seen = Instant::now();
|
||||||
if !mode_allows_terminal_updates(&client.mode) {
|
if !mode_allows_terminal_updates(&client.mode) {
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.input_rejected_mode",
|
||||||
|
&[
|
||||||
|
("session", session_name),
|
||||||
|
("mode", client.mode.clone()),
|
||||||
|
("summary", input_summary),
|
||||||
|
],
|
||||||
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
session
|
session
|
||||||
@@ -1697,6 +1769,14 @@ async fn handle_input(
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.context("terminal session has no pty")?
|
.context("terminal session has no pty")?
|
||||||
.write_all(&input.bytes)?;
|
.write_all(&input.bytes)?;
|
||||||
|
dosh::trace::event(
|
||||||
|
"server.pty_write",
|
||||||
|
&[
|
||||||
|
("session", session_name),
|
||||||
|
("seq", packet.header.seq.to_string()),
|
||||||
|
("summary", input_summary),
|
||||||
|
],
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2681,6 +2761,46 @@ async fn handle_file_request(
|
|||||||
send_file_response_to_client(state, socket, client_id, stream_id, FileResponse::Ok)
|
send_file_response_to_client(state, socket, client_id, stream_id, FileResponse::Ok)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
FileRequest::Readlink { path } => {
|
||||||
|
let path = clean_remote_path(&path, home)?;
|
||||||
|
let target =
|
||||||
|
fs::read_link(&path).with_context(|| format!("readlink {}", path.display()))?;
|
||||||
|
let target = target
|
||||||
|
.to_str()
|
||||||
|
.ok_or_else(|| anyhow!("symlink target is not valid UTF-8"))?
|
||||||
|
.to_string();
|
||||||
|
send_file_response_to_client(
|
||||||
|
state,
|
||||||
|
socket,
|
||||||
|
client_id,
|
||||||
|
stream_id,
|
||||||
|
FileResponse::LinkTarget { target },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
FileRequest::Symlink {
|
||||||
|
path,
|
||||||
|
target,
|
||||||
|
overwrite,
|
||||||
|
} => {
|
||||||
|
let path = clean_remote_path(&path, home)?;
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent)
|
||||||
|
.with_context(|| format!("create {}", parent.display()))?;
|
||||||
|
}
|
||||||
|
if let Ok(metadata) = fs::symlink_metadata(&path) {
|
||||||
|
anyhow::ensure!(overwrite, "destination exists: {}", path.display());
|
||||||
|
anyhow::ensure!(
|
||||||
|
!metadata.is_dir(),
|
||||||
|
"destination is a directory: {}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
|
||||||
|
}
|
||||||
|
create_symlink(&target, &path)?;
|
||||||
|
send_file_response_to_client(state, socket, client_id, stream_id, FileResponse::Ok)
|
||||||
|
.await
|
||||||
|
}
|
||||||
FileRequest::Remove { path, recursive } => {
|
FileRequest::Remove { path, recursive } => {
|
||||||
let path = clean_remote_path(&path, home)?;
|
let path = clean_remote_path(&path, home)?;
|
||||||
let metadata =
|
let metadata =
|
||||||
@@ -3065,6 +3185,17 @@ fn set_mode(path: &Path, mode: u32) -> Result<()> {
|
|||||||
fs::set_permissions(path, permissions).with_context(|| format!("chmod {}", path.display()))
|
fs::set_permissions(path, permissions).with_context(|| format!("chmod {}", path.display()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn create_symlink(target: &str, path: &Path) -> Result<()> {
|
||||||
|
std::os::unix::fs::symlink(target, path)
|
||||||
|
.with_context(|| format!("symlink {} -> {}", path.display(), target))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn create_symlink(_target: &str, _path: &Path) -> Result<()> {
|
||||||
|
bail!("symlink creation is not supported on this server platform")
|
||||||
|
}
|
||||||
|
|
||||||
fn upload_temp_path(final_path: &Path, stream_id: u64) -> PathBuf {
|
fn upload_temp_path(final_path: &Path, stream_id: u64) -> PathBuf {
|
||||||
let name = final_path
|
let name = final_path
|
||||||
.file_name()
|
.file_name()
|
||||||
|
|||||||
@@ -18,6 +18,14 @@ pub enum FileRequest {
|
|||||||
path: String,
|
path: String,
|
||||||
mode: Option<u32>,
|
mode: Option<u32>,
|
||||||
},
|
},
|
||||||
|
Readlink {
|
||||||
|
path: String,
|
||||||
|
},
|
||||||
|
Symlink {
|
||||||
|
path: String,
|
||||||
|
target: String,
|
||||||
|
overwrite: bool,
|
||||||
|
},
|
||||||
Remove {
|
Remove {
|
||||||
path: String,
|
path: String,
|
||||||
recursive: bool,
|
recursive: bool,
|
||||||
@@ -56,6 +64,9 @@ pub enum FileResponse {
|
|||||||
List {
|
List {
|
||||||
entries: Vec<FileEntry>,
|
entries: Vec<FileEntry>,
|
||||||
},
|
},
|
||||||
|
LinkTarget {
|
||||||
|
target: String,
|
||||||
|
},
|
||||||
Start {
|
Start {
|
||||||
meta: FileMeta,
|
meta: FileMeta,
|
||||||
offset: u64,
|
offset: u64,
|
||||||
|
|||||||
@@ -22,5 +22,6 @@ pub mod protocol;
|
|||||||
pub mod pty;
|
pub mod pty;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod ssh_agent;
|
pub mod ssh_agent;
|
||||||
|
pub mod trace;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
pub mod udp;
|
pub mod udp;
|
||||||
|
|||||||
+161
@@ -0,0 +1,161 @@
|
|||||||
|
use std::fs::{File, OpenOptions};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::{Mutex, OnceLock};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
static TRACE_FILE: OnceLock<Option<Mutex<File>>> = OnceLock::new();
|
||||||
|
static TRACE_BYTES: OnceLock<bool> = OnceLock::new();
|
||||||
|
|
||||||
|
pub fn enabled() -> bool {
|
||||||
|
TRACE_FILE.get_or_init(open_trace_file).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bytes_enabled() -> bool {
|
||||||
|
*TRACE_BYTES.get_or_init(|| truthy_env("DOSH_TRACE_BYTES"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn event(name: &str, fields: &[(&str, String)]) {
|
||||||
|
let Some(file) = TRACE_FILE.get_or_init(open_trace_file) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let now = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|duration| duration.as_millis())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let mut line = format!(
|
||||||
|
"ts_ms={} pid={} event={}",
|
||||||
|
now,
|
||||||
|
std::process::id(),
|
||||||
|
shell_escape(name)
|
||||||
|
);
|
||||||
|
for (key, value) in fields {
|
||||||
|
line.push(' ');
|
||||||
|
line.push_str(key);
|
||||||
|
line.push('=');
|
||||||
|
line.push_str(&shell_escape(value));
|
||||||
|
}
|
||||||
|
line.push('\n');
|
||||||
|
if let Ok(mut file) = file.lock() {
|
||||||
|
let _ = file.write_all(line.as_bytes());
|
||||||
|
let _ = file.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bytes_summary(bytes: &[u8]) -> String {
|
||||||
|
let mut parts = vec![
|
||||||
|
format!("len={}", bytes.len()),
|
||||||
|
format!(
|
||||||
|
"esc={}",
|
||||||
|
contains_byte(bytes, 0x1b) || contains_byte(bytes, 0x9b)
|
||||||
|
),
|
||||||
|
format!("focus={}", has_focus_report(bytes)),
|
||||||
|
format!("mouseish={}", looks_mouseish(bytes)),
|
||||||
|
format!("printable={}", printable_count(bytes)),
|
||||||
|
];
|
||||||
|
if bytes_enabled() {
|
||||||
|
parts.push(format!("hex={}", hex_prefix(bytes, 160)));
|
||||||
|
}
|
||||||
|
parts.join(",")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_trace_file() -> Option<Mutex<File>> {
|
||||||
|
let raw = std::env::var_os("DOSH_TRACE")?;
|
||||||
|
let normalized = raw.to_string_lossy().to_ascii_lowercase();
|
||||||
|
if normalized.is_empty() || matches!(normalized.as_str(), "0" | "false" | "off") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let path = if matches!(normalized.as_str(), "1" | "true" | "on") {
|
||||||
|
default_trace_path()
|
||||||
|
} else {
|
||||||
|
PathBuf::from(raw)
|
||||||
|
};
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
let _ = std::fs::create_dir_all(parent);
|
||||||
|
}
|
||||||
|
OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(&path)
|
||||||
|
.ok()
|
||||||
|
.map(Mutex::new)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_trace_path() -> PathBuf {
|
||||||
|
let root = dirs::cache_dir()
|
||||||
|
.unwrap_or_else(std::env::temp_dir)
|
||||||
|
.join("dosh")
|
||||||
|
.join("trace");
|
||||||
|
let exe = std::env::current_exe()
|
||||||
|
.ok()
|
||||||
|
.and_then(|path| {
|
||||||
|
path.file_stem()
|
||||||
|
.map(|stem| stem.to_string_lossy().to_string())
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| "dosh".to_string());
|
||||||
|
root.join(format!("{}-{}.log", exe, std::process::id()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn truthy_env(name: &str) -> bool {
|
||||||
|
std::env::var_os(name).is_some_and(|value| {
|
||||||
|
let normalized = value.to_string_lossy().to_ascii_lowercase();
|
||||||
|
!normalized.is_empty() && !matches!(normalized.as_str(), "0" | "false" | "off")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shell_escape(value: &str) -> String {
|
||||||
|
if value.bytes().all(|byte| {
|
||||||
|
byte.is_ascii_alphanumeric()
|
||||||
|
|| matches!(byte, b'.' | b'-' | b'_' | b':' | b'/' | b',' | b'=')
|
||||||
|
}) {
|
||||||
|
return value.to_string();
|
||||||
|
}
|
||||||
|
let mut out = String::from("'");
|
||||||
|
for ch in value.chars() {
|
||||||
|
if ch == '\'' {
|
||||||
|
out.push_str("'\\''");
|
||||||
|
} else {
|
||||||
|
out.push(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push('\'');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains_byte(bytes: &[u8], needle: u8) -> bool {
|
||||||
|
bytes.contains(&needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_focus_report(bytes: &[u8]) -> bool {
|
||||||
|
bytes
|
||||||
|
.windows(3)
|
||||||
|
.any(|window| matches!(window, b"\x1b[I" | b"\x1b[O"))
|
||||||
|
|| bytes
|
||||||
|
.windows(2)
|
||||||
|
.any(|window| matches!(window, b"\x9bI" | b"\x9bO"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn looks_mouseish(bytes: &[u8]) -> bool {
|
||||||
|
bytes.windows(3).any(|window| window == b"\x1b[<")
|
||||||
|
|| bytes.windows(2).any(|window| window == b"\x9b<")
|
||||||
|
|| bytes.iter().filter(|byte| **byte == b';').take(3).count() >= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn printable_count(bytes: &[u8]) -> usize {
|
||||||
|
bytes
|
||||||
|
.iter()
|
||||||
|
.filter(|byte| byte.is_ascii_graphic() || **byte == b' ')
|
||||||
|
.count()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_prefix(bytes: &[u8], max: usize) -> String {
|
||||||
|
let mut out = String::with_capacity(bytes.len().min(max) * 2);
|
||||||
|
for byte in bytes.iter().take(max) {
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
let _ = write!(&mut out, "{byte:02x}");
|
||||||
|
}
|
||||||
|
if bytes.len() > max {
|
||||||
|
out.push_str("...");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -1003,6 +1003,8 @@ fn native_file_copy_recursive_round_trip() {
|
|||||||
fs::create_dir_all(src.join("nested")).unwrap();
|
fs::create_dir_all(src.join("nested")).unwrap();
|
||||||
fs::write(src.join("root.txt"), b"root file\n").unwrap();
|
fs::write(src.join("root.txt"), b"root file\n").unwrap();
|
||||||
fs::write(src.join("nested/child.txt"), b"child file\n").unwrap();
|
fs::write(src.join("nested/child.txt"), b"child file\n").unwrap();
|
||||||
|
std::os::unix::fs::symlink("root.txt", src.join("root-link")).unwrap();
|
||||||
|
std::os::unix::fs::symlink("nested/child.txt", src.join("child-link")).unwrap();
|
||||||
|
|
||||||
let client_bin = env!("CARGO_BIN_EXE_dosh-client");
|
let client_bin = env!("CARGO_BIN_EXE_dosh-client");
|
||||||
let upload = Command::new(client_bin)
|
let upload = Command::new(client_bin)
|
||||||
@@ -1108,6 +1110,14 @@ fn native_file_copy_recursive_round_trip() {
|
|||||||
fs::read_to_string(downloaded.join("nested/child.txt")).unwrap(),
|
fs::read_to_string(downloaded.join("nested/child.txt")).unwrap(),
|
||||||
"child file\n"
|
"child file\n"
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_link(downloaded.join("root-link")).unwrap(),
|
||||||
|
PathBuf::from("root.txt")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_link(downloaded.join("child-link")).unwrap(),
|
||||||
|
PathBuf::from("nested/child.txt")
|
||||||
|
);
|
||||||
|
|
||||||
let remove = Command::new(client_bin)
|
let remove = Command::new(client_bin)
|
||||||
.arg("--dosh-host")
|
.arg("--dosh-host")
|
||||||
|
|||||||
Reference in New Issue
Block a user