Network System 0.1.1
High-performance modular networking library for scalable client-server applications
Loading...
Searching...
No Matches
kcenon::network::session::secure_session Class Reference

Manages a single connected secure (TLS/SSL) client session on the server side, providing asynchronous encrypted read/write operations. More...

#include <secure_session.h>

Inheritance diagram for kcenon::network::session::secure_session:
Inheritance graph
Collaboration diagram for kcenon::network::session::secure_session:
Collaboration graph

Public Member Functions

 secure_session (asio::ip::tcp::socket socket, asio::ssl::context &ssl_context, std::string_view server_id)
 Constructs a secure session with a given socket, SSL context, and server_id.
 
 ~secure_session () noexcept
 Destructor; calls stop_session() if not already stopped.
 
auto start_session () -> void
 Starts the session: performs SSL handshake, sets up read/error callbacks, and begins reading data.
 
auto stop_session () -> void
 Stops the session by closing the socket and marking the session as inactive.
 
auto is_stopped () const noexcept -> bool
 Checks if the session has been stopped.
 
auto send_packet (std::vector< uint8_t > &&data) -> void
 Sends data to the connected client with encryption.
 
auto set_receive_callback (std::function< void(const std::vector< uint8_t > &)> callback) -> void
 Sets the callback for received data.
 
auto set_disconnection_callback (std::function< void(const std::string &)> callback) -> void
 Sets the callback for disconnection.
 
auto set_error_callback (std::function< void(std::error_code)> callback) -> void
 Sets the callback for errors.
 
auto server_id () const -> const std::string &
 Gets the server identifier.
 

Private Member Functions

auto on_receive (const std::vector< uint8_t > &data) -> void
 Callback for when encrypted data arrives from the client.
 
auto on_error (std::error_code ec) -> void
 Callback for handling socket errors from secure_tcp_socket.
 
auto process_next_message () -> void
 Processes pending messages from the queue.
 

Private Attributes

std::string server_id_
 
std::shared_ptr< internal::secure_tcp_socketsocket_
 
std::atomic< bool > is_stopped_
 
std::deque< std::vector< uint8_t > > pending_messages_
 Queue of pending received messages awaiting processing.
 
std::mutex queue_mutex_
 Mutex protecting access to pending_messages_ queue.
 
std::function< void(const std::vector< uint8_t > &)> receive_callback_
 Callbacks for session events.
 
std::function< void(const std::string &)> disconnection_callback_
 
std::function< void(std::error_code)> error_callback_
 
std::mutex callback_mutex_
 Mutex protecting callback access.
 

Static Private Attributes

static constexpr size_t max_pending_messages_ = 1000
 Maximum number of pending messages before applying backpressure.
 

Detailed Description

Manages a single connected secure (TLS/SSL) client session on the server side, providing asynchronous encrypted read/write operations.

Responsibilities

  • Owns a secure_tcp_socket for non-blocking encrypted I/O.
  • Performs SSL handshake before data transmission.
  • Optionally applies compression/encryption via pipeline_ before sending, and can do the reverse upon receiving data (if needed).
  • Provides callbacks (on_receive, on_error) for data handling and error detection.

Lifecycle

  • Constructed with an accepted asio::ip::tcp::socket and SSL context.
  • start_session() performs SSL handshake and begins reading.
  • stop_session() closes the underlying socket, stopping further I/O.

Thread Safety

  • All public methods are thread-safe.
  • Session state (is_stopped_) is protected by atomic operations.
  • Pipeline mode flags are protected by mode_mutex_.
  • Socket operations are serialized through ASIO's io_context.

Definition at line 63 of file secure_session.h.

Constructor & Destructor Documentation

◆ secure_session()

kcenon::network::session::secure_session::secure_session ( asio::ip::tcp::socket socket,
asio::ssl::context & ssl_context,
std::string_view server_id )

Constructs a secure session with a given socket, SSL context, and server_id.

Parameters
socketThe asio::ip::tcp::socket (already connected).
ssl_contextSSL context for encryption settings.
server_idAn identifier for this server instance or context.

Definition at line 11 of file secure_session.cpp.

15 // Create the secure_tcp_socket wrapper
16 socket_ = std::make_shared<internal::secure_tcp_socket>(std::move(socket),
17 ssl_context);
18}
std::shared_ptr< internal::secure_tcp_socket > socket_
auto server_id() const -> const std::string &
Gets the server identifier.

