mirror of
https://git.alemi.dev/memo-cli.git
synced 2024-11-22 11:44:48 +01:00
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:
parent
54152cc5a1
commit
dd865ab683
2 changed files with 81 additions and 92 deletions
|
@ -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"
|
||||||
|
|
||||||
|
|
|
@ -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();
|
let paths = fs::read_dir("./").unwrap();
|
||||||
addr = format!("{}:{}", peer.ip(), peer.port());
|
let fname = req.file.chars().filter(|c| c.is_alphanumeric()).collect::<String>();
|
||||||
}
|
|
||||||
|
|
||||||
println!("[+] new connection from {}", addr);
|
for path in paths {
|
||||||
|
match path {
|
||||||
let mut reader = BufReader::new(&stream);
|
Ok(p) => {
|
||||||
let mut writer = BufWriter::new(&stream);
|
if p.path().ends_with(fname.as_str()) {
|
||||||
let mut buffer = String::new();
|
return Ok(NamedFile::open(p.path()).unwrap())
|
||||||
|
}
|
||||||
match reader.read_line(&mut buffer) {
|
},
|
||||||
Ok(_count) => {
|
Err(e) => println!("[!] could not list dirs : {}", e.to_string()),
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return Err(FileError{});
|
||||||
println!("[-] closed connection from : {}", addr);
|
}
|
||||||
|
|
||||||
|
#[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
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue