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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
// Copyright 2018-2019 Peter Williams <peter@newton.cx>
// Licensed under both the MIT License and the Apache-2.0 license.

#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/tokio-pty-process/0.4.0")]

//! Spawn a child process under a pseudo-TTY, interacting with it
//! asynchronously using Tokio.
//!
//! A [pseudo-terminal](https://en.wikipedia.org/wiki/Pseudoterminal) (or
//! “pseudo-TTY” or “PTY”) is a special Unix file handle that models the kind
//! of text terminal through which users used to interact with computers. A
//! PTY enables a specialized form of bidirectional interprocess communication
//! that a variety of user-facing Unix programs take advantage of.
//!
//! The basic way to use this crate is:
//!
//! 1. Create a Tokio [Reactor](https://docs.rs/tokio/*/tokio/reactor/struct.Reactor.html)
//!    that will handle all of your asynchronous I/O.
//! 2. Create an `AsyncPtyMaster` that represents your ownership of
//!    an OS pseudo-terminal.
//! 3. Use your master and the `spawn_pty_async` or `spawn_pty_async_raw`
//!    functions of the `CommandExt` extension trait, which extends
//!    `std::process::Command`, to launch a child process that is connected to
//!    your master.
//! 4. Optionally control the child process (e.g. send it signals) through the
//!    `Child` value returned by that function.
//!
//! This crate only works on Unix since pseudo-terminals are a Unix-specific
//! concept.
//!
//! The `Child` type is largely copied from Alex Crichton’s
//! [tokio-process](https://github.com/alexcrichton/tokio-process) crate.

extern crate bytes;
#[macro_use]
extern crate futures;
extern crate libc;
extern crate mio;
extern crate tokio;
extern crate tokio_io;
extern crate tokio_signal;

use futures::future::FlattenStream;
use futures::{Async, Future, Poll, Stream};
use libc::{c_int, c_ushort};
use mio::event::Evented;
use mio::unix::{EventedFd, UnixReady};
use mio::{PollOpt, Ready, Token};
use std::ffi::{CStr, OsStr, OsString};
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
use std::mem;
use std::os::unix::prelude::*;
use std::os::unix::process::CommandExt as StdUnixCommandExt;
use std::process::{self, ExitStatus};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::reactor::PollEvented2;
use tokio_signal::unix::Signal;
use tokio_signal::IoFuture;

mod split;
pub use split::{AsyncPtyMasterReadHalf, AsyncPtyMasterWriteHalf};

// First set of hoops to jump through: a read-write pseudo-terminal master
// with full async support. As far as I can tell, we need to create an inner
// wrapper type to implement Evented on a type that we can then wrap in a
// PollEvented. Lame.

#[derive(Debug)]
struct AsyncPtyFile(File);

impl AsyncPtyFile {
    pub fn new(inner: File) -> Self {
        AsyncPtyFile(inner)
    }
}

impl Read for AsyncPtyFile {
    fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
        self.0.read(bytes)
    }
}

impl Write for AsyncPtyFile {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        self.0.write(bytes)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl Evented for AsyncPtyFile {
    fn register(
        &self,
        poll: &mio::Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        EventedFd(&self.0.as_raw_fd()).register(poll, token, interest | UnixReady::hup(), opts)
    }

    fn reregister(
        &self,
        poll: &mio::Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest | UnixReady::hup(), opts)
    }

    fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {
        EventedFd(&self.0.as_raw_fd()).deregister(poll)
    }
}

/// A handle to a pseudo-TTY master that can be interacted with
/// asynchronously.
///
/// This type implements both `AsyncRead` and `AsyncWrite`.
pub struct AsyncPtyMaster(PollEvented2<AsyncPtyFile>);

