X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=src%2Fmain.rs;h=ddd9b914cdee26c44baf15e51526366fdecdfc7b;hb=73da6aae874c3d4efc3093173733c397a878fe06;hp=6c9ab2796d0fd05fe379d71719f2ba2fda43902b;hpb=6cc0700aa5b90500b620ca8dd5b2976892aee0a7;p=rup.git diff --git a/src/main.rs b/src/main.rs index 6c9ab27..ddd9b91 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,17 +1,16 @@ -extern crate actix_web; + extern crate listenfd; extern crate askama; extern crate percent_encoding; use listenfd::ListenFd; use actix_files as fs; -use actix_web::{web, middleware, App, HttpServer, HttpResponse, Responder, Result, web::Query}; +use actix_web::{ web, middleware, App, HttpServer, HttpResponse, web::Query }; use askama::Template; -use std::io::prelude::*; -use ron::de::from_reader; -use serde::Deserialize; -use std::{fs::File, env::args}; +use std::{ fs::File, path::Path, env::args, io::prelude::* }; +use ron::{ de::from_reader, ser::{ to_string_pretty, PrettyConfig } }; +use serde::{ Deserialize, Serialize }; use itertools::Itertools; @@ -29,7 +28,7 @@ pub struct Request { m: Option } -fn main_page(query: Query, key: &str) -> Result { +fn main_page(query: Query, key: &str) -> HttpResponse { let m = match &query.m { Some(b) => @@ -43,48 +42,73 @@ fn main_page(query: Query, key: &str) -> Result { let hello = MainTemplate { sentence: &m }; let s = hello.render().unwrap(); - Ok(HttpResponse::Ok().content_type("text/html").body(s)) + HttpResponse::Ok().content_type("text/html").body(s) } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Serialize)] struct Config { port: u16 } +const DEFAULT_CONFIG: Config = Config { port: 8082 }; + fn get_exe_name() -> String { - let first_arg = std::env::args().nth(0).unwrap(); - //dbg!(&first_arg); + let first_arg = std::env::args().next().unwrap(); let sep: &[_] = &['\\', '/']; first_arg[first_arg.rfind(sep).unwrap()+1..].to_string() } + +fn load_config() -> Config { + // unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF)); + match File::open(consts::FILE_CONF) { + Ok(file) => from_reader(file).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF)), + Err(_) => { + let mut file = File::create(consts::FILE_CONF) .unwrap(); + file.write_all(to_string_pretty(&DEFAULT_CONFIG, PrettyConfig::new()).unwrap().as_bytes()).unwrap(); // We do not use 'to_writer' because it can't pretty format the output. + DEFAULT_CONFIG + } + } +} + fn read_key() -> String { let mut key = String::new(); File::open(consts::FILE_KEY) - .expect(&format!("Failed to open key file: {}", consts::FILE_KEY)) + .unwrap_or_else(|_| panic!("Failed to open key file: {}", consts::FILE_KEY)) .read_to_string(&mut key) - .expect(&format!("Failed to read key file: {}", consts::FILE_KEY)); + .unwrap_or_else(|_| panic!("Failed to read key file: {}", consts::FILE_KEY)); String::from( percent_encoding::percent_decode(key.replace('\n', "").as_bytes()) .decode_utf8() - .expect(&format!("Failed to decode key file: {}", consts::FILE_KEY)) + .unwrap_or_else(|_| panic!("Failed to decode key file: {}", consts::FILE_KEY)) ) } -fn main() -> std::io::Result<()> { - let key = read_key(); +fn write_key(key : &str) { + let percent_encoded = percent_encoding::utf8_percent_encode(key, percent_encoding::NON_ALPHANUMERIC).to_string(); + let mut file = File::create(consts::FILE_KEY).unwrap(); + file.write_all(percent_encoded.as_bytes()).unwrap(); +} + +#[actix_rt::main] +async fn main() -> std::io::Result<()> { + let key = { + // If the key file doesn't exist then create a new one with a random key in it. + if !Path::new(consts::FILE_KEY).exists() { + let new_key = crypto::generate_key(); + write_key(&new_key); + println!("A key has been generated here: {}", consts::FILE_KEY); + new_key + } else { + read_key() + } + }; if process_args(&key) { return Ok(()) } println!("Starting RUP as web server..."); - let config: Config = { - let f = File::open(consts::FILE_CONF).expect(&format!("Failed to open configuration file {}", consts::FILE_CONF)); - match from_reader(f) { - Ok(c) => c, - Err(e) => panic!("Failed to load config: {}", e) - } - }; + let config = load_config(); println!("Configuration: {:?}", config); @@ -109,13 +133,13 @@ fn main() -> std::io::Result<()> { server.bind(&format!("0.0.0.0:{}", config.port)).unwrap() }; - server.run() + server.run().await } -fn process_args(key: &String) -> bool { +fn process_args(key: &str) -> bool { fn print_usage() { println!("Usage:"); - println!(" {} [--help] [--encrypt |--decrypt ]", get_exe_name()); + println!(" {} [--help] [--encrypt | --decrypt ]", get_exe_name()); } let args: Vec = args().collect(); @@ -124,9 +148,10 @@ fn process_args(key: &String) -> bool { print_usage(); return true } else if let Some((position_arg_encrypt, _)) = args.iter().find_position(|arg| arg == &"--encrypt") { - match args.iter().nth(position_arg_encrypt + 1) { + match args.get(position_arg_encrypt + 1) { Some(mess_to_encrypt) => { - match crypto::encrypt(&key, mess_to_encrypt) { + // Encrypt to version 2 (version 1 is obsolete). + match crypto::encrypt(&key, mess_to_encrypt, 2) { Ok(encrypted_mess) => { let encrypted_mess_encoded = percent_encoding::utf8_percent_encode(&encrypted_mess, percent_encoding::NON_ALPHANUMERIC).to_string(); println!("Encrypted message percent-encoded: {}", encrypted_mess_encoded); }, @@ -139,7 +164,7 @@ fn process_args(key: &String) -> bool { return true } else if let Some((position_arg_decrypt, _)) = args.iter().find_position(|arg| arg == &"--decrypt") { - match args.iter().nth(position_arg_decrypt + 1) { + match args.get(position_arg_decrypt + 1) { Some(cipher_text) => { let cipher_text_decoded = percent_encoding::percent_decode(cipher_text.as_bytes()).decode_utf8().expect("Unable to decode encoded cipher text"); match crypto::decrypt(&key, &cipher_text_decoded) { @@ -155,5 +180,5 @@ fn process_args(key: &String) -> bool { return true } - return false + false }