use std::path::PathBuf;
use teter_backend::registry::{self, Registry};
use teter_backend::session::{self, SessionConfig};
use teter_client::e2e::Secret;
#[derive(clap::Args)]
pub struct LinkArgs {
#[arg(long, env = "TETER_RELAY")]
relay: Option<String>,
#[arg(long)]
shell: Option<String>,
#[arg(long)]
ca_cert: Option<PathBuf>,
#[arg(long, env = "TETER_SOCKETS")]
sockets: Option<PathBuf>,
#[arg(long, env = "TETER_REGISTRY")]
registry: Option<PathBuf>,
#[arg(long, default_value_t = 3)]
pub(crate) in_use_status: u8,
}
#[derive(clap::Args)]
pub struct KillArgs {
name: String,
#[arg(long)]
ca_cert: Option<PathBuf>,
#[arg(long, env = "TETER_SOCKETS")]
sockets: Option<PathBuf>,
#[arg(long, env = "TETER_REGISTRY")]
registry: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct StatusArgs {
#[arg(long, env = "TETER_SOCKETS")]
sockets: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct SessionArgs {
#[arg(long)]
name: String,
#[arg(long)]
shell: String,
#[arg(long)]
sockets: PathBuf,
#[arg(long, default_value_t = teter_backend::screen::DEFAULT_HISTORY)]
history_lines: usize,
}
pub async fn link(args: LinkArgs) -> std::io::Result<()> {
let host = crate::machine::load_host()?
.filter(|host| !host.machine.is_empty())
.ok_or_else(|| {
std::io::Error::other(
"this machine is not registered: make a token on a logged-in device (teter token \
create), then run teter register --token <token> here",
)
})?;
let machine = teter_backend::MachineAuth {
id: host.machine.clone(),
key: std::sync::Arc::new(host.key()?),
account_keys: teter_common::account::unhex(&host.account_keys)
.ok_or_else(|| std::io::Error::other("host.json is damaged: register again"))?,
};
let relay = args.relay.unwrap_or_else(|| host.relay.clone());
if crate::endpoint(&relay, "backend") != crate::endpoint(&host.relay, "backend") {
tracing::warn!(
relay,
registered = host.relay,
"linking through a relay other than the one this machine registered with \
(--relay or TETER_RELAY): it must be another URL of the same relay"
);
}
let defaults = teter_backend::Config::new(
crate::endpoint(&relay, "backend"),
machine,
args.shell.unwrap_or_else(teter_backend::default_shell),
);
let config = teter_backend::Config {
ca_cert: args.ca_cert,
sockets: args.sockets.unwrap_or(defaults.sockets.clone()),
registry: match args.registry {
Some(path) => Some(path),
None => registry::default_path()
.inspect_err(|e| tracing::warn!(error = %e, "running without a session registry"))
.ok(),
},
..defaults
};
teter_backend::run(&config, |session| {
println!("session: {}", session.id);
println!("token: {}", session.frontend_token);
if let Some(name) = &session.name {
println!("name: {name}");
}
if let Some(channel) = &session.channel {
println!("channel: {channel}");
}
})
.await
}
pub async fn serve_session(args: SessionArgs) -> std::io::Result<()> {
let bound = session::bind(&args.sockets, &args.name)?;
let secret = Secret::generate()?;
let null = std::fs::OpenOptions::new().write(true).open("/dev/null")?;
rustix::stdio::dup2_stdout(null)?;
let config = SessionConfig {
history_lines: args.history_lines,
..SessionConfig::new(args.name, args.shell, secret)
};
session::serve(config, bound).await
}
pub async fn status(args: StatusArgs) -> std::io::Result<()> {
let sockets = args.sockets.unwrap_or_else(session::socket_dir);
let answers = teter_backend::status(&sockets).await?;
if answers.is_empty() {
return Err(std::io::Error::other(format!(
"no session runs (no socket in {})",
sockets.display()
)));
}
let mut answered = false;
for (name, answer) in answers {
match answer {
Ok(values) => {
answered = true;
println!("{}", values.name);
match values.relay {
Some((id, token)) => {
println!(" session: {id}");
println!(" token: {token}");
if let Some(channel) = &values.channel {
println!(" channel: {channel}");
}
}
None => println!(" session: none yet (no link has reached the relay)"),
}
println!(" secret: {}", *values.secret);
}
Err(e) => eprintln!("teter: {name}: {e}"),
}
}
if answered {
Ok(())
} else {
Err(std::io::Error::other(format!(
"no session process in {} answered",
sockets.display()
)))
}
}
pub async fn kill(args: KillArgs) -> std::io::Result<()> {
if args.name.contains(':') {
return crate::remote::kill(&args.name, args.ca_cert).await;
}
let registry = Registry::at(match args.registry {
Some(path) => path,
None => registry::default_path()?,
});
let sockets = args.sockets.unwrap_or_else(session::socket_dir);
let ended = match teter_backend::kill(&sockets, ®istry, &args.name).await {
Ok(ended) => ended,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(std::io::Error::new(
e.kind(),
format!("{e} on this machine (another machine's: teter kill machine:session)"),
));
}
Err(e) => return Err(e),
};
if ended {
println!("ended the session {:?}", args.name);
} else {
println!(
"removed the session {:?}; no session process of it ran",
args.name
);
}
Ok(())
}
pub fn session_failure() -> std::process::ExitCode {
std::process::ExitCode::from(session::FAILURE_EXIT)
}