lune-tty 0.1.0

A GPU-accelerated Wayland terminal emulator for Linux
Documentation
use std::ffi::OsString;
use std::io;
use std::os::unix::ffi::OsStringExt;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::thread;

use winit::event_loop::EventLoopProxy;

use super::Event;

pub(super) fn open(
    uri: Option<String>,
    fallback: Option<PathBuf>,
    proxy: EventLoopProxy<Event>,
) -> io::Result<()> {
    thread::Builder::new()
        .name("lune-open-directory".into())
        .spawn(move || {
            let _ = proxy.send_event(Event::DirectoryOpened(open_directory(
                uri.as_deref(),
                fallback,
            )));
        })?;
    Ok(())
}

pub(super) fn working_directory(
    uri: Option<&str>,
    foreground_pgid: Option<u32>,
    child_pid: u32,
) -> Option<PathBuf> {
    if let Some(uri) = uri {
        let mut hostname = [0; 256];
        if let Some(path) = local_path(uri, local_hostname(&mut hostname))
            && path.is_dir()
        {
            return Some(path);
        }
    }
    for pid in foreground_pgid
        .into_iter()
        .chain(std::iter::once(child_pid))
    {
        if let Some(path) = proc_cwd(pid)
            && path.is_dir()
        {
            return Some(path);
        }
    }
    None
}

fn proc_cwd(pid: u32) -> Option<PathBuf> {
    if pid == 0 {
        return None;
    }
    std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}

pub(super) fn is_valid_hyperlink(uri: &str) -> bool {
    let mut hostname = [0; 256];
    hyperlink_target(uri, local_hostname(&mut hostname)).is_some()
}

pub(super) fn open_hyperlink(uri: String, proxy: EventLoopProxy<Event>) -> io::Result<()> {
    thread::Builder::new()
        .name("lune-open-hyperlink".into())
        .spawn(move || {
            let _ = proxy.send_event(Event::HyperlinkOpened(open_uri(&uri)));
        })?;
    Ok(())
}

/// Decodes a remote `file://host/path` OSC 7 URI when `host` is non-local.
pub(super) fn remote_path(uri: &str) -> Option<(String, String)> {
    let mut hostname = [0; 256];
    remote_path_for_host(uri, local_hostname(&mut hostname))
}

fn remote_path_for_host(uri: &str, local_host: &[u8]) -> Option<(String, String)> {
    let (scheme, rest) = uri.as_bytes().split_at_checked(b"file://".len())?;
    if !scheme.eq_ignore_ascii_case(b"file://") {
        return None;
    }
    let (host, encoded) = rest.split_at(rest.iter().position(|&byte| byte == b'/')?);
    if host.is_empty()
        || host.eq_ignore_ascii_case(b"localhost")
        || host.eq_ignore_ascii_case(local_host)
    {
        return None;
    }
    let host = std::str::from_utf8(host).ok()?.to_owned();
    let decoded = decode_percent_path(encoded)?;
    let path = String::from_utf8(decoded).ok()?;
    Some((host, path))
}

fn local_hostname(buffer: &mut [u8; 256]) -> &[u8] {
    // SAFETY: The destination buffer is writable for the supplied length.
    let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
    if result == 0 {
        buffer.split(|&byte| byte == 0).next().unwrap_or_default()
    } else {
        &[]
    }
}

fn open_uri(uri: &str) -> io::Result<()> {
    let mut hostname = [0; 256];
    let target = hyperlink_target(uri, local_hostname(&mut hostname))
        .ok_or_else(|| io::Error::other("Unsupported or invalid hyperlink URI"))?;
    let status = Command::new("xdg-open")
        .arg(target)
        .stdin(Stdio::null())
        .status()?;
    if !status.success() {
        return Err(io::Error::other(format!("xdg-open returned {status}")));
    }
    Ok(())
}

fn hyperlink_target(uri: &str, hostname: &[u8]) -> Option<OsString> {
    if uri.is_empty() || uri.bytes().any(|b| b <= 0x20 || b == 0x7f) {
        return None;
    }
    let (scheme, rest) = uri.split_once(':')?;
    if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
        let authority = rest.strip_prefix("//")?;
        let host = authority.split('/').next().unwrap_or_default();
        return (!host.is_empty()).then(|| OsString::from(uri));
    }
    if scheme.eq_ignore_ascii_case("mailto") {
        return (!rest.is_empty()).then(|| OsString::from(uri));
    }
    if scheme.eq_ignore_ascii_case("file") {
        return local_path(uri, hostname).map(PathBuf::into_os_string);
    }
    None
}