References socket_.

◆ ~secure_session()

kcenon::network::session::secure_session::~secure_session ( )
noexcept

Destructor; calls stop_session() if not already stopped.

Definition at line 20 of file secure_session.cpp.

20 {
21 try {
22 // Call stop_session to clean up resources
24 } catch (...) {
25 // Destructor must not throw - swallow all exceptions
26 }
27}
auto stop_session() -> void
Stops the session by closing the socket and marking the session as inactive.

References stop_session().

Here is the call graph for this function:

Member Function Documentation

◆ is_stopped()

auto kcenon::network::session::secure_session::is_stopped ( ) const -> bool
inlinenodiscardnoexcept

Checks if the session has been stopped.

Returns
true if the session is stopped, false otherwise.

Definition at line 98 of file secure_session.h.

98 {
99 return is_stopped_.load(std::memory_order_relaxed);
100 }

References is_stopped_.

◆ on_error()

auto kcenon::network::session::secure_session::on_error ( std::error_code ec) -> void
private

Callback for handling socket errors from secure_tcp_socket.

Parameters
ecThe std::error_code describing the error.

By default, logs the error and calls stop_session().

Definition at line 145 of file secure_session.cpp.

145 {
146 NETWORK_LOG_ERROR("[secure_session] Socket error: " + ec.message());
147
148 // Invoke error callback if set
149 {
150 std::lock_guard<std::mutex> lock(callback_mutex_);
151 if (error_callback_) {
152 try {
153 error_callback_(ec);
154 } catch (const std::exception &e) {
155 NETWORK_LOG_ERROR("[secure_session] Exception in error callback: " +
156 std::string(e.what()));
157 }
158 }
159 }
160
161 stop_session();
162}
std::mutex callback_mutex_
Mutex protecting callback access.
std::function< void(std::error_code)> error_callback_
#define NETWORK_LOG_ERROR(msg)

References NETWORK_LOG_ERROR.

◆ on_receive()

auto kcenon::network::session::secure_session::on_receive ( const std::vector< uint8_t > & data) -> void
private

Callback for when encrypted data arrives from the client.

Parameters
dataA vector containing a chunk of received bytes.

Override or extend the logic here to parse messages, handle commands, etc. If decompression/decryption is needed, apply pipeline_ accordingly.

Definition at line 107 of file secure_session.cpp.

107 {
108 if (is_stopped_.load()) {
109 return;
110 }
111
112 NETWORK_LOG_DEBUG("[secure_session] Received " + std::to_string(data.size()) +
113 " bytes.");
114
115 // Check queue size before adding
116 {
117 std::lock_guard<std::mutex> lock(queue_mutex_);
118 size_t queue_size = pending_messages_.size();
119
120 // Apply backpressure if queue is getting full
121 if (queue_size >= max_pending_messages_) {
122 NETWORK_LOG_WARN("[secure_session] Queue size (" +
123 std::to_string(queue_size) + ") reached limit (" +
124 std::to_string(max_pending_messages_) +
125 "). Applying backpressure.");
126
127 // If queue is severely overflowing, disconnect the session
128 if (queue_size >= max_pending_messages_ * 2) {
129 NETWORK_LOG_ERROR("[secure_session] Queue overflow (" +
130 std::to_string(queue_size) +
131 "). Disconnecting abusive client.");
132 stop_session();
133 return;
134 }
135 }
136
137 // Add message to queue
138 pending_messages_.push_back(data);
139 }
140
141 // Process messages from queue
143}
auto process_next_message() -> void
Processes pending messages from the queue.
std::mutex queue_mutex_
Mutex protecting access to pending_messages_ queue.
std::deque< std::vector< uint8_t > > pending_messages_
Queue of pending received messages awaiting processing.
static constexpr size_t max_pending_messages_
Maximum number of pending messages before applying backpressure.
#define NETWORK_LOG_WARN(msg)
#define NETWORK_LOG_DEBUG(msg)

References NETWORK_LOG_DEBUG, NETWORK_LOG_ERROR, and NETWORK_LOG_WARN.

◆ process_next_message()

auto kcenon::network::session::secure_session::process_next_message ( ) -> void
private

Processes pending messages from the queue.

This method dequeues and processes messages one at a time. Implement actual message handling logic here.

Definition at line 164 of file secure_session.cpp.

