aboutsummaryrefslogtreecommitdiffstats
path: root/src/sys.rs
blob: 244a43d716f3d87a79fe22a15ed308b03dde2e27 (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
use std::os::unix::io::{AsRawFd as _, FromRawFd as _, IntoRawFd as _};

#[derive(Debug)]
pub struct Pty(pub nix::pty::PtyMaster);

impl Pty {
    pub fn open() -> crate::Result<Self> {
        let pt = nix::pty::posix_openpt(
            nix::fcntl::OFlag::O_RDWR
                | nix::fcntl::OFlag::O_NOCTTY
                | nix::fcntl::OFlag::O_CLOEXEC,
        )?;
        nix::pty::grantpt(&pt)?;
        nix::pty::unlockpt(&pt)?;

        Ok(Self(pt))
    }

    pub fn set_term_size(&self, size: crate::Size) -> crate::Result<()> {
        let size = size.into();
        let fd = self.0.as_raw_fd();

        // Safety: nix::pty::PtyMaster is required to contain a valid file
        // descriptor and size is guaranteed to be initialized because it's a
        // normal rust value, and nix::pty::Winsize is a repr(C) struct with
        // the same layout as `struct winsize` from sys/ioctl.h.
        Ok(unsafe {
            set_term_size_unsafe(fd, std::ptr::NonNull::from(&size).as_ptr())
        }
        .map(|_| ())?)
    }

    pub fn pts(&self) -> crate::Result<Pts> {
        Ok(Pts(std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(nix::pty::ptsname_r(&self.0)?)?
            .into_raw_fd()))
    }

    #[cfg(feature = "async")]
    pub fn set_nonblocking(&self) -> nix::Result<()> {
        let bits = nix::fcntl::fcntl(
            self.0.as_raw_fd(),
            nix::fcntl::FcntlArg::F_GETFL,
        )?;
        // Safety: bits was just returned from a F_GETFL call. ideally i would
        // just be able to use from_bits here, but it fails for some reason?
        let mut opts =
            unsafe { nix::fcntl::OFlag::from_bits_unchecked(bits) };
        opts |= nix::fcntl::OFlag::O_NONBLOCK;
        nix::fcntl::fcntl(
            self.0.as_raw_fd(),
            nix::fcntl::FcntlArg::F_SETFL(opts),
        )?;

        Ok(())
    }
}

impl std::os::unix::io::AsRawFd for Pty {
    fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
        self.0.as_raw_fd()
    }
}

pub struct Pts(std::os::unix::io::RawFd);

impl Pts {
    pub fn setup_subprocess(
        &self,
    ) -> nix::Result<(
        std::process::Stdio,
        std::process::Stdio,
        std::process::Stdio,
    )> {
        let pts_fd = self.0.as_raw_fd();

        let stdin = nix::fcntl::fcntl(
            pts_fd,
            nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(0),
        )?;
        let stdout = nix::fcntl::fcntl(
            pts_fd,
            nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(0),
        )?;
        let stderr = nix::fcntl::fcntl(
            pts_fd,
            nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(0),
        )?;

        // Safety: these file descriptors were all just returned from dup, so
        // they must be valid
        Ok((
            unsafe { std::process::Stdio::from_raw_fd(stdin) },
            unsafe { std::process::Stdio::from_raw_fd(stdout) },
            unsafe { std::process::Stdio::from_raw_fd(stderr) },
        ))
    }

    pub fn session_leader(&self) -> impl FnMut() -> std::io::Result<()> {
        let pts_fd = self.0.as_raw_fd();
        move || {
            nix::unistd::setsid()?;
            set_controlling_terminal(pts_fd)?;
            Ok(())
        }
    }
}

impl Drop for Pts {
    fn drop(&mut self) {
        let _ = nix::unistd::close(self.0);
    }
}

impl std::os::unix::io::AsRawFd for Pts {
    fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
        self.0
    }
}

fn set_controlling_terminal(fd: std::os::unix::io::RawFd) -> nix::Result<()> {
    // Safety: Pts is required to contain a valid file descriptor
    unsafe { set_controlling_terminal_unsafe(fd, std::ptr::null()) }
        .map(|_| ())
}

nix::ioctl_write_ptr_bad!(
    set_term_size_unsafe,
    libc::TIOCSWINSZ,
    nix::pty::Winsize
);

nix::ioctl_write_ptr_bad!(
    set_controlling_terminal_unsafe,
    libc::TIOCSCTTY,
    libc::c_int
);