Compare commits

..

No commits in common. "master" and "develop" have entirely different histories.

32 changed files with 254 additions and 1470 deletions

8
.gitignore vendored
View File

@ -40,12 +40,6 @@
*.cbp *.cbp
*.marks *.marks
# Vim
*.swp
# Project Files # Project Files
cmake-build-debug cmake-build-debug
.idea .idea
.cache
build
.DS_Store

View File

@ -2,22 +2,10 @@ cmake_minimum_required(VERSION 3.13)
project(Net) project(Net)
set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD 14)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include_directories(include/) include_directories(include/)
include_directories(utils/) include_directories(utils/)
IF (WIN32)
ELSEIF (APPLE)
set(OPENSSL_ROOT_DIR /usr/local/opt/openssl@1.1)
set(OPENSSL_LIBRARIES /usr/local/opt/openssl@1.1/lib)
ELSEIF (UNIX)
ENDIF ()
find_package(Boost REQUIRED thread) find_package(Boost REQUIRED thread)
find_package(OpenSSL 1.1.1 REQUIRED) find_package(OpenSSL 1.1.1 REQUIRED)
@ -27,4 +15,4 @@ enable_testing()
add_subdirectory(src) add_subdirectory(src)
add_subdirectory(test) add_subdirectory(test)

View File

@ -1,67 +0,0 @@
[
{
"directory": "/home/eric/NetCpp/build/src/utils",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/utils.dir/aes_cbc_encryptor.cpp.o -c /home/eric/NetCpp/src/utils/aes_cbc_encryptor.cpp",
"file": "/home/eric/NetCpp/src/utils/aes_cbc_encryptor.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/utils",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/utils.dir/random_generator.cpp.o -c /home/eric/NetCpp/src/utils/random_generator.cpp",
"file": "/home/eric/NetCpp/src/utils/random_generator.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/utils",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/utils.dir/rsa_key_chain.cpp.o -c /home/eric/NetCpp/src/utils/rsa_key_chain.cpp",
"file": "/home/eric/NetCpp/src/utils/rsa_key_chain.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/utils",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/utils.dir/sha256_generator.cpp.o -c /home/eric/NetCpp/src/utils/sha256_generator.cpp",
"file": "/home/eric/NetCpp/src/utils/sha256_generator.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/debug_tools",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/debugTools.dir/print_tools.cpp.o -c /home/eric/NetCpp/src/debug_tools/print_tools.cpp",
"file": "/home/eric/NetCpp/src/debug_tools/print_tools.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/communicate",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/commu.dir/tcp_client.cpp.o -c /home/eric/NetCpp/src/communicate/tcp_client.cpp",
"file": "/home/eric/NetCpp/src/communicate/tcp_client.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/communicate",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/commu.dir/tcp_server.cpp.o -c /home/eric/NetCpp/src/communicate/tcp_server.cpp",
"file": "/home/eric/NetCpp/src/communicate/tcp_server.cpp"
},
{
"directory": "/home/eric/NetCpp/build/src/communicate",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/commu.dir/tcp_session.cpp.o -c /home/eric/NetCpp/src/communicate/tcp_session.cpp",
"file": "/home/eric/NetCpp/src/communicate/tcp_session.cpp"
},
{
"directory": "/home/eric/NetCpp/build/test/test_util",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/testUtils.dir/main.cpp.o -c /home/eric/NetCpp/test/test_util/main.cpp",
"file": "/home/eric/NetCpp/test/test_util/main.cpp"
},
{
"directory": "/home/eric/NetCpp/build/test/test_util",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/testUtils.dir/test_aes.cpp.o -c /home/eric/NetCpp/test/test_util/test_aes.cpp",
"file": "/home/eric/NetCpp/test/test_util/test_aes.cpp"
},
{
"directory": "/home/eric/NetCpp/build/test/test_util",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/testUtils.dir/test_rsa.cpp.o -c /home/eric/NetCpp/test/test_util/test_rsa.cpp",
"file": "/home/eric/NetCpp/test/test_util/test_rsa.cpp"
},
{
"directory": "/home/eric/NetCpp/build/test/test_util",
"command": "/usr/bin/c++ -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/testUtils.dir/test_sha.cpp.o -c /home/eric/NetCpp/test/test_util/test_sha.cpp",
"file": "/home/eric/NetCpp/test/test_util/test_sha.cpp"
},
{
"directory": "/home/eric/NetCpp/build/test/test_commu",
"command": "/usr/bin/c++ -DDEBUG -I/home/eric/NetCpp/include -I/home/eric/NetCpp/utils -std=gnu++14 -o CMakeFiles/testCommu.dir/main.cpp.o -c /home/eric/NetCpp/test/test_commu/main.cpp",
"file": "/home/eric/NetCpp/test/test_commu/main.cpp"
}
]

View File

@ -1,8 +0,0 @@
#pragma once
#define MSG_VERSION 0x0
namespace Net{
}

View File

@ -1,161 +0,0 @@
#pragma once
#include <stdexcept>
#include <string>
#include <vector>
#include <queue>
#include <memory>
#include "communicate/commu_options.h"
#include "utils/sha256_generator.h"
using std::string;
using std::vector;
using std::shared_ptr;
using std::queue;
namespace Net {
// the structure to store the option part of a message
class Option {
public:
Option(const string &key, const string &value);
Option(const Option &o);
Option(Option &&o) noexcept;
Option& operator=(const Option &o);
Option& operator=(Option &&o) noexcept;
const string &getKey() const;
const string &getValue() const;
void updateValue(const string &value);
private:
// the key is unique within a message
shared_ptr<string> key;
shared_ptr<string> value;
};
class MessageFactory;
class Message {
public:
Message() noexcept;
void setHead(int32_t tid, int16_t type);
void addOption(const string &key, const string &value);
const string &getValue(const string &key) const;
void pushData(void *const buf, size_t size);
int32_t getTID() const;
const vector<char> &getData() const;
void clear();
private:
friend MessageFactory;
int32_t tid = -1;
int16_t version = MSG_VERSION;
int16_t type = 0x0;
vector<Option> options = vector<Option>();
vector<char> data = vector<char>();
static const string msg_head;
static const string msg_tail;
};
class MessageFactory {
public:
bool encodeMessage(Message &msg, vector<char> &raw_data);
bool decodeMessage(const vector<char> &raw_data, Message &msg);
bool decodeMessageHead(const vector<char> &raw_data, Message &msg);
bool decodeMessageOption(const vector<char> &raw_data, Message &msg);
bool decodeMessageBody(const vector<char> &raw_data, Message &msg);
bool decodeMessageTail(const vector<char> &raw_data, Message &msg);
bool checkMessageSign(const Message &msg);
private:
void encode_head(const Message &msg, vector<char> &raw_data);
void encode_options(const Message &msg, vector<char> &raw_data);
void encode_body(const Message &msg, vector<char> &raw_data);
void encode_tail(const Message &msg, vector<char> &raw_data);
ssize_t decode_head(const vector<char> &raw_data, Message &msg);
ssize_t decode_options(const vector<char> &raw_data, size_t offset, Message &msg);
ssize_t decode_body(const vector<char> &raw_data, size_t offset, Message &msg);
ssize_t decode_tail(const vector<char> &raw_Data, size_t offset, Message &msg);
void calculate_options_hash(const vector<char> &raw_data, int32_t end_index, int16_t &sum_hash);
SHA256Generator sign_gen;
};
class MessageParser {
public:
// send a received buffer to parse
void parse(const void *buf, size_t size);
// Get a parsed message from the queue
shared_ptr<Message> getMessage();
// Get the count of the parsed meaasge
size_t getMessageCount();
private:
// state recorder of a special part of a message
int head_state = -5;
int option_state = -4;
ssize_t body_state = -1;
int tail_state = -4;
// factory used to read data and form the message step by step
MessageFactory factory;
// store the message parsed
queue<shared_ptr<Message>> msgs;
// buffer to store the data give by
queue<char> buffer;
// buffer to temporarily store the data of the certain part related to the state of the parser
vector<char> temp_buffer;
// temporarily record the message concentrated
shared_ptr<Message> temp_msg;
// reset all state and refresh the parser
void reset_state();
void locate_head();
void locate_option();
void locate_body();
void locate_tail();
};
} // namespace Net

