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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#![allow(dead_code)]
use std::{
    fs::File,
    os::{
        fd::{AsFd, BorrowedFd, OwnedFd},
        unix::prelude::{AsRawFd, FromRawFd},
    },
    thread,
    time::{self, Duration},
};

pub use nix::Error;
use nix::{
    fcntl::{open, OFlag},
    ioctl_write_ptr_bad,
    libc::{self, winsize},
    pty::{grantpt, posix_openpt, unlockpt, PtyMaster},
    sys::{stat::Mode, termios},
    unistd::{close, isatty, setsid},
    Result,
};
use termios::SpecialCharacterIndices;
use tokio::process::Command;

const DEFAULT_TERM_COLS: u16 = 80;
const DEFAULT_TERM_ROWS: u16 = 24;

const DEFAULT_VEOF_CHAR: u8 = 0x4; // ^D
const DEFAULT_INTR_CHAR: u8 = 0x3; // ^C

const DEFAULT_TERMINATE_DELAY: Duration = Duration::from_millis(100);

#[derive(Debug)]
pub struct PtyProcess {
    master:          Master,
    eof_char:        u8,
    intr_char:       u8,
    terminate_delay: Duration,
}

impl PtyProcess {
    /// Spawns a child process and create a [PtyProcess].
    pub fn spawn(
        mut command: Command,
        rows: u16,
        cols: u16,
    ) -> std::io::Result<(Self, tokio::process::Child)> {
        let master = Master::open()?;
        master.grant_slave_access()?;
        master.unlock_slave()?;
        let slave_fd = master.get_slave_fd()?;
        command
            .stdin(slave_fd.try_clone()?)
            .stdout(slave_fd.try_clone()?)
            .stderr(slave_fd);
        let pts_name = master.get_slave_name()?;

        unsafe {
            command.pre_exec(move || -> std::io::Result<()> {
                make_controlling_tty(&pts_name)?;

                let stdin = std::io::stdin();
                set_echo(&stdin, false)?;
                set_term_size(stdin.as_raw_fd(), cols, rows)?;
                Ok(())
            });
        }
        Ok((
            PtyProcess {
                master,
                eof_char: get_eof_char(),
                intr_char: get_intr_char(),
                terminate_delay: DEFAULT_TERMINATE_DELAY,
            },
            command.spawn()?,
        ))
    }

    pub fn get_raw_handle(&self) -> std::io::Result<File> {
        self.master.get_file_handle()
    }

    /// Get a end of file character if set or a default.
    pub fn get_eof_char(&self) -> u8 {
        self.eof_char
    }

    /// Get a interapt character if set or a default.
    pub fn get_intr_char(&self) -> u8 {
        self.intr_char
    }

    /// Get window size of a terminal.
    ///
    /// Default size is 80x24.
    pub fn get_window_size(&self) -> Result<(u16, u16)> {
        get_term_size(self.master.as_fd().as_raw_fd())
    }

    /// Sets a terminal size.
    pub fn set_window_size(&self, cols: u16, rows: u16) -> Result<()> {
        set_term_size(self.master.as_fd().as_raw_fd(), cols, rows)
    }

    /// The function returns true if an echo setting is setup.
    pub fn get_echo(&self) -> Result<bool> {
        termios::tcgetattr(&self.master)
            .map(|flags| flags.local_flags.contains(termios::LocalFlags::ECHO))
    }

    /// Sets a echo setting for a terminal
    pub fn set_echo(&mut self, on: bool, timeout: Option<Duration>) -> Result<bool> {
        set_echo(&self.master, on)?;
        self.wait_echo(on, timeout)
    }

    /// Returns true if a underline `fd` connected with a TTY.
    pub fn isatty(&self) -> Result<bool> {
        isatty(self.master.as_fd().as_raw_fd())
    }

    /// Set the pty process's terminate approach delay.
    pub fn set_terminate_delay(&mut self, terminate_approach_delay: Duration) {
        self.terminate_delay = terminate_approach_delay;
    }

    fn wait_echo(&self, on: bool, timeout: Option<Duration>) -> Result<bool> {
        let now = time::Instant::now();
        while timeout.is_none() || now.elapsed() < timeout.unwrap() {
            if on == self.get_echo()? {
                return Ok(true)
            }

            thread::sleep(Duration::from_millis(100));
        }

        Ok(false)
    }
}

fn set_term_size(fd: i32, cols: u16, rows: u16) -> Result<()> {
    ioctl_write_ptr_bad!(_set_window_size, libc::TIOCSWINSZ, winsize);

    let size = winsize {
        ws_row:    rows,
        ws_col:    cols,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };

    let _ = unsafe { _set_window_size(fd, &size) }?;

    Ok(())
}

fn get_term_size(fd: i32) -> Result<(u16, u16)> {
    nix::ioctl_read_bad!(_get_window_size, libc::TIOCGWINSZ, winsize);

    let mut size = winsize {
        ws_col:    0,
        ws_row:    0,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };

    let _ = unsafe { _get_window_size(fd, &mut size) }?;

    Ok((size.ws_col, size.ws_row))
}