impl AsyncPtyMaster {
    /// Open a pseudo-TTY master.
    ///
    /// This function performs the C library calls `posix_openpt()`,
    /// `grantpt()`, and `unlockpt()`. It also sets the resulting pseudo-TTY
    /// master handle to nonblocking mode.
    pub fn open() -> Result<Self, io::Error> {
        let inner = unsafe {
            // On MacOS, O_NONBLOCK is not documented as an allowed option to
            // posix_openpt(), but it is in fact allowed and functional, and
            // trying to add it later with fcntl() is forbidden. Meanwhile, on
            // FreeBSD, O_NONBLOCK is *not* an allowed option to
            // posix_openpt(), and the only way to get a nonblocking PTY
            // master is to add the nonblocking flag with fcntl() later. So,
            // we have to jump through some #[cfg()] hoops.

            const APPLY_NONBLOCK_AFTER_OPEN: bool = cfg!(target_os = "freebsd");

            let fd = if APPLY_NONBLOCK_AFTER_OPEN {
                libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY)
            } else {
                libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY | libc::O_NONBLOCK)
            };

            if fd < 0 {
                return Err(io::Error::last_os_error());
            }

            if libc::grantpt(fd) != 0 {
                return Err(io::Error::last_os_error());
            }

            if libc::unlockpt(fd) != 0 {
                return Err(io::Error::last_os_error());
            }

            if APPLY_NONBLOCK_AFTER_OPEN {
                let flags = libc::fcntl(fd, libc::F_GETFL, 0);
                if flags < 0 {
                    return Err(io::Error::last_os_error());
                }

                if libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) == -1 {
                    return Err(io::Error::last_os_error());
                }
            }

            File::from_raw_fd(fd)
        };

        Ok(AsyncPtyMaster(PollEvented2::new(AsyncPtyFile::new(inner))))
    }

    /// Split the AsyncPtyMaster into an AsyncPtyReadHalf implementing `Read` and
    /// and `AsyncRead` as well as an `AsyncPtyWriteHalf` implementing
    /// `AsyncPtyWrite`.
    pub fn split(self) -> (AsyncPtyMasterReadHalf, AsyncPtyMasterWriteHalf) {
        split::split(self)
    }

    /// Open a pseudo-TTY slave that is connected to this master.
    ///
    /// The resulting file handle is *not* set to non-blocking mode.
    fn open_sync_pty_slave(&self) -> Result<File, io::Error> {
        let mut buf: [libc::c_char; 512] = [0; 512];
        let fd = self.as_raw_fd();

        #[cfg(not(any(target_os = "macos", target_os = "freebsd")))]
        {
            if unsafe { libc::ptsname_r(fd, buf.as_mut_ptr(), buf.len()) } != 0 {
                return Err(io::Error::last_os_error());
            }
        }
        #[cfg(any(target_os = "macos", target_os = "freebsd"))]
        unsafe {
            let st = libc::ptsname(fd);
            if st.is_null() {
                return Err(io::Error::last_os_error());
            }
            libc::strncpy(buf.as_mut_ptr(), st, buf.len());
        }

        let ptsname = OsStr::from_bytes(unsafe { CStr::from_ptr(&buf as _) }.to_bytes());
        OpenOptions::new().read(true).write(true).open(ptsname)
    }
}

impl AsRawFd for AsyncPtyMaster {
    fn as_raw_fd(&self) -> RawFd {
        self.0.get_ref().0.as_raw_fd()
    }
}

impl Read for AsyncPtyMaster {
    fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
        self.0.read(bytes)
    }
}

impl AsyncRead for AsyncPtyMaster {}

impl Write for AsyncPtyMaster {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        self.0.write(bytes)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl AsyncWrite for AsyncPtyMaster {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        self.0.shutdown()
    }
}

// Now, the async-ified child process framework.

/// A child process that can be interacted with through a pseudo-TTY.
#[must_use = "futures do nothing unless polled"]
pub struct Child {
    inner: process::Child,
    kill_on_drop: bool,
    reaped: bool,
    sigchld: FlattenStream<IoFuture<Signal>>,
}

impl fmt::Debug for Child {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Child")
            .field("pid", &self.inner.id())
            .field("inner", &self.inner)
            .field("kill_on_drop", &self.kill_on_drop)
            .field("reaped", &self.reaped)
            .field("sigchld", &"..")
            .finish()
    }
}

