-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.cpp
211 lines (174 loc) · 5.21 KB
/
server.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#include <vector>
#include <map>
#include <time.h>
#include <regex>
#include "algo.hpp"
#include "client.hpp"
#include "server.hpp"
#include "packets.hpp"
#include "logger.hpp"
#include "utils.hpp"
Server::Server(const Config &config) : server(), clientsManager(this)
{
server.config.port = (unsigned short) config["port"].asInt();
server.config.thread_pool_size = 1;
auto& chat = server.endpoint["^/chat/?$"];
chat.on_message = [&](ConnectionPtr connection, shared_ptr<InMessage> message) {
string msg = message->string();
try {
if (auto client = clientsManager.findClientByConnection(connection); client) {
client->onPacket(msg);
}
} catch (const exception &e) {
Logger::error("Exception: ", e.what(), "\nWhile processing message:", msg);
} catch (...) {
Logger::error("Unknown error while processing message:", msg);
}
};
chat.on_open = [&, this](ConnectionPtr connection) {
auto ip = getRealClientIp(connection);
Logger::info("Opened connection from ", ip);
auto counter = clientsManager.getCounterFromIp(ip);
if (counter.connections >= maxConnectionsFromIp) {
Logger::info("Connections limit reached for ", ip);
connection->send_close(WS_CLOSE_CODE_OK);
return;
}
if (counter.clients >= maxClientsFromIp) {
Logger::info("Orphan clients limit reached for ", ip, ", try to kill oldest orphan");
auto orphanCli = clientsManager.findFirstClient([&](ClientPtr c) {
return !c->getConnection() && c->getLastIP() == ip;
});
if (orphanCli) {
clientsManager.remove(orphanCli);
} else {
Logger::warn("Not found oldest orphan. Wtf? Did maxClientsFromIp < maxConnectionsFromIp?");
}
}
clientsManager.connect(connection);
};
chat.on_close = [&](ConnectionPtr connection, int status, const string& reason) {
auto ip = getRealClientIp(connection);
Logger::info("Closed connection from ", ip, " with status code ", status);
// normal close or browser page close
if (status == 1000 || status == 1001) {
clientsManager.remove(connection);
} else {
clientsManager.makeOrphan(connection);
}
};
chat.on_error = [&](auto connection, const boost::system::error_code& ec) {
auto ip = getRealClientIp(connection);
Logger::warn("Error in connection from ", ip,
". Error: ", ec, ", error message: ", ec.message());
clientsManager.makeOrphan(connection);
};
server.runWithInterval(pingInterval, [&]{
time_t cur = time(nullptr);
vector<ClientPtr> toKick;
for (auto &&cli : clientsManager.getClients()) {
auto timeWasted = cur - cli->lastPacketTime;
if (timeWasted > orphanTimeout) {
toKick.push_back(cli);
}
else if (timeWasted > connectTimeout) {
if (auto connection = cli->getConnection(); connection) {
closeConnection(connection);
clientsManager.makeOrphan(cli);
Logger::info("Orphaned connection (no ping): ", cli->getName(), " [", cli->getLastIP(), "]");
}
}
else if (timeWasted > pingTimeout) {
cli->sendPacket(PacketPing());
}
}
for (auto &&cli : toKick) {
if (auto connection = cli->getConnection(); connection) {
closeConnection(connection);
}
clientsManager.remove(cli);
Logger::info("Kicked outdated orphaned connection: ", cli->getName(), " [", cli->getLastIP(), "]");
}
});
}
void Server::start() {
Logger::info("Started wsserver at port ", server.config.port);
server.start();
}
void Server::stop() {
server.stop();
}
Json::Value Server::serialize() {
Json::Value val;
auto &sr = val["rooms"];
for (RoomPtr r : rooms) {
sr.append(r->serialize());
}
return val;
}
void Server::deserialize(const Json::Value &val) {
rooms.clear();
for (auto &v : val["rooms"]) {
RoomPtr rm = make_shared<Room>(this);
rm->setSelfPtr(rm);
rm->deserialize(v);
rooms.insert(rm);
}
}
void Server::sendRawData(ConnectionPtr conn, const string &rdata) {
conn->send(rdata);
}
void Server::sendPacket(ConnectionPtr conn, const Packet &pack) {
Json::FastWriter wr;
conn->send(wr.write(pack.serialize()));
}
RoomPtr Server::createRoom(string name) {
auto rm = getRoomByName(name);
if (rm)
return nullptr;
rm = make_shared<Room>(this);
rm->setName(name);
rm->setSelfPtr(rm);
rooms.insert(rm);
rm->onCreate();
return rm;
}
bool Server::removeRoom(string name) {
auto rm = getRoomByName(name);
if (rm) {
bool res = rooms.erase(rm) > 0;
if (res) {
rm->onDestroy();
}
return res;
}
return false;
}
RoomPtr Server::getRoomByName(string name) {
for (RoomPtr room : rooms) {
if (room->getName() == name) {
return room;
}
}
return nullptr;
}
void Server::closeConnection(ConnectionPtr connection) {
connection->send_close(WS_CLOSE_CODE_OK, "", [connection](auto ec){
if (ec) {
connection->close();
}
});
}
bool Server::reviveClient(ClientPtr currentClient, ClientPtr targetClient) {
auto currentConnection = currentClient->getConnection();
auto targetConnection = targetClient->getConnection();
auto result = clientsManager.reviveClient(currentClient, targetClient);
if (targetConnection) {
if (currentConnection != targetConnection) {
closeConnection(targetConnection);
} else {
Logger::error("Somehow reviving client with identical connections! currentClient == targetClient => ", currentClient == targetClient ? "true" : "false");
}
}
return result;
}