implement handling commands

This commit is contained in:
Astro 2022-09-23 23:23:47 +02:00
parent f5c8c67302
commit 1d4a72583f
1 changed files with 50 additions and 3 deletions

View File

@ -67,6 +67,7 @@ impl server::Server for Server {
.unwrap();
Handler {
file,
buffer: vec![],
user: "root".into(),
}
}
@ -79,6 +80,7 @@ fn send_str(session: &mut Session, channel: ChannelId, s: String) {
struct Handler {
file: File,
buffer: Vec<u8>,
user: String,
}
@ -86,6 +88,31 @@ impl Handler {
fn send_prompt(&self, session: &mut Session, channel: ChannelId) {
send_str(session, channel, format!("{}@fnordister:~$ ", self.user));
}
fn handle_command<F: FnMut(&str)>(&self, command: String, mut respond: F) {
dbg!(&command);
let program_len = command.find(|c: char| c.is_whitespace())
.unwrap_or(command.len());
let program = &command[..program_len];
dbg!(program);
match program {
"whoami" => respond(&self.user),
"id" => respond(&format!("uid=0({}) gid=0(root)", self.user)),
"uname" => respond("Linux fnordister 5.10.0-10-amd64 #1 SMP Debian 5.10.84-1 (2021-12-08) x86_64 GNU/Linux"),
"pwd" => respond("/"),
"ls" => {
respond("drwxr-xr-x 18 root root 18 Jan 4 1969 .");
respond("drwxr-xr-x 18 root root 18 Jan 4 1969 ..");
respond("drwxr-xr-x 18 root root 18 Jan 4 0000 ...");
},
"bash" => {}
"sh" => {}
"cd" => {}
"" => {}
_ => respond(&format!("{}: command not found", program)),
}
}
}
impl server::Handler for Handler {
@ -121,6 +148,14 @@ impl server::Handler for Handler {
writeln!(self.file, "Execute: {}\n", String::from_utf8_lossy(data))
.unwrap();
let line = String::from_utf8_lossy(data).into();
self.handle_command(line, |response| {
let mut data = Vec::from(response);
data.extend_from_slice(b"\r\n");
session.data(channel, data.into());
});
session.close(channel);
self.finished(session)
}
@ -149,12 +184,24 @@ impl server::Handler for Handler {
.unwrap();
// echo input back
session.data(channel, data.to_vec().into());
// pressed return?
if data.contains(&b'\r') {
writeln!(self.file).unwrap();
if self.buffer.len() < 1024 {
self.buffer.extend_from_slice(data);
}
if let Some(newline) = self.buffer.iter().position(|b| *b == b'\r') {
let rest = self.buffer.split_off(newline + 1);
let line: String = String::from_utf8_lossy(&self.buffer).into();
self.buffer = rest;
session.data(channel, b"\n".to_vec().into());
self.handle_command(line, |response| {
let mut data = Vec::from(response);
data.extend_from_slice(b"\r\n");
session.data(channel, data.into());
});
self.send_prompt(&mut session, channel);
}
self.finished(session)
}
}