silly and simple http implementation with actix

this has to be improved a ton but can be a barebones testbed for working
on client connectivity
This commit is contained in:
əlemi 2022-03-20 20:58:11 +01:00
parent 54152cc5a1
commit dd865ab683
No known key found for this signature in database
GPG key ID: BBCBFE5D7244634E
2 changed files with 81 additions and 92 deletions

View file

@ -6,4 +6,12 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
toml = "0.5.8"
env_logger = "0.9"
serde = { version = "1.0", features = ["derive"] }
base64 = "0.13.0"
openssl = "0.10"
derive_more = "0.99.17"
actix-web = { version = "4", features = ["openssl"] }
actix-files = "0.6.0"
#actix-multipart = "0.4.0"

View file

@ -1,99 +1,80 @@
use std::collections::LinkedList;
use std::io;
use std::fs;
use std::io::{BufRead, BufReader, BufWriter, Write, Read};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::thread;
fn main() {
// TODO load address and port from config toml
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
// TODO make a thread pool
let mut threads: LinkedList<thread::JoinHandle<()>> = LinkedList::new();
use actix_web::{middleware, web, App, HttpServer};
use actix_files::NamedFile;
// use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use serde::Deserialize;
use derive_more::{Display, Error};
use io::Write;
for stream in listener.incoming() {
match stream {
Ok(stream) => threads.push_back(thread::spawn(|| handle_connection(stream))),
Err(e) => println!("[!] ERROR establishing a connection : {}", e.to_string()),
}
#[derive(Deserialize)]
struct FileRequest {
file: String,
payload: String,
}
#[derive(Display, Debug, Error)]
struct FileError {}
impl actix_web::error::ResponseError for FileError {}
/// upload memo db
async fn put(req: web::Json<FileRequest>) -> Result<String, FileError> {
if req.payload.len() < 20480 {
let fname = req.file.chars().filter(|c| c.is_alphanumeric()).collect::<String>();
let f_res = web::block(||fs::File::create(fname)).await.unwrap();
if f_res.is_err() { return Err(FileError{}); }
let mut f = f_res.unwrap();
let _res = web::block(move || f.write(base64::decode(&req.payload).unwrap().as_slice())).await.unwrap();
return Ok("OK".to_string());
} else {
return Err(FileError{});
}
}
fn handle_connection(stream: TcpStream) {
let mut addr = "?.?.?.?".to_string();
if stream.peer_addr().is_ok() {
let peer: SocketAddr = stream.peer_addr().unwrap();
addr = format!("{}:{}", peer.ip(), peer.port());
}
println!("[+] new connection from {}", addr);
let mut reader = BufReader::new(&stream);
let mut writer = BufWriter::new(&stream);
let mut buffer = String::new();
match reader.read_line(&mut buffer) {
Ok(_count) => {
let mut s = buffer.as_str().splitn(2, " ");
let cmd = s.next().unwrap_or("").to_lowercase();
let arg = s.next().unwrap_or("").replace("\n", "");
match cmd.as_str() {
"get" => {
let paths = fs::read_dir("./").unwrap();
for path in paths {
match path {
Ok(p) => {
if p.path().ends_with(arg.as_str()) {
match fs::read_to_string(p.path()) {
Ok(contents) => {
println!("[<] serving file : {}", arg);
match writer.write(contents.as_bytes()) {
Ok(_) => writer.flush().unwrap(),
Err(e) => println!("[!] Error sending contents : {}", e.to_string()),
}
}
Err(e) => println!("[!] Error reading file {} : {}", arg, e.to_string()),
}
}
},
Err(e) => println!("[!] could not list dirs : {}", e.to_string()),
}
}
},
"put" => {
let mut fname : String = arg.chars().filter(|c| c.is_alphanumeric()).collect::<String>();
fname.push_str(".txt");
if fs::metadata(&fname).is_err() {
let mut file = fs::File::create(&fname).unwrap();
let mut buf = [0;4096];
loop {
match reader.read(&mut buf) {
Ok(count) => {
if count <= 0 { break }
match file.write(&buf[..count]) {
Ok(_c) => { /* TODO check that we write as many as read */ },
Err(_e) => {
// TODO log
break
}
}
},
Err(_e) => {
// TODO log if bad
break;
}
}
}
}
},
_ => println!("[!] Command misunderstood : '{}' '{}' [{}]", cmd, arg, buffer),
}
buffer.clear();
},
Err(e) => {
println!("[!] Error reading from socket : {}", e.to_string());
}
}
/// get memo db
async fn get(req: web::Json<FileRequest>) -> Result<NamedFile, FileError> {
// TODO better way to check if a file is in current directory!
let paths = fs::read_dir("./").unwrap();
let fname = req.file.chars().filter(|c| c.is_alphanumeric()).collect::<String>();
println!("[-] closed connection from : {}", addr);
for path in paths {
match path {
Ok(p) => {
if p.path().ends_with(fname.as_str()) {
return Ok(NamedFile::open(p.path()).unwrap())
}
},
Err(e) => println!("[!] could not list dirs : {}", e.to_string()),
}
}
return Err(FileError{});
}
#[actix_web::main]
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();
println!("Started http server: 127.0.0.1:8443");
// load TLS keys
// let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
// builder
// .set_private_key_file("key.pem", SslFiletype::PEM)
// .unwrap();
// builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| {
App::new()
// enable logger
.wrap(middleware::Logger::default())
// register simple handler, handle all methods
.service(web::resource("/get").to(get))
.service(web::resource("/put").to(put))
})
//.bind_openssl("127.0.0.1:8443", builder)?
.bind("127.0.0.1:8443")?
.run()
.await
}