View File

@ -1,13 +0,0 @@
//
// Created by 胡宇 on 2020/10/23.
//
#ifndef NET_TCP_H
#define NET_TCP_H
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif //NET_TCP_H

View File

@ -5,28 +5,29 @@
#ifndef NET_TCP_CLIENT_H #ifndef NET_TCP_CLIENT_H
#define NET_TCP_CLIENT_H #define NET_TCP_CLIENT_H
#include <project.h> #include <cstring>
#include <string>
#include <stdexcept>
#include <sstream>
#include "tcp.h" #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <boost/thread/thread.hpp>
namespace Net { namespace Net {
class TCPClient { class TCPClient {
public: public:
TCPClient(const std::string &ip, int port); TCPClient(const std::string &ip, int port);
~TCPClient(){
close(fd);
}
int sendData(const std::string &data); int sendData(const std::string &data);
private: private:
int fd{}; int fd{};
struct sockaddr_in client_addr{}; struct sockaddr_in client_addr{};
std::stringstream recv_buff; std::stringstream recv_buff;

View File

@ -5,93 +5,58 @@
#ifndef NET_TCP_SERVER_H #ifndef NET_TCP_SERVER_H
#define NET_TCP_SERVER_H #define NET_TCP_SERVER_H
// 基础依赖 #include <stdexcept>
#include <boost/thread/pthread/mutex.hpp> #include <cstdlib>
#include <project.h> #include <cstring>
#include <vector>
#include <sstream>
#include <string>
#include <queue>
// 扩展依赖 #include <sys/types.h>
#include "tcp.h" #include <sys/socket.h>
#include <netinet/in.h>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
using std::vector;
namespace Net { namespace Net {
class Message; class TCPServer {
public:
TCPServer(int port, int max_connection);
class Connection { ~TCPServer(){
public: stop();
Connection(int fd, struct sockaddr_in cli); close(fd);
}
const std::string getIP() const; void stop(){
if(p_accept_manager_thread != nullptr)
p_accept_manager_thread->interrupt();
this->status = -1;
}
const int16_t getPort() const; uint8_t readByte();
void sendMessage(const Message &msg) { private:
} int fd;
int status = 0;
struct sockaddr_in server_addr;
std::queue<uint8_t> recv_buff;
boost::mutex buff_mutex;
boost::thread *p_accept_manager_thread;
Message *recvMessage(uint32_t tid); void cycle();
private: static void accept_manager(TCPServer *server);
// socket fd
int fd;
// Information structure of this connection static void accept(int fd, boost::mutex *buff_mutex, std::queue<uint8_t> *recv_buff, const int *status);
struct sockaddr_in cli;
};
// void create_socket(int port);
// Provide stable, reliable, easy-to-use, many-to-one TCP communication. };
// Requirement:
// 1. It must be bound to an available port before use.
// Features:
// 1. Support communication concurrency based on multithreading.
//
class TCPServer {
public:
// }
// Please provide an avaliable port(1~65535) first
// The default maximum connection limit is 1024
//
TCPServer(uint16_t port, uint32_t max_connection);
~TCPServer() { #endif //NET_TCP_SERVER_H
stop();
close(fd);
}
void stop() {
if (p_conn_mgr_thrd != nullptr)
p_conn_mgr_thrd->interrupt();
this->status = -1;
}
uint8_t readByte();
private:
int fd;
int status = 0;
struct sockaddr_in server_addr;
std::queue<uint8_t> recv_buff;
boost::mutex buff_mutex;
boost::thread *p_conn_mgr_thrd;
void cycle();
static void connection_manager(TCPServer *server);
static void accept(int fd, boost::mutex *buff_mutex,
std::queue<uint8_t> *recv_buff, const int *status);
//
// Using the standard UNIX way to create a new socket
// Requirement:
// the given port need to be free for the binding
// Return:
// a new and initialized socket which can be given to listen()
void create_socket(int port);
};
} // namespace Net
#endif // NET_TCP_SERVER_H

View File

@ -1,27 +0,0 @@
//
// Created by 胡宇 on 2020/10/23.
//
#ifndef NET_TCP_SESSION_H
#define NET_TCP_SESSION_H
// 基础依赖
#include <project.h>
// 扩展依赖
#include "tcp.h"
class TCPSession {
public:
TCPSession(){
}
private:
};
#endif //NET_TCP_SESSION_H

View File

@ -5,15 +5,12 @@
#ifndef NET_PRINT_TOOLS_H #ifndef NET_PRINT_TOOLS_H
#define NET_PRINT_TOOLS_H #define NET_PRINT_TOOLS_H
#include <stdarg.h>
#include <string> #include <string>
#include <vector>
#include <map> #include <map>
using std::string; using std::string;
using std::initializer_list; using std::initializer_list;
using std::pair; using std::pair;
using std::vector;
//提示信息打印类函数 //提示信息打印类函数
namespace Net { namespace Net {
@ -22,18 +19,16 @@ namespace Net {
using FormalItem = pair<string, string>; using FormalItem = pair<string, string>;
void debugPrintError(const string error_info, ...); void debugPrintError(const string &error_info);
void debugPrintWarning(const string warning_info, ...); void debugPrintWarning(const string &warning_info);
void debugPrintSuccess(const string success_info, ...); void debugPrintSuccess(const string &success_info);
void printInfo(const string& info, const string& tag); void printInfo(const string& info, const string& tag);
void printInfoBuffer(const string& info, const string& tag); void printInfoBuffer(const string& info, const string& tag);
void printInfoBuffer(const vector<char>& info, const string& tag);
void printInfoFormal(const string& title, initializer_list<FormalItem> body); void printInfoFormal(const string& title, initializer_list<FormalItem> body);
} }
} }

View File

@ -1,31 +0,0 @@
//
// Created by 胡宇 on 2020/10/23.
//
#ifndef NET_PROJECT_H
#define NET_PROJECT_H
// 基础
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
// 基本
#include <stdexcept>
#include <cstdlib>
#include <cstring>
// 流
#include <sstream>
// 数据结构
#include <vector>
#include <string>
#include <queue>
// 高级组件
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#endif //NET_PROJECT_H

View File

@ -7,39 +7,41 @@
#include <cassert> #include <cassert>
#include <cstdint> #include <cstdint>
#include <string>
#include <openssl/aes.h> #include <openssl/aes.h>
#include <openssl/evp.h> #include <openssl/evp.h>
#include <string>
#include "debug_tools/print_tools.h" #include "debug_tools/print_tools.h"
#include "random_generator.h" #include "random_generator.h"
namespace Net { namespace Net {
class AESCBCEncryptor { class AESCBCEncryptor {
public: public:
AESCBCEncryptor();
string getKeyData() const; AESCBCEncryptor();
void encrypt(const std::string &data, std::string &encrypted_data); string getKeyData() const;
void decrypt(std::string &data, const std::string &encrypt_data); void encrypt(const std::string &data, std::string &encrypted_data);
private: void decrypt(std::string &data, const std::string &encrypt_data);
const int nrounds = 8;
uint8_t key[32], iv[32]; private:
const int nrounds = 8;
EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new(); uint8_t key[32], iv[32];
std::string key_data; EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new();
void generate_random_key_data(); std::string key_data;
void aes_init(std::string &key_data); void generate_random_key_data();
};
} // namespace Net void aes_init(std::string &key_data);
#endif // NET_AES_CBC_ENCRYPTOR_H };
}
#endif //NET_AES_CBC_ENCRYPTOR_H

View File

@ -2,14 +2,12 @@
#include <openssl/sha.h> #include <openssl/sha.h>
#include <string> #include <string>
#include <vector>
#include <fstream> #include <fstream>
#include <utility> #include <utility>
using std::string; using std::string;
using std::ifstream; using std::ifstream;
using std::stringstream; using std::stringstream;
using std::vector;
namespace Net { namespace Net {
@ -19,11 +17,11 @@ namespace Net {
*/ */
class SHA256Generator { class SHA256Generator {
public: public:
SHA256Generator(); SHA256Generator(string data);
void setRawData(const string &str); SHA256Generator(ifstream stream);
void setRawData(const vector<char> &c_array); void replace(string &str);
void generate(); void generate();
@ -31,9 +29,8 @@ namespace Net {
private: private:
bool if_generate = false; bool if_generate = false;
const void *raw_data = nullptr; string raw_data;
size_t raw_data_size = 0;
string sha256_data; string sha256_data;
}; };
} }

View File

@ -1,3 +1,3 @@
add_subdirectory(utils) add_subdirectory(utils)
add_subdirectory(debug_tools) add_subdirectory(debug_tools)
add_subdirectory(communicate) add_subdirectory(communicate)

View File

@ -1,3 +1,3 @@
file(GLOB commuSrc *.cpp) file(GLOB commuSrc *.cpp)
add_library(commu STATIC ${commuSrc}) add_library(commu STATIC ${commuSrc})

View File

@ -1,70 +0,0 @@
#include "communicate/message.h"
#include "communicate/commu_options.h"
#include <time.h>
namespace Net {
const string Message::msg_head = "MSG";
const string Message::msg_tail = "GSM";
void Message::addOption(const string &key, const string &value) {
for (Option &option : options) {
if (option.getKey() == key) {
option.updateValue(value);
return;
}
}
options.push_back(Option(key, value));
}
const string &Message::getValue(const string &key) const {
for (Option option : options) {
if (option.getKey() == key) {
return option.getValue();
}
}
throw new std::runtime_error("key not found");
}
void Message::pushData(void *const buf, size_t size) {
char *const c_buf = (char *const)buf;
for (size_t i = 0; i < size; i++) {
data.push_back(c_buf[i]);
}
addOption("size", std::to_string(data.size()));
}
void Message::clear() {
this->data.clear();
this->options.clear();
this->tid = 0;
this->type = 0x1;
}
void Message::setHead(int32_t tid, int16_t type) {
this->tid = tid;
this->type = type;
}
int32_t Message::getTID() const {
return tid;
}
const vector<char> &Message::getData() const {
return data;
}
Message::Message() noexcept {
time_t t = time(nullptr);
struct tm *p_tm = gmtime(&t);
char buf[22];
size_t w_bit = strftime(&buf[0], sizeof(buf), "%D %T %Z", p_tm);
addOption("date", buf);
}
} // namespace Net

View File

@ -1,305 +0,0 @@
#include "communicate/commu_options.h"
#include "communicate/message.h"
#include <stdexcept>
#include <stdio.h>
namespace Net {
bool MessageFactory::encodeMessage(Message &msg, vector<char> &raw_data) {
sign_gen.setRawData(msg.getData());
msg.addOption("sign", sign_gen.getHex());
encode_head(msg, raw_data);
encode_options(msg, raw_data);
encode_body(msg, raw_data);
encode_tail(msg, raw_data);
return true;
}
void MessageFactory::encode_head(const Message &msg, vector<char> &raw_data) {
raw_data.insert(raw_data.end(), msg.msg_head.cbegin(), msg.msg_head.cend());
raw_data.push_back(' ');
// 协议版本
const string s_version = std::to_string(msg.version);
raw_data.insert(raw_data.end(), s_version.cbegin(), s_version.cend());
raw_data.push_back(' ');
// 消息类型
const string s_type = std::to_string(msg.type);
raw_data.insert(raw_data.end(), s_type.cbegin(), s_type.cend());
raw_data.push_back(' ');
// 会话ID
const string s_tid = std::to_string(msg.tid);
raw_data.insert(raw_data.end(), s_tid.cbegin(), s_tid.cend());
raw_data.push_back('\r');
raw_data.push_back('\n');
}
void MessageFactory::encode_options(const Message &msg,
vector<char> &raw_data) {
for (auto &option : msg.options) {
raw_data.push_back('\"');
const string &key = option.getKey();
raw_data.insert(raw_data.end(), key.cbegin(), key.cend());
raw_data.push_back('\"');
raw_data.push_back(':');
raw_data.push_back('\"');
const string &value = option.getValue();
raw_data.insert(raw_data.end(), value.cbegin(), value.cend());
raw_data.push_back('\"');
raw_data.push_back('\r');
raw_data.push_back('\n');
}
// 计算头部和配置部分的哈希值
int16_t sum_hash;
calculate_options_hash(raw_data, raw_data.size() - 1, sum_hash);
const string sum_hash_str = std::to_string(sum_hash);
raw_data.insert(raw_data.end(), sum_hash_str.cbegin(), sum_hash_str.cend());
raw_data.push_back('\r');
raw_data.push_back('\n');
raw_data.push_back('\r');
raw_data.push_back('\n');
}
void MessageFactory::encode_body(const Message &msg, vector<char> &raw_data) {
raw_data.insert(raw_data.end(), msg.data.begin(), msg.data.end());
raw_data.push_back('\r');
raw_data.push_back('\n');
}
void MessageFactory::encode_tail(const Message &msg, vector<char> &raw_data) {
raw_data.insert(raw_data.end(), msg.msg_tail.cbegin(), msg.msg_tail.cend());
}
ssize_t MessageFactory::decode_head(const vector<char> &raw_data,
Message &msg) {
size_t index = 0;
for (auto &c : Message::msg_head) {
if (raw_data[index++] != c)
return -1;
}
if (raw_data[index++] != ' ')
return -1;
string s_version;
char c;
while ((c = raw_data[index++]) != ' ') {
s_version.push_back(c);
}
int16_t version = std::stoi(s_version);
if (version != MSG_VERSION)
return -1;
string s_type;
while ((c = raw_data[index++]) != ' ') {
s_type.push_back(c);
}
int16_t type = std::stoi(s_type);
string s_tid;
while ((c = raw_data[index++]) != '\r') {
s_tid.push_back(c);
}
int32_t tid = std::stoi(s_tid);
if (raw_data[index++] != '\n')
return -1;
msg.setHead(tid, type);
return index;
}
ssize_t MessageFactory::decode_options(const vector<char> &raw_data,
size_t offset, Message &msg) {
size_t index = offset;
char c;
while (raw_data[index++] == '\"') {
string key;
while ((c = raw_data[index++]) != '\"') {
key.push_back(c);
}
if (raw_data[index++] != ':') {
return -1;
}
if (raw_data[index++] != '\"') {
return -1;
}
string value;
while ((c = raw_data[index++]) != '\"') {
value.push_back(c);
}
if (raw_data[index++] != '\r' || raw_data[index++] != '\n')
return -1;
msg.addOption(key.c_str(), value.c_str());
}
int sum_hash_range = index - 2;
--index;
string sum_hash_str;
while((c = raw_data[index++]) != '\r') {
sum_hash_str.push_back(c);
}
if(raw_data[index++] != '\n') {
return -1;
}
int16_t sum_hash = std::stoi(sum_hash_str);
int16_t sum_hash_check;
calculate_options_hash(raw_data, sum_hash_range, sum_hash_check);
if(sum_hash_check != sum_hash) return -1;
if (raw_data[index++] != '\r' || raw_data[index++] != '\n')
return -1;
return index;
}
ssize_t MessageFactory::decode_body(const vector<char> &raw_data, size_t offset,
Message &msg) {
size_t index = offset;
int32_t size = 0;
string s_size;
try {
s_size = msg.getValue("size");
} catch (std::runtime_error e) {
return -1;
}
size = std::stoi(s_size);
msg.pushData((void *)&raw_data[index], size);
index += size;
if (raw_data[index++] != '\r' || raw_data[index++] != '\n')
return -1;
return index;
}
ssize_t MessageFactory::decode_tail(const vector<char> &raw_data, size_t offset,
Message &msg) {
size_t index = offset;
for (auto &c : Message::msg_tail) {
if (raw_data[index++] != c)
return -1;
}
return index;
}
void MessageFactory::calculate_options_hash(const vector<char> &raw_data, int32_t end_index, int16_t &sum_hash) {
if(end_index > raw_data.size()) {
throw std::runtime_error("end index out of range");
}
sum_hash = 0;
int32_t index = 0;
for(auto &c : raw_data) {
sum_hash += static_cast<int16_t>(c);
sum_hash %= 65535;
if (index++ >= end_index) break;
}
}
bool MessageFactory::decodeMessage(const vector<char> &raw_data, Message &msg) {
msg.clear();
ssize_t offset = decode_head(raw_data, msg);
if (!~offset)
return false;
offset = decode_options(raw_data, offset, msg);
if (!~offset)
return false;
offset = decode_body(raw_data, offset, msg);
if (!~offset)
return false;
offset = decode_tail(raw_data, offset, msg);
if (!~offset)
return false;
else
return true;
}
bool MessageFactory::checkMessageSign(const Message &msg) {
string sign;
try {
sign = msg.getValue("sign");
} catch (std::runtime_error e) {
return false;
}
sign_gen.setRawData(msg.getData());
return sign_gen.getHex() == sign;
}
bool MessageFactory::decodeMessageHead(const vector<char> &raw_data, Message &msg) {
if(!~decode_head(raw_data, msg)) return false;
else return true;
}
bool MessageFactory::decodeMessageOption(const vector<char> &raw_data, Message &msg) {
if(!~decode_options(raw_data, 0, msg)) return false;
else return true;
}
bool MessageFactory::decodeMessageBody(const vector<char> &raw_data, Message &msg) {
if(!~decode_body(raw_data, 0, msg)) return false;
return true;
}
bool MessageFactory::decodeMessageTail(const vector<char> &raw_data, Message &msg) {
if(!~decode_tail(raw_data, 0, msg)) return false;
return true;
}
} // namespace Net

View File

@ -1,254 +0,0 @@
#include "communicate/message.h"
#include <stdexcept>
#include <string>
namespace Net {
void MessageParser::parse(const void *buf, size_t size) {
// push all data in buff into queue named buffer
const char *c_buf = (const char *)buf;
for (int i = 0; i < size; i++) {
buffer.push(c_buf[i]);
}
// process the data byte by byte until the queue is empty
while(!buffer.empty()) {
// if there is no message concentrated then create new message
if (temp_msg == nullptr) {
temp_msg = std::make_shared<Message>();
}
if (head_state < 0) {
locate_head();
} else if (option_state < 0) {
locate_option();
} else if (body_state != 0) {
locate_body();
}
else if (tail_state < 0) {
locate_tail();
}
// tail processing done
if(!tail_state){
// release the message concentrated
msgs.push(temp_msg);
temp_msg = nullptr;
// reset the state of the parser
reset_state();
}
}
}
void MessageParser::locate_head() {
while (!buffer.empty()) {
char c = buffer.front();
buffer.pop();
temp_buffer.push_back(c);
if (head_state == -5) {
if (c == 'M')
head_state++;
continue;
}
if (head_state == -4) {
if (c != 'S') {
reset_state();
} else
head_state++;
continue;
}
if (head_state == -3) {
if (c != 'G') {
reset_state();
} else
head_state++;
continue;
}
if (head_state == -2) {
if (c == '\r') {
head_state++;
}
continue;
}
if (head_state == -1) {
if (c != '\n') {
reset_state();
} else {
head_state++;
if (!factory.decodeMessageHead(temp_buffer, *temp_msg)) {
reset_state();
}
temp_buffer.clear();
break;
}
}
}
}
void MessageParser::locate_option() {
while(!buffer.empty()) {
char c = buffer.front();
buffer.pop();
temp_buffer.push_back(c);
if(option_state == -4) {
if(c == '\"')
option_state++;
else if(c == '\r')
option_state = -1;
else if (c > 47 && c < 58)
option_state++;
continue;
}
if(option_state == -3) {
if(c == '\r'){
option_state++;
}
continue;
}
if(option_state == -2) {
if(c == '\n'){
option_state = -4;
}
else{
reset_state();
break;
}
continue;
}
if(option_state == -1) {
if(c != '\n'){
reset_state();
break;
}
else{
if(!factory.decodeMessageOption(temp_buffer, *temp_msg)) {
reset_state();
break;
}
option_state++;
temp_buffer.clear();
break;
}
}
}
}
void MessageParser::locate_body() {
while(!buffer.empty()) {
char c = buffer.front();
buffer.pop();
temp_buffer.push_back(c);
if(body_state == -1) {
string s_size;
try {
s_size = temp_msg->getValue("size");
} catch(std::runtime_error e) {
reset_state();
break;
}
body_state = std::stoul(s_size) + 2;
}
if(body_state > 1) {
body_state--;
continue;
}
if(body_state == 2) {
if(c == '\r'){
body_state--;
continue;
}
else{
reset_state();
break;
}
}
if(body_state == 1) {
if(c != '\n'){
reset_state();
break;
}
else{
if(!factory.decodeMessageBody(temp_buffer, *temp_msg)) {
reset_state();
break;
}
temp_buffer.clear();
body_state--;
break;
}
}
}
}
void MessageParser::locate_tail() {
while(!buffer.empty()) {
char c = buffer.front();
buffer.pop();
temp_buffer.push_back(c);
if(tail_state == -4) {
if(c == 'G')
tail_state++;
else{
reset_state();
break;
}
continue;
}
if(tail_state == -3) {
if(c == 'S')
tail_state++;
else{
reset_state();
break;
}
continue;
}
if(tail_state == -2) {
if(c == 'M')
tail_state++;
else{
reset_state();
break;
}
}
if(tail_state == -1) {
if(!factory.decodeMessageTail(temp_buffer, *temp_msg)) {
reset_state();
break;
}
tail_state++;
temp_buffer.clear();
break;
}
}
}
void MessageParser::reset_state() {
temp_buffer.clear();
// reset the message concentrated
if(temp_msg != nullptr)
temp_msg->clear();
// reset the state recorder
head_state = -5;
option_state = -4;
body_state = -1;
tail_state = -4;
}
shared_ptr<Message> MessageParser::getMessage() {
shared_ptr<Message> p_msg = nullptr;
if(!msgs.empty()){
p_msg = msgs.front();
msgs.pop();
}
return p_msg;
}
size_t MessageParser::getMessageCount() {
return msgs.size();
}
} // namespace Net

View File

@ -1,40 +0,0 @@
#include "communicate/message.h"
namespace Net {
Option::Option(const string &key, const string &value)
: key(std::make_shared<string>(key)), value(std::make_shared<string>(value)) {}
const string &Option::getKey() const { return *key; }
const string &Option::getValue() const { return *value; }
void Option::updateValue(const string &value) { *this->value = value; }
Option::Option(const Option &o) {
if(this == &o) return;
key = o.key;
value = o.value;
}
Option::Option(Option &&o) noexcept {
if(this == &o) return;
key = o.key;
value = o.value;
}
Option& Option::operator=(const Option &o) {
if(this == &o) return *this;
key = o.key;
value = o.value;
return *this;
}
Option& Option::operator=(Option &&o) noexcept {
if(this == &o) return *this;
key = o.key;
value = o.value;
return *this;
}
} // namespace Net

View File

@ -4,8 +4,6 @@
#include "communicate/tcp_client.h" #include "communicate/tcp_client.h"
extern int errno;
void Net::TCPClient::recv_data(Net::TCPClient *client) { void Net::TCPClient::recv_data(Net::TCPClient *client) {
u_char buff[1024]; u_char buff[1024];
int len; int len;
@ -15,18 +13,16 @@ void Net::TCPClient::recv_data(Net::TCPClient *client) {
} }
void Net::TCPClient::recv_cycle() { void Net::TCPClient::recv_cycle() {
boost::thread recv_thread(TCPClient::recv_data,this); boost::thread recv_thread(TCPClient::recv_data,
this);
recv_thread.detach(); recv_thread.detach();
} }
void Net::TCPClient::create_socket_and_connection() { void Net::TCPClient::create_socket_and_connection() {
if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
throw std::runtime_error(strerror(errno)); throw std::runtime_error("create socket failed.");
} }
if(connect(fd, (struct sockaddr *) &client_addr, sizeof(client_addr)) < 0){ connect(fd, (struct sockaddr *) &client_addr, sizeof(client_addr));
throw std::runtime_error(strerror(errno));
}
} }
int Net::TCPClient::sendData(const std::string &data) { int Net::TCPClient::sendData(const std::string &data) {

View File

@ -2,101 +2,79 @@
// Created by 胡宇 on 2020/7/7. // Created by 胡宇 on 2020/7/7.
// //
#include "communicate/tcp_server.h"
#include "debug_tools/print_tools.h" #include "debug_tools/print_tools.h"
#include <cstdio> #include "communicate/tcp_server.h"
#include <memory>
extern int errno;
void Net::TCPServer::cycle() { void Net::TCPServer::cycle() {
boost::thread accept_manager_thread(TCPServer::connection_manager, this); boost::thread accept_manager_thread(TCPServer::accept_manager, this);
this->p_conn_mgr_thrd = &accept_manager_thread; this->p_accept_manager_thread = &accept_manager_thread;
accept_manager_thread.detach(); accept_manager_thread.detach();
} }
void Net::TCPServer::connection_manager(Net::TCPServer *server) { void Net::TCPServer::accept_manager(Net::TCPServer *server) {
Net::PrintTools::debugPrintSuccess("AcceptManager Started."); Net::PrintTools::debugPrintSuccess("AcceptManager Started.");
while (true) { while(true){
struct sockaddr_in cli; int connect_fd = ::accept(server->fd, nullptr, nullptr);
socklen_t len = sizeof(cli); Net::PrintTools::debugPrintSuccess("New Connection.");
int connect_fd = ::accept(server->fd, (struct sockaddr *)&cli, &len); if(connect_fd == -1) throw std::runtime_error("accept tcp connection error");
Net::PrintTools::debugPrintSuccess("Get new connection from IP %s Port %d.", else{
inet_ntoa(cli.sin_addr), boost::thread accept_thread(TCPServer::accept, connect_fd, &server->buff_mutex, &server->recv_buff, &server->status);
htons(cli.sin_port)); accept_thread.detach();
}
if (connect_fd < 0)
throw std::runtime_error(strerror(errno));
else {
boost::thread accept_thread(TCPServer::accept, connect_fd,
&server->buff_mutex, &server->recv_buff,
&server->status);
accept_thread.detach();
} }
}
} }
void Net::TCPServer::accept(int fd, boost::mutex *buff_mutex, void Net::TCPServer::accept(int fd, boost::mutex *buff_mutex, std::queue<uint8_t> *recv_buff, const int *status) {
std::queue<uint8_t> *recv_buff, const int *status) { Net::PrintTools::debugPrintSuccess("Try Getting Data From Connection.");
Net::PrintTools::debugPrintSuccess("Try Getting Data From Connection."); uint8_t buff[1024];
uint8_t buff[1024]; int len;
int len; std::vector<uint8_t> accept_buff;
std::vector<uint8_t> accept_buff; while((len = recv(fd, buff, sizeof(buff), 0)) > 0 && *status == 0){
while ((len = recv(fd, buff, sizeof(buff), 0)) > 0 && *status == 0) { Net::PrintTools::debugPrintSuccess("Received.");
Net::PrintTools::debugPrintSuccess("Received."); for(int i = 0; i < len; ++i) accept_buff.push_back(buff[i]);
for (int i = 0; i < len; ++i) }
accept_buff.push_back(buff[i]); if(*status == 0) {
} buff_mutex->lock();
if (*status == 0) { for(unsigned char & i : accept_buff)
buff_mutex->lock(); recv_buff->push(i);
for (unsigned char &i : accept_buff) buff_mutex->unlock();
recv_buff->push(i); }
buff_mutex->unlock(); close(fd);
} Net::PrintTools::debugPrintSuccess("Connection Closed.");
close(fd);
Net::PrintTools::debugPrintSuccess("Connection Closed.");
} }
void Net::TCPServer::create_socket(int port) { void Net::TCPServer::create_socket(int port) {
if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
throw std::runtime_error(strerror(errno)); if(!~fd) throw std::runtime_error("could not create socket file.");
std::memset(&server_addr, 0, sizeof(struct sockaddr_in)); std::memset(&server_addr, 0, sizeof(struct sockaddr_in));
this->server_addr.sin_family = AF_INET; server_addr.sin_family = AF_INET;
this->server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
this->server_addr.sin_port = htons(port); server_addr.sin_port = htons(port);
// Try binding the socket to the given port
if (bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
// Close the socket created
close(fd);
throw std::runtime_error(strerror(errno));
}
} }
Net::TCPServer::TCPServer(uint16_t port, uint32_t max_connection = 1024) { Net::TCPServer::TCPServer(int port, int max_connection) {
// Create a new socket binding certain port create_socket(port);
create_socket(port);
if (listen(fd, max_connection) < 0) { if(bind(fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
// Close the socket created throw std::runtime_error("bind port failed.");
close(fd);
throw std::runtime_error(strerror(errno));
}
// Start running the engine cycle if(listen(fd, max_connection) == -1)
cycle(); throw std::runtime_error("listen socket failed.");
cycle();
} }
uint8_t Net::TCPServer::readByte() { uint8_t Net::TCPServer::readByte() {
uint8_t byte = '\0'; uint8_t byte = '\0';
buff_mutex.try_lock(); buff_mutex.try_lock();
if (!recv_buff.empty()) { if(!recv_buff.empty()) {
byte = recv_buff.front(); byte = recv_buff.front();
recv_buff.pop(); recv_buff.pop();
} }
buff_mutex.unlock(); buff_mutex.unlock();
return byte; return byte;
} }

View File

@ -1,5 +0,0 @@
//
// Created by 胡宇 on 2020/10/23.
//
#include "communicate/tcp_session.h"

View File

@ -7,75 +7,48 @@
using std::string; using std::string;
namespace Net { namespace Net {
namespace PrintTools { namespace PrintTools {
void debugPrintError(const string &error_info) {
printf("\033[31mError: %s\033[0m\n", error_info.data());
}
void print_buff(uint8_t *const buf, size_t size); void debugPrintWarning(const string &warning_info) {
printf("\033[33mWarning: %s\033[0m\n", warning_info.data());
}
void debugPrintError(const string error_info, ...) { void debugPrintSuccess(const string &success_info) {
va_list args; printf("\033[32m%s\033[0m\n", success_info.data());
va_start(args, error_info); }
string output = "\033[31m[Error] ";
output += error_info + string("\033[0m\n");
vprintf(output.c_str(), args);
}
void debugPrintWarning(const string warning_info, ...) { void printInfo(const string& info, const string& tag) {
va_list args; printf("[DEBUG INFO] %s ", info.data());
va_start(args, warning_info); if(!tag.empty())
string output = "\033[33m[Warning] "; printf("{ %s }\n",tag.data());
output += warning_info + string("\033[0m\n"); }
vprintf(output.c_str(), args);
}
void debugPrintSuccess(const string success_info, ...) { void printInfoFormal(const string& title, initializer_list<FormalItem> body) {
va_list args; printf("\n>>>\n {%s}\n",title.data());
va_start(args, success_info); printf(">-------------------------------------\n");
string output = "\033[32m[Success] "; for(auto &item : body){
output += success_info + string("\033[0m\n"); printf("[%s] : \"%s\"; \n", item.first.data(), item.second.data());
vprintf(output.c_str(), args); }
} printf("----------------------------------<\n<<<\n\n");
}
void printInfo(const string &info, const string &tag) { void printInfoBuffer(const string &info, const string& tag) {
printf("[DEBUG INFO] %s ", info.data()); printf("\n[DEBUG INFO (BUFFER)]\n");
if (!tag.empty()) printf(">----------------------------------------------\n");
printf("{ %s }\n", tag.data()); auto *p_i = (uint8_t *) &info[0];
} auto *p_e = (uint8_t *) &info[info.size()-1];
for(int c = 0;p_i < p_e; ++p_i, ++c){
if(!(c % 16) && c) printf("\n");
printf("%02x ",*p_i);
void printInfoFormal(const string &title, initializer_list<FormalItem> body) { }
printf("\n>>>\n {%s}\n", title.data()); printf("\n");
printf(">-------------------------------------\n"); printf("----------------------------------------------<\n");
for (auto &item : body) { if(!tag.empty())
printf("[%s] : \"%s\"; \n", item.first.data(), item.second.data()); printf("{ %s }\n\n",tag.data());
} }
printf("----------------------------------<\n<<<\n\n"); }
} }
void print_buff(uint8_t *const buf, size_t size) {
printf("\n[DEBUG INFO (BUFFER)]\n");
printf(">----------------------------------------------\n");
auto *p_i = buf;
auto *p_e = (uint8_t *const) & buf[size - 1];
for (int c = 0; p_i < p_e; ++p_i, ++c) {
if (!(c % 16) && c)
printf("\n");
printf("%02x ", *p_i);
}
printf("\n");
printf("----------------------------------------------<\n");
}
void printInfoBuffer(const string &info, const string &tag) {
print_buff((uint8_t *)&info[0], info.size());
if (!tag.empty())
printf("{ %s }\n\n", tag.data());
}
void printInfoBuffer(const vector<char> &info, const string &tag) {
print_buff((uint8_t *)&info[0], info.size());
if (!tag.empty())
printf("{ %s }\n\n", tag.data());
}
} // namespace PrintTools
} // namespace Net

View File

@ -4,78 +4,74 @@
#include "utils/aes_cbc_encryptor.h" #include "utils/aes_cbc_encryptor.h"
#include "utils/sha256_generator.h"
void Net::AESCBCEncryptor::encrypt(const string &data, string &encrypted_data) { void Net::AESCBCEncryptor::encrypt(const string &data, string &encrypted_data) {
int c_len = data.length() + AES_BLOCK_SIZE, f_len = 0; int c_len = data.length() + AES_BLOCK_SIZE, f_len = 0;
auto *encrypt_buffer = reinterpret_cast<uint8_t *>(malloc(c_len)); auto *encrypt_buffer = reinterpret_cast<uint8_t *>(malloc(c_len));
EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv);
EVP_EncryptUpdate(e_ctx, encrypt_buffer, &c_len, EVP_EncryptUpdate(e_ctx, encrypt_buffer, &c_len,
reinterpret_cast<const unsigned char *>(data.data()), reinterpret_cast<const unsigned char *>(data.data()), data.length());
data.length()); EVP_EncryptFinal_ex(e_ctx, encrypt_buffer + c_len, &f_len);
EVP_EncryptFinal_ex(e_ctx, encrypt_buffer + c_len, &f_len);
int len = c_len + f_len; int len = c_len + f_len;
if (!encrypted_data.empty()) if(!encrypted_data.empty()) encrypted_data.clear();
encrypted_data.clear();
encrypted_data.append(reinterpret_cast<const char *>(encrypt_buffer), len); encrypted_data.append(reinterpret_cast<const char *>(encrypt_buffer), len);
EVP_CIPHER_CTX_reset(e_ctx); EVP_CIPHER_CTX_reset(e_ctx);
} }
void Net::AESCBCEncryptor::decrypt(string &data, const string &encrypt_data) { void Net::AESCBCEncryptor::decrypt(string &data, const string &encrypt_data) {
int p_len = encrypt_data.length(), f_len = 0; int p_len = encrypt_data.length(), f_len = 0;
auto *plain_buffer = static_cast<uint8_t *>(malloc(p_len)); auto *plain_buffer = static_cast<uint8_t *>(malloc(p_len));
EVP_DecryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); EVP_DecryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv);
EVP_DecryptUpdate( EVP_DecryptUpdate(e_ctx, plain_buffer, &p_len,
e_ctx, plain_buffer, &p_len, reinterpret_cast<const unsigned char *>(encrypt_data.data()), encrypt_data.length());
reinterpret_cast<const unsigned char *>(encrypt_data.data()), EVP_DecryptFinal_ex(e_ctx, plain_buffer + p_len, &f_len);
encrypt_data.length());
EVP_DecryptFinal_ex(e_ctx, plain_buffer + p_len, &f_len);
int len = p_len + f_len; int len = p_len + f_len;
if (!data.empty()) if(!data.empty()) data.clear();
data.clear();
data.append(reinterpret_cast<const char *>(plain_buffer), len); data.append(reinterpret_cast<const char *>(plain_buffer), len);
EVP_CIPHER_CTX_reset(e_ctx); EVP_CIPHER_CTX_reset(e_ctx);
} }
void Net::AESCBCEncryptor::generate_random_key_data() { void Net::AESCBCEncryptor::generate_random_key_data() {
Rand::UniformUInt rand(0, UINT32_MAX); Rand::UniformUInt rand(0, UINT32_MAX);
uint32_t p_data[8]; uint32_t p_data[8];
for (unsigned int &i : p_data) { for(unsigned int & i : p_data){
i = rand.generate(); i = rand.generate();
} }
key_data.append(reinterpret_cast<const char *>(p_data), 32); key_data.append(reinterpret_cast<const char *>(p_data), 32);
} }
void Net::AESCBCEncryptor::aes_init(string &key_data) { void Net::AESCBCEncryptor::aes_init(string &key_data) {
int i =
EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), nullptr,
reinterpret_cast<const unsigned char *>(key_data.c_str()),
key_data.length(), nrounds, key, iv);
if (i != 32) {
throw std::runtime_error("key data must equal 256 bits.");
}
EVP_CIPHER_CTX_init(e_ctx); int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), nullptr,
EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); reinterpret_cast<const unsigned char *>(key_data.c_str()), key_data.length(),
nrounds, key, iv);
if (i != 32) {
throw std::runtime_error("key data must equal 256 bits.");
}
EVP_CIPHER_CTX_init(e_ctx);
EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv);
} }
string Net::AESCBCEncryptor::getKeyData() const { return key_data; } string Net::AESCBCEncryptor::getKeyData() const {
return key_data;
}
Net::AESCBCEncryptor::AESCBCEncryptor() { Net::AESCBCEncryptor::AESCBCEncryptor() {
generate_random_key_data(); generate_random_key_data();
aes_init(key_data); aes_init(key_data);
} }

View File

@ -8,10 +8,10 @@ void Net::SHA256Generator::generate() {
unsigned char hash[SHA256_DIGEST_LENGTH]; unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256; SHA256_CTX sha256;
SHA256_Init(&sha256); SHA256_Init(&sha256);
SHA256_Update(&sha256, raw_data, raw_data_size); SHA256_Update(&sha256, raw_data.c_str(), raw_data.size());
SHA256_Final(hash, &sha256); SHA256_Final(hash, &sha256);
stringstream buffer; stringstream buffer;
char buf[3]; char buf[2];
for(int i = 0; i < SHA256_DIGEST_LENGTH; ++i){ for(int i = 0; i < SHA256_DIGEST_LENGTH; ++i){
sprintf(buf,"%02x",hash[i]); sprintf(buf,"%02x",hash[i]);
buffer << buf; buffer << buf;
@ -20,16 +20,8 @@ void Net::SHA256Generator::generate() {
if_generate = true; if_generate = true;
} }
void Net::SHA256Generator::setRawData(const vector<char> &c_array) { void Net::SHA256Generator::replace(string &str) {
raw_data = &c_array[0]; this->raw_data = str;
raw_data_size = c_array.size();
if_generate = false;
}
void Net::SHA256Generator::setRawData(const string &str) {
raw_data = str.c_str();
raw_data_size = str.size();
if_generate = false;
} }
string Net::SHA256Generator::getHex() { string Net::SHA256Generator::getHex() {
@ -37,5 +29,13 @@ string Net::SHA256Generator::getHex() {
return this->sha256_data; return this->sha256_data;
} }
Net::SHA256Generator::SHA256Generator() { Net::SHA256Generator::SHA256Generator(ifstream stream) {
while (stream.good()) {
stream >> raw_data;
}
stream.close();
}
Net::SHA256Generator::SHA256Generator(string data) {
this->raw_data = std::move(data);
} }

View File

@ -1,7 +1,5 @@
find_package(GTest REQUIRED) find_package(GTest REQUIRED)
set(CMAKE_CXX_FLAGS_DEBUG "-g")
set(GTEST_LIB /usr/local/lib/) set(GTEST_LIB /usr/local/lib/)
set(GTEST_LIBS gtest gmock pthread dl) set(GTEST_LIBS gtest gmock pthread dl)
@ -9,4 +7,3 @@ link_directories(${GTEST_LIB})
add_subdirectory(test_util) add_subdirectory(test_util)
add_subdirectory(test_commu) add_subdirectory(test_commu)
add_subdirectory(test_commu_modules)

View File

@ -2,21 +2,30 @@
// Created by 胡宇 on 2020/7/9. // Created by 胡宇 on 2020/7/9.
// //
#include <cstdio>
#include <unistd.h> #include <unistd.h>
#include <cstdio>
#include "communicate/tcp_client.h"
#include "communicate/tcp_server.h"
#include "debug_tools/print_tools.h" #include "debug_tools/print_tools.h"
#include "communicate/tcp_server.h"
#include "communicate/tcp_client.h"
using namespace Net; using namespace Net;
int main(int argc, char *argv[]) { int main(int argc, char *argv[]){
PrintTools::debugPrintSuccess("TCPServer Started."); if(fork() == 0) {
TCPServer server(9048, 100); PrintTools::debugPrintSuccess("Child Started.");
while (true) { TCPClient client("127.0.0.1", 9048);
std::putchar(server.readByte()); for(int i = 0; i < 32; i++, usleep(1e4))
usleep(1e3); client.sendData("Hello");
} PrintTools::debugPrintSuccess("Child Exited.");
return 0; }
} else{
PrintTools::debugPrintSuccess("Father Started.");
TCPServer server(9048, 100);
while (true){
std::putchar(server.readByte());
usleep(1e3);
}
}
return 0;
}

View File

@ -1,8 +0,0 @@
file(GLOB testSrc *.cpp)
add_executable(testCommuModules ${testSrc})
target_link_libraries(testCommuModules commu utils ssl crypto debugTools ${GTEST_LIBS})
add_test(Name testCommuModules
COMMAND testCommuModules)

View File

@ -1,10 +0,0 @@
//
// Created by Eric Saturn on 2019/12/12.
//
#include <gtest/gtest.h>
int main(int argc, char *argv[]){
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -1,107 +0,0 @@
#include <gtest/gtest.h>
#include "debug_tools/print_tools.h"
#include "communicate/message.h"
using namespace Net;
TEST(Option_Test, base_test_1) {
Option op = Option("Size", "123");
Option op2 = std::move(op);
ASSERT_EQ(op.getKey(), "Size");
ASSERT_EQ(op.getValue(), "123");
ASSERT_EQ(op2.getKey(), "Size");
ASSERT_EQ(op2.getValue(), "123");
}
TEST(Message_Test, base_test_1) {
Message msg = Message();
msg.setHead(1, 0x1);
string buf = "hello world, wellcome";
msg.pushData((void *const)buf.data(), buf.size());
vector<char> rd;;
MessageFactory mf;
mf.encodeMessage(msg, rd);
PrintTools::printInfoBuffer(rd, "Message Raw Data");
for(auto &c : rd) {
printf("%c", c);
}
printf("\n");
ASSERT_TRUE(mf.decodeMessage(rd, msg));
ASSERT_EQ(msg.getTID(), 1);
printf("SIGN: %s\n", msg.getValue("sign").c_str());;
printf("DATE: %s\n", msg.getValue("date").c_str());;
printf("SIZE: %s\n", msg.getValue("size").c_str());;
ASSERT_EQ(msg.getData()[20], 'e');
ASSERT_EQ(msg.getData()[19], 'm');
ASSERT_EQ(msg.getData()[0], 'h');
ASSERT_TRUE(mf.checkMessageSign(msg));
}
TEST(MessageParser_Test, base_test_1) {
Message msg;
msg.setHead(0x2, 0x1);
msg.addOption("abc", "def");
char buf[] = "Hello WWWWWWWW!";
msg.pushData(buf, sizeof(buf));
MessageFactory mf;
vector<char> rd;
mf.encodeMessage(msg, rd);
MessageParser mp;
mp.parse(rd.data(), rd.size());
ASSERT_EQ(mp.getMessageCount(), 1);
shared_ptr<Message> p_msg = mp.getMessage();
ASSERT_EQ(p_msg->getData().size(), msg.getData().size());
ASSERT_EQ(p_msg->getTID(), msg.getTID());
ASSERT_EQ(p_msg->getValue("abc"), "def");
mp.parse(&rd[0], 8);
mp.parse(&rd[8], 32);
mp.parse(&rd[40], 100);
mp.parse(&rd[140], 27);
ASSERT_EQ(mp.getMessageCount(), 1);
mp.parse(&rd[0], 14);
mp.parse(&rd[14], 1);
mp.parse(&rd[15], 34);
mp.parse(&rd[49], 11);
mp.parse(&rd[60], 107);
ASSERT_EQ(mp.getMessageCount(), 2);
p_msg = mp.getMessage();
ASSERT_EQ(p_msg->getData().size(), msg.getData().size());
ASSERT_EQ(p_msg->getTID(), msg.getTID());
ASSERT_EQ(p_msg->getValue("abc"), "def");
ASSERT_EQ(mp.getMessageCount(), 1);
mp.parse(&rd[0], 15);
mp.parse(&rd[16], 34);
mp.parse(&rd[50], 10);
mp.parse(&rd[60], 107);
ASSERT_EQ(mp.getMessageCount(), 1);
mp.parse(&rd[0], 16);
mp.parse(&rd[16], 34);
mp.parse(&rd[50], 10);
mp.parse(&rd[60], 107);
ASSERT_EQ(mp.getMessageCount(), 1);
}

View File

@ -10,12 +10,11 @@
using namespace Net; using namespace Net;
TEST(SHA256Test, base_test_1){ TEST(SHA256Test, base_test_1){
SHA256Generator generator; SHA256Generator generator("Hello World.");
generator.setRawData("Hello World.");
generator.generate(); generator.generate();
PrintTools::printInfo(generator.getHex(), "SHA256 Hex"); PrintTools::printInfo(generator.getHex(), "SHA256 Hex");
ASSERT_EQ(generator.getHex(), ASSERT_EQ(generator.getHex(),
std::string("f4bb1975bf1f81f76ce824f7536c1e101a8060a632a52289d530a6f600d52c92")); std::string("f4bb1975bf1f81f76ce824f7536c1e101a8060a632a52289d530a6f600d52c92"));
} }