164 {
165 std::vector<uint8_t> message;
166
167 // Dequeue one message
168 {
169 std::lock_guard<std::mutex> lock(queue_mutex_);
170 if (pending_messages_.empty()) {
171 return;
172 }
173
174 message = std::move(pending_messages_.front());
175 pending_messages_.pop_front();
176 }
177
178 // Process the message
180 "[secure_session] Processing message of " +
181 std::to_string(message.size()) +
182 " bytes. Queue remaining: " + std::to_string(pending_messages_.size()));
183
184 // Invoke receive callback if set
185 {
186 std::lock_guard<std::mutex> lock(callback_mutex_);
187 if (receive_callback_) {
188 try {
190 } catch (const std::exception &e) {
191 NETWORK_LOG_ERROR("[secure_session] Exception in receive callback: " +
192 std::string(e.what()));
193 }
194 }
195 }
196
197 // If there are more messages, process them asynchronously
198 // to avoid blocking the receive thread
199 std::lock_guard<std::mutex> lock(queue_mutex_);
200 if (!pending_messages_.empty()) {
201 // In a production system, you might want to post this to a thread pool
202 // or use a work queue to process messages asynchronously
203 // For now, we just process one message per call
204 }
205}
std::function< void(const std::vector< uint8_t > &)> receive_callback_
Callbacks for session events.

References kcenon::network::message, NETWORK_LOG_DEBUG, and NETWORK_LOG_ERROR.

◆ send_packet()

auto kcenon::network::session::secure_session::send_packet ( std::vector< uint8_t > && data) -> void

Sends data to the connected client with encryption.

Parameters
dataThe raw bytes to transmit (moved for efficiency).

Notes

  • If compress_mode_ or encrypt_mode_ is true, the data will be processed by the pipeline's compress/encrypt functions before writing.
  • Data is moved (not copied) to avoid memory allocation overhead.
  • After calling this function, the original vector will be empty.

Definition at line 90 of file secure_session.cpp.

90 {
91 if (is_stopped_.load()) {
92 return;
93 }
94
95 // Send data directly over the secure connection
96 socket_->async_send(
97 std::move(data), [](std::error_code ec, std::size_t bytes_transferred) {
98 if (ec) {
99 NETWORK_LOG_ERROR("[secure_session] Send error: " + ec.message());
100 } else {
101 NETWORK_LOG_DEBUG("[secure_session] Sent " +
102 std::to_string(bytes_transferred) + " bytes");
103 }
104 });
105}

References NETWORK_LOG_DEBUG, and NETWORK_LOG_ERROR.

◆ server_id()

auto kcenon::network::session::secure_session::server_id ( ) const -> const std::string&
inlinenodiscard

Gets the server identifier.

Returns
The server_id string.

Definition at line 140 of file secure_session.h.

140 {
141 return server_id_;
142 }

References server_id_.

◆ set_disconnection_callback()

auto kcenon::network::session::secure_session::set_disconnection_callback ( std::function< void(const std::string &)> callback) -> void

Sets the callback for disconnection.

Parameters
callbackFunction called when the session stops.

Definition at line 213 of file secure_session.cpp.

214 {
215 std::lock_guard<std::mutex> lock(callback_mutex_);
216 disconnection_callback_ = std::move(callback);
217}
std::function< void(const std::string &)> disconnection_callback_

◆ set_error_callback()

auto kcenon::network::session::secure_session::set_error_callback ( std::function< void(std::error_code)> callback) -> void

Sets the callback for errors.

Parameters
callbackFunction called when an error occurs.

Definition at line 219 of file secure_session.cpp.

220 {
221 std::lock_guard<std::mutex> lock(callback_mutex_);
222 error_callback_ = std::move(callback);
223}

◆ set_receive_callback()

auto kcenon::network::session::secure_session::set_receive_callback ( std::function< void(const std::vector< uint8_t > &)> callback) -> void

Sets the callback for received data.

Parameters
callbackFunction called when data is received.

Definition at line 207 of file secure_session.cpp.

208 {
209 std::lock_guard<std::mutex> lock(callback_mutex_);
210 receive_callback_ = std::move(callback);
211}

◆ start_session()

auto kcenon::network::session::secure_session::start_session ( ) -> void

Starts the session: performs SSL handshake, sets up read/error callbacks, and begins reading data.

Definition at line 29 of file secure_session.cpp.