impl Child {
    fn new(inner: process::Child) -> Child {
        Child {
            inner: inner,
            kill_on_drop: true,
            reaped: false,
            sigchld: Signal::new(libc::SIGCHLD).flatten_stream(),
        }
    }

    /// Returns the OS-assigned process identifier associated with this child.
    pub fn id(&self) -> u32 {
        self.inner.id()
    }

    /// Forces the child to exit.
    ///
    /// This is equivalent to sending a SIGKILL on unix platforms.
    pub fn kill(&mut self) -> io::Result<()> {
        if self.reaped {
            Ok(())
        } else {
            self.inner.kill()
        }
    }

    /// Drop this `Child` without killing the underlying process.
    ///
    /// Normally a `Child` is killed if it's still alive when dropped, but this
    /// method will ensure that the child may continue running once the `Child`
    /// instance is dropped.
    pub fn forget(mut self) {
        self.kill_on_drop = false;
    }

    /// Check whether this `Child` has exited yet.
    pub fn poll_exit(&mut self) -> Poll<ExitStatus, io::Error> {
        assert!(!self.reaped);

        loop {
            if let Some(e) = self.try_wait()? {
                self.reaped = true;
                return Ok(e.into());
            }

            // If the child hasn't exited yet, then it's our responsibility to
            // ensure the current task gets notified when it might be able to
            // make progress.
            //
            // As described in `spawn` above, we just indicate that we can
            // next make progress once a SIGCHLD is received.
            if self.sigchld.poll()?.is_not_ready() {
                return Ok(Async::NotReady);
            }
        }
    }

    fn try_wait(&self) -> io::Result<Option<ExitStatus>> {
        let id = self.id() as c_int;
        let mut status = 0;

        loop {
            match unsafe { libc::waitpid(id, &mut status, libc::WNOHANG) } {
                0 => return Ok(None),

                n if n < 0 => {
                    let err = io::Error::last_os_error();
                    if err.kind() == io::ErrorKind::Interrupted {
                        continue;
                    }
                    return Err(err);
                }

                n => {
                    assert_eq!(n, id);
                    return Ok(Some(ExitStatus::from_raw(status)));
                }
            }
        }
    }
}

impl Future for Child {
    type Item = ExitStatus;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<ExitStatus, io::Error> {
        self.poll_exit()
    }
}

impl Drop for Child {
    fn drop(&mut self) {
        if self.kill_on_drop {
            drop(self.kill());
        }
    }
}

/// A Future for getting the Pty file descriptor.
///
/// # Example
///
/// ```
/// extern crate tokio;
/// extern crate tokio_pty_process;
///
/// use tokio_pty_process::{AsyncPtyMaster, AsyncPtyFd};
/// use tokio::prelude::*;
///
/// fn main() {
///     let master = AsyncPtyMaster::open()
///         .expect("Could not open the PTY");
///
///     let fd = AsyncPtyFd::from(master).wait()
///         .expect("Could not get the File descriptor");
/// }
/// ```
pub struct AsyncPtyFd<T: AsAsyncPtyFd>(T);

impl<T: AsAsyncPtyFd> AsyncPtyFd<T> {
    /// Construct a new AsyncPtyFd future
    pub fn from(inner: T) -> Self {
        AsyncPtyFd(inner)
    }
}

impl<T: AsAsyncPtyFd> Future for AsyncPtyFd<T> {
    type Item = RawFd;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<RawFd, io::Error> {
        self.0.as_async_pty_fd()
    }
}

/// Trait to asynchronously get the `RawFd` of the master side of the PTY
pub trait AsAsyncPtyFd {
    /// Return a `Poll` containing the RawFd
    fn as_async_pty_fd(&self) -> Poll<RawFd, io::Error>;
}

impl AsAsyncPtyFd for AsyncPtyMaster {
    fn as_async_pty_fd(&self) -> Poll<RawFd, io::Error> {
        Ok(Async::Ready(self.as_raw_fd()))
    }
}

/// Trait containing generalized methods for PTYs
pub trait PtyMaster {
    /// Return the full pathname of the slave device counterpart
    ///
    /// # Example
    ///
    /// ```
    /// extern crate tokio;
    /// extern crate tokio_pty_process;
    ///
    /// use std::ffi::OsString;
    /// use tokio::prelude::*;
    /// use tokio_pty_process::{AsyncPtyMaster, PtyMaster};
    ///
    /// struct PtsName<T: PtyMaster>(T);
    ///
    /// impl<T: PtyMaster> Future for PtsName<T> {
    ///     type Item = OsString;
    ///     type Error = std::io::Error;
    ///
    ///     fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
    ///         self.0.ptsname()
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let master = AsyncPtyMaster::open().expect("Could not open the PTY");
    ///
    ///     let ptsname = PtsName(master).wait().expect("Could not get the ptsname");
    ///
    ///     println!("PTS name: {}", ptsname.to_string_lossy());
    /// }
    /// ```
    fn ptsname(&self) -> Poll<OsString, io::Error>;

    /// Resize the PTY
    ///
    /// # Example
    ///
    /// ```
    /// extern crate tokio;
    /// extern crate tokio_pty_process;
    /// extern crate libc;
    ///
    /// use tokio_pty_process::{AsyncPtyMaster, PtyMaster, CommandExt};
    /// use tokio::prelude::*;
    /// use std::ffi::OsString;
    /// use libc::c_ushort;
    /// struct Resize<T: PtyMaster> {
    ///     pty: T,
    ///     rows: c_ushort,
    ///     cols: c_ushort,
    /// }
    ///
    /// impl<T: PtyMaster> Future for Resize<T> {
    ///     type Item = ();
    ///     type Error = std::io::Error;
    ///
    ///     fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
    ///         self.pty.resize(self.rows, self.cols)
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let master = AsyncPtyMaster::open().expect("Could not open the PTY");
    ///
    ///     // On macos, it's only possible to resize a PTY with a child spawned
    ///     // On it, so let's just do that:
    ///     #[cfg(target_os="macos")]
    ///     let mut child = std::process::Command::new("cat")
    ///         .spawn_pty_async(&master)
    ///         .expect("Could not spawn child");
    ///
    ///     Resize {
    ///         pty: master,
    ///         cols: 80,
    ///         rows: 50,
    ///     }
    ///     .wait()
    ///     .expect("Could not resize the PTY");
    ///
    ///     #[cfg(target_os="macos")]
    ///     child.kill().expect("Could not kill child");
    /// }
    /// ```
    fn resize(&self, rows: c_ushort, cols: c_ushort) -> Poll<(), io::Error>;

    /// Get the PTY size
    ///
    /// # Example
    ///
    /// ```
    /// extern crate tokio;
    /// extern crate tokio_pty_process;
    /// extern crate libc;
    ///
    /// use tokio_pty_process::{AsyncPtyMaster, PtyMaster, CommandExt};
    /// use tokio::prelude::*;
    /// use std::ffi::OsString;
    /// use libc::c_ushort;
    ///
    /// struct GetSize<'a, T: PtyMaster> (&'a T);
    /// impl<'a, T: PtyMaster> Future for GetSize<'a, T> {
    ///     type Item = (c_ushort, c_ushort);
    ///     type Error = std::io::Error;
    ///     fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
    ///         self.0.winsize()
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let master = AsyncPtyMaster::open().expect("Could not open the PTY");
    ///
    ///     // On macos, it's only possible to resize a PTY with a child spawned
    ///     // On it, so let's just do that:
    ///     #[cfg(target_os="macos")]
    ///     let mut child = std::process::Command::new("cat")
    ///         .spawn_pty_async(&master)
    ///         .expect("Could not spawn child");
    ///
    ///     let (rows, cols) = GetSize(&master)
    ///         .wait()
    ///         .expect("Could not get PTY size");
    ///
    ///     #[cfg(target_os="macos")]
    ///     child.kill().expect("Could not kill child");
    /// }
    /// ```
    fn winsize(&self) -> Poll<(c_ushort, c_ushort), io::Error>;
}

