Commit c8f6c4b8 authored by Alexander Danilov's avatar Alexander Danilov

Функция авторизации теперь требует передачи ключа, после выполнения...

Функция авторизации теперь требует передачи ключа, после выполнения авторизации и регистрации возвращается ответ со статусом.
Функции для регистрации и авторизации можно считать пригодными для использования
parent 121e641e
This diff is collapsed.
......@@ -3,9 +3,9 @@ name = "skaro"
crate-type = ["dylib"]
[package]
name = "untitled2"
version = "0.1.0"
authors = ["Alexandr Danilov <[email protected]>"]
name = "skaro"
version = "0.2.0"
authors = ["Alexander Danilov <[email protected]>"]
[dependencies]
websocket = "~0.20"
......
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "skaro.h"
void trigger_callback() {
printf("trigger_callback!");fflush(stdout);
}
void export_keys(const char* public_key, const char* private_key) {
printf("export_keys!");
printf(public_key);
fflush(stdout);
void skaro_export_keys(const char* public_key, const char* private_key) {
printf("export_keys!");
printf(public_key);
printf(private_key);
FILE *fp;
size_t count;
fp = fopen("private.key", "wb");
if(fp == NULL) {
perror("ошибка открытия пример.txt");
return;
}
count = fwrite(private_key, strlen(private_key), 1, fp);
printf("Записано %lu байт. fclose(fp) %s.\n", (unsigned long)count, fclose(fp) == 0 ? "успешно" : "с ошибкой");
fflush(stdout);
}
void skaro_on_register(const char* status, const char* info) {
printf("skaro_on_register");
printf(status);
printf(info);
}
void skaro_on_authorize(const char* status, const char* info) {
printf("skaro_on_authorize");
printf(status);
printf(info);
}
int main()
......@@ -26,11 +53,45 @@ int main()
c = getchar( );
skaro_register(x, "emlog", "log", "123");
skaro_register(x, "[email protected]", "modtest7", "mypass");
c = getchar( );
skaro_authorize(x);
FILE* f;
// открываем файл
if((f = fopen("private.key", "rb")) == NULL){
printf("Error opening file 'in'");
return 0;
}
// узнаем размер файла для создания буфера нужного размера
fseek(f, 0L, SEEK_END);
long size = ftell(f);
fseek(f, 0L, SEEK_SET);
// выделяем память под буфер
char* buf = (char*)malloc(sizeof(char) * size);
// читаем полностью весь файл в буфер
fread(buf, 1, size, f);
// выводим содержимое буфера в стандартный поток
fprintf(stdout, "%s", buf);
fclose(f);
skaro_authorize(x, "modtest7", buf, "mypass");
fflush(stdout);
skaro_disconnect(x);
......
typedef void * handle;
extern handle skaro_connect(const char*);
void skaro_authorize(handle);
void skaro_authorize(handle, const char*, const char*, const char*);
void skaro_register(handle, const char*, const char*, const char*);
void skaro_disconnect(handle);
......@@ -5,11 +5,11 @@ extern crate base64;
extern crate sha;
extern crate std;
extern {
extern "C" {
fn trigger_callback();
}
pub fn ws_connect(connection: &str) -> *mut (){
pub fn ws_connect(connection: &str) -> *mut () {
use std::thread;
use std::sync::mpsc::channel;
......@@ -33,7 +33,7 @@ pub fn ws_connect(connection: &str) -> *mut (){
let tx_1 = tx.clone();
let tx_2 = tx.clone();
let send_loop = thread::spawn(move || {
thread::spawn(move || {
loop {
// Send loop
let message = match rx.recv() {
......@@ -63,7 +63,7 @@ pub fn ws_connect(connection: &str) -> *mut (){
}
});
let receive_loop = thread::spawn(move || {
thread::spawn(move || {
// Receive loop
for message in receiver.incoming_messages() {
let message = match message {
......@@ -91,49 +91,9 @@ pub fn ws_connect(connection: &str) -> *mut (){
}
});
// loop {
//
// let mut input = String::new();
// stdin().read_line(&mut input).unwrap();
// let trimmed = input.trim();
//
// //websocket::Message::binary(handler::register().unwrap());
// let message = match trimmed {
// "/close" => {
// // Close the connection
// let _ = tx.send(Message::close());
// break;
// }
// "register" => Message::binary(::handler::register().unwrap()),
// "authorize" => Message::binary(::handler::authorize().unwrap()),
// // Send a ping
// "/ping" => Message::ping(b"PING".to_vec()),
// // Otherwise, just send text
// _ => Message::text(trimmed.to_string()),
// };
// match tx.send(message) {
// Ok(()) => (),
// Err(e) => {
// println!("Main Loop: {:?}", e);
// break;
// }
// }
//
// }
// We're exiting
println!("Waiting for child threads to exit");
//let _ = send_loop.join();
println!("_");
//let _ = receive_loop.join();
println!("Exited");
let context = Box::new(tx);
let handle = Box::into_raw(context) as *mut ();
handle
}
\ No newline at end of file
}
This diff is collapsed.
......@@ -4,6 +4,11 @@ extern crate openssl;
extern crate base64;
extern crate sha;
extern crate uuid;
// C API for Skaro library
extern crate libc;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::any::Any;
#[macro_use]
extern crate lazy_static;
......@@ -13,34 +18,38 @@ mod message;
mod handler;
mod parse;
// C API for Skaro library
extern crate libc;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::any::Any;
#[no_mangle]
pub extern fn skaro_connect(connection: *const c_char) -> *mut () {
dalek::ws_connect(unsafe{CStr::from_ptr(connection).to_string_lossy().into_owned().as_str()})
pub extern "C" fn skaro_connect(connection: *const c_char) -> *mut () {
println!("n---------===================ull 4");
dalek::ws_connect(unsafe { CStr::from_ptr(connection).to_string_lossy().into_owned().as_str() })
}
#[no_mangle]
pub extern fn skaro_disconnect(handle: *mut std::sync::mpsc::Sender<websocket::OwnedMessage<>>) {
let y: Box<Any> = unsafe{ Box::<std::sync::mpsc::Sender<websocket::OwnedMessage<>>>::from_raw(handle) };
pub extern "C" fn skaro_disconnect(handle: *mut std::sync::mpsc::Sender<websocket::OwnedMessage>) {
let y: Box<Any> =
unsafe { Box::<std::sync::mpsc::Sender<websocket::OwnedMessage>>::from_raw(handle) };
std::mem::forget(y);
}
#[no_mangle]
pub extern fn skaro_authorize(handle: *mut std::sync::mpsc::Sender<websocket::OwnedMessage<>>) {
println!("start skaro_authorize");
pub extern "C" fn skaro_authorize(handle: *mut std::sync::mpsc::Sender<websocket::OwnedMessage>,
c_login: *const c_char,
c_private_key: *const c_char,
c_password: *const c_char) {
let maybe_channel = unsafe{ handle.as_mut() };
let maybe_channel = unsafe { handle.as_mut() };
match maybe_channel {
Some(s) => {
s.send(websocket::OwnedMessage::Binary(::handler::authorize().unwrap()));
},
let login: &str = unsafe { CStr::from_ptr(c_login) }.to_str().unwrap();
let private_key: &str = unsafe { CStr::from_ptr(c_private_key) }.to_str().unwrap();
let password: &str = unsafe { CStr::from_ptr(c_password) }.to_str().unwrap();
let _ = s.send(websocket::OwnedMessage::Binary(::handler::authorize(login,
private_key,
password)
.unwrap()));
}
None => {
println!("null ptr");
}
......@@ -48,26 +57,27 @@ pub extern fn skaro_authorize(handle: *mut std::sync::mpsc::Sender<websocket::Ow
}
#[no_mangle]
pub extern fn skaro_register(
handle: *mut std::sync::mpsc::Sender<websocket::OwnedMessage<>>,
email: *const c_char,
login: *const c_char,
password: *const c_char
) {
pub extern "C" fn skaro_register(handle: *mut std::sync::mpsc::Sender<websocket::OwnedMessage>,
c_email: *const c_char,
c_login: *const c_char,
c_password: *const c_char) {
let maybe_channel = unsafe{ handle.as_mut() };
let maybe_channel = unsafe { handle.as_mut() };
match maybe_channel {
Some(s) => {
let email: &str = unsafe { CStr::from_ptr(c_email) }.to_str().unwrap();
let login: &str = unsafe { CStr::from_ptr(c_login) }.to_str().unwrap();
let password: &str = unsafe { CStr::from_ptr(c_password) }.to_str().unwrap();
let string_email: &str = unsafe{CStr::from_ptr(email)}.to_str().unwrap();
let string_login: &str = unsafe{CStr::from_ptr(login)}.to_str().unwrap();
let string_password: &str = unsafe{CStr::from_ptr(password)}.to_str().unwrap();
s.send(websocket::OwnedMessage::Binary(::handler::register(string_email, string_login, string_password).unwrap()));
},
let _ =
s.send(websocket::OwnedMessage::Binary(::handler::register(email,
login,
password)
.unwrap()));
}
None => {
println!("null ptr");
}
};
}
\ No newline at end of file
}
......@@ -11,4 +11,4 @@ impl SkaroMessage {
_ => "",
}
}
}
\ No newline at end of file
}
......@@ -13,13 +13,14 @@ pub fn cbor(raw: websocket::OwnedMessage) -> Option<Result<Vec<u8>, serde_cbor::
match raw {
websocket::OwnedMessage::Binary(payload) => {
let value : Value = from_slice(payload.as_slice()).unwrap();
let value: Value = from_slice(payload.as_slice()).unwrap();
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.insert(value::ObjectKey::String("error".to_string()),
Value::String("error".to_string()));
ret
}
};
......@@ -29,39 +30,36 @@ pub fn cbor(raw: websocket::OwnedMessage) -> Option<Result<Vec<u8>, serde_cbor::
"request" => {
handler::__request__(message).ok()
// match message.get_str("struct_type") {
// "authorize_rnd" => {
// Some(handler::request_authorize(message))
// },
// "register" => {
// println!("Register");
// None
// },
// _ => {
// println!("Error! Unexpected 'struct_type'");
// None
// }
// }
},
// match message.get_str("struct_type") {
// "authorize_rnd" => {
// Some(handler::request_authorize(message))
// },
// "register" => {
// println!("Register");
// None
// },
// _ => {
// println!("Error! Unexpected 'struct_type'");
// None
// }
// }
}
"error" => {
println!("Error type");
None
},
}
_ => {
println!("Error! Key 'type' not found");
None
}
}
},
}
_ => {
match true {
_ => {
None
}
_ => None,
}
}
}
}
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,91AC153EC27400406FB22AC3C4877D6F
QokdCGLOHh/GS1ojlaPU1xo0vPdSDUrEWCTNlyH3NPrWi1Bb8QvhLaLp/G2KOVJ1
Kf/Ls5NuC/O+eFzktFGChVvTozoKrHEv0nNO7Wj0egnsihUvIFIDax+q3qQFWfCI
J1HmWZIJGZxCkptuP+W0nd5z3H7LvAY8GzGz7ho5E3DvCmoC5AjIw3HHoXgejO2P
72yRGSbX8wUPbh+5mQP9CHyHH68tvtnx0WnpvjGt8btMTQPxsG2htc0mFZMjQbtN
x6HTbCXxkXpvbmWfORnSsANOe12MD+KPBUezvDnByBPgAgqa3jZqPlyKcDNyq3xa
JvLGkxbzWpyaXtS541ZvVUpRgLn5GMwEcfdVi6yhXopiLdS1/nCMVRuikX85XeyT
yCIapADUrDqjaeQSO6a9d9EDEWt1ABorod8992XIKEqSn/ejvUBlcXMt92ZdOKzJ
p8AGEZ/+dOkB+dbAxGsXcZMdqDPhkYx8kGFjzkDOELlPcf1ObZ8vSDoV3WIVePUU
RntiqKJKqjVBFefLSsvrNYWYCuedQRFrq9RNn/teV1tFCVA4NTr4rQZR2vT8IGEV
ffGt9Co09tSRqyo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FAAOCAQ8AMIIBCgKCAQEAy3kOkXUQNCPmw4/SoK6O
HnBL/LdRNzR1ffGHvchAYFvuppY32e88V/a5okAjAmaXqyPv/b9bHt2/j6StqBYo
GFCluvFF4TVnunvwSLzPeqACkzg6IGfVovmah7Sd+VEuCmtkETBvDTAdxbcKFWL2
MtSj6tpdN4rPdW6PlVMX5jelFCUeeiTB/v9q8xqIVM/k7on+d6aPkpZV/zm2+7yS
mJhs2myGAnBBnOuZSDDqk5cQIRmc7Q1B2/SXujZOfjP1G9Qczs2H2SMSOHfv5cck
+NKfyknx/04R3K2AILSeseWPo1SAqUsx+3Un+1i9SqqVwej9EEVOFNSuoyMYns1Y
+QIDAQAB
-----END PUBLIC KEY-----
......@@ -10,6 +10,7 @@
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Rust &lt;untitled2&gt;" level="project" />
<orderEntry type="library" name="Cargo &lt;untitled2&gt;" level="project" />
</component>
</module>
\ 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