Commit b5f657e1 authored by Alexander Danilov's avatar Alexander Danilov

Добавлена возможность ответа библиотекой серверу на запрос

parent f0220fd7
......@@ -11,4 +11,6 @@ openssl = "^0.9"
rustc-serialize = "^0.3"
rand = "^0.3"
base64 = "~0.5.0"
sha = {git = "https://github.com/andydude/rust-sha.git", tag = "v0.3.3"}
\ No newline at end of file
sha = {git = "https://github.com/andydude/rust-sha.git", tag = "v0.3.3"}
serde = "0.9.13"
serde_derive = "0.9.13"
\ No newline at end of file
use message;
use std::collections::HashMap;
use std::sync::Mutex;
// use std::sync::Mutex;
use serde_cbor;
use serde_cbor::Value;
use serde_cbor::to_vec;
use base64::{encode, decode};
use base64::decode;
use openssl::rsa::Rsa;
use openssl::rsa::PKCS1_PADDING;
......@@ -21,12 +19,12 @@ use sha::sha256::Sha256;
use sha::utils::Digest;
use sha::utils::DigestExt;
lazy_static! {
pub static ref DICT: Mutex<HashMap<&'static str, String>> = {
let mut map = HashMap::new();
Mutex::new(map)
};
}
//lazy_static! {
// pub static ref DICT: Mutex<HashMap<&'static str, String>> = {
// let mut map = HashMap::new();
// Mutex::new(map)
// };
//}
fn __export_keys(ref mut public_key: &Vec<u8>, ref mut private_key: &Vec<u8>) {
let mut buffer_pub = File::create("pub.key.txt").unwrap();
......@@ -37,13 +35,13 @@ fn __export_keys(ref mut public_key: &Vec<u8>, ref mut private_key: &Vec<u8>) {
pub fn check_connection(data: message::CheckConnection) {
println!("{}", data.token);
let mut dict = DICT.lock().unwrap();
dict.insert("token", data.token);
// HASHMAP.get(&0).unwrap()
}
//pub fn check_connection(data: message::CheckConnection) {
// println!("{}", data.token);
//
// let mut dict = DICT.lock().unwrap();
// dict.insert("token", data.token);
// // HASHMAP.get(&0).unwrap()
//}
pub fn register() -> Result<Vec<u8>, serde_cbor::Error> {
......@@ -70,28 +68,35 @@ pub fn register() -> Result<Vec<u8>, serde_cbor::Error> {
// 4. Клиент отсылает на сервер, а сервер сохраняет — логин, E-Mail, открытый ключ e,N.
let mut data = HashMap::new();
data.insert("chain_uuid", Value::String("455-936-574".to_string()));
data.insert("type", Value::String("register".to_string()));
data.insert("login", Value::String("modtest".to_string()));
data.insert("email", Value::String("[email protected]".to_string()));
data.insert("public_key", Value::String(public_key_string));
data.insert("on_request", Value::I64(42));
to_vec(&data)
serde_cbor::to_vec(&data)
}
pub fn authorize() -> Result<Vec<u8>, serde_cbor::Error> {
let mut data = HashMap::new();
data.insert("chain_uuid", Value::String("123-994-356".to_string()));
data.insert("type", Value::String("authorize".to_string()));
data.insert("login", Value::String("modtest".to_string()));
data.insert("on_request", Value::I64(16));
to_vec(&data)
serde_cbor::to_vec(&data)
}
pub fn request(data: message::Request) {}
pub fn request_authorize(obj: HashMap<serde_cbor::ObjectKey, serde_cbor::Value>) -> Result<Vec<u8>, serde_cbor::Error> {
pub fn requestAuthorize(dataget: message::RequestAuthorize) {
let encrypted_rnd = &decode(dataget.encrypted_rnd.as_bytes()).unwrap();
let encrypted_rnd = match obj.get(&serde_cbor::ObjectKey::String("encrypted_rnd".to_string())) {
Some(&Value::String(ref val)) => val.as_str(),
_ => "",
};
let chain_uuid = match obj.get(&serde_cbor::ObjectKey::String("chain_uuid".to_string())) {
Some(&Value::String(ref val)) => val.as_str(),
_ => "",
};
let encrypted_rnd = &decode(encrypted_rnd.as_bytes()).unwrap();
let pkey = include_bytes!("priv.key.txt");
let private_key = Rsa::private_key_from_pem_passphrase(pkey, b"foobar").unwrap();
......@@ -104,8 +109,9 @@ pub fn requestAuthorize(dataget: message::RequestAuthorize) {
println!("{:?}", res);
let mut data = HashMap::new();
data.insert("chain_uuid", Value::String(chain_uuid.to_string()));
data.insert("type", Value::String("request".to_string()));
data.insert("rnd_hash", Value::String(res));
data.insert("on_request", Value::I64(dataget.id));
data.insert("status", Value::String("200 OK".to_string()));
serde_cbor::to_vec(&data)
}
extern crate websocket;
extern crate serde_cbor;
#[macro_use]
extern crate lazy_static;
//#[macro_use]
//extern crate lazy_static;
extern crate openssl;
extern crate base64;
extern crate sha;
use serde_cbor::{from_slice, Value, ObjectKey};
mod message;
mod handler;
mod parse;
......@@ -27,7 +25,7 @@ fn main() {
let client = ClientBuilder::new(CONNECTION)
.unwrap()
.add_protocol("rust-websocket")
.add_protocol("cbor-typed")
.connect_insecure()
.unwrap();
......@@ -38,6 +36,7 @@ fn main() {
let (tx, rx) = channel();
let tx_1 = tx.clone();
let tx_2 = tx.clone();
let send_loop = thread::spawn(move || {
loop {
......@@ -69,10 +68,11 @@ fn main() {
let receive_loop = thread::spawn(move || {
// Receive loop
for message in receiver.incoming_messages() {
let message: websocket::Message = match message {
Ok(m) => m,
Err(e) => {
println!("Receive Loop: {:?}", e);
println!("Receive Loop Error: {:?}", e);
let _ = tx_1.send(websocket::Message::close());
return;
}
......@@ -80,15 +80,12 @@ fn main() {
println!("Receive Loop: {:?}", message);
match parse::cbor(message) {
Err(why) => panic!("{:?}", why),
Ok(data) => {
match data {
message::Mess::CheckConnection(data) => handler::check_connection(data),
message::Mess::Request(data) => handler::request(data),
message::Mess::RequestAuthorize(data) => handler::requestAuthorize(data),
message::Mess::Error(data) => println!("Неизвестный тип сообщения!"),
}
let message = parse::cbor(message);
match message {
None => println!("Отвечать не нужно"),
Some(data) => {
println!("Отвечаем: {:?}", data);
let _ = tx_2.send(websocket::Message::binary(data.unwrap()));
}
}
......
#[derive(Debug)]
pub struct CheckConnection {
pub token: String,
}
#[derive(Debug)]
pub struct Request {
pub id: u64,
pub register_type: String,
}
#[derive(Debug)]
pub struct RequestAuthorize {
pub encrypted_rnd: String,
pub id: i64,
}
#[derive(Debug)]
pub struct Error {}
#[derive(Debug)]
pub enum ProtocolError {
Error,
}
pub enum Mess {
CheckConnection(CheckConnection),
Request(Request),
RequestAuthorize(RequestAuthorize),
Error(Error),
}
//#[derive(Debug)]
//pub struct CheckConnection {
// pub token: String,
//}
//#[derive(Debug)]
//pub struct Request {
// pub id: u64,
// pub register_type: String,
//}
//#[derive(Debug)]
//pub struct RequestAuthorize {
// pub encrypted_rnd: String,
// pub id: i64,
//}
//#[derive(Debug)]
//pub struct Error {}
//#[derive(Debug)]
//pub enum ProtocolError {
// Error,
//}
//
//pub enum Mess {
// CheckConnection(CheckConnection),
// Request(Request),
// RequestAuthorize(RequestAuthorize),
// Error(Error),
//}
extern crate websocket;
extern crate serde_cbor;
use serde_cbor::{from_slice, Value, ObjectKey};
use serde_cbor::{from_slice, Value, value, ObjectKey};
use message;
use handler;
pub fn cbor(message: websocket::Message) -> Result<message::Mess, message::ProtocolError> {
let slice = message.payload.into_owned();
let value: Value = from_slice(slice.as_slice()).unwrap();
use std::collections::HashMap;
pub fn cbor(message: websocket::Message) -> Option<Result<Vec<u8>, serde_cbor::Error>> {
let payload = message.payload.into_owned();
let value : Value = from_slice(payload.as_slice()).unwrap();
println!("{:?}", value);
let val: message::Mess = if let Some(object) = value.as_object() {
let kind = match object.get(&ObjectKey::String("type".to_string())) {
Some(&Value::String(ref my_string)) => my_string.as_str(),
_ => "a", // default kind
};
match kind {
"check_connection" => {
let t: String = if let Some(object) = value.as_object() {
match object.get(&ObjectKey::String("token".to_string())) {
Some(&Value::String(ref my_string)) => my_string.clone(),
_ => "default_value".to_string(),
}
} else {
"error".to_string()
};
message::Mess::CheckConnection(message::CheckConnection { token: t })
},
"request" => {
let encrypted_rnd: String = if let Some(object) = value.as_object() {
match object.get(&ObjectKey::String("encrypted_rnd".to_string())) {
Some(&Value::String(ref my_string)) => my_string.clone(),
_ => "default_value".to_string(),
}
} else {
"error".to_string()
};
let id: i64 = if let Some(object) = value.as_object() {
match object.get(&ObjectKey::String("id".to_string())) {
Some(&Value::I64(ref my_int)) => my_int.clone(),
_ => 0,
}
} else {
0
};
message::Mess::RequestAuthorize(message::RequestAuthorize { encrypted_rnd: encrypted_rnd, id: id })
}
_ => message::Mess::Error(message::Error {}),
let obj = match value.as_object() {
Some(d) => d.clone(),
None => {
let mut ret = HashMap::new();
ret.insert(value::ObjectKey::String("error".to_string()), Value::String("error".to_string()));
ret
}
} else {
message::Mess::Error(message::Error {})
};
Ok(val)
}
fn request(value: Value) -> message::Mess {
println!("1 {:?}", value);
println!("2 {:?}", value.as_object());
let id: u64 = if let Some(object) = value.as_object() {
match object.get(&ObjectKey::String("id".to_string())) {
Some(&Value::U64(ref my_string)) => my_string.clone(),
_ => 0,
}
} else {
0
let message_type = match obj.get(&ObjectKey::String("type".to_string())) {
Some(&Value::String(ref my_string)) => my_string.as_str(),
_ => "",
};
let register_type: String = if let Some(object) = value.as_object() {
match object.get(&ObjectKey::String("register_type".to_string())) {
Some(&Value::String(ref my_string)) => my_string.clone(),
_ => "".to_string(),
match message_type {
"request" => {
let struct_type = match obj.get(&ObjectKey::String("struct_type".to_string())) {
Some(&Value::String(ref my_string)) => my_string.as_str(),
_ => "",
};
match struct_type {
"authorize_rnd" => {
Some(handler::request_authorize(obj.clone()))
},
"register" => {
println!("Register");
None
},
_ => {
println!("Error! Unexpected 'struct_type'");
None
}
}
},
"error" => {
println!("Error type");
None
},
_ => {
println!("Error! Key 'type' not found");
None
}
} else {
"".to_string()
};
}
}
message::Mess::Request(message::Request { id: id, register_type: register_type })
}
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment