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
|
//! tty related functionality
//!
use std::env;
use std::ffi::CStr;
use std::fs::File;
use std::mem;
use std::os::unix::io::FromRawFd;
use std::ptr;
use libc::{self, winsize, c_int, c_char};
macro_rules! die {
($($arg:tt)*) => {
println!($($arg)*);
::std::process::exit(1);
}
}
pub enum Error {
/// TODO
Unknown,
}
impl Error {
/// Build an Error from the current value of errno.
fn from_errno() -> Error {
let err = errno();
match err {
_ => Error::Unknown
}
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
/// Get the current value of errno
fn errno() -> c_int {
unsafe {
ptr::read(libc::__errno_location() as *const _)
}
}
enum Relation {
Child,
Parent
}
fn fork() -> Relation {
let res = unsafe {
libc::fork()
};
if res < 0 {
die!("fork failed");
}
if res == 0 {
Relation::Child
} else {
Relation::Parent
}
}
/// Get raw fds for master/slave ends of a new pty
fn openpty(rows: u8, cols: u8) -> (c_int, c_int) {
let mut master: c_int = 0;
let mut slave: c_int = 0;
let win = winsize {
ws_row: rows as libc::c_ushort,
ws_col: cols as libc::c_ushort,
ws_xpixel: 0,
ws_ypixel: 0,
};
let res = unsafe {
libc::openpty(&mut master, &mut slave, ptr::null_mut(), ptr::null(), &win)
};
if res < 0 {
die!("openpty failed");
}
(master, slave)
}
/// Really only needed on BSD, but should be fine elsewhere
fn set_controlling_terminal(fd: c_int) {
let res = unsafe {
libc::ioctl(fd, libc::TIOCSCTTY, 0)
};
if res < 0 {
die!("ioctl TIOCSCTTY failed: {}", errno());
}
}
#[derive(Debug)]
struct Passwd<'a> {
name: &'a str,
passwd: &'a str,
uid: libc::uid_t,
gid: libc::gid_t,
gecos: &'a str,
dir: &'a str,
shell: &'a str,
}
/// Return a Passwd struct with pointers into the provided buf
///
/// # Unsafety
///
/// If `buf` is changed while `Passwd` is alive, bad thing will almost certainly happen.
fn get_pw_entry<'a>(buf: &'a mut [i8; 1024]) -> Passwd<'a> {
// Create zeroed passwd struct
let mut entry = libc::passwd {
pw_name: ptr::null_mut(),
pw_passwd: ptr::null_mut(),
pw_uid: 0,
pw_gid: 0,
pw_gecos: ptr::null_mut(),
pw_dir: ptr::null_mut(),
pw_shell: ptr::null_mut(),
};
let mut res: *mut libc::passwd = ptr::null_mut();
// Try and read the pw file.
let uid = unsafe { libc::getuid() };
let status = unsafe {
libc::getpwuid_r(uid, &mut entry, buf.as_mut_ptr(), buf.len(), &mut res)
};
if status < 0 {
die!("getpwuid_r failed");
}
if res.is_null() {
die!("pw not found");
}
// sanity check
assert_eq!(entry.pw_uid, uid);
// Build a borrowed Passwd struct
//
// Transmute is used here to conveniently cast from the raw CStr to a &str with the appropriate
// lifetime.
Passwd {
name: unsafe { mem::transmute(CStr::from_ptr(entry.pw_name).to_str().unwrap()) },
passwd: unsafe { mem::transmute(CStr::from_ptr(entry.pw_passwd).to_str().unwrap()) },
uid: entry.pw_uid,
gid: entry.pw_gid,
gecos: unsafe { mem::transmute(CStr::from_ptr(entry.pw_gecos).to_str().unwrap()) },
dir: unsafe { mem::transmute(CStr::from_ptr(entry.pw_dir).to_str().unwrap()) },
shell: unsafe { mem::transmute(CStr::from_ptr(entry.pw_shell).to_str().unwrap()) },
}
}
/// Exec a shell
fn execsh() -> ! {
let mut buf = [0; 1024];
let pw = get_pw_entry(&mut buf);
// setup environment
env::set_var("LOGNAME", pw.name);
env::set_var("USER", pw.name);
env::set_var("SHELL", pw.shell);
env::set_var("HOME", pw.dir);
env::set_var("TERM", "xterm-256color"); // sigh
unsafe {
libc::signal(libc::SIGCHLD, libc::SIG_DFL);
libc::signal(libc::SIGHUP, libc::SIG_DFL);
libc::signal(libc::SIGINT, libc::SIG_DFL);
libc::signal(libc::SIGQUIT, libc::SIG_DFL);
libc::signal(libc::SIGTERM, libc::SIG_DFL);
libc::signal(libc::SIGALRM, libc::SIG_DFL);
}
// pw.shell is null terminated
let shell = unsafe { CStr::from_ptr(pw.shell.as_ptr() as *const _) };
let argv = [shell.as_ptr(), ptr::null()];
let res = unsafe {
libc::execvp(shell.as_ptr(), argv.as_ptr())
};
if res < 0 {
die!("execvp failed: {}", errno());
}
::std::process::exit(1);
}
/// Create a new tty and return a handle to interact with it.
pub fn new(rows: u8, cols: u8) -> File {
let (master, slave) = openpty(rows, cols);
match fork() {
Relation::Child => {
unsafe {
// Create a new process group
libc::setsid();
// Duplicate pty slave to be child stdin, stdoud, and stderr
libc::dup2(slave, 0);
libc::dup2(slave, 1);
libc::dup2(slave, 2);
}
set_controlling_terminal(slave);
// No longer need slave/master fds
unsafe {
libc::close(slave);
libc::close(master);
}
// Exec a shell!
execsh();
},
Relation::Parent => {
// Parent doesn't need slave fd
unsafe {
libc::close(slave);
}
// XXX should this really return a file?
// How should this be done? Could build a File::from_raw_fd, or maybe implement a custom
// type that can be used in a mio event loop? For now, just do the file option.
unsafe {
File::from_raw_fd(master)
}
}
}
}
#[test]
fn test_get_pw_entry() {
let mut buf: [i8; 1024] = [0; 1024];
let pw = get_pw_entry(&mut buf);
println!("{:?}", pw);
}
|