git.delta.rocks / remowt / refs/commits / eadb0bb3c19e

difftreelog

feat auto prompter

ymurrvruYaroslav Bolyukin4 days agoparent: #751b8f1.patch.diff
in: trunk

9 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -308,9 +308,9 @@
 
 [[package]]
 name = "bifrostlink"
-version = "0.2.3"
+version = "0.2.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "704657867d2107831c57edd363726440c86675464b5fc113702854e17062cafc"
+checksum = "ad2d0e30a2aa432b78f41f9676572f88201d4dc73bc2b7bc90704d2e02b7d062"
 dependencies = [
  "async-trait",
  "async_fn_traits",
@@ -327,9 +327,9 @@
 
 [[package]]
 name = "bifrostlink-macros"
-version = "0.2.3"
+version = "0.2.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "158308eb569b467c0116680f79d0ecc389f4d540f6d5a0c9279bfe79b1cd5bdb"
+checksum = "e2121559c45cbe89c4f8d1d741360d5b028577254f6beca053dc02332da85b43"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -338,9 +338,9 @@
 
 [[package]]
 name = "bifrostlink-ports"
-version = "0.2.3"
+version = "0.2.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7612993f0bd8bc6a71867461266567212a35a716b2a5aef5f9967ab08c891782"
+checksum = "e9395c4ccca497b0c50583e6de57aca921c046ae0c10f56030cd2c5a20db05f8"
 dependencies = [
  "bifrostlink",
  "bytes",
@@ -1835,7 +1835,7 @@
 
 [[package]]
 name = "polkit-backend"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "clap",
@@ -2055,7 +2055,7 @@
 
 [[package]]
 name = "remowt-agent"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "bifrostlink",
@@ -2083,7 +2083,7 @@
 
 [[package]]
 name = "remowt-client"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "bifrostlink",
@@ -2106,7 +2106,7 @@
 
 [[package]]
 name = "remowt-endpoints"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "bifrostlink",
@@ -2124,7 +2124,7 @@
 
 [[package]]
 name = "remowt-link-shared"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "bifrostlink",
  "bytes",
@@ -2138,7 +2138,7 @@
 
 [[package]]
 name = "remowt-plugin"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "bifrostlink",
@@ -2152,7 +2152,7 @@
 
 [[package]]
 name = "remowt-polkit-shared"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "nix",
  "serde",
@@ -2161,7 +2161,7 @@
 
 [[package]]
 name = "remowt-ssh"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "async-trait",
@@ -2189,8 +2189,9 @@
 
 [[package]]
 name = "remowt-ui-prompt"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
+ "anyhow",
  "bifrostlink",
  "bifrostlink-macros",
  "serde",
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
 resolver = "2"
 
 [workspace.package]
-version = "0.1.3"
+version = "0.1.4"
 license = "MIT"
 edition = "2021"
 repository = "https://git.delta.rocks/r/remowt"
@@ -52,7 +52,6 @@
 thiserror = "2.0.18"
 
 [profile.release]
-strip = true
 panic = "abort"
 opt-level = "z"
 lto = true
modifiedcmds/remowt-agent/src/askpass.rsdiffbeforeafterboth
--- a/cmds/remowt-agent/src/askpass.rs
+++ b/cmds/remowt-agent/src/askpass.rs
@@ -2,24 +2,25 @@
 use std::io::Write as _;
 
 use anyhow::Context as _;
-use remowt_ui_prompt::bifrost::PromptEndpointsClient;
-use remowt_ui_prompt::dbus::{DbusPrompterInterface, DbusPrompterProxy};
-use remowt_ui_prompt::Source;
+use remowt_ui_prompt::dbus::{DbusPrompterInterface, DbusPrompterProxy, BUS_NAME, PROMPTER_PATH};
+use remowt_ui_prompt::{Prompter, Source};
+use tracing::debug;
 use zbus::Connection;
-
-use remowt_link_shared::BifConfig;
-
-const BUS_NAME: &str = "lach.RemowtAskpass";
-const PROMPTER_PATH: &str = "/lach/Askpass";
 
-pub async fn serve(
-	conn: &Connection,
-	prompter: PromptEndpointsClient<BifConfig>,
-) -> anyhow::Result<()> {
+pub async fn serve<P>(conn: &Connection, prompter: P) -> anyhow::Result<()>
+where
+	P: Prompter + 'static,
+{
 	conn.object_server()
 		.at(PROMPTER_PATH, DbusPrompterInterface(prompter))
 		.await?;
-	conn.request_name(BUS_NAME).await?;
+	match conn.request_name(BUS_NAME).await {
+		Ok(()) => {}
+		Err(zbus::Error::NameTaken) => {
+			debug!("{BUS_NAME} already owned, chaining to upstream");
+		}
+		Err(e) => return Err(e.into()),
+	}
 	Ok(())
 }
 
modifiedcmds/remowt-agent/src/main.rsdiffbeforeafterboth
--- a/cmds/remowt-agent/src/main.rs
+++ b/cmds/remowt-agent/src/main.rs
@@ -11,7 +11,9 @@
 use bifrostlink_ports::stdio::from_stdio;
 use bifrostlink_ports::unix_socket::from_socket;
 use clap::Parser;
-use remowt_endpoints::{fs::Fs, nix_daemon::NixDaemon, pty::Pty, subprocess::Subprocess, systemd::Systemd};
+use remowt_endpoints::{
+	fs::Fs, nix_daemon::NixDaemon, pty::Pty, subprocess::Subprocess, systemd::Systemd,
+};
 use remowt_link_shared::{editor::EditorEndpointsClient, Address, BifConfig};
 use remowt_polkit_shared::{emphasize, BackendRequest, Identity, PidDisplay};
 use remowt_ui_prompt::bifrost::PromptEndpointsClient;
@@ -250,13 +252,16 @@
 	}
 }
 async fn main_real() -> anyhow::Result<()> {
-	let conn = Connection::system().await?;
+	let system_conn = Connection::system().await?;
 	let helper = SocketHelper {
 		fallback: SuidHelper,
 	};
-	register_auth_agent(&conn, Agent::new(helper, RofiPrompter)).await?;
+	register_auth_agent(&system_conn, Agent::new(helper, RofiPrompter)).await?;
+
+	let session_conn = Connection::session().await?;
+	askpass::serve(&session_conn, RofiPrompter).await?;
 
-	let _conn = conn;
+	let _keep_alive = (system_conn, session_conn);
 	pending().await
 }
 async fn main_real_agent(
modifiedcmds/remowt-ssh/src/main.rsdiffbeforeafterboth
after · cmds/remowt-ssh/src/main.rs
1use std::borrow::Cow;2use std::env::VarError;3use std::io;4use std::os::fd::{AsRawFd, RawFd};5use std::path::PathBuf;6use std::pin::Pin;7use std::task::{Context, Poll};89use anyhow::anyhow;10use clap::Parser;11use nix::libc;12use nix::sys::termios::{self, SetArg, Termios};13use remowt_client::editor::SshEditor;14use remowt_client::{AgentBundle, Remowt};15use remowt_link_shared::editor::serve_editor;16use remowt_ui_prompt::auto::AutoPrompter;17use remowt_ui_prompt::bifrost::serve_prompts;18use remowt_ui_prompt::{PrependSourcePrompter, Source};19use tokio::io::unix::AsyncFd;20use tokio::io::{AsyncRead, ReadBuf};21use tokio::signal::unix::{signal, SignalKind};22use tracing::debug;2324#[derive(Parser)]25enum Opts {26	/// Connect to remote host with remowt agent.27	Ssh {28		host: String,29		#[arg(long)]30		escalate: bool,31	},32	/// Connect to local host for testing the connectivity.33	Local {34		#[arg(long)]35		escalate: bool,36	},37}3839fn agents_dir() -> anyhow::Result<PathBuf> {40	std::env::var_os("REMOWT_AGENTS_DIR")41		.map(PathBuf::from)42		.or_else(|| option_env!("REMOWT_AGENTS_DIR").map(PathBuf::from))43		.ok_or_else(|| anyhow!("no remowt-agents bundle"))44}4546#[tokio::main(flavor = "current_thread")]47async fn main() -> anyhow::Result<()> {48	tracing_subscriber::fmt()49		.with_writer(std::io::stderr)50		.without_time()51		.init();52	let opts = Opts::parse();5354	let bundle = AgentBundle::from_dir(agents_dir()?)?;55	let (conn, escalate) = match &opts {56		Opts::Ssh { host, escalate } => (Remowt::connect(host, &bundle).await?, *escalate),57		Opts::Local { escalate } => (Remowt::connect_local(&bundle).await?, *escalate),58	};59	let mut rpc = conn.rpc();6061	serve_prompts(62		&mut rpc,63		PrependSourcePrompter {64			prompter: AutoPrompter::new().await,65			source: match opts {66				Opts::Ssh { host, .. } => vec![Source(Cow::Owned(format!("ssh host: {}", host)))],67				Opts::Local { .. } => vec![],68			},69			description: "".to_owned(),70		},71	);72	if let Some(sess) = conn.ssh() {73		serve_editor(&mut rpc, SshEditor { sess });74	}7576	debug!("entering shell");77	run_shell(&conn, escalate).await?;78	debug!("shell ended");7980	Ok(())81}8283async fn run_shell(conn: &Remowt, escalate: bool) -> anyhow::Result<()> {84	let term = match std::env::var("TERM") {85		Ok(v) => v,86		Err(VarError::NotPresent) => "xterm-256color".to_owned(),87		Err(e) => return Err(e.into()),88	};89	let (cols, rows) = term_size().unwrap_or((80, 24));9091	let shell = conn.open_shell(&term, cols, rows, escalate).await?;92	let resizer = shell.resizer();93	let stream = shell.stream;9495	let _raw = RawMode::enable();9697	if let Ok(mut winch) = signal(SignalKind::window_change()) {98		tokio::spawn(async move {99			while winch.recv().await.is_some() {100				if let Some((cols, rows)) = term_size() {101					let _ = resizer.resize(cols, rows).await;102				}103			}104		});105	}106107	let (mut from_remote, mut to_remote) = tokio::io::split(stream);108	let mut stdin = AsyncStdin::new()?;109	let mut stdout = tokio::io::stdout();110111	tokio::select! {112		r = tokio::io::copy(&mut from_remote, &mut stdout) => { r?; }113		_ = tokio::io::copy(&mut stdin, &mut to_remote) => {}114	}115116	Ok(())117}118119struct AsyncStdin {120	fd: AsyncFd<RawFd>,121	original_flags: i32,122}123124impl AsyncStdin {125	fn new() -> io::Result<Self> {126		let raw = libc::STDIN_FILENO;127		// SAFETY: F_GETFL/F_SETFL round-trip on a valid fd.128		let original_flags = unsafe { libc::fcntl(raw, libc::F_GETFL) };129		if original_flags < 0 {130			return Err(io::Error::last_os_error());131		}132		if unsafe { libc::fcntl(raw, libc::F_SETFL, original_flags | libc::O_NONBLOCK) } < 0 {133			return Err(io::Error::last_os_error());134		}135		Ok(Self {136			fd: AsyncFd::new(raw)?,137			original_flags,138		})139	}140}141142impl Drop for AsyncStdin {143	fn drop(&mut self) {144		// SAFETY: restoring the flags we saved on a valid fd.145		unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_SETFL, self.original_flags) };146	}147}148149impl AsyncRead for AsyncStdin {150	fn poll_read(151		self: Pin<&mut Self>,152		cx: &mut Context<'_>,153		buf: &mut ReadBuf<'_>,154	) -> Poll<io::Result<()>> {155		let this = self.get_mut();156		loop {157			let mut guard = match this.fd.poll_read_ready(cx) {158				Poll::Ready(Ok(g)) => g,159				Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),160				Poll::Pending => return Poll::Pending,161			};162			let unfilled = buf.initialize_unfilled();163			let res = guard.try_io(|inner| {164				let fd = *inner.get_ref();165				// SAFETY: writing into `unfilled`'s own backing storage.166				let n = unsafe { libc::read(fd, unfilled.as_mut_ptr().cast(), unfilled.len()) };167				if n < 0 {168					Err(io::Error::last_os_error())169				} else {170					Ok(n as usize)171				}172			});173			match res {174				Ok(Ok(n)) => {175					buf.advance(n);176					return Poll::Ready(Ok(()));177				}178				Ok(Err(e)) => return Poll::Ready(Err(e)),179				Err(_would_block) => continue,180			}181		}182	}183}184185fn term_size() -> Option<(u16, u16)> {186	let mut ws: libc::winsize = unsafe { std::mem::zeroed() };187	let rc = unsafe { libc::ioctl(libc::STDIN_FILENO, libc::TIOCGWINSZ, &mut ws) };188	if rc != 0 || ws.ws_col == 0 {189		None190	} else {191		Some((ws.ws_col, ws.ws_row))192	}193}194195struct RawMode {196	original: Termios,197}198199impl RawMode {200	fn enable() -> Option<Self> {201		let stdin = std::io::stdin();202		// SAFETY: trivial libc call on a borrowed fd.203		if unsafe { libc::isatty(stdin.as_raw_fd()) } != 1 {204			return None;205		}206		let original = termios::tcgetattr(&stdin).ok()?;207		let mut raw = original.clone();208		termios::cfmakeraw(&mut raw);209		termios::tcsetattr(&stdin, SetArg::TCSANOW, &raw).ok()?;210		Some(Self { original })211	}212}213214impl Drop for RawMode {215	fn drop(&mut self) {216		let _ = termios::tcsetattr(std::io::stdin(), SetArg::TCSANOW, &self.original);217	}218}
modifiedcrates/remowt-ui-prompt/Cargo.tomldiffbeforeafterboth
--- a/crates/remowt-ui-prompt/Cargo.toml
+++ b/crates/remowt-ui-prompt/Cargo.toml
@@ -6,6 +6,7 @@
 license.workspace = true
 
 [dependencies]
+anyhow.workspace = true
 bifrostlink.workspace = true
 bifrostlink-macros.workspace = true
 serde.workspace = true
addedcrates/remowt-ui-prompt/src/auto.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/remowt-ui-prompt/src/auto.rs
@@ -0,0 +1,83 @@
+use anyhow::bail;
+use tracing::debug;
+use zbus::fdo::DBusProxy;
+use zbus::names::BusName;
+
+use crate::dbus::{DbusPrompterProxy, BUS_NAME, PROMPTER_PATH};
+use crate::rofi::RofiPrompter;
+use crate::{Prompter, Result, Source};
+
+pub struct AutoPrompter {
+	dbus: Option<DbusPrompterProxy<'static>>,
+	fallback: RofiPrompter,
+}
+
+impl AutoPrompter {
+	pub async fn new() -> Self {
+		let dbus = match Self::try_dbus().await {
+			Ok(p) => Some(p),
+			Err(e) => {
+				debug!("dbus prompter unavailable, falling back to rofi: {e}");
+				None
+			}
+		};
+		Self {
+			dbus,
+			fallback: RofiPrompter,
+		}
+	}
+
+	async fn try_dbus() -> anyhow::Result<DbusPrompterProxy<'static>> {
+		let conn = zbus::Connection::session().await?;
+		let dbus = DBusProxy::new(&conn).await?;
+		let name = BusName::try_from(BUS_NAME)?;
+		if !dbus.name_has_owner(name).await? {
+			bail!("{BUS_NAME} not registered on session bus");
+		}
+		let proxy = DbusPrompterProxy::builder(&conn)
+			.destination(BUS_NAME)?
+			.path(PROMPTER_PATH)?
+			.build()
+			.await?;
+		Ok(proxy)
+	}
+}
+
+impl Prompter for AutoPrompter {
+	async fn prompt_enum(
+		&self,
+		prompt: &str,
+		description: &str,
+		variants: &[&str],
+		source: &[Source],
+	) -> Result<u32> {
+		if let Some(dbus) = &self.dbus {
+			return Prompter::prompt_enum(dbus, prompt, description, variants, source).await;
+		}
+		self.fallback
+			.prompt_enum(prompt, description, variants, source)
+			.await
+	}
+
+	async fn prompt_text(
+		&self,
+		echo: bool,
+		prompt: &str,
+		description: &str,
+		source: &[Source],
+	) -> Result<String> {
+		if let Some(dbus) = &self.dbus {
+			return Prompter::prompt_text(dbus, echo, prompt, description, source).await;
+		}
+		self.fallback
+			.prompt_text(echo, prompt, description, source)
+			.await
+	}
+
+	async fn display_text(&self, error: bool, description: &str, source: &[Source]) -> Result<()> {
+		if let Some(dbus) = &self.dbus {
+			return Prompter::display_text(dbus, error, description, source).await;
+		}
+		self.fallback.display_text(error, description, source).await
+	}
+}
modifiedcrates/remowt-ui-prompt/src/dbus.rsdiffbeforeafterboth
--- a/crates/remowt-ui-prompt/src/dbus.rs
+++ b/crates/remowt-ui-prompt/src/dbus.rs
@@ -5,17 +5,25 @@
 use crate::{BlockingPrompter, Result};
 use crate::{Error, Prompter};
 
+pub const BUS_NAME: &str = "lach.RemowtAskpass";
+pub const PROMPTER_PATH: &str = "/lach/Askpass";
+
 pub struct DbusPrompterInterface<P>(pub P);
 
 #[interface(name = "lach.PolkitInputHandler")]
 impl<P: Prompter + Send + Sync + 'static> DbusPrompterInterface<P> {
-	async fn prompt_radio(
+	async fn prompt_enum(
 		&self,
 		prompt: &str,
 		description: &str,
+		variants: Vec<String>,
 		source: Vec<Source>,
-	) -> fdo::Result<bool> {
-		Ok(self.0.prompt_radio(prompt, description, &source).await?)
+	) -> fdo::Result<u32> {
+		let variants: Vec<&str> = variants.iter().map(|v| v.as_str()).collect();
+		Ok(self
+			.0
+			.prompt_enum(prompt, description, &variants, &source)
+			.await?)
 	}
 	async fn prompt_text(
 		&self,
modifiedcrates/remowt-ui-prompt/src/lib.rsdiffbeforeafterboth
--- a/crates/remowt-ui-prompt/src/lib.rs
+++ b/crates/remowt-ui-prompt/src/lib.rs
@@ -3,6 +3,7 @@
 use std::future::Future;
 use std::result;
 
+pub mod auto;
 pub mod bifrost;
 pub mod dbus;
 pub mod rofi;