#[derive(Debug)]
struct Master {
    fd: PtyMaster,
}

impl Master {
    fn open() -> Result<Self> {
        let master_fd = posix_openpt(OFlag::O_RDWR)?;
        // Set close-on-exec flag
        nix::fcntl::fcntl(
            master_fd.as_raw_fd(),
            nix::fcntl::FcntlArg::F_SETFD(nix::fcntl::FdFlag::FD_CLOEXEC),
        )?;
        Ok(Self { fd: master_fd })
    }

    fn grant_slave_access(&self) -> Result<()> {
        grantpt(&self.fd)
    }

    fn unlock_slave(&self) -> Result<()> {
        unlockpt(&self.fd)
    }

    fn get_slave_name(&self) -> Result<String> {
        get_slave_name(&self.fd)
    }

    fn get_slave_fd(&self) -> Result<OwnedFd> {
        let slave_name = self.get_slave_name()?;
        let slave_fd = open(
            slave_name.as_str(),
            OFlag::O_RDWR | OFlag::O_NOCTTY,
            Mode::empty(),
        )?;
        Ok(unsafe { OwnedFd::from_raw_fd(slave_fd) })
    }

    fn get_file_handle(&self) -> std::io::Result<File> {
        let fd = self.as_fd().try_clone_to_owned()?;
        let file = fd.into();

        Ok(file)
    }
}

impl AsFd for Master {
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.fd.as_raw_fd()) }
    }
}

fn get_slave_name(fd: &PtyMaster) -> Result<String> {
    nix::pty::ptsname_r(fd)
}

fn set_echo(fd: impl AsFd, on: bool) -> Result<()> {
    // Set echo off
    // Even though there may be something left behind https://stackoverflow.com/a/59034084
    let mut flags = termios::tcgetattr(fd.as_fd())?;
    match on {
        true => flags.local_flags |= termios::LocalFlags::ECHO,
        false => flags.local_flags &= !termios::LocalFlags::ECHO,
    }

    termios::tcsetattr(fd, termios::SetArg::TCSANOW, &flags)?;
    Ok(())
}

pub fn set_raw(fd: impl AsFd) -> Result<()> {
    let mut flags = termios::tcgetattr(fd.as_fd())?;

    termios::cfmakeraw(&mut flags);
    termios::tcsetattr(fd, termios::SetArg::TCSANOW, &flags)?;
    Ok(())
}

fn get_this_term_char(char: SpecialCharacterIndices) -> Option<u8> {
    for &fd in &[std::io::stdin().as_fd(), std::io::stdout().as_fd()] {
        if let Ok(char) = get_term_char(fd, char) {
            return Some(char)
        }
    }

    None
}

fn get_intr_char() -> u8 {
    get_this_term_char(SpecialCharacterIndices::VINTR).unwrap_or(DEFAULT_INTR_CHAR)
}

fn get_eof_char() -> u8 {
    get_this_term_char(SpecialCharacterIndices::VEOF).unwrap_or(DEFAULT_VEOF_CHAR)
}

fn get_term_char(fd: impl AsFd, char: SpecialCharacterIndices) -> Result<u8> {
    let flags = termios::tcgetattr(fd)?;
    let b = flags.control_chars[char as usize];
    Ok(b)
}

fn make_controlling_tty(pts_name: &str) -> Result<()> {
    // https://github.com/pexpect/ptyprocess/blob/c69450d50fbd7e8270785a0552484182f486092f/ptyprocess/_fork_pty.py

    // Disconnect from controlling tty, if any
    //
    // it may be a simmilar call to ioctl TIOCNOTTY
    // https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
    let fd = open("/dev/tty", OFlag::O_RDWR | OFlag::O_NOCTTY, Mode::empty());
    match fd {
        Ok(fd) => {
            close(fd)?;
        },
        Err(Error::ENXIO) => {
            // Sometimes we get ENXIO right here which 'probably' means
            // that we has been already disconnected from controlling tty.
            // Specifically it was discovered on ubuntu-latest Github CI
            // platform.
        },
        Err(err) => return Err(err),
    }

    // setsid() will remove the controlling tty. Also the ioctl TIOCNOTTY does this.
    // https://www.win.tue.nl/~aeb/linux/lk/lk-10.html
    setsid()?;

    // Verify we are disconnected from controlling tty by attempting to open
    // it again.  We expect that OSError of ENXIO should always be raised.
    let fd = open("/dev/tty", OFlag::O_RDWR | OFlag::O_NOCTTY, Mode::empty());
    match fd {
        Err(Error::ENXIO) => {}, // ok
        Ok(fd) => {
            close(fd)?;
            return Err(Error::ENOTSUP)
        },
        Err(_) => return Err(Error::ENOTSUP),
    }

    // Verify we can open child pty.
    let fd = open(pts_name, OFlag::O_RDWR, Mode::empty())?;
    close(fd)?;

    // Verify we now have a controlling tty.
    let fd = open("/dev/tty", OFlag::O_WRONLY, Mode::empty())?;
    close(fd)?;
    Ok(())
}