Update dependencies
[rup.git] / src / main.rs
index 15b9c02..ddd9b91 100644 (file)
@@ -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, 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;
 
@@ -46,17 +45,31 @@ fn main_page(query: Query<Request>, key: &str) -> HttpResponse {
     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();
+    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)
@@ -71,21 +84,31 @@ fn read_key() -> String {
     )
 }
 
+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 = read_key();
+    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).unwrap_or_else(|_| panic!("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);
 
@@ -116,7 +139,7 @@ async fn main() -> std::io::Result<()> {
 fn process_args(key: &str) -> bool {
     fn print_usage() {
         println!("Usage:");
-        println!(" {} [--help] [--encrypt <plain-text>|--decrypt <cipher-text>]", get_exe_name());
+        println!(" {} [--help] [--encrypt <plain-text> | --decrypt <cipher-text>]", get_exe_name());
     }
 
     let args: Vec<String> = args().collect();
@@ -127,7 +150,8 @@ fn process_args(key: &str) -> bool {
     } else if let Some((position_arg_encrypt, _)) = args.iter().find_position(|arg| arg == &"--encrypt") {
         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); },