fn open_directory(uri: Option<&str>, fallback: Option<PathBuf>) -> io::Result<()> {
    let path = match uri {
        Some(uri) => {
            let mut hostname = [0; 256];
            local_path(uri, local_hostname(&mut hostname))
                .ok_or_else(|| io::Error::other("The shell did not report a local directory"))?
        }
        None => match fallback {
            Some(path) => path,
            None => std::env::current_dir()?,
        },
    };
    if !path.metadata()?.is_dir() {
        return Err(io::Error::other("The reported path is not a directory"));
    }
    let status = Command::new("xdg-open")
        .arg(path)
        .stdin(Stdio::null())
        .status()?;
    if !status.success() {
        return Err(io::Error::other(format!("xdg-open returned {status}")));
    }
    Ok(())
}

fn local_path(uri: &str, hostname: &[u8]) -> Option<PathBuf> {
    let (scheme, rest) = uri.as_bytes().split_at_checked(b"file://".len())?;
    if !scheme.eq_ignore_ascii_case(b"file://") {
        return None;
    }
    let (host, encoded) = rest.split_at(rest.iter().position(|&byte| byte == b'/')?);
    if !(host.is_empty()
        || host.eq_ignore_ascii_case(b"localhost")
        || host.eq_ignore_ascii_case(hostname))
    {
        return None;
    }
    let path = decode_percent_path(encoded)?;
    Some(PathBuf::from(OsString::from_vec(path)))
}

fn decode_percent_path(encoded: &[u8]) -> Option<Vec<u8>> {
    let mut path = Vec::with_capacity(encoded.len());
    let mut bytes = encoded.iter().copied();
    while let Some(byte) = bytes.next() {
        let byte = match byte {
            b'?' | b'#' => return None,
            b'%' => {
                let high = char::from(bytes.next()?).to_digit(16)?;
                let low = char::from(bytes.next()?).to_digit(16)?;
                (high * 16 + low) as u8
            }
            _ => byte,
        };
        if byte == 0 {
            return None;
        }
        path.push(byte);
    }
    Some(path)
}

#[cfg(test)]
mod tests {
    use super::{hyperlink_target, local_path, remote_path_for_host};
    use std::ffi::OsStr;
    use std::os::unix::ffi::OsStrExt;

    #[test]
    fn hyperlink_targets_allow_only_safe_schemes() {
        let host = b"local.example.test";
        assert_eq!(
            hyperlink_target("https://example.com/docs", host).as_deref(),
            Some(OsStr::new("https://example.com/docs"))
        );
        assert_eq!(
            hyperlink_target("HTTP://example.com", host).as_deref(),
            Some(OsStr::new("HTTP://example.com"))
        );
        assert_eq!(
            hyperlink_target("mailto:dev@example.com", host).as_deref(),
            Some(OsStr::new("mailto:dev@example.com"))
        );
        assert_eq!(
            hyperlink_target("file://localhost/tmp/test.txt", host).as_deref(),
            Some(OsStr::new("/tmp/test.txt"))
        );
        for bad in [
            "",
            "https://",
            "https://example.com/has space",
            "javascript:alert(1)",
            "file://remote.example.test/etc/passwd",
            "mailto:",
        ] {
            assert!(hyperlink_target(bad, host).is_none(), "{bad}");
        }
    }

    #[test]
    fn directory_reports_decode_only_local_file_paths() {
        let host = b"local.example.test";
        for authority in ["", "localhost", "LOCAL.example.test"] {
            let uri = format!("FILE://{authority}/build%20output/%E2%98%BE%23%FF");
            let path = local_path(&uri, host).unwrap();
            assert_eq!(
                path.as_os_str().as_bytes(),
                b"/build output/\xe2\x98\xbe#\xff"
            );
        }
        for rejected in [
            "http://localhost/build",
            "file://remote.example.test/build",
            "file://localhost/build?query",
            "file://localhost/build#frag",
            "file://localhost/bad%2",
            "file://localhost/bad%00",
        ] {
            assert!(local_path(rejected, host).is_none(), "{rejected}");
        }

        assert_eq!(
            remote_path_for_host("file://remote.example/srv/my%20app", host),
            Some(("remote.example".to_owned(), "/srv/my app".to_owned()))
        );
        assert!(remote_path_for_host("file://localhost/tmp", host).is_none());
        assert!(remote_path_for_host("file://local.example.test/tmp", host).is_none());
    }
}