impl<T: AsAsyncPtyFd> PtyMaster for T {
    fn ptsname(&self) -> Poll<OsString, io::Error> {
        let mut buf: [libc::c_char; 512] = [0; 512];
        let fd = try_ready!(self.as_async_pty_fd());

        #[cfg(not(any(target_os = "macos", target_os = "freebsd")))]
        {
            if unsafe { libc::ptsname_r(fd, buf.as_mut_ptr(), buf.len()) } != 0 {
                return Err(io::Error::last_os_error());
            }
        }
        #[cfg(any(target_os = "macos", target_os = "freebsd"))]
        unsafe {
            let st = libc::ptsname(fd);
            if st.is_null() {
                return Err(io::Error::last_os_error());
            }
            libc::strncpy(buf.as_mut_ptr(), st, buf.len());
        }
        let ptsname = OsStr::from_bytes(unsafe { CStr::from_ptr(&buf as _) }.to_bytes());
        Ok(Async::Ready(ptsname.to_os_string()))
    }

    fn winsize(&self) -> Poll<(c_ushort, c_ushort), io::Error> {
        let fd = try_ready!(self.as_async_pty_fd());
        let mut winsz: libc::winsize = unsafe { std::mem::zeroed() };
        if unsafe { libc::ioctl(fd, libc::TIOCGWINSZ.into(), &mut winsz) } != 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(Async::Ready((winsz.ws_row, winsz.ws_col)))
    }

    fn resize(&self, rows: c_ushort, cols: c_ushort) -> Poll<(), io::Error> {
        let fd = try_ready!(self.as_async_pty_fd());
        let winsz = libc::winsize {
            ws_row: rows,
            ws_col: cols,
            ws_xpixel: 0,
            ws_ypixel: 0,
        };
        if unsafe { libc::ioctl(fd, libc::TIOCSWINSZ.into(), &winsz) } != 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(Async::Ready(()))
    }
}

/// A private trait for the extending `std::process::Command`.
trait CommandExtInternal {
    fn spawn_pty_async_full(&mut self, ptymaster: &AsyncPtyMaster, raw: bool) -> io::Result<Child>;
}

impl CommandExtInternal for process::Command {
    fn spawn_pty_async_full(&mut self, ptymaster: &AsyncPtyMaster, raw: bool) -> io::Result<Child> {
        let master_fd = ptymaster.as_raw_fd();
        let slave = ptymaster.open_sync_pty_slave()?;
        let slave_fd = slave.as_raw_fd();

        self.stdin(slave.try_clone()?);
        self.stdout(slave.try_clone()?);
        self.stderr(slave);

        // XXX any need to close slave handles in the parent process beyond
        // what's done here?

        self.before_exec(move || {
            unsafe {
                if raw {
                    let mut attrs: libc::termios = mem::zeroed();

                    if libc::tcgetattr(slave_fd, &mut attrs as _) != 0 {
                        return Err(io::Error::last_os_error());
                    }

                    libc::cfmakeraw(&mut attrs as _);

                    if libc::tcsetattr(slave_fd, libc::TCSANOW, &attrs as _) != 0 {
                        return Err(io::Error::last_os_error());
                    }
                }

                // This is OK even though we don't own master since this process is
                // about to become something totally different anyway.
                if libc::close(master_fd) != 0 {
                    return Err(io::Error::last_os_error());
                }

                if libc::setsid() < 0 {
                    return Err(io::Error::last_os_error());
                }

                if libc::ioctl(0, libc::TIOCSCTTY.into(), 1) != 0 {
                    return Err(io::Error::last_os_error());
                }
            }

            Ok(())
        });

        Ok(Child::new(self.spawn()?))
    }
}

/// An extension trait for the `std::process::Command` type.
///
/// This trait provides new `spawn_pty_async` and `spawn_pty_async_raw`
/// methods that allow one to spawn a new process that is connected to the
/// current process through a pseudo-TTY.
pub trait CommandExt {
    /// Spawn a subprocess that connects to the current one through a
    /// pseudo-TTY in canonical (“cooked“, not “raw”) mode.
    ///
    /// This function creates the necessary PTY slave and uses
    /// `std::process::Command::before_exec` to do the neccessary setup before
    /// the child process is spawned. In particular, it calls `setsid()` to
    /// launch a new TTY sesson.
    ///
    /// The child process’s standard input, standard output, and standard
    /// error are all connected to the pseudo-TTY slave.
    fn spawn_pty_async(&mut self, ptymaster: &AsyncPtyMaster) -> io::Result<Child>;