29 {
30 if (is_stopped_.load()) {
31 return;
32 }
33
34 // Perform SSL handshake first
35 auto self = shared_from_this();
36 socket_->async_handshake(
37 asio::ssl::stream_base::server, [this, self](std::error_code ec) {
38 if (ec) {
39 NETWORK_LOG_ERROR("[secure_session] SSL handshake failed: " +
40 ec.message());
42 return;
43 }
44
45 NETWORK_LOG_INFO("[secure_session] SSL handshake completed");
46
47 // Set up callbacks after successful handshake
48 socket_->set_receive_callback(
49 [this, self](const std::vector<uint8_t> &data) {
50 on_receive(data);
51 });
52 socket_->set_error_callback(
53 [this, self](std::error_code ec) { on_error(ec); });
54
55 // Begin reading
56 socket_->start_read();
57
58 NETWORK_LOG_INFO("[secure_session] Started secure session on server: " +
60 });
61}
auto on_error(std::error_code ec) -> void
Callback for handling socket errors from secure_tcp_socket.
auto on_receive(const std::vector< uint8_t > &data) -> void
Callback for when encrypted data arrives from the client.
#define NETWORK_LOG_INFO(msg)

References NETWORK_LOG_ERROR, and NETWORK_LOG_INFO.

◆ stop_session()

auto kcenon::network::session::secure_session::stop_session ( ) -> void

Stops the session by closing the socket and marking the session as inactive.

Definition at line 63 of file secure_session.cpp.

63 {
64 if (is_stopped_.exchange(true)) {
65 return;
66 }
67 // Close socket safely using atomic close() method
68 // This prevents data races between close and async read operations
69 if (socket_) {
70 socket_->close();
71 }
72
73 // Invoke disconnection callback if set
74 {
75 std::lock_guard<std::mutex> lock(callback_mutex_);
77 try {
79 } catch (const std::exception &e) {
81 "[secure_session] Exception in disconnection callback: " +
82 std::string(e.what()));
83 }
84 }
85 }
86
87 NETWORK_LOG_INFO("[secure_session] Stopped.");
88}

References NETWORK_LOG_ERROR, and NETWORK_LOG_INFO.

Referenced by ~secure_session().

Here is the caller graph for this function:

Member Data Documentation

◆ callback_mutex_

std::mutex kcenon::network::session::secure_session::callback_mutex_
mutableprivate

Mutex protecting callback access.

Definition at line 209 of file secure_session.h.

◆ disconnection_callback_

std::function<void(const std::string&)> kcenon::network::session::secure_session::disconnection_callback_
private

Definition at line 203 of file secure_session.h.

◆ error_callback_

std::function<void(std::error_code)> kcenon::network::session::secure_session::error_callback_
private

Definition at line 204 of file secure_session.h.

◆ is_stopped_

std::atomic<bool> kcenon::network::session::secure_session::is_stopped_
private
Initial value:
{
false
}

Indicates whether this session is stopped.

Definition at line 177 of file secure_session.h.

177 {
178 false
179 };

Referenced by is_stopped().

◆ max_pending_messages_

size_t kcenon::network::session::secure_session::max_pending_messages_ = 1000
staticconstexprprivate

Maximum number of pending messages before applying backpressure.

When this limit is reached, a warning is logged. If doubled, the session is disconnected.

Definition at line 197 of file secure_session.h.

◆ pending_messages_

std::deque<std::vector<uint8_t> > kcenon::network::session::secure_session::pending_messages_
private

Queue of pending received messages awaiting processing.

Definition at line 184 of file secure_session.h.

◆ queue_mutex_

std::mutex kcenon::network::session::secure_session::queue_mutex_
mutableprivate

Mutex protecting access to pending_messages_ queue.

Definition at line 189 of file secure_session.h.

◆ receive_callback_

std::function<void(const std::vector<uint8_t>&)> kcenon::network::session::secure_session::receive_callback_
private

Callbacks for session events.

Definition at line 202 of file secure_session.h.

◆ server_id_

std::string kcenon::network::session::secure_session::server_id_
private

Identifier for the server side.

Definition at line 172 of file secure_session.h.

Referenced by server_id().

◆ socket_

std::shared_ptr<internal::secure_tcp_socket> kcenon::network::session::secure_session::socket_
private

The wrapped secure TCP socket for this session.

Definition at line 175 of file secure_session.h.

Referenced by secure_session().


The documentation for this class was generated from the following files: