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
use crate::error::*;
use crate::pty::Pty as _;

use ::std::os::unix::io::AsRawFd as _;

#[cfg(any(feature = "backend-async-std", feature = "backend-smol"))]
mod async_process;
#[cfg(feature = "backend-std")]
mod std;
#[cfg(feature = "backend-tokio")]
mod tokio;

/// Adds methods to the existing `Command` struct.
///
/// This trait is automatically implemented for a backend's `Command` struct
/// when that backend's feature is enabled.
pub trait Command {
    type Child;
    type Pty;

    /// Creates a new pty, associates the command's stdin/stdout/stderr with
    /// that pty, and then calls `spawn`. This will override any previous
    /// calls to `stdin`/`stdout`/`stderr`.
    fn spawn_pty(
        &mut self,
        size: Option<&crate::pty::Size>,
    ) -> Result<Child<Self::Child, Self::Pty>>;
}

impl<T> Command for T
where
    T: CommandImpl,
    T::Pty: crate::pty::Pty,
    <<T as CommandImpl>::Pty as crate::pty::Pty>::Pt:
        ::std::os::unix::io::AsRawFd,
{
    type Child = T::Child;
    type Pty = T::Pty;

    fn spawn_pty(
        &mut self,
        size: Option<&crate::pty::Size>,
    ) -> Result<Child<Self::Child, Self::Pty>> {
        let (pty, pts, stdin, stdout, stderr) = setup_pty::<Self::Pty>(size)?;

        let pt_fd = pty.pt().as_raw_fd();
        let pts_fd = pts.as_raw_fd();

        self.std_fds(stdin, stdout, stderr);

        let pre_exec = move || {
            nix::unistd::setsid().map_err(|e| e.as_errno().unwrap())?;
            set_controlling_terminal(pts_fd)
                .map_err(|e| e.as_errno().unwrap())?;

            // in the parent, destructors will handle closing these file
            // descriptors (other than pt, used by the parent to
            // communicate with the child) when the function ends, but in
            // the child, we end by calling exec(), which doesn't call
            // destructors.

            // XXX unwrap
            nix::unistd::close(pt_fd).map_err(|e| e.as_errno().unwrap())?;
            nix::unistd::close(pts_fd).map_err(|e| e.as_errno().unwrap())?;
            // at this point, stdin/stdout/stderr have already been
            // reopened as fds 0/1/2 in the child, so we can (and should)
            // close the originals
            nix::unistd::close(stdin).map_err(|e| e.as_errno().unwrap())?;
            nix::unistd::close(stdout).map_err(|e| e.as_errno().unwrap())?;
            nix::unistd::close(stderr).map_err(|e| e.as_errno().unwrap())?;

            Ok(())
        };
        // safe because setsid() and close() are async-signal-safe functions
        // and ioctl() is a raw syscall (which is inherently
        // async-signal-safe).
        unsafe { self.pre_exec_impl(pre_exec) };

        let child = self.spawn_impl().map_err(Error::Spawn)?;

        Ok(Child { child, pty })
    }
}

/// Wrapper struct adding pty methods to the normal `Child` struct.
pub struct Child<C, P> {
    child: C,
    pty: P,
}

impl<C, P> Child<C, P>
where
    P: crate::pty::Pty,
{
    /// Returns a reference to the pty.
    ///
    /// The underlying pty instance is guaranteed to implement
    /// [`AsRawFd`](::std::os::unix::io::AsRawFd), as well as the appropriate
    /// `Read` and `Write` traits for the associated backend.
    pub fn pty(&self) -> &P::Pt {
        self.pty.pt()
    }

    /// Returns a mutable reference to the pty.
    ///
    /// The underlying pty instance is guaranteed to implement
    /// [`AsRawFd`](::std::os::unix::io::AsRawFd), as well as the appropriate
    /// `Read` and `Write` traits for the associated backend.
    ///
    /// This method is primarily useful for the tokio backend, since tokio's
    /// `AsyncRead` and `AsyncWrite` traits have methods which take mutable
    /// references.
    pub fn pty_mut(&mut self) -> &mut P::Pt {
        self.pty.pt_mut()
    }

    /// Causes the pty to change its size.
    ///
    /// This will additionally cause a `SIGWINCH` signal to be sent to the
    /// running process.
    pub fn resize_pty(&self, size: &crate::pty::Size) -> Result<()> {
        self.pty.resize(size)
    }
}

impl<C, P> ::std::ops::Deref for Child<C, P> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
        &self.child
    }
}

impl<C, P> ::std::ops::DerefMut for Child<C, P> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.child
    }
}

// XXX shouldn't be pub?
pub trait CommandImpl {
    type Child;
    type Pty;

    fn std_fds(
        &mut self,
        stdin: ::std::os::unix::io::RawFd,
        stdout: ::std::os::unix::io::RawFd,
        stderr: ::std::os::unix::io::RawFd,
    );
    unsafe fn pre_exec_impl<F>(&mut self, f: F)
    where
        F: FnMut() -> ::std::io::Result<()> + Send + Sync + 'static;
    fn spawn_impl(&mut self) -> ::std::io::Result<Self::Child>;
}

fn setup_pty<P>(
    size: Option<&crate::pty::Size>,
) -> Result<(
    P,
    ::std::fs::File,
    ::std::os::unix::io::RawFd,
    ::std::os::unix::io::RawFd,
    ::std::os::unix::io::RawFd,
)>
where
    P: crate::pty::Pty,
{
    let pty = P::new()?;
    if let Some(size) = size {
        pty.resize(size)?;
    }

    let pts = pty.pts()?;
    let pts_fd = pts.as_raw_fd();

    let stdin = nix::unistd::dup(pts_fd).map_err(Error::SpawnNix)?;
    let stdout = nix::unistd::dup(pts_fd).map_err(Error::SpawnNix)?;
    let stderr = nix::unistd::dup(pts_fd).map_err(Error::SpawnNix)?;

    Ok((pty, pts, stdin, stdout, stderr))
}

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

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