teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter attach`: attaches this terminal to a teter session.

use std::io::Write;
use std::path::PathBuf;

use crossterm::terminal;
use futures_util::{StreamExt, stream};
use teter_common::SessionId;
use teter_frontend::{Config, End};
use tokio::signal::unix::{SignalKind, signal};
/// Attach this terminal to a teter session. Ctrl-] detaches.
///
/// Logged in, name it as `machine[:session]` (the default session is
/// `main`): everything else comes from the account. Without an account, give
/// the values `teter status` shows; the secret then comes from TETER_SECRET,
/// never from the command line, where other users could read it in the
/// process list.
#[derive(clap::Args)]
pub struct AttachArgs {
    /// The session, as `machine[:session]`, from the logged-in account.
    target: Option<String>,

    /// The relay, such as wss://relay.example.com (its /frontend endpoint;
    /// one ending in /backend or /frontend is taken as the relay's).
    /// Logged in: the account's.
    #[arg(long, env = "TETER_RELAY", required_unless_present = "target")]
    relay: Option<String>,

    /// The session ID `teter status` shows (without an account).
    #[arg(long, env = "TETER_SESSION", required_unless_present = "target")]
    session: Option<SessionId>,

    /// The channel `teter status` shows (without an account).
    #[arg(long, env = "TETER_CHANNEL", required_unless_present = "target")]
    channel: Option<String>,

    /// The frontend token `teter status` shows (without an account).
    #[arg(
        long,
        env = "TETER_TOKEN",
        hide_env_values = true,
        required_unless_present = "target"
    )]
    token: Option<String>,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,

    /// Lines of the session's history to write first, into this terminal's
    /// scrollback (default: all the session keeps; 0 for none).
    #[arg(long, default_value_t = u32::MAX, hide_default_value = true)]
    history: u32,
}

/// Raw mode for as long as it lives; dropping it restores the terminal.
struct RawMode;

impl RawMode {
    #[expect(
        clippy::let_underscore_must_use,
        reason = "the terminal layer: restoring raw mode and the last messages to stderr are all that is left to try"
    )]
    fn enable() -> std::io::Result<Self> {
        terminal::enable_raw_mode()?;
        // A panic restores the terminal before the message is printed.
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            let _ = terminal::disable_raw_mode();
            previous(info);
        }));
        Ok(Self)
    }
}

impl Drop for RawMode {
    #[expect(
        clippy::let_underscore_must_use,
        reason = "the terminal layer: restoring raw mode and the last messages to stderr are all that is left to try"
    )]
    fn drop(&mut self) {
        let _ = terminal::disable_raw_mode();
    }
}

/// Attaches; the exit code, which the process must exit with at once (a
/// pending read of stdin holds a thread that would otherwise keep it alive
/// after the session).
pub async fn attach(args: AttachArgs) -> i32 {
    let args_history = args.history;
    let rejoin = rejoin_for(&args);
    let config = match &args.target {
        Some(target) => match crate::sessions::resolve(target, args.ca_cert.clone()).await {
            Ok(config) => config,
            Err(e) => {
                eprintln!("teter: {e}");
                return 1;
            }
        },
        None => match by_hand(args) {
            Ok(config) => config,
            Err(code) => return code,
        },
    };
    let config = Config {
        history: args_history,
        rows: terminal_size().1,
        ..config
    };
    run(&config, rejoin).await
}

/// How long one attempt to join again may take.
const REJOIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// How the attachment joins again after a lost link (#81): by name, the
/// session is found again (another relay session after a relay restart,
/// another secret after a session process restart); by hand, the same
/// session, which is gone when the relay no longer knows it.
fn rejoin_for(args: &AttachArgs) -> Box<dyn FnOnce(&Config) -> teter_frontend::Rejoin> {
    let ca_cert = args.ca_cert.clone();
    match args.target.clone() {
        Some(target) => Box::new(move |_| teter_frontend::Rejoin {
            label: target.clone(),
            connect: Box::new(move || {
                let (target, ca_cert) = (target.clone(), ca_cert.clone());
                // The whole attempt in one deadline: finding the session
                // again asks the relay too.
                Box::pin(async move {
                    tokio::time::timeout(REJOIN_TIMEOUT, rejoin_by_name(target, ca_cert))
                        .await
                        .unwrap_or_else(|_| {
                            Err(teter_frontend::RejoinError::Retry(std::io::Error::other(
                                "finding the session again took too long",
                            )))
                        })
                })
            }),
        }),
        None => Box::new(|config: &Config| {
            // A join again asks no history: it is in the scrollback already.
            let config = Config {
                history: 0,
                rows: 0,
                sealed_history: false,
                ..config.clone()
            };
            teter_frontend::Rejoin {
                label: format!("session {}", config.session),
                connect: Box::new(move || {
                    let config = config.clone();
                    Box::pin(async move { joined(&config, true).await })
                }),
            }
        }),
    }
}

/// Finds session `target` again through the account, and joins it.
async fn rejoin_by_name(
    target: String,
    ca_cert: Option<std::path::PathBuf>,
) -> Result<
    (
        teter_client::Relay,
        teter_frontend::Target,
        teter_client::e2e::Secret,
    ),
    teter_frontend::RejoinError,
> {
    let config = crate::sessions::resolve(&target, ca_cert)
        .await
        .map_err(|e| {
            let text = e.to_string();
            // Gone for good: no such machine or session, or one the account
            // does not trust.
            if text.contains("has no session named")
                || text.contains("no machine named")
                || text.contains("not approved")
            {
                teter_frontend::RejoinError::Gone(text)
            } else {
                teter_frontend::RejoinError::Retry(e)
            }
        })?;
    // A join again: the history kept on disk is on the screen already.
    let config = Config {
        sealed_history: false,
        ..config
    };
    joined(&config, false).await
}

/// Joins `config`'s session; when `fixed` (given by hand), a relay that no
/// longer knows it means it is gone.
async fn joined(
    config: &Config,
    fixed: bool,
) -> Result<
    (
        teter_client::Relay,
        teter_frontend::Target,
        teter_client::e2e::Secret,
    ),
    teter_frontend::RejoinError,
> {
    // A relay that takes the connection and never answers is tried again.
    let attempt = tokio::time::timeout(REJOIN_TIMEOUT, teter_frontend::join(config))
        .await
        .unwrap_or_else(|_| Err(std::io::Error::other("the relay did not answer the join")));
    match attempt {
        Ok(relay) => Ok((
            relay,
            teter_frontend::Target {
                session: config.session,
                channel: config.channel.clone(),
            },
            config.secret.clone(),
        )),
        Err(e) if fixed && e.to_string().contains("no such session") => {
            Err(teter_frontend::RejoinError::Gone(e.to_string()))
        }
        Err(e) => Err(teter_frontend::RejoinError::Retry(e)),
    }
}

/// The session the values given by hand name, with TETER_SECRET; an exit
/// code when they do not.
fn by_hand(args: AttachArgs) -> Result<Config, i32> {
    // From the environment only: an argument shows in the process list.
    let text = match std::env::var("TETER_SECRET") {
        // The one copy, wiped once parsed.
        Ok(text) => zeroize::Zeroizing::new(text),
        Err(std::env::VarError::NotPresent) => {
            eprintln!(
                "teter: TETER_SECRET is not set: give it the secret `teter status` shows, or log \
                 in and attach as machine:session"
            );
            return Err(2);
        }
        Err(std::env::VarError::NotUnicode(_)) => {
            eprintln!("teter: TETER_SECRET is not text");
            return Err(2);
        }
    };
    let secret = match teter_client::e2e::Secret::parse(&text) {
        Ok(secret) => secret,
        Err(e) => {
            eprintln!("teter: TETER_SECRET: {e}");
            return Err(2);
        }
    };
    drop(text);
    let (Some(relay), Some(session), Some(token), Some(channel)) =
        (args.relay, args.session, args.token, args.channel)
    else {
        eprintln!("teter: give --relay, --session, --token and --channel, or machine:session");
        return Err(2);
    };
    Ok(Config {
        relay: crate::endpoint(&relay, "frontend"),
        session,
        token,
        secret,
        ca_cert: args.ca_cert,
        channel: Some(channel),
        history: 0,
        rows: 0,
        sealed_history: false,
    })
}

async fn run(config: &Config, rejoin: Box<dyn FnOnce(&Config) -> teter_frontend::Rejoin>) -> i32 {
    // Join before raw mode, so errors print on a normal terminal.
    let relay = match teter_frontend::join(config).await {
        Ok(relay) => relay,
        Err(e) => {
            eprintln!("teter: {e}");
            return 1;
        }
    };
    let size = terminal_size();
    let resizes = resizes();
    let (Ok(mut hangup), Ok(mut terminate)) = (
        signal(SignalKind::hangup()),
        signal(SignalKind::terminate()),
    ) else {
        eprintln!("teter: cannot watch signals");
        return 1;
    };

    let raw = match RawMode::enable() {
        Ok(raw) => raw,
        Err(e) => {
            eprintln!("teter: cannot put the terminal in raw mode: {e}");
            return 1;
        }
    };
    // A hangup or a termination detaches from inside the loop, so the
    // session is left properly.
    let signalled = async move {
        tokio::select! {
            _ = hangup.recv() => {}
            _ = terminate.recv() => {}
        }
    };
    let ended = teter_frontend::attach_reconnecting(
        relay,
        teter_frontend::Target {
            session: config.session,
            channel: config.channel.clone(),
        },
        config.secret.clone(),
        tokio::io::stdin(),
        tokio::io::stdout(),
        size,
        resizes,
        signalled,
        rejoin(config),
    )
    .await;
    drop(raw);
    report(ended)
}

/// The terminal's sizes as it is resized, or none if its resizes cannot be watched.
fn resizes() -> futures_util::stream::BoxStream<'static, (u16, u16)> {
    match signal(SignalKind::window_change()) {
        Ok(winch) => stream::unfold(winch, |mut winch| async move {
            winch.recv().await?;
            Some((terminal_size(), winch))
        })
        .boxed(),
        Err(_) => stream::empty().boxed(),
    }
}

/// How the session ended, told on stderr, and the exit code.
#[expect(
    clippy::let_underscore_must_use,
    reason = "the last messages to stderr are all that is left to try"
)]
/// A CAN (0x18) goes to the terminal (stdout, when it is one) first, ending an escape sequence the
/// session's output may have left open, so the message shows whole.
fn report(ended: std::io::Result<End>) -> i32 {
    let mut stdout = std::io::stdout();
    // Only to a terminal: a redirected output gets nothing it did not print.
    if std::io::IsTerminal::is_terminal(&stdout) {
        let _ = stdout.write_all(b"\x18");
        let _ = stdout.flush();
    }
    let mut stderr = std::io::stderr();
    let code = match ended {
        Ok(End::Detached) => {
            let _ = writeln!(stderr, "\r\n[detached]");
            0
        }
        Ok(End::SessionEnded(reason)) => {
            let _ = writeln!(stderr, "\r\n[session ended: {reason}]");
            0
        }
        Err(e) => {
            let _ = writeln!(stderr, "\r\nteter: {e}");
            1
        }
    };
    let _ = std::io::stdout().flush();
    code
}

/// The terminal's size, or 80x24 when it cannot be read or reports a zero
/// (some environments without a real terminal do): a zero would cut the
/// session's screen to nothing (#141).
fn terminal_size() -> (u16, u16) {
    match terminal::size() {
        Ok((columns, rows)) if columns > 0 && rows > 0 => (columns, rows),
        _ => (80, 24),
    }
}