mirror of
https://git.alemi.dev/memo-cli.git
synced 2024-11-22 11:14:49 +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,
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_connection(stream: TcpStream) {
|
#[derive(Display, Debug, Error)]
|
||||||
let mut addr = "?.?.?.?".to_string();
|
struct FileError {}
|
||||||
if stream.peer_addr().is_ok() {
|
impl actix_web::error::ResponseError for FileError {}
|
||||||
let peer: SocketAddr = stream.peer_addr().unwrap();
|
|
||||||
addr = format!("{}:{}", peer.ip(), peer.port());
|
/// 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{});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("[+] new connection from {}", addr);
|
/// get memo db
|
||||||
|
async fn get(req: web::Json<FileRequest>) -> Result<NamedFile, FileError> {
|
||||||
let mut reader = BufReader::new(&stream);
|
// TODO better way to check if a file is in current directory!
|
||||||
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");
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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