Added and Fixed.

This commit is contained in:
Saturneic 2019-02-08 22:11:07 +08:00
parent d1a7d8141f
commit e7d167d8d9
12 changed files with 1229 additions and 356 deletions

View File

@ -7,6 +7,9 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
9227C804220D6E4D00AE694C /* model.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9227C803220D6E4D00AE694C /* model.cpp */; };
9227C85B220D702800AE694C /* controller.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9227C85A220D702800AE694C /* controller.cpp */; };
9227C860220DAD9B00AE694C /* aes.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9227C85F220DAD9B00AE694C /* aes.cpp */; };
926E0965220B17FA00AD5D5B /* client.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 926E0964220B17FA00AD5D5B /* client.cpp */; }; 926E0965220B17FA00AD5D5B /* client.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 926E0964220B17FA00AD5D5B /* client.cpp */; };
9277A16021FD725F009C5F11 /* md5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15421FD725F009C5F11 /* md5.cpp */; }; 9277A16021FD725F009C5F11 /* md5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15421FD725F009C5F11 /* md5.cpp */; };
9277A16121FD725F009C5F11 /* cproj_cpt.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15521FD725F009C5F11 /* cproj_cpt.cpp */; }; 9277A16121FD725F009C5F11 /* cproj_cpt.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9277A15521FD725F009C5F11 /* cproj_cpt.cpp */; };
@ -39,6 +42,11 @@
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
9221D9EB21EA5142007310A7 /* Net */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = Net; sourceTree = BUILT_PRODUCTS_DIR; }; 9221D9EB21EA5142007310A7 /* Net */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = Net; sourceTree = BUILT_PRODUCTS_DIR; };
9227C803220D6E4D00AE694C /* model.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = model.cpp; path = src/model.cpp; sourceTree = "<group>"; };
9227C85A220D702800AE694C /* controller.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = controller.cpp; path = src/controller.cpp; sourceTree = "<group>"; };
9227C85E220DAD2800AE694C /* aes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = aes.h; path = include/aes.h; sourceTree = "<group>"; };
9227C85F220DAD9B00AE694C /* aes.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = aes.cpp; path = src/aes.cpp; sourceTree = "<group>"; };
9227C861220DAF8700AE694C /* aes.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = aes.hpp; path = include/aes.hpp; sourceTree = "<group>"; };
926E09632209D9D300AD5D5B /* instruct.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = instruct.h; path = include/instruct.h; sourceTree = "<group>"; }; 926E09632209D9D300AD5D5B /* instruct.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = instruct.h; path = include/instruct.h; sourceTree = "<group>"; };
926E0964220B17FA00AD5D5B /* client.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = client.cpp; path = src/client.cpp; sourceTree = "<group>"; }; 926E0964220B17FA00AD5D5B /* client.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = client.cpp; path = src/client.cpp; sourceTree = "<group>"; };
9277A14621FD7246009C5F11 /* cmap.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = cmap.h; path = include/cmap.h; sourceTree = "<group>"; }; 9277A14621FD7246009C5F11 /* cmap.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = cmap.h; path = include/cmap.h; sourceTree = "<group>"; };
@ -126,12 +134,14 @@
92C34C38220747B300AB38D3 /* sha1.h */, 92C34C38220747B300AB38D3 /* sha1.h */,
9277A14B21FD7246009C5F11 /* cpart.h */, 9277A14B21FD7246009C5F11 /* cpart.h */,
9277A14A21FD7246009C5F11 /* cthread.h */, 9277A14A21FD7246009C5F11 /* cthread.h */,
9227C861220DAF8700AE694C /* aes.hpp */,
9277A14D21FD7246009C5F11 /* md5.h */, 9277A14D21FD7246009C5F11 /* md5.h */,
9277A14F21FD7246009C5F11 /* memory_type.h */, 9277A14F21FD7246009C5F11 /* memory_type.h */,
9277A14E21FD7246009C5F11 /* memory.h */, 9277A14E21FD7246009C5F11 /* memory.h */,
9277A14821FD7246009C5F11 /* net.h */, 9277A14821FD7246009C5F11 /* net.h */,
9277A14721FD7246009C5F11 /* server.h */, 9277A14721FD7246009C5F11 /* server.h */,
9277A15021FD7246009C5F11 /* type.h */, 9277A15021FD7246009C5F11 /* type.h */,
9227C85E220DAD2800AE694C /* aes.h */,
926E09632209D9D300AD5D5B /* instruct.h */, 926E09632209D9D300AD5D5B /* instruct.h */,
); );
name = include; name = include;
@ -144,6 +154,7 @@
9277A15221FD725F009C5F11 /* addr.cpp */, 9277A15221FD725F009C5F11 /* addr.cpp */,
9277A15C21FD725F009C5F11 /* clock.cpp */, 9277A15C21FD725F009C5F11 /* clock.cpp */,
9277A15921FD725F009C5F11 /* cmap.cpp */, 9277A15921FD725F009C5F11 /* cmap.cpp */,
9227C85F220DAD9B00AE694C /* aes.cpp */,
9277A15A21FD725F009C5F11 /* cpart.cpp */, 9277A15A21FD725F009C5F11 /* cpart.cpp */,
9277A15521FD725F009C5F11 /* cproj_cpt.cpp */, 9277A15521FD725F009C5F11 /* cproj_cpt.cpp */,
92C34C36220747A200AB38D3 /* sha1.cpp */, 92C34C36220747A200AB38D3 /* sha1.cpp */,
@ -156,6 +167,8 @@
9277A18A220076EE009C5F11 /* sql.cpp */, 9277A18A220076EE009C5F11 /* sql.cpp */,
9277A18F220079DB009C5F11 /* cproj_proj.cpp */, 9277A18F220079DB009C5F11 /* cproj_proj.cpp */,
926E0964220B17FA00AD5D5B /* client.cpp */, 926E0964220B17FA00AD5D5B /* client.cpp */,
9227C803220D6E4D00AE694C /* model.cpp */,
9227C85A220D702800AE694C /* controller.cpp */,
); );
name = src; name = src;
sourceTree = "<group>"; sourceTree = "<group>";
@ -230,13 +243,16 @@
9277A16621FD725F009C5F11 /* cpart.cpp in Sources */, 9277A16621FD725F009C5F11 /* cpart.cpp in Sources */,
9277A16121FD725F009C5F11 /* cproj_cpt.cpp in Sources */, 9277A16121FD725F009C5F11 /* cproj_cpt.cpp in Sources */,
9277A190220079DB009C5F11 /* cproj_proj.cpp in Sources */, 9277A190220079DB009C5F11 /* cproj_proj.cpp in Sources */,
9227C85B220D702800AE694C /* controller.cpp in Sources */,
92C34C37220747A200AB38D3 /* sha1.cpp in Sources */, 92C34C37220747A200AB38D3 /* sha1.cpp in Sources */,
9277A16021FD725F009C5F11 /* md5.cpp in Sources */, 9277A16021FD725F009C5F11 /* md5.cpp in Sources */,
92C34C3B22074B6500AB38D3 /* rsa.cpp in Sources */, 92C34C3B22074B6500AB38D3 /* rsa.cpp in Sources */,
9277A16521FD725F009C5F11 /* cmap.cpp in Sources */, 9277A16521FD725F009C5F11 /* cmap.cpp in Sources */,
9277A16221FD725F009C5F11 /* main.cpp in Sources */, 9277A16221FD725F009C5F11 /* main.cpp in Sources */,
9227C804220D6E4D00AE694C /* model.cpp in Sources */,
92C34C272205C63A00AB38D3 /* server.cpp in Sources */, 92C34C272205C63A00AB38D3 /* server.cpp in Sources */,
92C34C282205C94600AB38D3 /* addr.cpp in Sources */, 92C34C282205C94600AB38D3 /* addr.cpp in Sources */,
9227C860220DAD9B00AE694C /* aes.cpp in Sources */,
92C34C292205C95F00AB38D3 /* socket.cpp in Sources */, 92C34C292205C95F00AB38D3 /* socket.cpp in Sources */,
926E0965220B17FA00AD5D5B /* client.cpp in Sources */, 926E0965220B17FA00AD5D5B /* client.cpp in Sources */,
); );

90
include/aes.h Executable file
View File

@ -0,0 +1,90 @@
#ifndef _AES_H_
#define _AES_H_
#include <stdint.h>
// #define the macros below to 1/0 to enable/disable the mode of operation.
//
// CBC enables AES encryption in CBC-mode of operation.
// CTR enables encryption in counter-mode.
// ECB enables the basic ECB 16-byte block algorithm. All can be enabled simultaneously.
// The #ifndef-guard allows it to be configured before #include'ing or at compile time.
#ifndef CBC
#define CBC 1
#endif
#ifndef ECB
#define ECB 1
#endif
#ifndef CTR
#define CTR 1
#endif
#define AES128 1
//#define AES192 1
//#define AES256 1
#define AES_BLOCKLEN 16 //Block length in bytes AES is 128b block only
#if defined(AES256) && (AES256 == 1)
#define AES_KEYLEN 32
#define AES_keyExpSize 240
#elif defined(AES192) && (AES192 == 1)
#define AES_KEYLEN 24
#define AES_keyExpSize 208
#else
#define AES_KEYLEN 16 // Key length in bytes
#define AES_keyExpSize 176
#endif
struct AES_ctx
{
uint8_t RoundKey[AES_keyExpSize];
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
uint8_t Iv[AES_BLOCKLEN];
#endif
};
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
#endif
#if defined(ECB) && (ECB == 1)
// buffer size is exactly AES_BLOCKLEN bytes;
// you need only AES_init_ctx as IV is not used in ECB
// NB: ECB is considered insecure for most uses
void AES_ECB_encrypt(struct AES_ctx* ctx, uint8_t* buf);
void AES_ECB_decrypt(struct AES_ctx* ctx, uint8_t* buf);
#endif // #if defined(ECB) && (ECB == !)
#if defined(CBC) && (CBC == 1)
// buffer size MUST be mutile of AES_BLOCKLEN;
// Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
#endif // #if defined(CBC) && (CBC == 1)
#if defined(CTR) && (CTR == 1)
// Same function for encrypting as for decrypting.
// IV is incremented for every block, and used after encryption as XOR-compliment for output
// Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
#endif // #if defined(CTR) && (CTR == 1)
#endif //_AES_H_

12
include/aes.hpp Executable file
View File

@ -0,0 +1,12 @@
#ifndef _AES_HPP_
#define _AES_HPP_
#ifndef __cplusplus
#error Do not include the hpp header in a c project!
#endif //__cplusplus
extern "C" {
#include "aes.h"
}
#endif //_AES_HPP_

View File

