-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTcpSession.cpp
192 lines (177 loc) · 4.91 KB
/
TcpSession.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
* Copyright (C) 2021 Ilya Entin
*/
#include "TcpSession.h"
#include <array>
#include "Server.h"
#include "ServerOptions.h"
#include "Task.h"
#include "Tcp.h"
namespace tcp {
TcpSession::TcpSession(ServerWeakPtr server,
ConnectionPtr connection,
std::string_view msgHash,
const CryptoPP::SecByteBlock& pubB,
std::string_view signatureWithPubKey) :
RunnableT(ServerOptions::_maxTcpSessions),
Session(server, msgHash, pubB, signatureWithPubKey),
_connection(std::move(connection)),
_ioContext(_connection->_ioContext),
_socket(std::move(_connection->_socket)),
_timeoutTimer(_ioContext) {}
bool TcpSession::start() {
boost::system::error_code ec;
_socket.set_option(boost::asio::socket_base::reuse_address(true), ec);
if (ec) {
LogError << ec.what() << '\n';
return false;
}
Info << _socket.local_endpoint() << ' ' << _socket.remote_endpoint() << '\n';
boost::asio::post(_ioContext, [this] { readRequest(); });
return true;
}
void TcpSession::sendStatusToClient() {
auto lambda = [this] (
const HEADER& header, std::string_view idStr, const CryptoPP::SecByteBlock& pubA) {
Tcp::sendMsg(_socket, header, idStr, pubA);
};
Session::sendStatusToClient(lambda, _status);
}
void TcpSession::run() noexcept {
try {
switch (_status) {
case STATUS::MAX_OBJECTS_OF_TYPE:
case STATUS::MAX_TOTAL_OBJECTS:
_status = STATUS::NONE;
break;
default:
break;
}
CountRunning countRunning;
_ioContext.run();
}
catch (const std::exception& e) {
LogError << e.what() << '\n';
}
}
void TcpSession::stop() {
_stopped = true;
_ioContext.stop();
}
bool TcpSession::sendReply() {
auto [header, payload] = buildReply(_status);
if (payload.empty())
return false;
asyncWait();
boost::asio::post(_ioContext, [this, header] { write(header); });
return true;
}
void TcpSession::readRequest() {
asyncWait();
boost::asio::async_read_until(_socket,
boost::asio::dynamic_string_buffer(_request),
ENDOFMESSAGE,
[this] (const boost::system::error_code& ec, std::size_t transferred) {
if (_request.ends_with(ENDOFMESSAGE))
_request.erase(transferred - ENDOFMESSAGESZ);
auto self = weak_from_this().lock();
if (!self)
return;
if (ec) {
switch (ec.value()) {
case boost::asio::error::eof:
case boost::asio::error::connection_reset:
case boost::asio::error::broken_pipe:
case boost::asio::error::connection_refused:
Info << ec.what() << '\n';
break;
default:
Warn << ec.what() << '\n';
break;
}
boost::asio::post(_ioContext, [this] {
_timeoutTimer.cancel();
});
return;
}
if (processTask())
boost::asio::post(_ioContext, [this] { sendReply(); });
else {
boost::asio::post(_ioContext, [this] {
_timeoutTimer.cancel();
});
}
});
std::size_t numberCanceled = _timeoutTimer.cancel();
if (numberCanceled == 0) {
LogError << "timeout\n";
_status = STATUS::TCP_TIMEOUT;
}
}
void TcpSession::write(const HEADER& header) {
char headerBuffer[HEADER_SIZE] = {};
serialize(header, headerBuffer);
std::array<boost::asio::const_buffer, 3> asioBuffers{ boost::asio::buffer(headerBuffer),
boost::asio::buffer(_responseData),
boost::asio::buffer(ENDOFMESSAGE) };
boost::asio::async_write(_socket,
asioBuffers,
boost::asio::transfer_all(),
[this](const boost::system::error_code& ec, std::size_t transferred[[maybe_unused]]) {
auto self = weak_from_this().lock();
if (!self)
return;
if (ec) {
LogError << ec.what() << '\n';
boost::asio::post(_ioContext, [this] {
_timeoutTimer.cancel();
});
return;
}
std::size_t numberCanceled = _timeoutTimer.cancel();
if (numberCanceled == 0) {
LogError << "timeout\n";
_status = STATUS::TCP_TIMEOUT;
return;
}
_request.erase(_request.cbegin(), _request.cend());
boost::asio::post(_ioContext, [this] { readRequest(); });
});
}
void TcpSession::asyncWait() {
boost::system::error_code ec;
_timeoutTimer.expires_from_now(
boost::posix_time::milliseconds(ServerOptions::_tcpTimeout), ec);
if (ec) {
LogError << ec.what() << '\n';
return;
}
_timeoutTimer.async_wait([this](const boost::system::error_code& ec) {
auto self = weak_from_this().lock();
if (!self)
return;
if (ec) {
switch (ec.value()) {
case boost::asio::error::eof:
case boost::asio::error::connection_reset:
case boost::asio::error::broken_pipe:
case boost::asio::error::connection_refused:
Info << ec.what() << '\n';
break;
case boost::asio::error::operation_aborted:
break;
default:
LogError << ec.what() << '\n';
break;
}
}
});
}
void TcpSession::displayCapacityCheck(std::atomic<unsigned>& totalNumberObjects) const {
Session::displayCapacityCheck(totalNumberObjects,
getNumberObjects(),
getNumberRunningByType(),
_maxNumberRunningByType,
_status);
}
} // end of namespace tcp