4 extern crate percent_encoding
;
6 use listenfd
::ListenFd
;
8 use actix_web
::{ web
, middleware
, App
, HttpServer
, HttpResponse
, web
::Query
};
11 use std
::{ fs
::File
, path
::Path
, env
::args
, io
::prelude
::* };
12 use ron
::{ de
::from_reader
, ser
::{ to_string_pretty
, PrettyConfig
} };
13 use serde
::{ Deserialize
, Serialize
};
15 use itertools
::Itertools
;
21 #[template(path = "main.html")]
22 struct MainTemplate
<'a
> {
26 #[derive(Deserialize)]
31 fn main_page(query
: Query
<Request
>, key
: &str) -> HttpResponse
{
35 match crypto
::decrypt(key
, b
) {
37 Err(_e
) => String
::from(consts
::DEFAULT_MESSAGE
) // TODO: log error.
39 None
=> String
::from(consts
::DEFAULT_MESSAGE
)
42 let hello
= MainTemplate
{ sentence
: &m
};
44 let s
= hello
.render().unwrap();
45 HttpResponse
::Ok().content_type("text/html").body(s
)
48 #[derive(Debug, Deserialize, Serialize)]
53 const DEFAULT_CONFIG
: Config
= Config
{ port
: 8082 };
55 fn get_exe_name() -> String
{
56 let first_arg
= std
::env
::args().next().unwrap();
57 let sep
: &[_
] = &['
\\'
, '
/'
];
58 first_arg
[first_arg
.rfind(sep
).unwrap()+1..].to_string()
61 fn load_config() -> Config
{
62 // unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
63 match File
::open(consts
::FILE_CONF
) {
64 Ok(file
) => from_reader(file
).unwrap_or_else(|_
| panic!("Failed to open configuration file {}", consts
::FILE_CONF
)),
66 let mut file
= File
::create(consts
::FILE_CONF
) .unwrap();
67 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.
73 fn read_key() -> String
{
74 let mut key
= String
::new();
75 File
::open(consts
::FILE_KEY
)
76 .unwrap_or_else(|_
| panic!("Failed to open key file: {}", consts
::FILE_KEY
))
77 .read_to_string(&mut key
)
78 .unwrap_or_else(|_
| panic!("Failed to read key file: {}", consts
::FILE_KEY
));
81 percent_encoding
::percent_decode(key
.replace('
\n'
, "").as_bytes())
83 .unwrap_or_else(|_
| panic!("Failed to decode key file: {}", consts
::FILE_KEY
))
87 fn write_key(key
: &str) {
88 let percent_encoded
= percent_encoding
::utf8_percent_encode(key
, percent_encoding
::NON_ALPHANUMERIC
).to_string();
89 let mut file
= File
::create(consts
::FILE_KEY
).unwrap();
90 file
.write_all(percent_encoded
.as_bytes()).unwrap();
94 async
fn main() -> std
::io
::Result
<()> {
96 // If the key file doesn't exist then create a new one with a random key in it.
97 if !Path
::new(consts
::FILE_KEY
).exists() {
98 let new_key
= crypto
::generate_key();
100 println!("A key has been generated here: {}", consts
::FILE_KEY
);
107 if process_args(&key
) { return Ok(()) }
109 println!("Starting RUP as web server...");
111 let config
= load_config();
113 println!("Configuration: {:?}", config
);
115 let mut listenfd
= ListenFd
::from_env();
119 let key
= key
.clone(); // Is this neccessary??
122 .wrap(middleware
::Compress
::default())
123 .wrap(middleware
::Logger
::default())
124 .service(web
::resource("/").to(move |query
| main_page(query
, &key
)))
125 .service(fs
::Files
::new("/static", "static").show_files_listing())
130 if let Some(l
) = listenfd
.take_tcp_listener(0).unwrap() {
131 server
.listen(l
).unwrap()
133 server
.bind(&format!("0.0.0.0:{}", config
.port
)).unwrap()
139 fn process_args(key
: &str) -> bool
{
142 println!(" {} [--help] [--encrypt <plain-text> | --decrypt <cipher-text>]", get_exe_name());
145 let args
: Vec
<String
> = args().collect();
147 if args
.iter().any(|arg
| arg
== "--help") {
150 } else if let Some((position_arg_encrypt
, _
)) = args
.iter().find_position(|arg
| arg
== &"--encrypt") {
151 match args
.get(position_arg_encrypt
+ 1) {
152 Some(mess_to_encrypt
) => {
153 // Encrypt to version 2 (version 1 is obsolete).
154 match crypto
::encrypt(&key
, mess_to_encrypt
, 2) {
155 Ok(encrypted_mess
) => {
156 let encrypted_mess_encoded
= percent_encoding
::utf8_percent_encode(&encrypted_mess
, percent_encoding
::NON_ALPHANUMERIC
).to_string();
157 println!("Encrypted message percent-encoded: {}", encrypted_mess_encoded
); },
159 println!("Unable to encrypt: {:?}", error
)
162 None
=> print_usage()
166 } else if let Some((position_arg_decrypt
, _
)) = args
.iter().find_position(|arg
| arg
== &"--decrypt") {
167 match args
.get(position_arg_decrypt
+ 1) {
168 Some(cipher_text
) => {
169 let cipher_text_decoded
= percent_encoding
::percent_decode(cipher_text
.as_bytes()).decode_utf8().expect("Unable to decode encoded cipher text");
170 match crypto
::decrypt(&key
, &cipher_text_decoded
) {
172 println!("Decrypted message: {}", plain_text
),
174 println!("Unable to decrypt: {:?}", error
)
177 None
=> print_usage()