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 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [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::fs;
use std::io::{BufRead, BufReader, BufWriter, Write, Read};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::thread;
fn main() { use actix_web::{middleware, web, App, HttpServer};
// TODO load address and port from config toml use actix_files::NamedFile;
let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); // use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
// TODO make a thread pool use serde::Deserialize;
let mut threads: LinkedList<thread::JoinHandle<()>> = LinkedList::new(); use derive_more::{Display, Error};
use io::Write;
for stream in listener.incoming() { #[derive(Deserialize)]
match stream { struct FileRequest {
Ok(stream) => threads.push_back(thread::spawn(|| handle_connection(stream))), file: String,
Err(e) => println!("[!] ERROR establishing a connection : {}", e.to_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) { /// get memo db
let mut addr = "?.?.?.?".to_string(); async fn get(req: web::Json<FileRequest>) -> Result<NamedFile, FileError> {
if stream.peer_addr().is_ok() { // TODO better way to check if a file is in current directory!
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(); let paths = fs::read_dir("./").unwrap();
let fname = req.file.chars().filter(|c| c.is_alphanumeric()).collect::<String>();
for path in paths { for path in paths {
match path { match path {
Ok(p) => { Ok(p) => {
if p.path().ends_with(arg.as_str()) { if p.path().ends_with(fname.as_str()) {
match fs::read_to_string(p.path()) { return Ok(NamedFile::open(p.path()).unwrap())
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()), Err(e) => println!("[!] could not list dirs : {}", e.to_string()),
} }
} }
}, return Err(FileError{});
"put" => { }
let mut fname : String = arg.chars().filter(|c| c.is_alphanumeric()).collect::<String>();
fname.push_str(".txt"); #[actix_web::main]
if fs::metadata(&fname).is_err() { async fn main() -> io::Result<()> {
let mut file = fs::File::create(&fname).unwrap(); std::env::set_var("RUST_LOG", "actix_web=debug");
let mut buf = [0;4096]; env_logger::init();
loop {
match reader.read(&mut buf) { println!("Started http server: 127.0.0.1:8443");
Ok(count) => {
if count <= 0 { break } // load TLS keys
match file.write(&buf[..count]) { // let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
Ok(_c) => { /* TODO check that we write as many as read */ }, // builder
Err(_e) => { // .set_private_key_file("key.pem", SslFiletype::PEM)
// TODO log // .unwrap();
break // builder.set_certificate_chain_file("cert.pem").unwrap();
}
} HttpServer::new(|| {
}, App::new()
Err(_e) => { // enable logger
// TODO log if bad .wrap(middleware::Logger::default())
break; // 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")?
_ => println!("[!] Command misunderstood : '{}' '{}' [{}]", cmd, arg, buffer), .run()
} .await
buffer.clear();
},
Err(e) => {
println!("[!] Error reading from socket : {}", e.to_string());
}
}
println!("[-] closed connection from : {}", addr);
} }