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
pub mod history;
pub mod proc;
pub mod prompt;
pub mod unixsignal;
extern crate nix;
extern crate whoami;
use history::ShellHistory;
use proc::{ShellError, ShellProc, ShellProcState};
use prompt::ShellPrompt;
use crate::config::PromptConfig;
use crate::translator::ioprocessor::IOProcessor;
use std::path::PathBuf;
use std::time::{Duration};
#[derive(Copy, Clone, PartialEq, std::fmt::Debug)]
pub enum ShellState {
Shell,
SubprocessRunning,
Terminated,
Unknown
}
pub struct Shell {
pub history: ShellHistory,
process: ShellProc,
prompt: ShellPrompt,
props: ShellProps,
state: ShellState
}
pub(crate) struct ShellProps {
pub username: String,
pub hostname: String,
pub elapsed_time: Duration,
pub exit_status: u8,
pub wrkdir: PathBuf
}
impl Shell {
pub fn start(exec: String, args: Vec<String>, prompt_config: &PromptConfig) -> Result<Shell, ShellError> {
let mut argv: Vec<String> = Vec::with_capacity(1 + args.len());
let shell_prompt: ShellPrompt = ShellPrompt::new(prompt_config);
argv.push(exec.clone());
for arg in args.iter() {
argv.push(arg.clone());
}
let shell_process: ShellProc = match ShellProc::start(argv) {
Ok(p) => p,
Err(err) => return Err(err),
};
let user: String = whoami::username();
let hostname: String = Shell::get_hostname();
let wrkdir: PathBuf = shell_process.wrkdir.clone();
Ok(Shell {
process: shell_process,
prompt: shell_prompt,
props: ShellProps::new(hostname, user, wrkdir),
history: ShellHistory::new(),
state: ShellState::Shell
})
}
pub fn stop(&mut self) -> Result<u8, ShellError> {
while self.get_state() != ShellState::Terminated {
let _ = self.process.kill();
}
self.history.clear();
self.process.cleanup()
}
pub fn read(&mut self) -> Result<(Option<String>, Option<String>), ShellError> {
self.process.read()
}
pub fn write(&mut self, input: String) -> Result<(), ShellError> {
self.process.write(input)
}
#[allow(dead_code)]
pub fn raise(&mut self, sig: unixsignal::UnixSignal) -> Result<(), ShellError> {
self.process.raise(sig.to_nix_signal())
}
pub fn get_state(&mut self) -> ShellState {
let proc_state: ShellProcState = self.process.update_state();
match self.state {
_ => {
self.state = match proc_state {
ShellProcState::Idle => ShellState::Shell,
ShellProcState::SubprocessRunning => ShellState::SubprocessRunning,
_ => ShellState::Terminated
};
self.state
}
}
}
pub fn refresh_env(&mut self) {
self.props.username = whoami::username();
self.props.hostname = Shell::get_hostname();
self.props.wrkdir = self.process.wrkdir.clone();
self.props.exit_status = self.process.exit_status;
self.props.elapsed_time = self.process.exec_time;
}
pub fn get_promptline(&mut self, processor: &IOProcessor) -> String {
self.prompt.get_line(&self.props, processor)
}
fn get_hostname() -> String {
let full_hostname: String = whoami::hostname();
let tokens: Vec<&str> = full_hostname.split(".").collect();
String::from(*tokens.get(0).unwrap())
}
}
impl ShellProps {
pub(self) fn new(hostname: String, username: String, wrkdir: PathBuf) -> ShellProps {
ShellProps {
hostname: hostname,
username: username,
wrkdir: wrkdir,
elapsed_time: Duration::from_secs(0),
exit_status: 0
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread::sleep;
use std::time::{Duration, Instant};
#[test]
fn test_shell_props_new() {
let shell_props: ShellProps = ShellProps::new(String::from("computer"), String::from("root"), PathBuf::from("/tmp/"));
sleep(Duration::from_millis(500));
assert_eq!(shell_props.username, String::from("root"));
assert_eq!(shell_props.hostname, String::from("computer"));
assert_eq!(shell_props.wrkdir, PathBuf::from("/tmp/"));
assert_eq!(shell_props.elapsed_time.as_millis(), 0);
assert_eq!(shell_props.exit_status, 0);
}
#[test]
fn test_shell_start() {
let shell: String = String::from("sh");
let mut shell_env: Shell = Shell::start(shell, vec![], &PromptConfig::default()).ok().unwrap();
sleep(Duration::from_millis(500));
assert_ne!(shell_env.process.pid, 0);
assert_eq!(shell_env.get_state(), ShellState::Shell);
assert_eq!(shell_env.history.len(), 0);
assert_eq!(shell_env.state, ShellState::Shell);
println!("Username: {}", shell_env.props.username);
println!("Hostname: {}", shell_env.props.hostname);
println!("Working directory: {}", shell_env.props.wrkdir.display());
assert!(shell_env.props.username.len() > 0);
assert!(shell_env.props.hostname.len() > 0);
assert!(format!("{}", shell_env.props.wrkdir.display()).len() > 0);
shell_env.refresh_env();
assert_eq!(shell_env.stop().unwrap(), 9);
sleep(Duration::from_millis(500));
assert_eq!(shell_env.get_state(), ShellState::Terminated);
}
#[test]
fn test_shell_start_failed() {
let shell: String = String::from("pipponbash");
let mut shell_env: Shell = Shell::start(shell, vec![], &PromptConfig::default()).unwrap();
sleep(Duration::from_millis(500));
assert_eq!(shell_env.get_state(), ShellState::Terminated);
}
#[test]
fn test_shell_exec() {
let shell: String = String::from("sh");
let mut shell_env: Shell = Shell::start(shell, vec![], &PromptConfig::default()).ok().unwrap();
sleep(Duration::from_millis(500));
assert_ne!(shell_env.process.pid, 0);
assert_eq!(shell_env.get_state(), ShellState::Shell);
let command: String = String::from("head -n 2\n");
assert!(shell_env.write(command).is_ok());
sleep(Duration::from_millis(500));
assert_eq!(shell_env.get_state(), ShellState::SubprocessRunning);
let stdin: String = String::from("foobar\n");
assert!(shell_env.write(stdin.clone()).is_ok());
sleep(Duration::from_millis(500));
let t_start: Instant = Instant::now();
let mut test_must_pass: bool = false;
loop {
let (stdout, stderr) = shell_env.read().ok().unwrap();
if stdout.is_some() {
assert_eq!(stdout.unwrap(), stdin);
assert!(stderr.is_none());
break;
}
sleep(Duration::from_millis(50));
if t_start.elapsed() > Duration::from_secs(1) {
test_must_pass = true;
break;
}
}
assert_eq!(shell_env.get_state(), ShellState::SubprocessRunning);
if ! test_must_pass {
let stdin: String = String::from("foobar\n");
assert!(shell_env.write(stdin.clone()).is_ok());
sleep(Duration::from_millis(50));
assert!(shell_env.read().is_ok());
sleep(Duration::from_millis(50));
assert_eq!(shell_env.get_state(), ShellState::Shell);
}
assert!(shell_env.process.kill().is_ok());
sleep(Duration::from_millis(500));
assert_eq!(shell_env.get_state(), ShellState::Terminated);
assert_eq!(shell_env.stop().unwrap(), 9);
}
#[test]
fn test_shell_terminate_gracefully() {
let shell: String = String::from("sh");
let mut shell_env: Shell = Shell::start(shell, vec![], &PromptConfig::default()).ok().unwrap();
sleep(Duration::from_millis(500));
assert_ne!(shell_env.process.pid, 0);
assert_eq!(shell_env.get_state(), ShellState::Shell);
sleep(Duration::from_millis(500));
let command: String = String::from("exit 5\n");
assert!(shell_env.write(command).is_ok());
sleep(Duration::from_millis(1000));
assert_eq!(shell_env.get_state(), ShellState::Terminated);
assert_eq!(shell_env.stop().unwrap(), 5);
}
#[test]
fn test_shell_raise() {
let shell: String = String::from("sh");
let mut shell_env: Shell = Shell::start(shell, vec![], &PromptConfig::default()).ok().unwrap();
sleep(Duration::from_millis(500));
assert!(shell_env.raise(unixsignal::UnixSignal::Sigint).is_ok());
sleep(Duration::from_millis(500));
assert_eq!(shell_env.get_state(), ShellState::Terminated);
assert_eq!(shell_env.stop().unwrap(), 2);
}
#[test]
fn test_shell_hostname() {
assert_ne!(Shell::get_hostname(), String::from(""));
}
}