-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathconnection.cpp
More file actions
276 lines (232 loc) · 7.68 KB
/
Copy pathconnection.cpp
File metadata and controls
276 lines (232 loc) · 7.68 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2023 The Forgotten Server Authors and Alejandro Mujica for many specific source code changes, All rights reserved.
// Use of this source code is governed by the GPL-2.0 License that can be found in the LICENSE file.
#include "otpch.h"
#include "configmanager.h"
#include "connection.h"
#include "outputmessage.h"
#include "protocol.h"
#include "scheduler.h"
#include "server.h"
extern ConfigManager g_config;
Connection_ptr ConnectionManager::createConnection(boost::asio::io_context& io_context, ConstServicePort_ptr servicePort)
{
std::lock_guard<std::mutex> lockClass(connectionManagerLock);
auto connection = std::make_shared<Connection>(io_context, servicePort);
connections.insert(connection);
return connection;
}
void ConnectionManager::releaseConnection(const Connection_ptr& connection)
{
std::lock_guard<std::mutex> lockClass(connectionManagerLock);
connections.erase(connection);
}
void ConnectionManager::closeAll()
{
std::lock_guard<std::mutex> lockClass(connectionManagerLock);
for (const auto& connection : connections) {
try {
boost::system::error_code error;
connection->socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
connection->socket.close(error);
} catch (boost::system::system_error&) {
}
}
connections.clear();
}
// Connection
void Connection::close(bool force)
{
//any thread
ConnectionManager::getInstance().releaseConnection(shared_from_this());
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
if (closed) {
return;
}
closed = true;
if (protocol) {
g_dispatcher.addTask(
createTask(std::bind(&Protocol::release, protocol)));
}
if (messageQueue.empty() || force) {
closeSocket();
} else {
//will be closed by the destructor or onWriteOperation
}
}
void Connection::closeSocket()
{
if (socket.is_open()) {
try {
readTimer.cancel();
writeTimer.cancel();
boost::system::error_code error;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
socket.close(error);
} catch (boost::system::system_error& e) {
std::cout << "[Network error - Connection::closeSocket] " << e.what() << std::endl;
}
}
}
Connection::~Connection()
{
closeSocket();
}
void Connection::accept(Protocol_ptr protocol)
{
this->protocol = protocol;
g_dispatcher.addTask(createTask(std::bind(&Protocol::onConnect, protocol)));
accept();
}
void Connection::accept()
{
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
try {
readTimer.expires_after(std::chrono::seconds(CONNECTION_READ_TIMEOUT));
readTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr<Connection>(shared_from_this()), std::placeholders::_1));
// Read size of the first packet
boost::asio::async_read(socket,
boost::asio::buffer(msg.getBuffer(), NetworkMessage::HEADER_LENGTH),
std::bind(&Connection::parseHeader, shared_from_this(), std::placeholders::_1));
} catch (boost::system::system_error& e) {
std::cout << "[Network error - Connection::accept] " << e.what() << std::endl;
close(FORCE_CLOSE);
}
}
void Connection::parseHeader(const boost::system::error_code& error)
{
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
readTimer.cancel();
if (error) {
close(FORCE_CLOSE);
return;
} else if (closed) {
return;
}
//if (!g_dispatcher.beatIOSync)
// std::this_thread::sleep_for(std::chrono::milliseconds(50)); // Game Beat Delay
uint16_t size = msg.getLengthHeader();
if (size == 0 || size >= NETWORKMESSAGE_MAXSIZE - 16) {
close(FORCE_CLOSE);
return;
}
try {
readTimer.expires_after(std::chrono::seconds(CONNECTION_READ_TIMEOUT));
readTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr<Connection>(shared_from_this()),
std::placeholders::_1));
// Read packet content
msg.setLength(size + NetworkMessage::HEADER_LENGTH);
boost::asio::async_read(socket, boost::asio::buffer(msg.getBodyBuffer(), size),
std::bind(&Connection::parsePacket, shared_from_this(), std::placeholders::_1));
} catch (boost::system::system_error& e) {
std::cout << "[Network error - Connection::parseHeader] " << e.what() << std::endl;
close(FORCE_CLOSE);
}
}
void Connection::parsePacket(const boost::system::error_code& error)
{
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
readTimer.cancel();
if (error) {
close(FORCE_CLOSE);
return;
} else if (closed) {
return;
}
if (!receivedFirst) {
// First message received
receivedFirst = true;
if (!protocol) {
// Game protocol has already been created at this point
protocol = service_port->make_protocol(msg, shared_from_this());
if (!protocol) {
close(FORCE_CLOSE);
return;
}
} else {
msg.skipBytes(1); // Skip protocol ID
}
protocol->onRecvFirstMessage(msg);
} else {
protocol->onRecvMessage(msg); // Send the packet to the current protocol
}
try {
readTimer.expires_after(std::chrono::milliseconds(50));
readTimer.async_wait([self = shared_from_this()](const boost::system::error_code& ec) {
if (!ec) {
self->readTimer.expires_after(std::chrono::seconds(CONNECTION_READ_TIMEOUT));
self->readTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr<Connection>(self), std::placeholders::_1));
// Wait to the next packet
boost::asio::async_read(self->socket,
boost::asio::buffer(self->msg.getBuffer(), NetworkMessage::HEADER_LENGTH),
std::bind(&Connection::parseHeader, self, std::placeholders::_1));
}
});
} catch (boost::system::system_error& e) {
std::cout << "[Network error - Connection::parsePacket] " << e.what() << std::endl;
close(FORCE_CLOSE);
}
}
void Connection::send(const OutputMessage_ptr& msg)
{
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
if (closed) {
return;
}
bool noPendingWrite = messageQueue.empty();
messageQueue.emplace_back(msg);
if (noPendingWrite) {
internalSend(msg);
}
}
void Connection::internalSend(const OutputMessage_ptr& msg)
{
protocol->onSendMessage(msg);
try {
writeTimer.expires_after(std::chrono::seconds(CONNECTION_WRITE_TIMEOUT));
writeTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr<Connection>(shared_from_this()),
std::placeholders::_1));
boost::asio::async_write(socket,
boost::asio::buffer(msg->getOutputBuffer(), msg->getLength()),
std::bind(&Connection::onWriteOperation, shared_from_this(), std::placeholders::_1));
} catch (boost::system::system_error& e) {
std::cout << "[Network error - Connection::internalSend] " << e.what() << std::endl;
close(FORCE_CLOSE);
}
}
uint32_t Connection::getIP()
{
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
// IP-address is expressed in network byte order
boost::system::error_code error;
const boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(error);
if (error) {
return 0;
}
return htonl(static_cast<unsigned long>(endpoint.address().to_v4().to_uint()));
}
void Connection::onWriteOperation(const boost::system::error_code& error)
{
std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
writeTimer.cancel();
messageQueue.pop_front();
if (error) {
messageQueue.clear();
close(FORCE_CLOSE);
return;
}
if (!messageQueue.empty()) {
internalSend(messageQueue.front());
} else if (closed) {
closeSocket();
}
}
void Connection::handleTimeout(ConnectionWeak_ptr connectionWeak, const boost::system::error_code& error)
{
if (error == boost::asio::error::operation_aborted) {
//The timer has been manually canceled
return;
}
if (auto connection = connectionWeak.lock()) {
connection->close(FORCE_CLOSE);
}
}