From cf8e3cf696c7c3a074f3d79b478dee47c185c8d1 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 26 Jun 2020 20:28:56 +0800 Subject: [PATCH 1/9] Add Comment; Chang the CMake structure of the Project; --- CMakeLists.txt | 27 ++------- include/cmap.h | 2 +- include/cproj.h | 2 +- .../{error.h => debug_tools/print_tools.h} | 13 +++-- .../rsa_key_chain.h} | 23 +++++--- .../sha256_generator.h} | 4 ++ src/CMakeLists.txt | 2 + src/debug_tools/CMakeLists.txt | 1 + .../print_tools.cpp} | 26 ++++----- src/utils/CMakeLists.txt | 1 + .../rsa_key_chain.cpp} | 7 ++- .../sha256_generator.cpp} | 5 +- test/CMakeLists.txt | 8 +++ test/env.h | 2 +- test/rsa_test.cpp | 52 ------------------ test/test_util/CMakeLists.txt | 9 +++ test/{test_main.cpp => test_util/main.cpp} | 8 +-- test/test_util/test_rsa.cpp | 55 +++++++++++++++++++ 18 files changed, 134 insertions(+), 113 deletions(-) rename include/{error.h => debug_tools/print_tools.h} (70%) rename include/{rsa_cpp_binding.h => utils/rsa_key_chain.h} (88%) rename include/{sha256_cpp_binding.h => utils/sha256_generator.h} (89%) create mode 100644 src/CMakeLists.txt create mode 100644 src/debug_tools/CMakeLists.txt rename src/{error.cpp => debug_tools/print_tools.cpp} (66%) create mode 100644 src/utils/CMakeLists.txt rename src/{rsa_cpp_binding.cpp => utils/rsa_key_chain.cpp} (93%) rename src/{sha256_cpp_binding.cpp => utils/sha256_generator.cpp} (86%) create mode 100644 test/CMakeLists.txt delete mode 100644 test/rsa_test.cpp create mode 100644 test/test_util/CMakeLists.txt rename test/{test_main.cpp => test_util/main.cpp} (53%) create mode 100644 test/test_util/test_rsa.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 39864fd..e4430af 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.15) +cmake_minimum_required(VERSION 3.13) project(Net) set(CMAKE_CXX_STANDARD 14) @@ -7,29 +7,10 @@ include_directories(include/) include_directories(utils/) find_package(Boost REQUIRED) -find_package(OpenSSL REQUIRED) - -message(STATUS SSL ${OPENSSL_LIBRARIES}) - -include(GoogleTest) - -set(OPENSSL_LIBS /usr/local/lib/libssl.dylib /usr/local/lib/libcrypto.dylib) -set(GTEST_LIB /usr/local/lib/) -set(GTEST_LIBS gtest pthread dl) +find_package(OpenSSL 1.1.1 REQUIRED) include_directories(${Boost_INCLUDE_DIRS} ${OPENSSL_INCLUDE_DIR} ${SQLiteCpp_INCLUDE_DIRS}) -link_directories(${GTEST_LIB}) -aux_source_directory(src SOURCE_ALL) +add_subdirectory(src) -add_executable(NetTest test/test_main.cpp) - -gtest_add_tests(TARGET NetTest - TEST_SUFFIX .noArgs - TEST_LIST noArgsTests) - -add_library(m_error STATIC src/error.cpp) -add_library(m_rsa STATIC src/rsa_cpp_binding.cpp) - -target_link_libraries(NetTest m_rsa m_error ${GTEST_LIBS} ssl crypto boost_program_options) -set_tests_properties(${noArgsTests} PROPERTIES TIMEOUT 10) \ No newline at end of file +add_subdirectory(test) \ No newline at end of file diff --git a/include/cmap.h b/include/cmap.h index 9307956..53a8bee 100644 --- a/include/cmap.h +++ b/include/cmap.h @@ -11,7 +11,7 @@ #include "type.h" #include "cpart.h" -#include "sha256_cpp_binding.h" +#include "util/sha256_generator.h" #include "sql.h" //计算模块管理对象间的依赖关系管理结构 diff --git a/include/cproj.h b/include/cproj.h index 949b1cc..fce1c8a 100644 --- a/include/cproj.h +++ b/include/cproj.h @@ -11,7 +11,7 @@ #include "type.h" #include "cpart.h" -#include "sha256_cpp_binding.h" +#include "util/sha256_generator.h" #include "sql.h" class Proj; diff --git a/include/error.h b/include/debug_tools/print_tools.h similarity index 70% rename from include/error.h rename to include/debug_tools/print_tools.h index d20088d..548764e 100644 --- a/include/error.h +++ b/include/debug_tools/print_tools.h @@ -2,8 +2,8 @@ // Created by Eric Saturn on 2019/12/12. // -#ifndef NET_ERROR_H -#define NET_ERROR_H +#ifndef NET_PRINT_TOOLS_H +#define NET_PRINT_TOOLS_H #include #include @@ -14,7 +14,8 @@ using std::pair; //提示信息打印类函数 namespace Net { - namespace error { + + namespace printTools { using FormalItem = pair; @@ -22,17 +23,17 @@ namespace Net { void printWarning(string warning_info); - void printSuccess(string succes_info); + void printSuccess(string success_info); void printRed(string red_info); void printInfo(const string& info, string tag = ""); - void printInfoBuffer(const string& info, string tag = ""); + void printInfoBuffer(const string& info, const string& tag = ""); void printInfoFormal(const string& title, initializer_list body); } } -#endif //NET_ERROR_H +#endif //NET_PRINT_TOOLS_H diff --git a/include/rsa_cpp_binding.h b/include/utils/rsa_key_chain.h similarity index 88% rename from include/rsa_cpp_binding.h rename to include/utils/rsa_key_chain.h index 97a179f..07861ab 100644 --- a/include/rsa_cpp_binding.h +++ b/include/utils/rsa_key_chain.h @@ -2,11 +2,11 @@ // Created by Eric Saturn on 2019/12/10. // -#ifndef NET_RSA_CPP_BINDING_H -#define NET_RSA_CPP_BINDING_H +#ifndef NET_RSA_KEY_CHAIN_H +#define NET_RSA_KEY_CHAIN_H -#include "error.h" -#include "../src/bignumber.cpp" +#include "debug_tools/print_tools.h" +#include "../../src/bignumber.cpp" #include #include @@ -18,6 +18,10 @@ using namespace std; namespace Net { + + /** + * The Public Key For A RSA Key Chain + */ class RSAPubKey{ public: explicit RSAPubKey(const RSA *rsa){ @@ -29,7 +33,7 @@ namespace Net { } void printInfo(){ - error::printInfoFormal("RSAPubKey Info", { + printTools::printInfoFormal("RSAPubKey Info", { {"n", this->n.getDataHex()}, {"e", this->e.getDataHex()} }); @@ -39,6 +43,9 @@ namespace Net { BigNumber e; }; + /** + * The Private Key For A RSA Key Chain + */ class RSAPrvKey{ public: explicit RSAPrvKey(const RSA *rsa) { @@ -54,8 +61,8 @@ namespace Net { this->q.copyFrom(q); } - void printInfo(){ - error::printInfoFormal("RSAPrvKey Info", { + void printInfo() const{ + printTools::printInfoFormal("RSAPrvKey Info", { {"n", this->n.getDataHex()}, {"e", this->e.getDataHex()}, {"d", this->d.getDataHex()}, @@ -134,4 +141,4 @@ namespace Net { } -#endif //NET_RSA_CPP_BINDING_H +#endif //NET_RSA_KEY_CHAIN_H diff --git a/include/sha256_cpp_binding.h b/include/utils/sha256_generator.h similarity index 89% rename from include/sha256_cpp_binding.h rename to include/utils/sha256_generator.h index e3bb3ff..fc58c87 100644 --- a/include/sha256_cpp_binding.h +++ b/include/utils/sha256_generator.h @@ -9,6 +9,10 @@ using std::string; using std::ifstream; using std::stringstream; +/** + * The Generator of SHA256 Hex + * We can use it in an easy way. + */ class SHA256Generator{ public: SHA256Generator(string data){ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..4f991e6 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(utils) +add_subdirectory(debug_tools) \ No newline at end of file diff --git a/src/debug_tools/CMakeLists.txt b/src/debug_tools/CMakeLists.txt new file mode 100644 index 0000000..7c1e1a5 --- /dev/null +++ b/src/debug_tools/CMakeLists.txt @@ -0,0 +1 @@ +add_library(debugTools STATIC print_tools.cpp) \ No newline at end of file diff --git a/src/error.cpp b/src/debug_tools/print_tools.cpp similarity index 66% rename from src/error.cpp rename to src/debug_tools/print_tools.cpp index d6ba7f1..072ab80 100644 --- a/src/error.cpp +++ b/src/debug_tools/print_tools.cpp @@ -2,29 +2,29 @@ // Created by Eric Saturn on 2019/12/12. // -#include "error.h" +#include "debug_tools/print_tools.h" using std::string; namespace Net { - namespace error { - void printError(string error_info) { + namespace printTools { + void printError(const string &error_info) { printf("\033[31mError: %s\033[0m\n", error_info.data()); } - void printWarning(string warning_info) { + void printWarning(const string &warning_info) { printf("\033[33mWarning: %s\033[0m\n", warning_info.data()); } - void printSuccess(string succes_info) { - printf("\033[32m%s\033[0m\n", succes_info.data()); + void printSuccess(const string &success_info) { + printf("\033[32m%s\033[0m\n", success_info.data()); } - void printRed(string red_info) { + void printRed(const string &red_info) { printf("\033[31m%s\n\033[0m", red_info.data()); } - void printInfo(const string& info, string tag) { + void printInfo(const string& info, string &tag) { printf("[DEBUG INFO] %s ", info.data()); if(tag.size()) printf("{ %s }\n",tag.data()); @@ -33,17 +33,17 @@ namespace Net { void printInfoFormal(const string& title, initializer_list body) { printf("\n>>>\n {%s}\n",title.data()); printf(">-------------------------------------\n"); - for(auto item : body){ + for(auto &item : body){ printf("[%s] : \"%s\"; \n", item.first.data(), item.second.data()); } printf("----------------------------------<\n<<<\n\n"); } - void printInfoBuffer(const string &info, string tag) { + void printInfoBuffer(const string &info, const string& tag) { printf("\n[DEBUG INFO (BUFFER)]\n"); printf(">----------------------------------------------\n"); - uint8_t *p_i = (uint8_t *) &info[0]; - uint8_t *p_e = (uint8_t *) &info[info.size()-1]; + 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); @@ -51,7 +51,7 @@ namespace Net { } printf("\n"); printf("----------------------------------------------<\n"); - if(tag.size()) + if(!tag.empty()) printf("{ %s }\n\n",tag.data()); } } diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt new file mode 100644 index 0000000..c2e71bb --- /dev/null +++ b/src/utils/CMakeLists.txt @@ -0,0 +1 @@ +add_library(utils STATIC rsa_key_chain.cpp) \ No newline at end of file diff --git a/src/rsa_cpp_binding.cpp b/src/utils/rsa_key_chain.cpp similarity index 93% rename from src/rsa_cpp_binding.cpp rename to src/utils/rsa_key_chain.cpp index 6a9b774..9880f19 100644 --- a/src/rsa_cpp_binding.cpp +++ b/src/utils/rsa_key_chain.cpp @@ -2,7 +2,10 @@ // Created by Eric Saturn on 2019/12/10. // -#include "rsa_cpp_binding.h" +#include +#include "utils/rsa_key_chain.h" + +using std::runtime_error; void Net::RSAKeyChain::generateKeyPair() { BigNumber e; @@ -56,6 +59,6 @@ bool Net::RSAKeyChain::checkKey() { if(!this->if_prv_key) throw runtime_error("illegal call of checkKey"); if(this->key_pair == nullptr) throw runtime_error("key pair is invalid"); int return_code = RSA_check_key(this->key_pair); - if(return_code == -1) throw runtime_error("error occur when rsa check key"); + if(return_code == -1) throw runtime_error("printTools occur when rsa check key"); else return return_code == 1; } diff --git a/src/sha256_cpp_binding.cpp b/src/utils/sha256_generator.cpp similarity index 86% rename from src/sha256_cpp_binding.cpp rename to src/utils/sha256_generator.cpp index bfc5301..cd75f18 100644 --- a/src/sha256_cpp_binding.cpp +++ b/src/utils/sha256_generator.cpp @@ -1,6 +1,9 @@ #include "type.h" -#include "sha256_cpp_binding.h" +#include "util/sha256_generator.h" +/** + * Generate SHA256 Hex Code + */ void SHA256Generator::generate() { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000..65da75a --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,8 @@ +find_package(GTest REQUIRED) + +set(GTEST_LIB /usr/local/lib/) +set(GTEST_LIBS gtest gmock pthread dl) + +link_directories(${GTEST_LIB}) + +add_subdirectory(test_util) diff --git a/test/env.h b/test/env.h index fd39229..d2f2d1c 100644 --- a/test/env.h +++ b/test/env.h @@ -5,7 +5,7 @@ #ifndef NET_ENV_H #define NET_ENV_H -#include "rsa_cpp_binding.h" +#include "utils/rsa_key_chain.h" class GlobalTestEnv : public testing::Environment{ public: diff --git a/test/rsa_test.cpp b/test/rsa_test.cpp deleted file mode 100644 index 1ae60bd..0000000 --- a/test/rsa_test.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// -// Created by Eric Saturn on 2019/12/12. -// - -#include -#include - -#include "env.h" - -using namespace Net; -using namespace std; - -extern GlobalTestEnv *_env; - -TEST(RSATest, init_test_1) { - -} - -TEST(RSATest, generate_test_1) { - _env->rsa->generateKeyPair(); - error::printInfo(to_string(_env->rsa->getBufferSize()), string("Buffer Size")); -} - -TEST(RSATest, pub_encrypt_test_1) { - string encrypted_data; - _env->rsa->publicKeyEncrypt(_env->rsa_test_data, encrypted_data); - error::printInfoBuffer(encrypted_data, "Encrypted Data"); - _env->rsa_encrypt_data = encrypted_data; -} - -TEST(RSATest, prv_decrypt_test_1){ - string data; - _env->rsa->privateKeyDecrypt(data, _env->rsa_encrypt_data); - error::printInfo(data, "Decrypt Data"); - ASSERT_EQ(data, _env->rsa_test_data); -} - -TEST(RSATest, pub_key_get_test_1){ - _env->pubKey = shared_ptr(new RSAPubKey(_env->rsa->getRSA())); - -} - -TEST(RSATest, prv_key_get_test_1){ - _env->prvKey = shared_ptr(new RSAPrvKey(_env->rsa->getRSA())); - ASSERT_EQ(_env->rsa->checkKey(), true); - _env->prvKey->printInfo(); -} - -TEST(RSATest, prv_key_build_key_chain){ - RSAKeyChain keyChain(*_env->prvKey); - ASSERT_EQ(keyChain.checkKey(), true); -} \ No newline at end of file diff --git a/test/test_util/CMakeLists.txt b/test/test_util/CMakeLists.txt new file mode 100644 index 0000000..6925f9a --- /dev/null +++ b/test/test_util/CMakeLists.txt @@ -0,0 +1,9 @@ + +add_executable(testUtils main.cpp) + +message(${GTEST_LIBS}) + +link_libraries(testUtils utils debugTools ${GTEST_LIBS}) + +add_test(Name testUtils + COMMAND testUtils) \ No newline at end of file diff --git a/test/test_main.cpp b/test/test_util/main.cpp similarity index 53% rename from test/test_main.cpp rename to test/test_util/main.cpp index 39098e8..d9a0cf1 100644 --- a/test/test_main.cpp +++ b/test/test_util/main.cpp @@ -4,14 +4,12 @@ #include -#include "rsa_test.cpp" +#include "../env.h" -#include "env.h" - -GlobalTestEnv *_env; +GlobalTestEnv *env; int main(int argc, char *argv[]){ ::testing::InitGoogleTest(&argc, argv); - _env = dynamic_cast(::testing::AddGlobalTestEnvironment(new GlobalTestEnv)); + env = dynamic_cast(::testing::AddGlobalTestEnvironment(new GlobalTestEnv)); return RUN_ALL_TESTS(); } diff --git a/test/test_util/test_rsa.cpp b/test/test_util/test_rsa.cpp new file mode 100644 index 0000000..79dc25c --- /dev/null +++ b/test/test_util/test_rsa.cpp @@ -0,0 +1,55 @@ +// +// Created by Eric Saturn on 2019/12/12. +// + +#include + +#include + +#include "../env.h" + +#include "utils/rsa_key_chain.h" + +using namespace Net; +using namespace std; + +extern GlobalTestEnv *env; + +TEST(RSATest, init_test_1) { + +} + +TEST(RSATest, generate_test_1) { + env->rsa->generateKeyPair(); + printTools::printInfo(to_string(env->rsa->getBufferSize()), string("Buffer Size")); +} + +TEST(RSATest, pub_encrypt_test_1) { + string encrypted_data; + env->rsa->publicKeyEncrypt(env->rsa_test_data, encrypted_data); + printTools::printInfoBuffer(encrypted_data, "Encrypted Data"); + env->rsa_encrypt_data = encrypted_data; +} + +TEST(RSATest, prv_decrypt_test_1){ + string data; + env->rsa->privateKeyDecrypt(data, env->rsa_encrypt_data); + printTools::printInfo(data, "Decrypt Data"); + ASSERT_EQ(data, env->rsa_test_data); +} + +TEST(RSATest, pub_key_get_test_1){ + env->pubKey = std::make_shared(env->rsa->getRSA()); + +} + +TEST(RSATest, prv_key_get_test_1){ + env->prvKey = std::make_shared(env->rsa->getRSA()); + ASSERT_EQ(env->rsa->checkKey(), true); + env->prvKey->printInfo(); +} + +TEST(RSATest, prv_key_build_key_chain){ + RSAKeyChain keyChain(*env->prvKey); + ASSERT_EQ(keyChain.checkKey(), true); +} \ No newline at end of file From d7fa7cde37f493a3fea3b514fcdc1a27082f9c2b Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 26 Jun 2020 22:13:27 +0800 Subject: [PATCH 2/9] solve some problems on linker. --- CMakeLists.txt | 2 ++ include/debug_tools/print_tools.h | 2 +- src/debug_tools/print_tools.cpp | 4 ++-- src/utils/CMakeLists.txt | 4 +++- test/test_util/CMakeLists.txt | 4 ++-- test/test_util/test_rsa.cpp | 3 ++- 6 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e4430af..60d5931 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,6 +11,8 @@ find_package(OpenSSL 1.1.1 REQUIRED) include_directories(${Boost_INCLUDE_DIRS} ${OPENSSL_INCLUDE_DIR} ${SQLiteCpp_INCLUDE_DIRS}) +enable_testing() + add_subdirectory(src) add_subdirectory(test) \ No newline at end of file diff --git a/include/debug_tools/print_tools.h b/include/debug_tools/print_tools.h index 548764e..f128306 100644 --- a/include/debug_tools/print_tools.h +++ b/include/debug_tools/print_tools.h @@ -27,7 +27,7 @@ namespace Net { void printRed(string red_info); - void printInfo(const string& info, string tag = ""); + void printInfo(const string& info, const string& tag = ""); void printInfoBuffer(const string& info, const string& tag = ""); diff --git a/src/debug_tools/print_tools.cpp b/src/debug_tools/print_tools.cpp index 072ab80..b84cd25 100644 --- a/src/debug_tools/print_tools.cpp +++ b/src/debug_tools/print_tools.cpp @@ -24,9 +24,9 @@ namespace Net { printf("\033[31m%s\n\033[0m", red_info.data()); } - void printInfo(const string& info, string &tag) { + void printInfo(const string& info, const string& tag) { printf("[DEBUG INFO] %s ", info.data()); - if(tag.size()) + if(!tag.empty()) printf("{ %s }\n",tag.data()); } diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index c2e71bb..be848b2 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1 +1,3 @@ -add_library(utils STATIC rsa_key_chain.cpp) \ No newline at end of file +add_library(utils STATIC rsa_key_chain.cpp) + +target_link_libraries(utils debugTools ssl crypto) \ No newline at end of file diff --git a/test/test_util/CMakeLists.txt b/test/test_util/CMakeLists.txt index 6925f9a..22e7f6b 100644 --- a/test/test_util/CMakeLists.txt +++ b/test/test_util/CMakeLists.txt @@ -1,9 +1,9 @@ -add_executable(testUtils main.cpp) +add_executable(testUtils main.cpp test_rsa.cpp) message(${GTEST_LIBS}) -link_libraries(testUtils utils debugTools ${GTEST_LIBS}) +target_link_libraries(testUtils utils debugTools ${GTEST_LIBS}) add_test(Name testUtils COMMAND testUtils) \ No newline at end of file diff --git a/test/test_util/test_rsa.cpp b/test/test_util/test_rsa.cpp index 79dc25c..ac443b4 100644 --- a/test/test_util/test_rsa.cpp +++ b/test/test_util/test_rsa.cpp @@ -21,7 +21,8 @@ TEST(RSATest, init_test_1) { TEST(RSATest, generate_test_1) { env->rsa->generateKeyPair(); - printTools::printInfo(to_string(env->rsa->getBufferSize()), string("Buffer Size")); + string data = std::to_string(env->rsa->getBufferSize()); + printTools::printInfo(data, "Buffer Size"); } TEST(RSATest, pub_encrypt_test_1) { From d11f31cd024ef7297559fdcbee86d3573ed5cd44 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 26 Jun 2020 22:15:37 +0800 Subject: [PATCH 3/9] solve problems on cmake. --- include/debug_tools/print_tools.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/debug_tools/print_tools.h b/include/debug_tools/print_tools.h index f128306..68e0a33 100644 --- a/include/debug_tools/print_tools.h +++ b/include/debug_tools/print_tools.h @@ -27,9 +27,9 @@ namespace Net { void printRed(string red_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 printInfoFormal(const string& title, initializer_list body); } From 7b01638c9f92f817c289871d1c544b2d827e5352 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 26 Jun 2020 22:18:21 +0800 Subject: [PATCH 4/9] make cmake files better. --- test/test_util/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test_util/CMakeLists.txt b/test/test_util/CMakeLists.txt index 22e7f6b..598a561 100644 --- a/test/test_util/CMakeLists.txt +++ b/test/test_util/CMakeLists.txt @@ -1,5 +1,7 @@ -add_executable(testUtils main.cpp test_rsa.cpp) +file(GLOB testSrc *.cpp) + +add_executable(testUtils ${testSrc}) message(${GTEST_LIBS}) From 48b9f1b65e7a066e9668d4ba2179a0b455316f16 Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 7 Jul 2020 03:28:29 +0800 Subject: [PATCH 5/9] Add aes cbc module --- include/debug_tools/print_tools.h | 2 +- include/utils/aes_cbc_encryptor.h | 50 +++++++++++++++++++++++ include/utils/random_generator.h | 30 ++++++++++++++ include/utils/rsa_key_chain.h | 7 +++- include/utils/sha256_generator.h | 1 + src/debug_tools/print_tools.cpp | 2 +- src/utils/CMakeLists.txt | 2 +- src/utils/aes_cbc_encryptor.cpp | 68 +++++++++++++++++++++++++++++++ src/utils/random_generator.cpp | 11 +++++ src/utils/rsa_key_chain.cpp | 12 +++--- test/test_util/test_aes.cpp | 25 ++++++++++++ test/test_util/test_rsa.cpp | 6 +-- 12 files changed, 201 insertions(+), 15 deletions(-) create mode 100644 include/utils/aes_cbc_encryptor.h create mode 100644 include/utils/random_generator.h create mode 100644 src/utils/aes_cbc_encryptor.cpp create mode 100644 src/utils/random_generator.cpp create mode 100644 test/test_util/test_aes.cpp diff --git a/include/debug_tools/print_tools.h b/include/debug_tools/print_tools.h index 68e0a33..bce018a 100644 --- a/include/debug_tools/print_tools.h +++ b/include/debug_tools/print_tools.h @@ -15,7 +15,7 @@ using std::pair; //提示信息打印类函数 namespace Net { - namespace printTools { + namespace PrintTools { using FormalItem = pair; diff --git a/include/utils/aes_cbc_encryptor.h b/include/utils/aes_cbc_encryptor.h new file mode 100644 index 0000000..6777f88 --- /dev/null +++ b/include/utils/aes_cbc_encryptor.h @@ -0,0 +1,50 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#ifndef NET_AES_CBC_ENCRYPTOR_H +#define NET_AES_CBC_ENCRYPTOR_H + +#include +#include +#include +#include +#include + +#include "debug_tools/print_tools.h" +#include "random_generator.h" + +namespace Net { + + class AESCBCEncryptor { + public: + + AESCBCEncryptor() { + generate_random_key_data(); + aes_init(key_data); + } + + string getKeyData() const{ + return key_data; + } + + void encrypt(const std::string &data, std::string &encrypted_data); + + void decrypt(std::string &data, const std::string &encrypt_data); + + private: + const int nrounds = 8; + uint8_t key[32], iv[32]; + EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new(); + + std::string key_data; + + void generate_random_key_data(); + + void aes_init(std::string &key_data); + + }; + +} + +#endif //NET_AES_CBC_ENCRYPTOR_H diff --git a/include/utils/random_generator.h b/include/utils/random_generator.h new file mode 100644 index 0000000..e18ff84 --- /dev/null +++ b/include/utils/random_generator.h @@ -0,0 +1,30 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#ifndef NET_RANDOM_GENERATOR_H +#define NET_RANDOM_GENERATOR_H + +#include +#include + +namespace Net{ + namespace Rand{ + +// 范围均匀分布无符号32位整数 + class UniformUInt { + public: + UniformUInt(uint32_t min, uint32_t max) : uniformInt(min, max){ + + } + + int generate() const; + private: + boost::uniform_int uniformInt; + }; + + } +} + + +#endif //NET_RANDOM_GENERATOR_H diff --git a/include/utils/rsa_key_chain.h b/include/utils/rsa_key_chain.h index 07861ab..5cdbe8d 100644 --- a/include/utils/rsa_key_chain.h +++ b/include/utils/rsa_key_chain.h @@ -33,7 +33,7 @@ namespace Net { } void printInfo(){ - printTools::printInfoFormal("RSAPubKey Info", { + PrintTools::printInfoFormal("RSAPubKey Info", { {"n", this->n.getDataHex()}, {"e", this->e.getDataHex()} }); @@ -62,7 +62,7 @@ namespace Net { } void printInfo() const{ - printTools::printInfoFormal("RSAPrvKey Info", { + PrintTools::printInfoFormal("RSAPrvKey Info", { {"n", this->n.getDataHex()}, {"e", this->e.getDataHex()}, {"d", this->d.getDataHex()}, @@ -102,13 +102,16 @@ namespace Net { this->if_prv_key = true; } +// 生成一对公私钥 void generateKeyPair(); // 检查私钥是否合法 bool checkKey(); +// 公钥加密 void publicKeyEncrypt(const string &data, string &encrypted_data); +// 私钥解密 void privateKeyDecrypt(string &data, const string& encrypted_data); uint32_t getBufferSize() const { diff --git a/include/utils/sha256_generator.h b/include/utils/sha256_generator.h index fc58c87..bbaf89f 100644 --- a/include/utils/sha256_generator.h +++ b/include/utils/sha256_generator.h @@ -32,6 +32,7 @@ public: if(!if_generate) generate(); return this->sha256_data; } + private: bool if_generate = false; string raw_data; diff --git a/src/debug_tools/print_tools.cpp b/src/debug_tools/print_tools.cpp index b84cd25..a974def 100644 --- a/src/debug_tools/print_tools.cpp +++ b/src/debug_tools/print_tools.cpp @@ -7,7 +7,7 @@ using std::string; namespace Net { - namespace printTools { + namespace PrintTools { void printError(const string &error_info) { printf("\033[31mError: %s\033[0m\n", error_info.data()); } diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index be848b2..6d39b9b 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,3 +1,3 @@ -add_library(utils STATIC rsa_key_chain.cpp) +add_library(utils STATIC rsa_key_chain.cpp aes_cbc_encryptor.cpp random_generator.cpp) target_link_libraries(utils debugTools ssl crypto) \ No newline at end of file diff --git a/src/utils/aes_cbc_encryptor.cpp b/src/utils/aes_cbc_encryptor.cpp new file mode 100644 index 0000000..7de5b60 --- /dev/null +++ b/src/utils/aes_cbc_encryptor.cpp @@ -0,0 +1,68 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include "utils/aes_cbc_encryptor.h" + + +void Net::AESCBCEncryptor::encrypt(const string &data, string &encrypted_data) { + int c_len = data.length() + AES_BLOCK_SIZE, f_len = 0; + + auto *encrypt_buffer = reinterpret_cast(malloc(c_len)); + + EVP_EncryptInit_ex(e_ctx, nullptr, nullptr, nullptr, nullptr); + EVP_EncryptUpdate(e_ctx, encrypt_buffer, &c_len, + reinterpret_cast(data.data()), data.length()); + EVP_EncryptFinal_ex(e_ctx, encrypt_buffer + c_len, &f_len); + + int len = c_len + f_len; + + if(!encrypted_data.empty()) encrypted_data.clear(); + + encrypted_data.append(reinterpret_cast(encrypt_buffer), len); + + free(encrypt_buffer); +} + +void Net::AESCBCEncryptor::decrypt(string &data, const string &encrypt_data) { + int p_len = encrypt_data.length(), f_len = 0; + auto *plain_buffer = static_cast(malloc(p_len)); + + EVP_DecryptInit_ex(e_ctx, nullptr, nullptr, nullptr, nullptr); + EVP_DecryptUpdate(e_ctx, plain_buffer, &p_len, + reinterpret_cast(encrypt_data.data()), encrypt_data.length()); + EVP_DecryptFinal_ex(e_ctx, plain_buffer + p_len, &f_len); + + int len = p_len + f_len; + + if(!data.empty()) data.clear(); + + data.append(reinterpret_cast(plain_buffer), len); + + free(plain_buffer); +} + +void Net::AESCBCEncryptor::generate_random_key_data() { + Rand::UniformUInt rand(0, UINT32_MAX); + + uint32_t p_data[8]; + for(unsigned int & i : p_data){ + i = rand.generate(); + } + + key_data.append(reinterpret_cast(p_data), 32); +} + +void Net::AESCBCEncryptor::aes_init(string &key_data) { + + + int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), nullptr, + reinterpret_cast(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); +} diff --git a/src/utils/random_generator.cpp b/src/utils/random_generator.cpp new file mode 100644 index 0000000..81d2d5b --- /dev/null +++ b/src/utils/random_generator.cpp @@ -0,0 +1,11 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include "utils/random_generator.h" + +boost::random::mt19937 rand_seed; + +int Net::Rand::UniformUInt::generate() const { + return uniformInt(rand_seed); +} diff --git a/src/utils/rsa_key_chain.cpp b/src/utils/rsa_key_chain.cpp index 9880f19..a11d80a 100644 --- a/src/utils/rsa_key_chain.cpp +++ b/src/utils/rsa_key_chain.cpp @@ -24,13 +24,12 @@ void Net::RSAKeyChain::privateKeyDecrypt(string &data, const string &encrypted_d if(this->key_pair == nullptr) throw runtime_error("key pair is invalid"); if(encrypted_data.size() != buffer_size) throw runtime_error("encrypt data's size is abnormal"); // 使用私钥解密 - int decrypted_size = -1; unique_ptrp_buffer (new unsigned char[buffer_size]); - if((decrypted_size = RSA_private_decrypt(encrypted_data.size(), + if(RSA_private_decrypt(encrypted_data.size(), reinterpret_cast(&encrypted_data[0]), p_buffer.get(), key_pair, - RSA_PKCS1_OAEP_PADDING)) == -1) + RSA_PKCS1_OAEP_PADDING) == -1) throw runtime_error(ERR_error_string(ERR_get_error(), nullptr)); else data = string(reinterpret_cast(p_buffer.get())); } @@ -46,12 +45,11 @@ void Net::RSAKeyChain::publicKeyEncrypt(const string &data, string &encrypted_da string tmp_data = data; tmp_data.resize(buffer_size - 42); // 使用公钥加密 - int encrypted_size = -1; - if((encrypted_size = RSA_public_encrypt(tmp_data.size(), + if(RSA_public_encrypt(tmp_data.size(), reinterpret_cast(&tmp_data[0]), reinterpret_cast(&encrypted_data[0]), key_pair, - RSA_PKCS1_OAEP_PADDING)) == -1) + RSA_PKCS1_OAEP_PADDING) == -1) throw runtime_error(ERR_error_string(ERR_get_error(), nullptr)); } @@ -59,6 +57,6 @@ bool Net::RSAKeyChain::checkKey() { if(!this->if_prv_key) throw runtime_error("illegal call of checkKey"); if(this->key_pair == nullptr) throw runtime_error("key pair is invalid"); int return_code = RSA_check_key(this->key_pair); - if(return_code == -1) throw runtime_error("printTools occur when rsa check key"); + if(return_code == -1) throw runtime_error("PrintTools occur when rsa check key"); else return return_code == 1; } diff --git a/test/test_util/test_aes.cpp b/test/test_util/test_aes.cpp new file mode 100644 index 0000000..8c3ff64 --- /dev/null +++ b/test/test_util/test_aes.cpp @@ -0,0 +1,25 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include + +#include "utils/aes_cbc_encryptor.h" + +using namespace Net; + +TEST(AES_Test, base_test_1){ + AESCBCEncryptor encryptor; + + PrintTools::printInfoBuffer(encryptor.getKeyData(), "Key Data"); + + std::string data, encrypt_data; + + encryptor.encrypt("Hello World", encrypt_data); + + PrintTools::printInfoBuffer(encrypt_data, "Encrypt Data"); + + encryptor.decrypt(data, encrypt_data); + + ASSERT_EQ(data, std::string("Hello World")); +} \ No newline at end of file diff --git a/test/test_util/test_rsa.cpp b/test/test_util/test_rsa.cpp index ac443b4..ff8131d 100644 --- a/test/test_util/test_rsa.cpp +++ b/test/test_util/test_rsa.cpp @@ -22,20 +22,20 @@ TEST(RSATest, init_test_1) { TEST(RSATest, generate_test_1) { env->rsa->generateKeyPair(); string data = std::to_string(env->rsa->getBufferSize()); - printTools::printInfo(data, "Buffer Size"); + PrintTools::printInfo(data, "Buffer Size"); } TEST(RSATest, pub_encrypt_test_1) { string encrypted_data; env->rsa->publicKeyEncrypt(env->rsa_test_data, encrypted_data); - printTools::printInfoBuffer(encrypted_data, "Encrypted Data"); + PrintTools::printInfoBuffer(encrypted_data, "Encrypted Data"); env->rsa_encrypt_data = encrypted_data; } TEST(RSATest, prv_decrypt_test_1){ string data; env->rsa->privateKeyDecrypt(data, env->rsa_encrypt_data); - printTools::printInfo(data, "Decrypt Data"); + PrintTools::printInfo(data, "Decrypt Data"); ASSERT_EQ(data, env->rsa_test_data); } From 7ed517a56140059e04413c89c5540aa2aeaae42b Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 7 Jul 2020 10:12:06 +0800 Subject: [PATCH 6/9] fix problem on aes. --- src/utils/aes_cbc_encryptor.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/aes_cbc_encryptor.cpp b/src/utils/aes_cbc_encryptor.cpp index 7de5b60..bcf627c 100644 --- a/src/utils/aes_cbc_encryptor.cpp +++ b/src/utils/aes_cbc_encryptor.cpp @@ -10,7 +10,7 @@ void Net::AESCBCEncryptor::encrypt(const string &data, string &encrypted_data) { auto *encrypt_buffer = reinterpret_cast(malloc(c_len)); - EVP_EncryptInit_ex(e_ctx, nullptr, nullptr, nullptr, nullptr); + EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); EVP_EncryptUpdate(e_ctx, encrypt_buffer, &c_len, reinterpret_cast(data.data()), data.length()); EVP_EncryptFinal_ex(e_ctx, encrypt_buffer + c_len, &f_len); @@ -21,14 +21,14 @@ void Net::AESCBCEncryptor::encrypt(const string &data, string &encrypted_data) { encrypted_data.append(reinterpret_cast(encrypt_buffer), len); - free(encrypt_buffer); + EVP_CIPHER_CTX_reset(e_ctx); } void Net::AESCBCEncryptor::decrypt(string &data, const string &encrypt_data) { int p_len = encrypt_data.length(), f_len = 0; auto *plain_buffer = static_cast(malloc(p_len)); - EVP_DecryptInit_ex(e_ctx, nullptr, nullptr, nullptr, nullptr); + EVP_DecryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); EVP_DecryptUpdate(e_ctx, plain_buffer, &p_len, reinterpret_cast(encrypt_data.data()), encrypt_data.length()); EVP_DecryptFinal_ex(e_ctx, plain_buffer + p_len, &f_len); @@ -39,7 +39,7 @@ void Net::AESCBCEncryptor::decrypt(string &data, const string &encrypt_data) { data.append(reinterpret_cast(plain_buffer), len); - free(plain_buffer); + EVP_CIPHER_CTX_reset(e_ctx); } void Net::AESCBCEncryptor::generate_random_key_data() { From fbd4f0695b708c175a59bf22917d15c91382397c Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 7 Jul 2020 10:37:08 +0800 Subject: [PATCH 7/9] add --- include/communicate/tcp_server.h | 16 +++++++++++++ include/type.h | 2 -- include/utils/aes_cbc_encryptor.h | 11 ++++----- include/utils/sha256_generator.h | 38 ++++++++++++++----------------- src/communicate/CMakeLists.txt | 5 ++++ src/communicate/tcp_server.cpp | 5 ++++ src/utils/CMakeLists.txt | 4 +++- src/utils/aes_cbc_encryptor.cpp | 9 ++++++++ src/utils/sha256_generator.cpp | 24 +++++++++++++++++-- test/test_util/test_sha.cpp | 20 ++++++++++++++++ 10 files changed, 101 insertions(+), 33 deletions(-) create mode 100644 include/communicate/tcp_server.h create mode 100644 src/communicate/CMakeLists.txt create mode 100644 src/communicate/tcp_server.cpp create mode 100644 test/test_util/test_sha.cpp diff --git a/include/communicate/tcp_server.h b/include/communicate/tcp_server.h new file mode 100644 index 0000000..7a25365 --- /dev/null +++ b/include/communicate/tcp_server.h @@ -0,0 +1,16 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#ifndef NET_TCP_SERVER_H +#define NET_TCP_SERVER_H + +namespace Net { + + class TCPServer { + + }; + +} + +#endif //NET_TCP_SERVER_H diff --git a/include/type.h b/include/type.h index 4f95d2f..7876a01 100644 --- a/include/type.h +++ b/include/type.h @@ -51,8 +51,6 @@ #include #include -#include - using std::string; using std::vector; diff --git a/include/utils/aes_cbc_encryptor.h b/include/utils/aes_cbc_encryptor.h index 6777f88..8eb1a3b 100644 --- a/include/utils/aes_cbc_encryptor.h +++ b/include/utils/aes_cbc_encryptor.h @@ -19,14 +19,9 @@ namespace Net { class AESCBCEncryptor { public: - AESCBCEncryptor() { - generate_random_key_data(); - aes_init(key_data); - } + AESCBCEncryptor(); - string getKeyData() const{ - return key_data; - } + string getKeyData() const; void encrypt(const std::string &data, std::string &encrypted_data); @@ -34,7 +29,9 @@ namespace Net { private: const int nrounds = 8; + uint8_t key[32], iv[32]; + EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new(); std::string key_data; diff --git a/include/utils/sha256_generator.h b/include/utils/sha256_generator.h index bbaf89f..ac988c0 100644 --- a/include/utils/sha256_generator.h +++ b/include/utils/sha256_generator.h @@ -9,32 +9,28 @@ using std::string; using std::ifstream; using std::stringstream; +namespace Net { + /** * The Generator of SHA256 Hex * We can use it in an easy way. */ -class SHA256Generator{ -public: - SHA256Generator(string data){ - this->raw_data = std::move(data); - } + class SHA256Generator { + public: + SHA256Generator(string data); - SHA256Generator(ifstream stream){ - while(stream.good()){ - stream >> raw_data; - } - stream.close(); - } + SHA256Generator(ifstream stream); - void generate(); + void replace(string &str); - string getHex(){ - if(!if_generate) generate(); - return this->sha256_data; - } + void generate(); -private: - bool if_generate = false; - string raw_data; - string sha256_data; -}; + string getHex(); + + private: + bool if_generate = false; + string raw_data; + string sha256_data; + }; + +} \ No newline at end of file diff --git a/src/communicate/CMakeLists.txt b/src/communicate/CMakeLists.txt new file mode 100644 index 0000000..78a9530 --- /dev/null +++ b/src/communicate/CMakeLists.txt @@ -0,0 +1,5 @@ +file(GLOB commuSrc *.cpp) + +add_library(commu STATIC ${commuSrc}) + +target_link_libraries(commu utils debugTools) \ No newline at end of file diff --git a/src/communicate/tcp_server.cpp b/src/communicate/tcp_server.cpp new file mode 100644 index 0000000..7dc2ca8 --- /dev/null +++ b/src/communicate/tcp_server.cpp @@ -0,0 +1,5 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include "communicate/tcp_server.h" diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index 6d39b9b..0fd6aa0 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,3 +1,5 @@ -add_library(utils STATIC rsa_key_chain.cpp aes_cbc_encryptor.cpp random_generator.cpp) +file(GLOB utilSrc *.cpp) + +add_library(utils STATIC ${utilSrc}) target_link_libraries(utils debugTools ssl crypto) \ No newline at end of file diff --git a/src/utils/aes_cbc_encryptor.cpp b/src/utils/aes_cbc_encryptor.cpp index bcf627c..33c06e9 100644 --- a/src/utils/aes_cbc_encryptor.cpp +++ b/src/utils/aes_cbc_encryptor.cpp @@ -66,3 +66,12 @@ void Net::AESCBCEncryptor::aes_init(string &key_data) { 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; +} + +Net::AESCBCEncryptor::AESCBCEncryptor() { + generate_random_key_data(); + aes_init(key_data); +} diff --git a/src/utils/sha256_generator.cpp b/src/utils/sha256_generator.cpp index cd75f18..09d3d91 100644 --- a/src/utils/sha256_generator.cpp +++ b/src/utils/sha256_generator.cpp @@ -1,10 +1,10 @@ #include "type.h" -#include "util/sha256_generator.h" +#include "utils/sha256_generator.h" /** * Generate SHA256 Hex Code */ -void SHA256Generator::generate() { +void Net::SHA256Generator::generate() { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); @@ -19,3 +19,23 @@ void SHA256Generator::generate() { sha256_data = buffer.str(); if_generate = true; } + +void Net::SHA256Generator::replace(string &str) { + this->raw_data = str; +} + +string Net::SHA256Generator::getHex() { + if (!if_generate) generate(); + return this->sha256_data; +} + +Net::SHA256Generator::SHA256Generator(ifstream stream) { + while (stream.good()) { + stream >> raw_data; + } + stream.close(); +} + +Net::SHA256Generator::SHA256Generator(string data) { + this->raw_data = std::move(data); +} diff --git a/test/test_util/test_sha.cpp b/test/test_util/test_sha.cpp new file mode 100644 index 0000000..b213fe6 --- /dev/null +++ b/test/test_util/test_sha.cpp @@ -0,0 +1,20 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include + +#include "utils/sha256_generator.h" +#include "debug_tools/print_tools.h" + +using namespace Net; + +TEST(SHA256Test, base_test_1){ + SHA256Generator generator("Hello World."); + generator.generate(); + + PrintTools::printInfo(generator.getHex(), "SHA256 Hex"); + + ASSERT_EQ(generator.getHex(), + std::string("f4bb1975bf1f81f76ce824f7536c1e101a8060a632a52289d530a6f600d52c92")); +} \ No newline at end of file From dd1e30d4ead64ca26733f1142542b15a0dcfc263 Mon Sep 17 00:00:00 2001 From: eric Date: Wed, 8 Jul 2020 02:58:41 +0800 Subject: [PATCH 8/9] add tcp server. --- include/communicate/tcp_server.h | 45 ++++++++++++++++++++++++ src/CMakeLists.txt | 3 +- src/communicate/tcp_server.cpp | 60 ++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 1 deletion(-) diff --git a/include/communicate/tcp_server.h b/include/communicate/tcp_server.h index 7a25365..ff732b1 100644 --- a/include/communicate/tcp_server.h +++ b/include/communicate/tcp_server.h @@ -5,10 +5,55 @@ #ifndef NET_TCP_SERVER_H #define NET_TCP_SERVER_H +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + + namespace Net { class TCPServer { + public: + TCPServer(int port, int max_connection); + ~TCPServer(){ + stop(); + close(fd); + } + + void stop(){ + if(p_accept_manager_thread != nullptr) + p_accept_manager_thread->interrupt(); + this->status = -1; + } + + uint8_t readByte(); + + private: + int fd; + int status = 0; + struct sockaddr_in server_addr; + std::stringstream recv_buff; + boost::mutex buff_mutex; + boost::thread *p_accept_manager_thread; + + void cycle(); + + static void accept_manager(TCPServer *server); + + static void accept(int fd, boost::mutex *buff_mutex, std::stringstream *recv_buff, const int *status); + + void create_socket(int port); }; } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4f991e6..f508e42 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,2 +1,3 @@ add_subdirectory(utils) -add_subdirectory(debug_tools) \ No newline at end of file +add_subdirectory(debug_tools) +add_subdirectory(communicate) \ No newline at end of file diff --git a/src/communicate/tcp_server.cpp b/src/communicate/tcp_server.cpp index 7dc2ca8..2e5feee 100644 --- a/src/communicate/tcp_server.cpp +++ b/src/communicate/tcp_server.cpp @@ -3,3 +3,63 @@ // #include "communicate/tcp_server.h" + +void Net::TCPServer::cycle() { + boost::thread accept_manager_thread(TCPServer::accept_manager, this); + this->p_accept_manager_thread = &accept_manager_thread; + accept_manager_thread.join(); +} + +void Net::TCPServer::accept_manager(Net::TCPServer *server) { + while(true){ + int connect_fd = ::accept(server->fd, nullptr, nullptr); + if(connect_fd == -1) throw std::runtime_error("accept tcp connection error"); + 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, std::stringstream *recv_buff, const int *status) { + uint8_t buff[1024]; + int len; + std::vector accept_buff; + while((len = recv(fd, buff, sizeof(buff), 0)) > 0 && *status == 0){ + for(int i = 0; i < len; ++i) accept_buff.push_back(buff[i]); + } + if(*status == 0) { + buff_mutex->lock(); + recv_buff->write(reinterpret_cast(accept_buff.data()), accept_buff.size()); + buff_mutex->unlock(); + } + close(fd); +} + +void Net::TCPServer::create_socket(int port) { + fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(!~fd) throw std::runtime_error("could not create socket file."); + + std::memset(&server_addr, 0, sizeof(struct sockaddr_in)); + server_addr.sin_family = AF_INET; + server_addr.sin_addr.s_addr = htonl(INADDR_ANY); + server_addr.sin_port = htons(port); +} + +Net::TCPServer::TCPServer(int port, int max_connection) { + + create_socket(port); + + if(bind(fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) + throw std::runtime_error("bind port failed."); + + if(listen(fd, max_connection) == -1) + throw std::runtime_error("listen socket failed."); + + + cycle(); +} + +uint8_t Net::TCPServer::readByte() { + return recv_buff.get(); +} From 9c6ba70c4502f0f32b0389df79cd88a832198546 Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 9 Jul 2020 02:30:27 +0800 Subject: [PATCH 9/9] add tcp client; test tcp server and client; --- CMakeLists.txt | 2 +- include/communicate/tcp_client.h | 45 +++++++++++++++++++++++++++++++ include/communicate/tcp_server.h | 5 ++-- include/debug_tools/print_tools.h | 8 +++--- src/communicate/CMakeLists.txt | 4 +-- src/communicate/tcp_client.cpp | 41 ++++++++++++++++++++++++++++ src/communicate/tcp_server.cpp | 23 +++++++++++++--- src/debug_tools/print_tools.cpp | 10 +++---- src/utils/CMakeLists.txt | 2 -- test/CMakeLists.txt | 1 + test/test_commu/CMakeLists.txt | 9 +++++++ test/test_commu/main.cpp | 31 +++++++++++++++++++++ test/test_util/CMakeLists.txt | 2 +- 13 files changed, 158 insertions(+), 25 deletions(-) create mode 100644 include/communicate/tcp_client.h create mode 100644 src/communicate/tcp_client.cpp create mode 100644 test/test_commu/CMakeLists.txt create mode 100644 test/test_commu/main.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 60d5931..9c6aa19 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ set(CMAKE_CXX_STANDARD 14) include_directories(include/) include_directories(utils/) -find_package(Boost REQUIRED) +find_package(Boost REQUIRED thread) find_package(OpenSSL 1.1.1 REQUIRED) include_directories(${Boost_INCLUDE_DIRS} ${OPENSSL_INCLUDE_DIR} ${SQLiteCpp_INCLUDE_DIRS}) diff --git a/include/communicate/tcp_client.h b/include/communicate/tcp_client.h new file mode 100644 index 0000000..f081424 --- /dev/null +++ b/include/communicate/tcp_client.h @@ -0,0 +1,45 @@ +// +// Created by 胡宇 on 2020/7/9. +// + +#ifndef NET_TCP_CLIENT_H +#define NET_TCP_CLIENT_H + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace Net { + + class TCPClient { + public: + TCPClient(const std::string &ip, int port); + + int sendData(const std::string &data); + + + private: + int fd{}; + struct sockaddr_in client_addr{}; + + std::stringstream recv_buff; + + void create_socket_and_connection(); + + void recv_cycle(); + + static void recv_data(TCPClient *client); + }; + +} + + +#endif //NET_TCP_CLIENT_H diff --git a/include/communicate/tcp_server.h b/include/communicate/tcp_server.h index ff732b1..90288bd 100644 --- a/include/communicate/tcp_server.h +++ b/include/communicate/tcp_server.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -43,7 +44,7 @@ namespace Net { int fd; int status = 0; struct sockaddr_in server_addr; - std::stringstream recv_buff; + std::queue recv_buff; boost::mutex buff_mutex; boost::thread *p_accept_manager_thread; @@ -51,7 +52,7 @@ namespace Net { static void accept_manager(TCPServer *server); - static void accept(int fd, boost::mutex *buff_mutex, std::stringstream *recv_buff, const int *status); + static void accept(int fd, boost::mutex *buff_mutex, std::queue *recv_buff, const int *status); void create_socket(int port); }; diff --git a/include/debug_tools/print_tools.h b/include/debug_tools/print_tools.h index bce018a..11e154f 100644 --- a/include/debug_tools/print_tools.h +++ b/include/debug_tools/print_tools.h @@ -19,13 +19,11 @@ namespace Net { using FormalItem = pair; - void printError(string error_info); + void debugPrintError(const string &error_info); - void printWarning(string warning_info); + void debugPrintWarning(const string &warning_info); - void printSuccess(string success_info); - - void printRed(string red_info); + void debugPrintSuccess(const string &success_info); void printInfo(const string& info, const string& tag); diff --git a/src/communicate/CMakeLists.txt b/src/communicate/CMakeLists.txt index 78a9530..aa67340 100644 --- a/src/communicate/CMakeLists.txt +++ b/src/communicate/CMakeLists.txt @@ -1,5 +1,3 @@ file(GLOB commuSrc *.cpp) -add_library(commu STATIC ${commuSrc}) - -target_link_libraries(commu utils debugTools) \ No newline at end of file +add_library(commu STATIC ${commuSrc}) \ No newline at end of file diff --git a/src/communicate/tcp_client.cpp b/src/communicate/tcp_client.cpp new file mode 100644 index 0000000..2f2053d --- /dev/null +++ b/src/communicate/tcp_client.cpp @@ -0,0 +1,41 @@ +// +// Created by 胡宇 on 2020/7/9. +// + +#include "communicate/tcp_client.h" + +void Net::TCPClient::recv_data(Net::TCPClient *client) { + u_char buff[1024]; + int len; + while ((len = recv(client->fd, buff, sizeof(buff), 0)) > 0) { + client->recv_buff.write(reinterpret_cast(buff), len); + } +} + +void Net::TCPClient::recv_cycle() { + boost::thread recv_thread(TCPClient::recv_data, + this); + recv_thread.detach(); +} + +void Net::TCPClient::create_socket_and_connection() { + if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { + throw std::runtime_error("create socket failed."); + } + connect(fd, (struct sockaddr *) &client_addr, sizeof(client_addr)); +} + +int Net::TCPClient::sendData(const std::string &data) { + create_socket_and_connection(); + recv_cycle(); + int len = send(fd, data.data(), data.size(), 0); + close(fd); + return len; +} + +Net::TCPClient::TCPClient(const std::string &ip, int port) { + std::memset(&client_addr, 0, sizeof(client_addr)); + client_addr.sin_family = AF_INET; + client_addr.sin_addr.s_addr = inet_addr(ip.c_str()); + client_addr.sin_port = htons(port); +} diff --git a/src/communicate/tcp_server.cpp b/src/communicate/tcp_server.cpp index 2e5feee..578fe72 100644 --- a/src/communicate/tcp_server.cpp +++ b/src/communicate/tcp_server.cpp @@ -2,17 +2,21 @@ // Created by 胡宇 on 2020/7/7. // +#include "debug_tools/print_tools.h" #include "communicate/tcp_server.h" void Net::TCPServer::cycle() { boost::thread accept_manager_thread(TCPServer::accept_manager, this); this->p_accept_manager_thread = &accept_manager_thread; - accept_manager_thread.join(); + accept_manager_thread.detach(); } void Net::TCPServer::accept_manager(Net::TCPServer *server) { + Net::PrintTools::debugPrintSuccess("AcceptManager Started."); while(true){ int connect_fd = ::accept(server->fd, nullptr, nullptr); + Net::PrintTools::debugPrintSuccess("New Connection."); + if(connect_fd == -1) throw std::runtime_error("accept tcp connection error"); else{ boost::thread accept_thread(TCPServer::accept, connect_fd, &server->buff_mutex, &server->recv_buff, &server->status); @@ -21,19 +25,23 @@ void Net::TCPServer::accept_manager(Net::TCPServer *server) { } } -void Net::TCPServer::accept(int fd, boost::mutex *buff_mutex, std::stringstream *recv_buff, const int *status) { +void Net::TCPServer::accept(int fd, boost::mutex *buff_mutex, std::queue *recv_buff, const int *status) { + Net::PrintTools::debugPrintSuccess("Try Getting Data From Connection."); uint8_t buff[1024]; int len; std::vector accept_buff; while((len = recv(fd, buff, sizeof(buff), 0)) > 0 && *status == 0){ + Net::PrintTools::debugPrintSuccess("Received."); for(int i = 0; i < len; ++i) accept_buff.push_back(buff[i]); } if(*status == 0) { buff_mutex->lock(); - recv_buff->write(reinterpret_cast(accept_buff.data()), accept_buff.size()); + for(unsigned char & i : accept_buff) + recv_buff->push(i); buff_mutex->unlock(); } close(fd); + Net::PrintTools::debugPrintSuccess("Connection Closed."); } void Net::TCPServer::create_socket(int port) { @@ -61,5 +69,12 @@ Net::TCPServer::TCPServer(int port, int max_connection) { } uint8_t Net::TCPServer::readByte() { - return recv_buff.get(); + uint8_t byte = '\0'; + buff_mutex.try_lock(); + if(!recv_buff.empty()) { + byte = recv_buff.front(); + recv_buff.pop(); + } + buff_mutex.unlock(); + return byte; } diff --git a/src/debug_tools/print_tools.cpp b/src/debug_tools/print_tools.cpp index a974def..dc46784 100644 --- a/src/debug_tools/print_tools.cpp +++ b/src/debug_tools/print_tools.cpp @@ -8,22 +8,18 @@ using std::string; namespace Net { namespace PrintTools { - void printError(const string &error_info) { + void debugPrintError(const string &error_info) { printf("\033[31mError: %s\033[0m\n", error_info.data()); } - void printWarning(const string &warning_info) { + void debugPrintWarning(const string &warning_info) { printf("\033[33mWarning: %s\033[0m\n", warning_info.data()); } - void printSuccess(const string &success_info) { + void debugPrintSuccess(const string &success_info) { printf("\033[32m%s\033[0m\n", success_info.data()); } - void printRed(const string &red_info) { - printf("\033[31m%s\n\033[0m", red_info.data()); - } - void printInfo(const string& info, const string& tag) { printf("[DEBUG INFO] %s ", info.data()); if(!tag.empty()) diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index 0fd6aa0..d327464 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,5 +1,3 @@ file(GLOB utilSrc *.cpp) add_library(utils STATIC ${utilSrc}) - -target_link_libraries(utils debugTools ssl crypto) \ No newline at end of file diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 65da75a..adb5254 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -6,3 +6,4 @@ set(GTEST_LIBS gtest gmock pthread dl) link_directories(${GTEST_LIB}) add_subdirectory(test_util) +add_subdirectory(test_commu) diff --git a/test/test_commu/CMakeLists.txt b/test/test_commu/CMakeLists.txt new file mode 100644 index 0000000..0634114 --- /dev/null +++ b/test/test_commu/CMakeLists.txt @@ -0,0 +1,9 @@ + +file(GLOB testSrc *.cpp) + +add_compile_definitions(DEBUG) + +add_executable(testCommu ${testSrc}) + +target_link_libraries(testCommu commu debugTools Boost::thread) + diff --git a/test/test_commu/main.cpp b/test/test_commu/main.cpp new file mode 100644 index 0000000..1d83182 --- /dev/null +++ b/test/test_commu/main.cpp @@ -0,0 +1,31 @@ +// +// Created by 胡宇 on 2020/7/9. +// + +#include +#include + +#include "debug_tools/print_tools.h" +#include "communicate/tcp_server.h" +#include "communicate/tcp_client.h" + +using namespace Net; + +int main(int argc, char *argv[]){ + if(fork() == 0) { + PrintTools::debugPrintSuccess("Child Started."); + TCPClient client("127.0.0.1", 9048); + for(int i = 0; i < 32; i++, usleep(1e4)) + client.sendData("Hello"); + PrintTools::debugPrintSuccess("Child Exited."); + } + else{ + PrintTools::debugPrintSuccess("Father Started."); + TCPServer server(9048, 100); + while (true){ + std::putchar(server.readByte()); + usleep(1e3); + } + } + return 0; +} \ No newline at end of file diff --git a/test/test_util/CMakeLists.txt b/test/test_util/CMakeLists.txt index 598a561..ffda1a7 100644 --- a/test/test_util/CMakeLists.txt +++ b/test/test_util/CMakeLists.txt @@ -5,7 +5,7 @@ add_executable(testUtils ${testSrc}) message(${GTEST_LIBS}) -target_link_libraries(testUtils utils debugTools ${GTEST_LIBS}) +target_link_libraries(testUtils utils debugTools ssl crypto ${GTEST_LIBS}) add_test(Name testUtils COMMAND testUtils) \ No newline at end of file