1+ #include < memory>
2+ #include < mutex>
13#ifdef CPPNET_OPENSSL
24#include " openssl/err.h"
35#include " openssl/ssl.h"
79
810namespace cppnet {
911
10- SSLSocket::SSLSocket (SSL *ssl, const Socket &soc) {
12+ SSLSocket::SSLSocket (SSL *ssl, const Socket &soc, Mode mode ) {
1113 if (ssl == nullptr ) {
1214 err_msg_ = " [logicerr]:ssl is nullptr" ;
1315 return ;
@@ -20,6 +22,11 @@ SSLSocket::SSLSocket(SSL *ssl, const Socket &soc) {
2022 ssl_ = ssl;
2123 SSL_set_fd (ssl_, fd_);
2224 status_ = kInit ;
25+
26+ if (mode_ == Mode::kSafely ) {
27+ pmutex_ = std::make_unique<std::mutex>();
28+ }
29+ mode_ = mode;
2330}
2431
2532int SSLSocket::Close () {
@@ -33,6 +40,11 @@ int SSLSocket::Close() {
3340}
3441
3542int SSLSocket::CloseSSL () {
43+ std::shared_ptr<std::lock_guard<std::mutex>> plock_guard = nullptr ;
44+ if (mode_ == Mode::kSafely && pmutex_ != nullptr ) {
45+ plock_guard = std::make_shared<std::lock_guard<std::mutex>>(*pmutex_);
46+ }
47+
3648 if (ssl_ != nullptr ) {
3749 SSL_shutdown (ssl_);
3850 SSL_free (ssl_);
@@ -61,6 +73,15 @@ int SSLSocket::Connect(Address &addr) {
6173}
6274
6375int SSLSocket::IORead (void *buf, size_t len, int flag) {
76+ std::shared_ptr<std::lock_guard<std::mutex>> plock_guard = nullptr ;
77+ if (mode_ == Mode::kSafely && pmutex_ != nullptr ) {
78+ plock_guard = std::make_shared<std::lock_guard<std::mutex>>(*pmutex_);
79+ if (ssl_ == nullptr ) {
80+ err_msg_ = " [syserr]:ssl is nullptr" ;
81+ return kLogicErr ;
82+ }
83+ }
84+
6485 if (flag == MSG_WAITALL) {
6586 auto rc = 0 ;
6687 auto total_len = 0 ;
@@ -80,6 +101,15 @@ int SSLSocket::IORead(void *buf, size_t len, int flag) {
80101}
81102
82103int SSLSocket::IOWrite (const void *buf, size_t len, int flag) {
104+ std::shared_ptr<std::lock_guard<std::mutex>> plock_guard = nullptr ;
105+ if (mode_ == Mode::kSafely && pmutex_ != nullptr ) {
106+ plock_guard = std::make_shared<std::lock_guard<std::mutex>>(*pmutex_);
107+ if (ssl_ == nullptr ) {
108+ err_msg_ = " [syserr]:ssl is nullptr" ;
109+ return kLogicErr ;
110+ }
111+ }
112+
83113 return SSL_write (ssl_, buf, len);
84114}
85115
0 commit comments