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
#![cfg(any(target_os = "linux", target_os = "android"))]

#[macro_use]
extern crate nix;
extern crate libc;

use nix::errno::Errno;
use std::error;
use std::fs::{File, OpenOptions};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;

mod ioctl {
    ioctl_write_ptr!(tiocsptlck, 'T', 0x31, libc::c_int);
    ioctl_read!(tiocgptn, 'T', 0x30, libc::c_uint);
    ioctl_write_ptr_bad!(tiocswinsz, libc::TIOCSWINSZ, libc::winsize);
}

//pub struct OpenedPty {
//    master: File,
//    slave: File,
//    name: String,
//}

pub fn openpty(
    termios: Option<&libc::termios>,
    winsize: Option<&libc::winsize>,
    name: Option<String>,
) -> Result<(File, File, String), Box<error::Error>> {
    let master = OpenOptions::new()
        .read(true)
        .write(true)
        .custom_flags(libc::O_NOCTTY)
        .open("/dev/ptmx")?;

    let mut pts_number = 0;
    unsafe {
        ioctl::tiocsptlck(master.as_raw_fd(), &mut (pts_number as libc::c_int))?;
        ioctl::tiocgptn(master.as_raw_fd(), &mut pts_number)?;
    }

    let name = name.unwrap_or_else(|| format!("/dev/pts/{}", pts_number));
    let slave = OpenOptions::new()
        .read(true)
        .write(true)
        .custom_flags(libc::O_NOCTTY)
        .open(&name)?;

    if let Some(tio) = termios {
        Errno::result(unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, tio) })?;
    }

    if let Some(ws) = winsize {
        unsafe {
            ioctl::tiocswinsz(slave.as_raw_fd(), ws)?;
        }
    }

    Ok((master, slave, name))
}