@ -20,4 +20,31 @@
#include "sha1.h" #include "sha1.h"
#include "rsa.h" #include "rsa.h"
namespace error{
void printError(string error_info);
void printWarning(string warning_info);
void printSuccess(string succes_info);
}
struct instructions{
int (*unpack)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*construct)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*update)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*server)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*client)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*set)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*init)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
};
int update(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int construct(string instruct,vector<string> &config, vector<string> &lconfig, vector<string> &target);
int server(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int client(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int init(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int set(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
bool config_search(vector<string> &configs,string tfg);
void getSQEPublicKey(respond *pres,void *args);
#endif /* instruct_h */ #endif /* instruct_h */

View File

@ -30,14 +30,40 @@ struct compute_result{
//请求数据包 //请求数据包
struct request { struct request {
// 匹配id
rng::rng64 r_id; rng::rng64 r_id;
// 类型
string type; string type;
// 数据
string data; string data;
// 接收端口
uint32_t recv_port; uint32_t recv_port;
// 标记是否为加密请求
bool if_encrypt;
Addr t_addr; Addr t_addr;
request(); request();
}; };
//加密端对端报文
struct encrypt_post{
// 明文部分
// 注册客户端id
rng::rng64 client_id;
// 目标ip
string ip;
// 目标端口
int port;
// 加密部分
// 匹配id
rng::rng64 p_id;
// 类型
uint32_t type;
// 内容
Byte *buff;
};
//回复数据包
struct respond { struct respond {
rng::rng64 r_id; rng::rng64 r_id;
string type; string type;
@ -57,9 +83,19 @@ public:
// 记录块的大小及内容所在的内存地址 // 记录块的大小及内容所在的内存地址
vector<pair<unsigned int, void *>> buffs; vector<pair<unsigned int, void *>> buffs;
void AddBuff(void *pbuff, uint32_t size); void AddBuff(void *pbuff, uint32_t size);
bool if_encrypt = false;
~packet(); ~packet();
}; };
//注册客户端管理
struct client_register{
// 客户端id
rng::rng64 client_id;
// 通信密钥
rng::rng128 key;
};
//带标签的二进制串管理结构 //带标签的二进制串管理结构
class raw_data{ class raw_data{
public: public:
@ -84,12 +120,13 @@ public:
//请求监听管理结构 //请求监听管理结构
struct request_listener{ struct request_listener{
void (*callback)(respond *); void (*callback)(respond *,void *args);
request *p_req; request *p_req;
uint32_t timeout; uint32_t timeout;
uint32_t clicks; uint32_t clicks;
raw_data trwd; raw_data trwd;
bool active; bool active;
void *args;
~request_listener(); ~request_listener();
}; };
@ -112,6 +149,9 @@ protected:
list<packet *> packets_out; list<packet *> packets_out;
struct server_info tsi; struct server_info tsi;
sqlite3 *psql; sqlite3 *psql;
// 服务器公私钥
public_key_class pkc;
private_key_class prc;
public: public:
// 服务器类的接收套接字对象与发送套接字对象 // 服务器类的接收套接字对象与发送套接字对象
SocketUDPServer socket; SocketUDPServer socket;
@ -142,6 +182,10 @@ public:
static bool CheckRawMsg(char *p_rdt, ssize_t size); static bool CheckRawMsg(char *p_rdt, ssize_t size);
// 处理一个已贴上标签的原始二进制串,获得其包含的信息 // 处理一个已贴上标签的原始二进制串,获得其包含的信息
static void ProcessSignedRawMsg(char *p_rdt, ssize_t size, raw_data &rdt); static void ProcessSignedRawMsg(char *p_rdt, ssize_t size, raw_data &rdt);
// 解码已加密的原始二进制串
void DecryptRSARawMsg(raw_data &rdt, private_key_class &pkc);
// 编码原始二进制串
void EncryptRSARawMsg(raw_data &rdt, public_key_class &pkc);
// 服务器守护线程 // 服务器守护线程
friend void *serverDeamon(void *psvr); friend void *serverDeamon(void *psvr);
// 处理RawData // 处理RawData
@ -165,9 +209,10 @@ class SQEServer:public Server{
protected: protected:
// 请求数据包 // 请求数据包
list<request *> req_list; list<request *> req_list;
// 服务器公私钥 // 注册客户端管理
public_key_class pkc; list<client_register *> client_lst;
private_key_class prc; // 加密端对端报文
list<encrypt_post *>post_lst;
public: public:
SQEServer(int port = 9048); SQEServer(int port = 9048);
void ProcessPacket(void); void ProcessPacket(void);
@ -176,6 +221,9 @@ public:
static void Request2Packet(packet &pkt, request &req); static void Request2Packet(packet &pkt, request &req);
static void Respond2Packet(packet &pkt, respond &res); static void Respond2Packet(packet &pkt, respond &res);
static void Packet2Respond(packet &pkt, respond &res); static void Packet2Respond(packet &pkt, respond &res);
static void Post2Packet(packet &pkt, encrypt_post &pst, rng::rng128 key);
static void Packet2Post(packet &pkt, encrypt_post &pst, rng::rng128 key);
}; };
class Client{ class Client{
@ -187,6 +235,8 @@ class Client{
uint32_t listen_port; uint32_t listen_port;
SocketUDPServer socket; SocketUDPServer socket;
SocketUDPClient send_socket; SocketUDPClient send_socket;
// 广场服务器通信公钥
public_key_class sqe_pbc;
public: public:
// 构造函数(send_port指的是发送的目标端口) // 构造函数(send_port指的是发送的目标端口)
Client(int port = 9050, string send_ip = "127.0.0.1",int send_port = 9049); Client(int port = 9050, string send_ip = "127.0.0.1",int send_port = 9049);
@ -195,7 +245,9 @@ public:
// 新的请求 // 新的请求
void NewRequest(request **ppreq,string send_ip,int send_port,string type, string data); void NewRequest(request **ppreq,string send_ip,int send_port,string type, string data);
// 新的请求监听 // 新的请求监听
void NewRequestListener(request *preq, int timeout, void (*callback)(respond *)); void NewRequestListener(request *preq, int timeout, void *args, void (*callback)(respond *, void *));
// 设置公钥
void SetPublicKey(public_key_class &t_pbc);
// 友元回复接受守护进程 // 友元回复接受守护进程
friend void *clientRespondDeamon(void *); friend void *clientRespondDeamon(void *);
}; };
@ -222,5 +274,7 @@ void setClientClock(Client *pclient,int clicks);
void *clientRequestDeamon(void *pvclt); void *clientRequestDeamon(void *pvclt);
//客户端回复接收守护线程 //客户端回复接收守护线程
void *clientRespondDeamon(void *pvclt); void *clientRespondDeamon(void *pvclt);
//客户端待机守护线程
void *clientWaitDeamon(void *pvclt);
#endif /* server_h */ #endif /* server_h */

572
src/aes.cpp Executable file
View File

@ -0,0 +1,572 @@
/*
This is an implementation of the AES algorithm, specifically ECB, CTR and CBC mode.
Block size can be chosen in aes.h - available choices are AES128, AES192, AES256.
The implementation is verified against the test vectors in:
National Institute of Standards and Technology Special Publication 800-38A 2001 ED
ECB-AES128
----------
plain-text:
6bc1bee22e409f96e93d7e117393172a
ae2d8a571e03ac9c9eb76fac45af8e51
30c81c46a35ce411e5fbc1191a0a52ef
f69f2445df4f9b17ad2b417be66c3710
key:
2b7e151628aed2a6abf7158809cf4f3c
resulting cipher
3ad77bb40d7a3660a89ecaf32466ef97
f5d3d58503b9699de785895a96fdbaaf
43b1cd7f598ece23881b00e3ed030688
7b0c785e27e8ad3f8223207104725dd4
NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0)
You should pad the end of the string with zeros if this is not the case.
For AES192/256 the key size is proportionally larger.
*/
/*****************************************************************************/
/* Includes: */
/*****************************************************************************/
#include <stdint.h>
#include <string.h> // CBC mode, for memset
#include "aes.h"
/*****************************************************************************/
/* Defines: */
/*****************************************************************************/
// The number of columns comprising a state in AES. This is a constant in AES. Value=4
#define Nb 4
#if defined(AES256) && (AES256 == 1)
#define Nk 8
#define Nr 14
#elif defined(AES192) && (AES192 == 1)
#define Nk 6
#define Nr 12
#else
#define Nk 4 // The number of 32 bit words in a key.
#define Nr 10 // The number of rounds in AES Cipher.
#endif
// jcallan@github points out that declaring Multiply as a function
// reduces code size considerably with the Keil ARM compiler.
// See this link for more information: https://github.com/kokke/tiny-AES-C/pull/3
#ifndef MULTIPLY_AS_A_FUNCTION
#define MULTIPLY_AS_A_FUNCTION 0
#endif
/*****************************************************************************/
/* Private variables: */
/*****************************************************************************/
// state - array holding the intermediate results during decryption.
typedef uint8_t state_t[4][4];
// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
// The numbers below can be computed dynamically trading ROM for RAM -
// This can be useful in (embedded) bootloader applications, where ROM is often limited.
static const uint8_t sbox[256] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
static const uint8_t rsbox[256] = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
// The round constant word array, Rcon[i], contains the values given by
// x to the power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
static const uint8_t Rcon[11] = {
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 };
/*
* Jordan Goulder points out in PR #12 (https://github.com/kokke/tiny-AES-C/pull/12),
* that you can remove most of the elements in the Rcon array, because they are unused.
*
* From Wikipedia's article on the Rijndael key schedule @ https://en.wikipedia.org/wiki/Rijndael_key_schedule#Rcon
*
* "Only the first some of these constants are actually used up to rcon[10] for AES-128 (as 11 round keys are needed),
* up to rcon[8] for AES-192, up to rcon[7] for AES-256. rcon[0] is not used in AES algorithm."
*/
/*****************************************************************************/
/* Private functions: */
/*****************************************************************************/
/*
static uint8_t getSBoxValue(uint8_t num)
{
return sbox[num];
}
*/
#define getSBoxValue(num) (sbox[(num)])
/*
static uint8_t getSBoxInvert(uint8_t num)
{
return rsbox[num];
}
*/
#define getSBoxInvert(num) (rsbox[(num)])
// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key)
{
unsigned i, j, k;
uint8_t tempa[4]; // Used for the column/row operations
// The first round key is the key itself.
for (i = 0; i < Nk; ++i)
{
RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
}
// All other round keys are found from the previous round keys.
for (i = Nk; i < Nb * (Nr + 1); ++i)
{
{
k = (i - 1) * 4;
tempa[0]=RoundKey[k + 0];
tempa[1]=RoundKey[k + 1];
tempa[2]=RoundKey[k + 2];
tempa[3]=RoundKey[k + 3];
}
if (i % Nk == 0)
{
// This function shifts the 4 bytes in a word to the left once.
// [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
// Function RotWord()
{
const uint8_t u8tmp = tempa[0];
tempa[0] = tempa[1];
tempa[1] = tempa[2];
tempa[2] = tempa[3];
tempa[3] = u8tmp;
}
// SubWord() is a function that takes a four-byte input word and
// applies the S-box to each of the four bytes to produce an output word.
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
tempa[0] = tempa[0] ^ Rcon[i/Nk];
}
#if defined(AES256) && (AES256 == 1)
if (i % Nk == 4)
{
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
}
#endif
j = i * 4; k=(i - Nk) * 4;
RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0];
RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1];
RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2];
RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3];
}
}
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key)
{
KeyExpansion(ctx->RoundKey, key);
}
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv)
{
KeyExpansion(ctx->RoundKey, key);
memcpy (ctx->Iv, iv, AES_BLOCKLEN);
}
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv)
{
memcpy (ctx->Iv, iv, AES_BLOCKLEN);
}
#endif
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
static void AddRoundKey(uint8_t round,state_t* state,uint8_t* RoundKey)
{
uint8_t i,j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j];
}
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void SubBytes(state_t* state)
{
uint8_t i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxValue((*state)[j][i]);
}
}
}
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
static void ShiftRows(state_t* state)
{
uint8_t temp;
// Rotate first row 1 columns to left
temp = (*state)[0][1];
(*state)[0][1] = (*state)[1][1];
(*state)[1][1] = (*state)[2][1];
(*state)[2][1] = (*state)[3][1];
(*state)[3][1] = temp;
// Rotate second row 2 columns to left
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to left
temp = (*state)[0][3];
(*state)[0][3] = (*state)[3][3];
(*state)[3][3] = (*state)[2][3];
(*state)[2][3] = (*state)[1][3];
(*state)[1][3] = temp;
}
static uint8_t xtime(uint8_t x)
{
return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
}
// MixColumns function mixes the columns of the state matrix
static void MixColumns(state_t* state)
{
uint8_t i;
uint8_t Tmp, Tm, t;
for (i = 0; i < 4; ++i)
{
t = (*state)[i][0];
Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ;
Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ;
Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ;
Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ;
}
}
// Multiply is used to multiply numbers in the field GF(2^8)
// Note: The last call to xtime() is unneeded, but often ends up generating a smaller binary
// The compiler seems to be able to vectorize the operation better this way.
// See https://github.com/kokke/tiny-AES-c/pull/34
#if MULTIPLY_AS_A_FUNCTION
static uint8_t Multiply(uint8_t x, uint8_t y)
{
return (((y & 1) * x) ^
((y>>1 & 1) * xtime(x)) ^
((y>>2 & 1) * xtime(xtime(x))) ^
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); /* this last call to xtime() can be omitted */
}
#else
#define Multiply(x, y) \
( ((y & 1) * x) ^ \
((y>>1 & 1) * xtime(x)) ^ \
((y>>2 & 1) * xtime(xtime(x))) ^ \
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \
((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \
#endif
#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
static void InvMixColumns(state_t* state)
{
int i;
uint8_t a, b, c, d;
for (i = 0; i < 4; ++i)
{
a = (*state)[i][0];
b = (*state)[i][1];
c = (*state)[i][2];
d = (*state)[i][3];
(*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
(*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
(*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
(*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void InvSubBytes(state_t* state)
{
uint8_t i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxInvert((*state)[j][i]);
}
}
}
static void InvShiftRows(state_t* state)
{
uint8_t temp;
// Rotate first row 1 columns to right
temp = (*state)[3][1];
(*state)[3][1] = (*state)[2][1];
(*state)[2][1] = (*state)[1][1];
(*state)[1][1] = (*state)[0][1];
(*state)[0][1] = temp;
// Rotate second row 2 columns to right
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to right
temp = (*state)[0][3];
(*state)[0][3] = (*state)[1][3];
(*state)[1][3] = (*state)[2][3];
(*state)[2][3] = (*state)[3][3];
(*state)[3][3] = temp;
}
#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
// Cipher is the main function that encrypts the PlainText.
static void Cipher(state_t* state, uint8_t* RoundKey)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(0, state, RoundKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for (round = 1; round < Nr; ++round)
{
SubBytes(state);
ShiftRows(state);
MixColumns(state);
AddRoundKey(round, state, RoundKey);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
SubBytes(state);
ShiftRows(state);
AddRoundKey(Nr, state, RoundKey);
}
#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
static void InvCipher(state_t* state,uint8_t* RoundKey)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(Nr, state, RoundKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for (round = (Nr - 1); round > 0; --round)
{
InvShiftRows(state);
InvSubBytes(state);
AddRoundKey(round, state, RoundKey);
InvMixColumns(state);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
InvShiftRows(state);
InvSubBytes(state);
AddRoundKey(0, state, RoundKey);
}
#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
/*****************************************************************************/
/* Public functions: */
/*****************************************************************************/
#if defined(ECB) && (ECB == 1)
void AES_ECB_encrypt(struct AES_ctx *ctx, uint8_t* buf)
{
// The next function call encrypts the PlainText with the Key using AES algorithm.
Cipher((state_t*)buf, ctx->RoundKey);
}
void AES_ECB_decrypt(struct AES_ctx* ctx, uint8_t* buf)
{
// The next function call decrypts the PlainText with the Key using AES algorithm.
InvCipher((state_t*)buf, ctx->RoundKey);
}
#endif // #if defined(ECB) && (ECB == 1)
#if defined(CBC) && (CBC == 1)
static void XorWithIv(uint8_t* buf, uint8_t* Iv)
{
uint8_t i;
for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size
{
buf[i] ^= Iv[i];
}
}
void AES_CBC_encrypt_buffer(struct AES_ctx *ctx,uint8_t* buf, uint32_t length)
{
uintptr_t i;
uint8_t *Iv = ctx->Iv;
for (i = 0; i < length; i += AES_BLOCKLEN)
{
XorWithIv(buf, Iv);
Cipher((state_t*)buf, ctx->RoundKey);
Iv = buf;
buf += AES_BLOCKLEN;
//printf("Step %d - %d", i/16, i);
}
/* store Iv in ctx for next call */
memcpy(ctx->Iv, Iv, AES_BLOCKLEN);
}
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
{
uintptr_t i;
uint8_t storeNextIv[AES_BLOCKLEN];
for (i = 0; i < length; i += AES_BLOCKLEN)
{
memcpy(storeNextIv, buf, AES_BLOCKLEN);
InvCipher((state_t*)buf, ctx->RoundKey);
XorWithIv(buf, ctx->Iv);
memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN);
buf += AES_BLOCKLEN;
}
}
#endif // #if defined(CBC) && (CBC == 1)
#if defined(CTR) && (CTR == 1)
/* Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
{
uint8_t buffer[AES_BLOCKLEN];
unsigned i;
int bi;
for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi)
{
if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */
{
memcpy(buffer, ctx->Iv, AES_BLOCKLEN);
Cipher((state_t*)buffer,ctx->RoundKey);
/* Increment Iv and handle overflow */
for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi)
{
/* inc will owerflow */
if (ctx->Iv[bi] == 255)
{
ctx->Iv[bi] = 0;
continue;
}
ctx->Iv[bi] += 1;
break;
}
bi = 0;
}
buf[i] = (buf[i] ^ buffer[bi]);
}
}
#endif // #if defined(CTR) && (CTR == 1)

View File

@ -34,17 +34,18 @@ void *clientRespondDeamon(void *pvclt){
do{ do{
tlen = pclient->socket.RecvRAW(&str,taddr); tlen = pclient->socket.RecvRAW(&str,taddr);
if(tlen > 0){ if(tlen > 0){
// 记录有效数据包 // 记录有效数据包
if(Server::CheckRawMsg(str, tlen)){ if(Server::CheckRawMsg(str, tlen)){
raw_data *ptrdt = new raw_data(); raw_data *ptrdt = new raw_data();
Server::ProcessSignedRawMsg(str, tlen, *ptrdt); Server::ProcessSignedRawMsg(str, tlen, *ptrdt);
ptrdt->address = *(struct sockaddr_in *)taddr.RawObj(); ptrdt->address = *(struct sockaddr_in *)taddr.RawObj();
if (memcmp(&ptrdt->info,"SPKT",sizeof(uint32_t))) { if (!memcmp(&ptrdt->info,"SPKT",sizeof(uint32_t))) {
packet npkt; packet npkt;
Server::Rawdata2Packet(npkt, *ptrdt); Server::Rawdata2Packet(npkt, *ptrdt);
if(npkt.type == RESPOND_TYPE){ if(npkt.type == RESPOND_TYPE){
printf("Get Respond.\n");
respond *pnres = new respond(); respond *pnres = new respond();
SQEServer::Packet2Respond(npkt, *pnres); SQEServer::Packet2Respond(npkt, *pnres);
// 加锁 // 加锁
@ -77,12 +78,9 @@ void Client::ProcessRequestListener(void){
if(!lreq->active) continue; if(!lreq->active) continue;
// 检查回复号与请求号是否相同 // 检查回复号与请求号是否相同
if(!memcmp(&lreq->p_req->r_id,&pres->r_id,sizeof(rng::rng64))){ if(!memcmp(&lreq->p_req->r_id,&pres->r_id,sizeof(rng::rng64))){
// 检查是否为源地址发来的回复 // 调用回调函数
if(!memcmp(lreq->p_req->t_addr.Obj(),pres->t_addr.Obj(),sizeof(sockaddr_in))){ lreq->callback(pres,lreq->args);
// 调用回调函数 lreq->active = false;
lreq->callback(pres);
lreq->active = false;
}
} }
} }
delete pres; delete pres;
@ -104,9 +102,9 @@ void Client::ProcessRequestListener(void){
} }
} }
else{ else{
lreq->callback(NULL,lreq->args);
delete lreq; delete lreq;
lreq->active = false; lreq->active = false;
printf("Request TimeOut.\n");
} }
} }
// 请求列表 // 请求列表
@ -147,7 +145,7 @@ void Client::NewRequest(request **ppreq,string send_ip,int send_port,string type
*ppreq = pnreq; *ppreq = pnreq;
} }
void Client::NewRequestListener(request *preq, int timeout, void (*callback)(respond *)){ void Client::NewRequestListener(request *preq, int timeout, void *args, void (*callback)(respond *,void *)){
request_listener *pnrl = new request_listener(); request_listener *pnrl = new request_listener();
packet npkt; packet npkt;
pnrl->active = true; pnrl->active = true;
@ -155,6 +153,7 @@ void Client::NewRequestListener(request *preq, int timeout, void (*callback)(res
pnrl->timeout = timeout; pnrl->timeout = timeout;
pnrl->clicks = 0; pnrl->clicks = 0;
pnrl->p_req = preq; pnrl->p_req = preq;
pnrl->args = args;
SQEServer::Request2Packet(npkt, *preq); SQEServer::Request2Packet(npkt, *preq);
Server::Packet2Rawdata(npkt, pnrl->trwd); Server::Packet2Rawdata(npkt, pnrl->trwd);
Server::SignedRawdata(&pnrl->trwd,"SPKT"); Server::SignedRawdata(&pnrl->trwd,"SPKT");
@ -167,3 +166,7 @@ request_listener::~request_listener(){
Server::freeRawdataServer(trwd); Server::freeRawdataServer(trwd);
delete p_req; delete p_req;
} }
void Client::SetPublicKey(public_key_class &t_pbc){
sqe_pbc = t_pbc;
}

353
src/controller.cpp Normal file
View File

@ -0,0 +1,353 @@
//
// controller.cpp
// Net
//
// Created by 胡一兵 on 2019/2/8.
// Copyright © 2019年 Bakantu. All rights reserved.
//
#include "instruct.h"
extern string PRIME_SOURCE_FILE;
//线程阻塞开关
int if_wait = 1;
int init(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
sqlite3_open("info.db", &psql);
const char *pzTail;
if(targets[0] == "server"){
sql::table_create(psql, "server_info", {
{"sqes_public","NONE"},
{"sqes_private","NONE"},
{"key_sha1","TEXT"}
});
sql::insert_info(psql, &psqlsmt, "server_info", {
{"sqes_public","?1"},
{"sqes_private","?2"},
{"key_sha1","?3"},
});
struct public_key_class npbkc;
struct private_key_class nprkc;
rsa_gen_keys(&npbkc, &nprkc, PRIME_SOURCE_FILE);
sqlite3_bind_blob(psqlsmt, 1, &npbkc, sizeof(public_key_class), SQLITE_TRANSIENT);
sqlite3_bind_blob(psqlsmt, 2, &nprkc, sizeof(private_key_class), SQLITE_TRANSIENT);
if(targets[1].size() < 6) error::printWarning("Key is too weak.");
string sha1_hex;
SHA1_Easy(sha1_hex, targets[1], targets.size());
sqlite3_bind_text(psqlsmt, 3, sha1_hex.data(), -1, SQLITE_TRANSIENT);
if(sqlite3_step(psqlsmt) != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
error::printSuccess("Succeed.");
sqlite3_close(psql);
return 0;
}
else{
try {
sql::table_create(psql, "client_info", {
{"name","TEXT"},
{"tag","TEXT"},
{"admin_key_sha1","TEXT"},
{"msqes_ip","TEXT"},
{"msqes_port","INT"},
{"msqes_key","TEXT"},
{"msqes_rsa_public","NONE"},
});
sql::table_create(psql, "sqes_info", {
{"sqes_ip","TEXT PRIMARY KEY"},
{"sqes_port","INT"},
{"sqes_key","TEXT"},
{"rsa_public","NONE"},
});
} catch (const char *error_info) {
if(!strcmp(error_info, "fail to create table")){
if(!config_search(configs, "-f")){
printf("\033[33mWarning: Have Already run init process.Try configure -f to continue.\n\033[0m");
return 0;
}
else{
string sql_quote = "DELETE FROM client_info;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
int rtn = sqlite3_step(psqlsmt);
if(rtn == SQLITE_DONE){
}
else{
const char *error = sqlite3_errmsg(psql);
int errorcode = sqlite3_extended_errcode(psql);
printf("\033[31mSQL Error: [%d]%s\n\033[0m",errorcode,error);
throw error;
}
sqlite3_finalize(psqlsmt);
}
}
}
}
sql::insert_info(psql, &psqlsmt, "client_info", {
{"name","?1"},
{"tag","?2"}
});
if(setting_file::if_name_illegal(targets[0]));
else{
error::printError("Args(name) abnormal.");
}
if(setting_file::if_name_illegal(targets[1]));
else{
error::printError("Args(tag) abnormal.");
}
sqlite3_bind_text(psqlsmt, 1, targets[0].data(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(psqlsmt, 2, targets[1].data(), -1, SQLITE_TRANSIENT);
int rtn = sqlite3_step(psqlsmt);
if(rtn == SQLITE_DONE){
}
else throw "sql writes error";
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return 0;
}
int set(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
if(targets.size() < 2){
error::printError("Args error.");
return -1;
}
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
const char *pzTail;
if(sqlite3_open("info.db", &psql) == SQLITE_ERROR){
sql::printError(psql);
return -1;
}
string sql_quote = "SELECT count(*) FROM sqlite_master WHERE name = 'client_info';";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_step(psqlsmt);
int if_find = sqlite3_column_int(psqlsmt, 0);
if(if_find);
else{
error::printError("Couldn't do set before init process.");
return -1;
}
sqlite3_finalize(psqlsmt);
if(targets[0] == "square"){
sql_quote = "UPDATE client_info SET msqes_ip = ?1, msqes_port = ?2 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
if(!Addr::checkValidIP(targets[1])){
error::printError("Args(ipaddr) is abnomal.");
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return -1;
}
sqlite3_bind_text(psqlsmt, 1, targets[1].data(), -1, SQLITE_TRANSIENT);
stringstream ss;
ss<<targets[2];
int port;
ss>>port;
if(port > 0 && port <= 65535);
else{
error::printError("Args(port) is abnomal.");
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return -1;
}
sqlite3_bind_int(psqlsmt, 2, port);
int rtn = sqlite3_step(psqlsmt);
if(rtn != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else if (targets[0] == "key"){
if(targets[1] == "admin"){
string hexresult;
SHA1_Easy(hexresult, targets[2], targets[2].size());
if(targets[1].size() < 6){
error::printWarning("Key is too weak.");
}
sql_quote = "UPDATE client_info SET admin_key_sha1 = ?1 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_bind_text(psqlsmt, 1, hexresult.data(), -1, SQLITE_TRANSIENT);
if(sqlite3_step(psqlsmt) != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else if(targets[1] == "square"){
sql_quote = "UPDATE client_info SET msqes_key = ?1 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_bind_text(psqlsmt, 1, targets[2].data(), -1, SQLITE_TRANSIENT);
if(sqlite3_step(psqlsmt) != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else{
error::printError("Args(type) is abnormal.");
return -1;
}
}
error::printSuccess("Succeed.");
sqlite3_close(psql);
return 0;
}
int server(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
initClock();
setThreadsClock();
if(targets.size() == 0){
Server nsvr;
setServerClock(&nsvr, 3);
}
else{
if(targets[0] == "square"){
SQEServer nsvr;
setServerClockForSquare(&nsvr, 3);
}
}
while(1) usleep(10000);
return 0;
}
int update(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
try {
Proj nproj(targets[0], "netc.proj");
nproj.UpdateProcess();
} catch (const char *err_info) {
printf("\033[31mError: %s\n\033[0m",err_info);
return -1;
}
printf("\033[32mSucceed.\n\033[0m");
return 0;
}
int construct(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
try{
// 读取工程文件
Proj nproj(targets[0],"netc.proj");
// 检查数据库文件是否存在
string tdb_path = targets[0] + "/dbs/" + nproj.GetName() +".db";
#ifdef DEBUG
printf("Search Database %s\n",tdb_path.data());
#endif
if(!access(tdb_path.data(), R_OK)){
// 设置为强制执行
if(config_search(configs, "-f")){
if(remove(tdb_path.data()) == -1){
printf("\033[31m");
printf("Error: Process meet unknown error.\n");
printf("\033[0m");
return -1;
}
}
else{
printf("\033[33m");
printf("Warning:Database has already existed. Use -f to continue process.\n");
printf("\033[0m");
return 0;
}
}
// 总体信息检查
nproj.GeneralCheckInfo();
// 收集信息
nproj.SearchInfo();
// 构建入口函数索引
nproj.BuildFuncIndex();
// 检查cpt文件信息
nproj.CheckCptInfo();
// 编译涉及源文件
nproj.CompileUsedSrcFiles();
// 检查入口函数信息
nproj.CheckFuncInfo();
// 建立数据库
nproj.DBProcess();
}
catch(char const *error_info){
printf("\033[31mError:");
printf("%s\033[0m\n",error_info);
return -1;
}
printf("\033[32mSucceed.\n\033[0m");
return 0;
}
int client(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
const char *pzTail;
if(sqlite3_open("info.db", &psql) == SQLITE_ERROR){
sql::printError(psql);
return -1;
}
// 初始化时钟
initClock();
setThreadsClock();
// 建立客户端
Client nclt(9050);
setClientClock(&nclt, 3);
request *preq;
// 获得主广场服务器的通信公钥
string sql_quote = "select count(*) from client_info where rowid = 1 and msqes_rsa_public is null;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_step(psqlsmt);
int if_null = sqlite3_column_int(psqlsmt, 0);
sqlite3_finalize(psqlsmt);
// 获得主广场服务器的ip地址及其通信端口
string msqe_ip;
int msqe_port;
sql_quote = "select msqes_ip,msqes_port from client_info where rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_step(psqlsmt);
msqe_ip = (const char *)sqlite3_column_text(psqlsmt, 0);
msqe_port = sqlite3_column_int(psqlsmt, 1);
sqlite3_finalize(psqlsmt);
// 如果本地没有主广场服务器的公钥
if(if_null){
nclt.NewRequest(&preq, msqe_ip, msqe_port, "client-square request", "request for public key");
nclt.NewRequestListener(preq, 30, psql, getSQEPublicKey);
while (if_wait == 1) {
sleep(10);
}
if(!if_wait){
#ifdef DEBUG
printf("Succeed In Getting Rsa Public Key From SQEServer.\n");
#endif
}
else{
#ifdef DEBUG
printf("Error In Getting Rsa Public Key From SQEServer.\n");
#endif
throw "connection error";
return -1;
}
}
// 获得与广场服务器的通信的公钥
sql_quote = "select msqes_rsa_public from client_info where rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_step(psqlsmt);
public_key_class *ppbc = (public_key_class *)sqlite3_column_blob(psqlsmt, 0);
nclt.SetPublicKey(*ppbc);
sqlite3_finalize(psqlsmt);
rng::rng128 key
// 已获得主广场服务器的密钥,进行启动客户端守护进程前的准备工作
nclt.NewRequest(&preq, msqe_ip, msqe_port, "client-register request", "");
nclt.NewRequestListener(preq, 30, psql, getSQEPublicKey);
return 0;
}

View File

@ -8,37 +8,6 @@
#include "instruct.h" #include "instruct.h"
extern string PRIME_SOURCE_FILE;
int update(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int construct(string instruct,vector<string> &config, vector<string> &lconfig, vector<string> &target);
int server(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int client(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int init(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
int set(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets);
struct instructions{
int (*unpack)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*construct)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*update)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*server)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*client)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*set)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
int (*init)(string, vector<string> &, vector<string> &, vector<string> &) = NULL;
};
namespace error {
void printError(string error_info){
printf("\033[31mError: %s\n\033[0m",error_info.data());
}
void printWarning(string warning_info){
printf("\033[33mWarning: %s\n\033[0m",warning_info.data());
}
void printSuccess(string succes_info){
printf("\033[32m%s\n\033[0m",succes_info.data());
}
}
int main(int argc, const char *argv[]){ int main(int argc, const char *argv[]){
// 命令 // 命令
string instruct; string instruct;
@ -109,302 +78,5 @@ int main(int argc, const char *argv[]){
return 0; return 0;
} }
bool config_search(vector<string> &configs,string tfg){
for(auto config : configs){
if(config == tfg) return true;
}
return false;
}
int init(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
sqlite3_open("info.db", &psql);
const char *pzTail;
if(targets[0] == "server"){
sql::table_create(psql, "server_info", {
{"sqes_public","NONE"},
{"sqes_private","NONE"},
{"key_sha1","TEXT"}
});
sql::insert_info(psql, &psqlsmt, "server_info", {
{"sqes_public","?1"},
{"sqes_private","?2"},
{"key_sha1","?3"},
});
struct public_key_class npbkc;
struct private_key_class nprkc;
rsa_gen_keys(&npbkc, &nprkc, PRIME_SOURCE_FILE);
sqlite3_bind_blob(psqlsmt, 1, &npbkc, sizeof(public_key_class), SQLITE_TRANSIENT);
sqlite3_bind_blob(psqlsmt, 2, &nprkc, sizeof(private_key_class), SQLITE_TRANSIENT);
if(targets[1].size() < 6) error::printWarning("Key is too weak.");
string sha1_hex;
SHA1_Easy(sha1_hex, targets[1], targets.size());
sqlite3_bind_text(psqlsmt, 3, sha1_hex.data(), -1, SQLITE_TRANSIENT);
if(sqlite3_step(psqlsmt) != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
error::printSuccess("Succeed.");
sqlite3_close(psql);
return 0;
}
else{
try {
sql::table_create(psql, "client_info", {
{"name","TEXT"},
{"tag","TEXT"},
{"admin_key_sha1","TEXT"},
{"msqes_ip","TEXT"},
{"msqes_port","INT"},
{"msqes_key","TEXT"},
{"msqes_rsa_public","TEXT"},
});
sql::table_create(psql, "sqes_info", {
{"sqes_ip","TEXT PRIMARY KEY"},
{"sqes_port","INT"},
{"sqes_key","TEXT"},
{"rsa_public","TEXT"},
});
} catch (const char *error_info) {
if(!strcmp(error_info, "fail to create table")){
if(!config_search(configs, "-f")){
printf("\033[33mWarning: Have Already run init process.Try configure -f to continue.\n\033[0m");
return 0;
}
else{
string sql_quote = "DELETE FROM client_info;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
int rtn = sqlite3_step(psqlsmt);
if(rtn == SQLITE_DONE){
}
else{
const char *error = sqlite3_errmsg(psql);
int errorcode = sqlite3_extended_errcode(psql);
printf("\033[31mSQL Error: [%d]%s\n\033[0m",errorcode,error);
throw error;
}
sqlite3_finalize(psqlsmt);
}
}
}
}
sql::insert_info(psql, &psqlsmt, "client_info", {
{"name","?1"},
{"tag","?2"}
});
if(setting_file::if_name_illegal(targets[0]));
else{
error::printError("Args(name) abnormal.");
}
if(setting_file::if_name_illegal(targets[1]));
else{
error::printError("Args(tag) abnormal.");
}
sqlite3_bind_text(psqlsmt, 1, targets[0].data(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(psqlsmt, 2, targets[1].data(), -1, SQLITE_TRANSIENT);
int rtn = sqlite3_step(psqlsmt);
if(rtn == SQLITE_DONE){
}
else throw "sql writes error";
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return 0;
}
int set(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
if(targets.size() < 2){
error::printError("Args error.");
return -1;
}
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
const char *pzTail;
if(sqlite3_open("info.db", &psql) == SQLITE_ERROR){
sql::printError(psql);
}
string sql_quote = "SELECT count(*) FROM sqlite_master WHERE name = 'client_info';";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_step(psqlsmt);
int if_find = sqlite3_column_int(psqlsmt, 0);
if(if_find);
else{
error::printError("Couldn't do set before init process.");
return -1;
}
sqlite3_finalize(psqlsmt);
if(targets[0] == "square"){
sql_quote = "UPDATE client_info SET msqes_ip = ?1, msqes_port = ?2 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
if(!Addr::checkValidIP(targets[1])){
error::printError("Args(ipaddr) is abnomal.");
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return -1;
}
sqlite3_bind_text(psqlsmt, 1, targets[1].data(), -1, SQLITE_TRANSIENT);
stringstream ss;
ss<<targets[2];
int port;
ss>>port;
if(port > 0 && port <= 65535);
else{
error::printError("Args(port) is abnomal.");
sqlite3_finalize(psqlsmt);
sqlite3_close(psql);
return -1;
}
sqlite3_bind_int(psqlsmt, 2, port);
int rtn = sqlite3_step(psqlsmt);
if(rtn != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else if (targets[0] == "key"){
if(targets[1] == "admin"){
string hexresult;
SHA1_Easy(hexresult, targets[2], targets[2].size());
if(targets[1].size() < 6){
error::printWarning("Key is too weak.");
}
sql_quote = "UPDATE client_info SET admin_key_sha1 = ?1 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_bind_text(psqlsmt, 1, hexresult.data(), -1, SQLITE_TRANSIENT);
if(sqlite3_step(psqlsmt) != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else if(targets[1] == "square"){
sql_quote = "UPDATE client_info SET msqes_key = ?1 WHERE rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_bind_text(psqlsmt, 1, targets[2].data(), -1, SQLITE_TRANSIENT);
if(sqlite3_step(psqlsmt) != SQLITE_DONE){
sql::printError(psql);
}
sqlite3_finalize(psqlsmt);
}
else{
error::printError("Args(type) is abnormal.");
return -1;
}
}
error::printSuccess("Succeed.");
sqlite3_close(psql);
return 0;
}
int server(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
sqlite3 *psql;
sqlite3_stmt *psqlsmt;
const char *pzTail;
initClock();
setThreadsClock();
if(targets.size() == 0){
Server nsvr;
setServerClock(&nsvr, 3);
}
else{
if(targets[0] == "square"){
SQEServer nsvr;
setServerClockForSquare(&nsvr, 3);
}
}
while(1) usleep(10000);
return 0;
}
int update(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
try {
Proj nproj(targets[0], "netc.proj");
nproj.UpdateProcess();
} catch (const char *err_info) {
printf("\033[31mError: %s\n\033[0m",err_info);
return -1;
}
printf("\033[32mSucceed.\n\033[0m");
return 0;
}
int construct(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
try{
// 读取工程文件
Proj nproj(targets[0],"netc.proj");
// 检查数据库文件是否存在
string tdb_path = targets[0] + "/dbs/" + nproj.GetName() +".db";
#ifdef DEBUG
printf("Search Database %s\n",tdb_path.data());
#endif
if(!access(tdb_path.data(), R_OK)){
// 设置为强制执行
if(config_search(configs, "-f")){
if(remove(tdb_path.data()) == -1){
printf("\033[31m");
printf("Error: Process meet unknown error.\n");
printf("\033[0m");
return -1;
}
}
else{
printf("\033[33m");
printf("Warning:Database has already existed. Use -f to continue process.\n");
printf("\033[0m");
return 0;
}
}
// 总体信息检查
nproj.GeneralCheckInfo();
// 收集信息
nproj.SearchInfo();
// 构建入口函数索引
nproj.BuildFuncIndex();
// 检查cpt文件信息
nproj.CheckCptInfo();
// 编译涉及源文件
nproj.CompileUsedSrcFiles();
// 检查入口函数信息
nproj.CheckFuncInfo();
// 建立数据库
nproj.DBProcess();
}
catch(char const *error_info){
printf("\033[31mError:");
printf("%s\033[0m\n",error_info);
return -1;
}
printf("\033[32mSucceed.\n\033[0m");
return 0;
}
int client(string instruct, vector<string> &configs, vector<string> &lconfigs, vector<string> &targets){
return 0;
}
void wiki_cpart(void){
CPart ncp("./PCS","./Libs","a.cpp","A");
void *a = main_pool.bv_malloc<double>(2.0);
void *b = main_pool.bv_malloc<double>(3.5);
void *c = main_pool.bv_malloc<int>(5);
ncp.AddCPArgsIn(a);
ncp.AddCPArgsIn(b);
ncp.AddCPArgsIn(c);
ncp.Run();
void *oa = ncp.args_out[0];
printf("%d",*((int *)oa));
main_pool.b_free(a);
main_pool.b_free(b);
main_pool.b_free(c);
}

48
src/model.cpp Normal file
View File

@ -0,0 +1,48 @@
//
// model.cpp
// Net
//
// Created by 胡一兵 on 2019/2/8.
// Copyright © 2019年 Bakantu. All rights reserved.
//
#include "instruct.h"
extern int if_wait;
namespace error {
void printError(string error_info){
printf("\033[31mError: %s\n\033[0m",error_info.data());
}
void printWarning(string warning_info){
printf("\033[33mWarning: %s\n\033[0m",warning_info.data());
}
void printSuccess(string succes_info){
printf("\033[32m%s\n\033[0m",succes_info.data());
}
}
bool config_search(vector<string> &configs,string tfg){
for(auto config : configs){
if(config == tfg) return true;
}
return false;
}
void getSQEPublicKey(respond *pres,void *args){
if(pres != nullptr){
public_key_class *npbc = (public_key_class *)pres->buff;
sqlite3 *psql = (sqlite3 *)args;
sqlite3_stmt *psqlsmt;
const char *pzTail;
string sql_quote = "update client_info set msqes_rsa_public = ?1 where rowid = 1;";
sqlite3_prepare(psql, sql_quote.data(), -1, &psqlsmt, &pzTail);
sqlite3_bind_blob(psqlsmt, 1, npbc, sizeof(public_key_class), SQLITE_TRANSIENT);
sqlite3_step(psqlsmt);
sqlite3_finalize(psqlsmt);
if_wait = 0;
}
else if_wait = -1;
}

View File

@ -257,6 +257,20 @@ void Server::ProcessSignedRawMsg(char *p_rdt, ssize_t size, raw_data &rdt){
rdt.size = size-3*sizeof(uint32_t); rdt.size = size-3*sizeof(uint32_t);
} }
void Server::DecryptRSARawMsg(raw_data &rdt, private_key_class &pkc){
Byte *p_data = rdt.data;
rdt.data = rsa_decrypt((const long long *) p_data, rdt.size, &pkc);
rdt.size /= 8;
free(p_data);
}
void Server::EncryptRSARawMsg(raw_data &rdt, public_key_class &pkc){
Byte *p_data = rdt.data;
rdt.data = (Byte *) rsa_encrypt((const char *)p_data, rdt.size, &pkc);
rdt.size *= 8;
free(p_data);
}
void *serverDeamon(void *pvcti){ void *serverDeamon(void *pvcti){
clock_thread_info *pcti = (clock_thread_info *) pvcti; clock_thread_info *pcti = (clock_thread_info *) pvcti;
Server *psvr = (Server *) pcti->args; Server *psvr = (Server *) pcti->args;
@ -278,7 +292,6 @@ void *serverDeamon(void *pvcti){
raw_data *ptrdt = new raw_data(); raw_data *ptrdt = new raw_data();
Server::ProcessSignedRawMsg(str, tlen, *ptrdt); Server::ProcessSignedRawMsg(str, tlen, *ptrdt);
ptrdt->address = *(struct sockaddr_in *)taddr.RawObj(); ptrdt->address = *(struct sockaddr_in *)taddr.RawObj();
printf("[First]: %d\n",taddr.Obj()->);
psvr->rawdata_in.push_back(ptrdt); psvr->rawdata_in.push_back(ptrdt);
} }
@ -338,6 +351,21 @@ void Server::ProcessRawData(void){
// 加锁 // 加锁
if (pthread_mutex_lock(&mutex_rp) != 0) throw "lock error"; if (pthread_mutex_lock(&mutex_rp) != 0) throw "lock error";
packet *pnpkt = new packet(); packet *pnpkt = new packet();
// 标记未加密
pnpkt->if_encrypt = false;
Rawdata2Packet(*pnpkt,*prdt);
pnpkt->address = prdt->address;
packets_in.push_back(pnpkt);
// 解锁
pthread_mutex_unlock(&mutex_rp);
}
// 编码加密包
else if(!memcmp(&prdt->info, "RPKT", sizeof(uint32_t))){
if (pthread_mutex_lock(&mutex_rp) != 0) throw "lock error";
packet *pnpkt = new packet();
// 标记数据已被加密
pnpkt->if_encrypt = true;
Server::DecryptRSARawMsg(*prdt, prc);
Rawdata2Packet(*pnpkt,*prdt); Rawdata2Packet(*pnpkt,*prdt);
pnpkt->address = prdt->address; pnpkt->address = prdt->address;
packets_in.push_back(pnpkt); packets_in.push_back(pnpkt);
@ -410,7 +438,7 @@ SQEServer::SQEServer(int port):Server(port){
void SQEServer::Packet2Request(packet &pkt, request &req){ void SQEServer::Packet2Request(packet &pkt, request &req){
if(pkt.type == REQUSET_TYPE){ if(pkt.type == REQUSET_TYPE){
req.r_id = *(uint32_t *)pkt.buffs[0].second; req.r_id = *(rng::rng64 *)pkt.buffs[0].second;
req.type = (const char *)pkt.buffs[1].second; req.type = (const char *)pkt.buffs[1].second;
req.data = (const char *)pkt.buffs[2].second; req.data = (const char *)pkt.buffs[2].second;
req.t_addr = Addr(*(struct sockaddr_in *)pkt.buffs[3].second); req.t_addr = Addr(*(struct sockaddr_in *)pkt.buffs[3].second);
@ -422,7 +450,7 @@ void SQEServer::Request2Packet(packet &pkt, request &req){
pkt.address = *req.t_addr.Obj(); pkt.address = *req.t_addr.Obj();
// 请求的类型标识号 // 请求的类型标识号
pkt.type = REQUSET_TYPE; pkt.type = REQUSET_TYPE;
pkt.AddBuff((void *)&req.r_id, sizeof(req.r_id)); pkt.AddBuff((void *)&req.r_id, sizeof(rng::rng64));
pkt.AddBuff((void *)req.type.data(), (uint32_t)req.type.size()); pkt.AddBuff((void *)req.type.data(), (uint32_t)req.type.size());
pkt.AddBuff((void *)req.data.data(), (uint32_t)req.data.size()); pkt.AddBuff((void *)req.data.data(), (uint32_t)req.data.size());
pkt.AddBuff((void *)req.t_addr.Obj(), sizeof(struct sockaddr_in)); pkt.AddBuff((void *)req.t_addr.Obj(), sizeof(struct sockaddr_in));
@ -468,16 +496,18 @@ void SQEServer::ProcessRequset(void){
} }
void SQEServer::Packet2Respond(packet &pkt, respond &res){ void SQEServer::Packet2Respond(packet &pkt, respond &res){
res.r_id = *(uint32_t *)pkt.buffs[0].second; res.r_id = *(rng::rng64 *)pkt.buffs[0].second;
res.t_addr.SetSockAddr(*(struct sockaddr_in *)pkt.buffs[1].second); res.t_addr.SetSockAddr(*(struct sockaddr_in *)pkt.buffs[1].second);
res.type = (const char *)pkt.buffs[2].second; res.type = (const char *)pkt.buffs[2].second;
res.buff_size = pkt.buffs[3].first; res.buff_size = pkt.buffs[3].first;
res.buff = (Byte *)malloc(res.buff_size);
memcpy(res.buff,pkt.buffs[3].second,res.buff_size); memcpy(res.buff,pkt.buffs[3].second,res.buff_size);
} }
void SQEServer::Respond2Packet(packet &pkt, respond &res){ void SQEServer::Respond2Packet(packet &pkt, respond &res){
pkt.type = RESPOND_TYPE; pkt.type = RESPOND_TYPE;
pkt.AddBuff((void *) &res.r_id, sizeof(uint32_t)); pkt.address = *res.t_addr.Obj();
pkt.AddBuff((void *) &res.r_id, sizeof(rng::rng64));
pkt.AddBuff((void *) res.t_addr.Obj(), sizeof(sockaddr_in)); pkt.AddBuff((void *) res.t_addr.Obj(), sizeof(sockaddr_in));
pkt.AddBuff((void *) res.type.data(), (uint32_t)res.type.size()); pkt.AddBuff((void *) res.type.data(), (uint32_t)res.type.size());
pkt.AddBuff((void *) res.buff, res.buff_size); pkt.AddBuff((void *) res.buff, res.buff_size);
@ -513,7 +543,6 @@ void Server::ProcessSendPackets(void){
Packet2Rawdata(*ppkt, nrwd); Packet2Rawdata(*ppkt, nrwd);
SignedRawdata(&nrwd, "SPKT"); SignedRawdata(&nrwd, "SPKT");
send_socket.SetSendSockAddr(ppkt->address); send_socket.SetSendSockAddr(ppkt->address);
printf("[Final]: %d\n",ppkt->address.sin_addr.s_addr);
SentRawdata(&nrwd); SentRawdata(&nrwd);
freeRawdataServer(nrwd); freeRawdataServer(nrwd);
freePcaketServer(*ppkt); freePcaketServer(*ppkt);

View File

@ -18,10 +18,11 @@ int main(int argc, char *argv[])
initClock(); initClock();
setThreadsClock(); setThreadsClock();
setClientClock(&nclt,2); setClientClock(&nclt,2);
nclt.NewRequest(&preq, "127.0.0.1", 9048, "client-square request", "request for public key");
nclt.NewRequestListener(preq, 10, getSQEPublicKey);
while (1) { while (1) {
sleep(10); nclt.NewRequest(&preq, "127.0.0.1", 9048, "client-square request", "request for public key");
nclt.NewRequestListener(preq, 10, getSQEPublicKey);
sleep(10000);
} }
} catch (char const *str) { } catch (char const *str) {
@ -30,7 +31,3 @@ int main(int argc, char *argv[])
} }
} }
void getSQEPublicKey(respond *pres){
printf("Get Respond.\n");
}