Skip to content

Commit ea2d03f

Browse files
committed
Add various pty functions
* grantpt * ptsname/ptsname_r * posix_openpt * unlockpt
1 parent 8498bd9 commit ea2d03f

File tree

5 files changed

+244
-0
lines changed

5 files changed

+244
-0
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
1010
([#582](https://github.com/nix-rust/nix/pull/582)
1111
- Added `nix::unistd::{openat, fstatat, readlink, readlinkat}`
1212
([#551](https://github.com/nix-rust/nix/pull/551))
13+
- Added `nix::pty::{grantpt, posix_openpt, ptsname/ptsname_r, unlockpt}`
14+
([#556](https://github.com/nix-rust/nix/pull/556)
1315

1416
### Changed
1517
- Marked `sys::mman::{ mmap, munmap, madvise, munlock, msync }` as unsafe.

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ pub mod mount;
4444
#[cfg(target_os = "linux")]
4545
pub mod mqueue;
4646

47+
pub mod pty;
48+
4749
#[cfg(any(target_os = "linux", target_os = "macos"))]
4850
pub mod poll;
4951

src/pty.rs

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
//! Create master and slave virtual pseudo-terminals (PTTYs)
2+
3+
use std::ffi::CStr;
4+
use std::os::unix::prelude::*;
5+
6+
use libc;
7+
8+
use {Error, fcntl, Result};
9+
10+
#[derive(Debug)]
11+
pub struct PtyMaster(RawFd);
12+
13+
impl AsRawFd for PtyMaster {
14+
fn as_raw_fd(&self) -> RawFd {
15+
self.0
16+
}
17+
}
18+
19+
impl IntoRawFd for PtyMaster {
20+
fn into_raw_fd(self) -> RawFd {
21+
self.0
22+
}
23+
}
24+
25+
impl Drop for PtyMaster {
26+
fn drop(&mut self) {
27+
let _ = ::unistd::close(self.0);
28+
}
29+
}
30+
31+
/// Grant access to a slave pseudoterminal (see
32+
/// [grantpt(3)](http://man7.org/linux/man-pages/man3/grantpt.3.html))
33+
///
34+
/// `grantpt()` changes the mode and owner of the slave pseudoterminal device corresponding to the
35+
/// master pseudoterminal referred to by `fd`. This is a necessary step towards opening the slave.
36+
#[inline]
37+
pub fn grantpt(fd: &PtyMaster) -> Result<()> {
38+
if unsafe { libc::grantpt(fd.as_raw_fd()) } < 0 {
39+
return Err(Error::last().into());
40+
}
41+
42+
Ok(())
43+
}
44+
45+
/// Open a pseudoterminal device (see
46+
/// [posix_openpt(3)](http://man7.org/linux/man-pages/man3/posix_openpt.3.html))
47+
///
48+
/// `posix_openpt()` returns a file descriptor to an existing unused pseuterminal master device.
49+
///
50+
/// # Examples
51+
///
52+
/// A common use case with this function is to open both a master and slave PTTY pair. This can be
53+
/// done as follows:
54+
///
55+
/// ```
56+
/// use std::path::Path;
57+
/// use nix::fcntl::{O_RDWR, open};
58+
/// use nix::pty::*;
59+
/// use nix::sys::stat;
60+
///
61+
/// # #[allow(dead_code)]
62+
/// # fn run() -> nix::Result<()> {
63+
/// // Open a new PTTY master
64+
/// let master_fd = posix_openpt(O_RDWR)?;
65+
///
66+
/// // Allow a slave to be generated for it
67+
/// grantpt(master_fd)?;
68+
/// unlockpt(master_fd)?;
69+
///
70+
/// // Get the name of the slave
71+
/// let slave_name = ptsname(master_fd)?;
72+
///
73+
/// // Try to open the slave
74+
/// # #[allow(unused_variables)]
75+
/// let slave_fd = open(Path::new(&slave_name), O_RDWR, stat::Mode::empty())?;
76+
/// # Ok(())
77+
/// # }
78+
/// ```
79+
#[inline]
80+
pub fn posix_openpt(flags: fcntl::OFlag) -> Result<PtyMaster> {
81+
let fd = unsafe {
82+
libc::posix_openpt(flags.bits())
83+
};
84+
85+
if fd < 0 {
86+
return Err(Error::last().into());
87+
}
88+
89+
Ok(PtyMaster(fd))
90+
}
91+
92+
/// Get the name of the slave pseudoterminal (see
93+
/// [ptsname(3)](http://man7.org/linux/man-pages/man3/ptsname.3.html))
94+
///
95+
/// `ptsname()` returns the name of the slave pseudoterminal device corresponding to the master
96+
/// referred to by `fd`. Note that this function is *not* threadsafe. For that see `ptsname_r()`.
97+
///
98+
/// This value is useful for opening the slave ptty once the master has already been opened with
99+
/// `posix_openpt()`.
100+
#[inline]
101+
pub fn ptsname(fd: &PtyMaster) -> Result<String> {
102+
let name_ptr = unsafe { libc::ptsname(fd.as_raw_fd()) };
103+
if name_ptr.is_null() {
104+
return Err(Error::last().into());
105+
}
106+
107+
let name = unsafe {
108+
CStr::from_ptr(name_ptr)
109+
};
110+
Ok(name.to_string_lossy().into_owned())
111+
}
112+
113+
/// Get the name of the slave pseudoterminal (see
114+
/// [ptsname(3)](http://man7.org/linux/man-pages/man3/ptsname.3.html))
115+
///
116+
/// `ptsname_r()` returns the name of the slave pseudoterminal device corresponding to the master
117+
/// referred to by `fd`. This is the threadsafe version of `ptsname()`, but it is not part of the
118+
/// POSIX standard and is instead a Linux-specific extension.
119+
///
120+
/// This value is useful for opening the slave ptty once the master has already been opened with
121+
/// `posix_openpt()`.
122+
#[cfg(any(target_os = "android", target_os = "linux"))]
123+
#[inline]
124+
pub fn ptsname_r(fd: &PtyMaster) -> Result<String> {
125+
let mut name_buf = [0 as libc::c_char; 64];
126+
if unsafe { libc::ptsname_r(fd.as_raw_fd(), name_buf.as_mut_ptr(), name_buf.len()) } != 0 {
127+
return Err(Error::last().into());
128+
}
129+
130+
let name = unsafe {
131+
CStr::from_ptr(name_buf.as_ptr())
132+
};
133+
Ok(name.to_string_lossy().into_owned())
134+
}
135+
136+
/// Unlock a pseudoterminal master/slave pseudoterminal pair (see
137+
/// [unlockpt(3)](http://man7.org/linux/man-pages/man3/unlockpt.3.html))
138+
///
139+
/// `unlockpt()` unlocks the slave pseudoterminal device corresponding to the master pseudoterminal
140+
/// referred to by `fd`. This must be called before trying to open the slave side of a
141+
/// pseuoterminal.
142+
#[inline]
143+
pub fn unlockpt(fd: &PtyMaster) -> Result<()> {
144+
if unsafe { libc::unlockpt(fd.as_raw_fd()) } < 0 {
145+
return Err(Error::last().into());
146+
}
147+
148+
Ok(())
149+
}

test/test.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ mod test_mq;
2323

2424
#[cfg(any(target_os = "linux", target_os = "macos"))]
2525
mod test_poll;
26+
mod test_pty;
2627

2728
use nixtest::assert_size_of;
2829

test/test_pty.rs

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
use std::path::Path;
2+
use nix::fcntl::{O_RDWR, open};
3+
use nix::pty::*;
4+
use nix::sys::stat;
5+
use nix::unistd::close;
6+
7+
/// Test equivalence of `ptsname` and `ptsname_r`
8+
#[test]
9+
#[cfg(any(target_os = "android", target_os = "linux"))]
10+
fn test_ptsname_equivalence() {
11+
// Open a new PTTY master
12+
let master_fd = posix_openpt(O_RDWR).unwrap();
13+
assert!(master_fd.as_raw_fd() > 0);
14+
15+
// Get the name of the slave
16+
let slave_name = ptsname(&master_fd).unwrap();
17+
let slave_name_r = ptsname_r(&master_fd).unwrap();
18+
assert_eq!(slave_name, slave_name_r);
19+
}
20+
21+
/// Test data copying of `ptsname`
22+
#[test]
23+
#[cfg(any(target_os = "android", target_os = "linux"))]
24+
fn test_ptsname_copy() {
25+
// Open a new PTTY master
26+
let master_fd = posix_openpt(O_RDWR).unwrap();
27+
assert!(master_fd.as_raw_fd() > 0);
28+
29+
// Get the name of the slave
30+
let slave_name1 = ptsname(&master_fd).unwrap();
31+
let slave_name2 = ptsname(&master_fd).unwrap();
32+
assert!(slave_name1 == slave_name2);
33+
assert!(slave_name1.as_ptr() != slave_name2.as_ptr());
34+
}
35+
36+
/// Test data copying of `ptsname_r`
37+
#[test]
38+
#[cfg(any(target_os = "android", target_os = "linux"))]
39+
fn test_ptsname_r_copy() {
40+
// Open a new PTTY master
41+
let master_fd = posix_openpt(O_RDWR).unwrap();
42+
assert!(master_fd.as_raw_fd() > 0);
43+
44+
// Get the name of the slave
45+
let slave_name1 = ptsname_r(&master_fd).unwrap();
46+
let slave_name2 = ptsname_r(&master_fd).unwrap();
47+
assert!(slave_name1 == slave_name2);
48+
assert!(slave_name1.as_ptr() != slave_name2.as_ptr());
49+
}
50+
51+
/// Test that `ptsname` returns different names for different devices
52+
#[test]
53+
#[cfg(any(target_os = "android", target_os = "linux"))]
54+
fn test_ptsname_unique() {
55+
// Open a new PTTY master
56+
let master1_fd = posix_openpt(O_RDWR).unwrap();
57+
assert!(master1_fd.as_raw_fd() > 0);
58+
59+
// Open a second PTTY master
60+
let master2_fd = posix_openpt(O_RDWR).unwrap();
61+
assert!(master2_fd.as_raw_fd() > 0);
62+
63+
// Get the name of the slave
64+
let slave_name1 = ptsname(&master1_fd).unwrap();
65+
let slave_name2 = ptsname(&master2_fd).unwrap();
66+
assert!(slave_name1 != slave_name2);
67+
}
68+
69+
/// Test opening a master/slave PTTY pair
70+
///
71+
/// This is a single larger test because much of these functions aren't useful by themselves. So for
72+
/// this test we perform the basic act of getting a file handle for a connect master/slave PTTY
73+
/// pair.
74+
#[test]
75+
fn test_open_ptty_pair() {
76+
// Open a new PTTY master
77+
let master_fd = posix_openpt(O_RDWR).unwrap();
78+
assert!(master_fd.as_raw_fd() > 0);
79+
80+
// Allow a slave to be generated for it
81+
grantpt(&master_fd).unwrap();
82+
unlockpt(&master_fd).unwrap();
83+
84+
// Get the name of the slave
85+
let slave_name = ptsname(&master_fd).unwrap();
86+
87+
// Open the slave device
88+
let slave_fd = open(Path::new(&slave_name), O_RDWR, stat::Mode::empty()).unwrap();
89+
assert!(slave_fd > 0);
90+
}

0 commit comments

Comments
 (0)