diff --git a/src/executor.rs b/src/executor.rs index 1349080..6a12203 100644 --- a/src/executor.rs +++ b/src/executor.rs @@ -1,13 +1,14 @@ -use crate::executor::python::PythonExecutor; - +use crate::executor::{php::PhpExecutor, python::PythonExecutor}; +pub mod php; pub mod python; + pub mod helper; pub fn executors() -> Vec> { vec![ + Box::new(PhpExecutor {}), Box::new(PythonExecutor {}), - ] } diff --git a/src/executor/helper.rs b/src/executor/helper.rs index e7e8d58..6bed093 100644 --- a/src/executor/helper.rs +++ b/src/executor/helper.rs @@ -1,4 +1,4 @@ -use std::{fs::create_dir_all, process::ExitStatus}; +use std::{fs::create_dir_all, io::Read, process::{ChildStdout, ExitStatus}}; use rand::{distributions::Alphanumeric, Rng, thread_rng}; @@ -28,3 +28,17 @@ pub fn exit_code_msg(code: ExitStatus) -> String { "Command exited with unknown code".into() } } + +pub fn get_stdout(stdout: Option) -> Result { + let ret = { + if let Some(mut sout) = stdout { + let mut buf = vec![]; + sout.read_to_end(&mut buf).map_err(|x| x.to_string())?; + String::from_utf8(buf).map_err(|x| x.to_string())? + } else { + "Couldn't get stdout from the process".into() + } + }; + + Ok(ret) +} \ No newline at end of file diff --git a/src/executor/php.rs b/src/executor/php.rs new file mode 100644 index 0000000..38cc157 --- /dev/null +++ b/src/executor/php.rs @@ -0,0 +1,42 @@ +use std::fs; +use std::process::Command; +use std::process::Stdio; + +use super::Executor; + +use super::helper::*; + +#[derive(Debug, Clone, Copy)] +pub struct PhpExecutor {} + +impl Executor for PhpExecutor { + fn id(&self) -> String { + "php".into() + } + + fn exec(&self, code: String) -> Result { + assure_dir_exists().map_err(|x| x.to_string())?; + + let path = create_path(); + + // 1. Save the code + fs::write(path.clone(), code).map_err(|x| x.to_string())?; + + // 2. Run it! + let mut out = Command::new("php") + .arg(path) + .stdout(Stdio::piped()) + .spawn() + .map_err(|x| x.to_string())?; + + // 3. Grab the exit code + let exit_status = out.wait().map_err(|x| x.to_string())?; + + let mut stdout: String = get_stdout(out.stdout)?; + + stdout += "\n\n"; + stdout += exit_code_msg(exit_status).as_str(); + + Ok(stdout) + } +} \ No newline at end of file diff --git a/src/web/executor.rs b/src/web/executor.rs index 855bc3f..f5584d4 100644 --- a/src/web/executor.rs +++ b/src/web/executor.rs @@ -2,7 +2,7 @@ use serde::{Serialize, Deserialize}; use warp::{reject::Rejection, reply::{json, with_status, Reply}, Filter, http::StatusCode}; -use crate::{executor::{executors, executors_id, get_executor, python::PythonExecutor, Executor}, SharedState}; +use crate::{executor::{executors, get_executor}, SharedState}; #[derive(Serialize, Deserialize)] struct ExecutorData {