    /// Spawn a subprocess that connects to the current one through a
    /// pseudo-TTY in raw (“non-canonical”, not “cooked”) mode.
    ///
    /// This function creates the necessary PTY slave and uses
    /// `std::process::Command::before_exec` to do the neccessary setup before
    /// the child process is spawned. In particular, it sets the slave PTY
    /// handle to raw mode and calls `setsid()` to launch a new TTY sesson.
    ///
    /// The child process’s standard input, standard output, and standard
    /// error are all connected to the pseudo-TTY slave.
    fn spawn_pty_async_raw(&mut self, ptymaster: &AsyncPtyMaster) -> io::Result<Child>;
}

impl CommandExt for process::Command {
    fn spawn_pty_async(&mut self, ptymaster: &AsyncPtyMaster) -> io::Result<Child> {
        self.spawn_pty_async_full(ptymaster, false)
    }

    fn spawn_pty_async_raw(&mut self, ptymaster: &AsyncPtyMaster) -> io::Result<Child> {
        self.spawn_pty_async_full(ptymaster, true)
    }
}

#[cfg(test)]
mod tests {
    extern crate errno;
    extern crate libc;

    use super::*;

    /// Test that the PTY master file descriptor is in nonblocking mode. We do
    /// this in a pretty hacky and dumb way, by creating the AsyncPtyMaster
    /// and then just snarfing its FD and seeing whether a Unix `read(2)` call
    /// errors out with EWOULDBLOCK (instead of blocking forever). In
    /// principle it would be nice to actually spawn a subprogram and test
    /// reading through the whole Tokio I/O subsystem, but that's annoying to
    /// implement and can actually muddy the picture. Namely: if you try to
    /// `master.read()` inside a Tokio event loop here, on Linux you'll get an
    /// ErrorKind::WouldBlock I/O error from Tokio without it even attempting
    /// the underlying `read(2)` system call, because Tokio uses epoll to test
    /// the FD's readiness in a way that works orthogonal to whether it's set
    /// to non-blocking mode.
    #[test]
    fn basic_nonblocking() {
        let master = AsyncPtyMaster::open().unwrap();

        let fd = master.as_raw_fd();
        let mut buf = [0u8; 128];
        let rval = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, 128) };
        let errno: i32 = errno::errno().into();

        assert_eq!(rval, -1);
        assert_eq!(errno, libc::EWOULDBLOCK as i32);
    }

    struct GetSize<'a, T: PtyMaster>(&'a T);
    impl<'a, T: PtyMaster> Future for GetSize<'a, T> {
        type Item = (c_ushort, c_ushort);
        type Error = std::io::Error;
        fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
            self.0.winsize()
        }
    }

    struct Resize<'a, T: PtyMaster> {
        pty: &'a T,
        rows: c_ushort,
        cols: c_ushort,
    }
    impl<'a, T: PtyMaster> Future for Resize<'a, T> {
        type Item = ();
        type Error = std::io::Error;
        fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
            self.pty.resize(self.rows, self.cols)
        }
    }

    #[test]
    fn test_winsize() {
        let master = AsyncPtyMaster::open().expect("Could not open the PTY");

        // On macos, it's only possible to resize a PTY with a child spawned
        // On it, so let's just do that:
        #[cfg(target_os = "macos")]
        let mut child = std::process::Command::new("cat")
            .spawn_pty_async(&master)
            .expect("Could not spawn child");

        // Set the size
        Resize {
            pty: &master,
            cols: 80,
            rows: 50,
        }
        .wait()
        .expect("Could not resize the PTY");

        let (rows, cols) = GetSize(&master).wait().expect("Could not get PTY size");

        assert_eq!(cols, 80);
        assert_eq!(rows, 50);

        #[cfg(target_os = "macos")]
        child.kill().expect("Could not kill child");
    }
}