about summary refs log tree commit diff
path: root/users/grfn/xanthous/server/src/pty.rs
blob: 234ecd8f23369fa22f11c05a137e2daf2788a66f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use std::io::{self};
use std::os::unix::prelude::{AsRawFd, CommandExt, FromRawFd};
use std::pin::Pin;
use std::process::{abort, Command};
use std::task::{Context, Poll};

use eyre::{bail, Result};
use futures::Future;
use nix::pty::{forkpty, Winsize};
use nix::sys::termios::Termios;
use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
use nix::unistd::{ForkResult, Pid};
use tokio::fs::File;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::signal::unix::{signal, Signal, SignalKind};
use tokio::task::spawn_blocking;

mod ioctl {
    use super::Winsize;
    use libc::TIOCSWINSZ;
    use nix::ioctl_write_ptr_bad;

    ioctl_write_ptr_bad!(tiocswinsz, TIOCSWINSZ, Winsize);
}

async fn asyncify<F, T>(f: F) -> Result<T>
where
    F: FnOnce() -> Result<T> + Send + 'static,
    T: Send + 'static,
{
    match spawn_blocking(f).await {
        Ok(res) => res,
        Err(_) => bail!("background task failed",),
    }
}

pub struct Child {
    pub tty: File,
    pub pid: Pid,
}

pub struct ChildHandle {
    pub tty: File,
}

pub struct WaitPid {
    pid: Pid,
    signal: Signal,
}

impl WaitPid {
    pub fn new(pid: Pid) -> Self {
        Self {
            pid,
            signal: signal(SignalKind::child()).unwrap(),
        }
    }
}

impl Future for WaitPid {
    type Output = nix::Result<WaitStatus>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let _ = self.signal.poll_recv(cx);
        match waitpid(self.pid, Some(WaitPidFlag::WNOHANG)) {
            Ok(WaitStatus::StillAlive) => Poll::Pending,
            result => Poll::Ready(result),
        }
    }
}

impl Child {
    pub async fn handle(&self) -> io::Result<ChildHandle> {
        Ok(ChildHandle {
            tty: self.tty.try_clone().await?,
        })
    }
}

impl ChildHandle {
    pub async fn resize_window(&mut self, winsize: Winsize) -> Result<()> {
        let fd = self.tty.as_raw_fd();
        asyncify(move || unsafe {
            ioctl::tiocswinsz(fd, &winsize as *const Winsize)?;
            Ok(())
        })
        .await
    }
}

pub async fn spawn(
    mut cmd: Command,
    winsize: Option<Winsize>,
    termios: Option<Termios>,
) -> Result<Child> {
    asyncify(move || unsafe {
        let res = forkpty(winsize.as_ref(), termios.as_ref())?;
        match res.fork_result {
            ForkResult::Parent { child } => Ok(Child {
                pid: child,
                tty: File::from_raw_fd(res.master),
            }),
            ForkResult::Child => {
                cmd.exec();
                abort();
            }
        }
    })
    .await
}

impl AsyncRead for Child {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.tty).poll_read(cx, buf)
    }
}

impl AsyncWrite for Child {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        Pin::new(&mut self.tty).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.tty).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.tty).poll_shutdown(cx)
    }
}

impl AsyncRead for ChildHandle {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.tty).poll_read(cx, buf)
    }
}

impl AsyncWrite for ChildHandle {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        Pin::new(&mut self.tty).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.tty).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.tty).poll_shutdown(cx)
    }
}