history ok

This commit is contained in:
Justine 2022-12-07 02:20:25 +01:00
parent 2fa6237406
commit 1c897536c9
4 changed files with 348 additions and 60 deletions

155
Cargo.lock generated
View File

@ -5,3 +5,158 @@ version = 3
[[package]]
name = "Rshell"
version = "0.1.0"
dependencies = [
"dirs",
]
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "dirs"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"
dependencies = [
"libc",
"redox_users",
"winapi",
]
[[package]]
name = "getrandom"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "libc"
version = "0.2.138"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8"
[[package]]
name = "proc-macro2"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags",
]
[[package]]
name = "redox_users"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b"
dependencies = [
"getrandom",
"redox_syscall",
"thiserror",
]
[[package]]
name = "syn"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

View File

@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dirs = "4.0.0"

View File

@ -12,3 +12,13 @@ I can also add basic features:
Later, I can even make something useful out of it. For example, I could make it so that it is configurable via a config file. I could make it the default terminal via ssh for some user and make it so the terminal opens directly in a docker container, or chrooted or smthing, as a basic form of honeypot.
# Done
* A basic history system. Writes to ~/history.rshell
* Tests for this history system
# Todo
* Other tests for the rest of the features
* Add a builtin history command
* Get some sleep
* Order the file (modules...)

View File

@ -2,10 +2,149 @@ use std::process::Command;
use std::io::stdin;
use std::io::stdout;
use std::io::Write;
use std::io::ErrorKind;
use std::path::Path;
use std::env;
use std::process::Child;
use std::process::Stdio;
use std::fs::File;
use std::fs::OpenOptions;
use std::fs;
use std::io::{self, prelude::*, BufReader};
//used for home directory
extern crate dirs;
fn process_line(input: String) -> bool {
// must be peekable so we know when we are on the last command
let mut commands = input.trim().split(" | ").peekable();
//Will be used later, in the case of pipes
let mut previous_command = None;
//While have commands to process...
while let Some(command) = commands.next() {
//First command is divided...
let mut parts = command.trim().split_whitespace();
//into a command...
let mut command = parts.next().unwrap();
//and args
let args = parts;
//builtins : exit and cd are special
match command {
"cd" => {
//If a dir is given, we use it by dereferencing
//otherwise it is /
let new_dir = args.peekable().peek().map_or("/", |x| *x);
let root = Path::new(new_dir);
if let Err(e) = env::set_current_dir(&root) {
eprintln!("{}", e);
}
previous_command = None;
},
"exit" => return true,
//not builtin: we process it
command => {
//If we are at the first command (aka previous_command is None)...
let stdin = previous_command.map_or(
//We inherit, meaning stdin gets the stream from its parent
//what I guess that means is that the child (our command)
//inherits the file descriptors (stdin, stdout, stderr)
//from the process of this very own rust program !
Stdio::inherit(),
//otherwise, our input is the output from the last command
//(from converts a ChildStdOut to a Stdio)
|output: Child| Stdio::from(output.stdout.unwrap())
);
let stdout = if commands.peek().is_some() {
// there is another command piped behind this one
// prepare to send output to the next command
Stdio::piped()
} else {
// there are no more commands piped behind this one
// send output to shell stdout
// the child inherits from the parent's file descriptor
Stdio::inherit()
};
//Run the command
let output = Command::new(command)
.args(args)
.stdin(stdin)
.stdout(stdout)
//spawn : execute the command as a child process, returning a handle to it
.spawn();
//Checking for errors
//If it matched, previous_command becomes the output of this to be used
//next loop
match output {
Ok(output) => { previous_command = Some(output); },
Err(e) => {
previous_command = None;
eprintln!("{}", e);
},
};
}
}
}
if let Some(mut final_command) = previous_command {
// block until the final command has finished
final_command.wait();
}
return false;
}
fn write_to_history(command: &str, number: &i32) -> Result<(), std::io::Error> {
//Write a command to history
let filepath = dirs::home_dir().unwrap().join("history.rshell");
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(&filepath)
.unwrap();
writeln!(file, "{} {}", number, command.trim())?;
return Ok(())
}
fn get_history_number() -> Result<i32, std::io::Error> {
//Get the latest number found in history file
let filepath = dirs::home_dir().unwrap().join("history.rshell");
let file = File::open(filepath)?;
let mut reader = BufReader::new(file).lines();
let myline = String::from(reader.last().unwrap()?);
let mut number = myline.split(' ').next().expect("???").parse().unwrap();
//number = number + 1;
return Ok(number);
}
fn get_hist_from_number(number: &i32) -> Option<String> {
//Returns a command from its number in hist file
let filepath = dirs::home_dir().unwrap().join("history.rshell");
if filepath.exists() {
let file = File::open(filepath).expect("Error opening history file, should NOT happen");
let mut reader = BufReader::new(file).lines();
for line in reader {
let current_line = line.expect("Empty history file ? Please rm it");
let mut s = current_line.split_whitespace();
let n: i32 = s.next().expect("Error reading a line in hist file").parse().unwrap();
let c = s.next().expect("No command!");
if &n == number {
return Some(String::from(c));
}
}
return None;
} else {
return None;
}
}
fn main(){
loop {
@ -14,67 +153,50 @@ fn main(){
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
let number = match get_history_number() {
Ok(n) => n + 1,
Err(_) => 1
};
// must be peekable so we know when we are on the last command
let mut commands = input.trim().split(" | ").peekable();
let mut previous_command = None;
while let Some(command) = commands.next() {
let mut parts = command.trim().split_whitespace();
let command = parts.next().unwrap();
let args = parts;
match command {
"cd" => {
let new_dir = args.peekable().peek()
.map_or("/", |x| *x);
let root = Path::new(new_dir);
if let Err(e) = env::set_current_dir(&root) {
eprintln!("{}", e);
}
previous_command = None;
},
"exit" => return,
command => {
let stdin = previous_command
.map_or(
Stdio::inherit(),
|output: Child| Stdio::from(output.stdout.unwrap())
);
let stdout = if commands.peek().is_some() {
// there is another command piped behind this one
// prepare to send output to the next command
Stdio::piped()
} else {
// there are no more commands piped behind this one
// send output to shell stdout
Stdio::inherit()
};
let output = Command::new(command)
.args(args)
.stdin(stdin)
.stdout(stdout)
.spawn();
match output {
Ok(output) => { previous_command = Some(output); },
Err(e) => {
previous_command = None;
eprintln!("{}", e);
},
};
}
}
write_to_history(&input, &number);
if process_line(input) {
return
}
if let Some(mut final_command) = previous_command {
// block until the final command has finished
final_command.wait();
}
}
}
//tests should be run with a history file such as:
//1 ls
//TODO make a function that creates such history file when testing
#[cfg(test)]
mod tests {
use super::*;
fn inittests() {
let filepath = dirs::home_dir().unwrap().join("history.rshell");
//if the file exists, new will truncate it
let file = File::create(&filepath).expect("Could not create test history");
writeln!(&file, "1 ls");
}
#[test]
fn test_gethistnumber() {
inittests();
let mynumber = get_history_number().unwrap();
assert_eq!(mynumber, 1);
}
#[test]
fn test_gethistfromnumber() {
inittests();
let mycmd = get_hist_from_number(&1).unwrap();
assert_eq!(mycmd, String::from("ls"));
}
}