forked from CESNET/ipfixcol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cpp
416 lines (358 loc) · 10.8 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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/**
* \file Server.cpp
* \author Lukas Hutak <[email protected]>
* \brief Server output
*
* Copyright (C) 2015 CESNET, z.s.p.o.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Company nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* ALTERNATIVELY, provided that this notice is retained in full, this
* product may be distributed under the terms of the GNU General Public
* License (GPL) version 2 or later, in which case the provisions
* of the GPL apply INSTEAD OF those given above.
*
* This software is provided ``as is, and any express or implied
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose are disclaimed.
* In no event shall the company or contributors be liable for any
* direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute
* goods or services; loss of use, data, or profits; or business
* interruption) however caused and on any theory of liability, whether
* in contract, strict liability, or tort (including negligence or
* otherwise) arising in any way out of the use of this software, even
* if advised of the possibility of such damage.
*
*/
#include "Server.h"
#include <stdexcept>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netdb.h>
#include <arpa/inet.h>
// Default server port
#define DEFAULT_PORT (4800)
// How many pending connections queue will hold
#define BACKLOG (10)
// Name of plugin
static const char *msg_module = "json_storage(server)";
/**
* \brief Class constructor
*
* Parse configuration, create and bind server's socket and create acceptor's
* thread
*/
Server::Server(const pugi::xpath_node &config)
{
_non_blocking = false;
_acceptor = NULL;
// Load and check the configuration
std::string port = config.node().child_value("port");
std::string blocking = config.node().child_value("blocking");
// Check the server configuration
if (port.empty()) {
throw std::invalid_argument("Invalid source port specification.");
}
if (blocking == "yes" || blocking == "true" || blocking == "1") {
_non_blocking = false;
} else if (blocking == "no" || blocking == "false" || blocking == "0") {
_non_blocking = true;
} else {
throw std::invalid_argument("Invalid blocking mode specification.");
}
int serv_fd;
int ret_val;
// New socket configuration
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET; // Use IPv4
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // Wildcard IP address
hints.ai_protocol = IPPROTO_TCP; // TCP
// Create new socket
struct addrinfo *servinfo, *iter;
if ((ret_val = getaddrinfo(NULL, port.c_str(), &hints, &servinfo)) != 0) {
throw std::runtime_error("Server initialization failed (" +
std::string(gai_strerror(ret_val)) + ")");
}
for(iter = servinfo; iter != NULL; iter = iter->ai_next) {
serv_fd = socket(iter->ai_family, iter->ai_socktype, iter->ai_protocol);
if ((serv_fd) == -1) {
continue;
}
int yes = 1;
if (setsockopt(serv_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
close(serv_fd);
continue;
}
if (bind(serv_fd, iter->ai_addr, iter->ai_addrlen) == -1) {
// Failed to bind
close(serv_fd);
continue;
}
// Success
break;
}
freeaddrinfo(servinfo);
// Check if new socket is ready
if (iter == NULL) {
throw std::runtime_error("Server failed to bind to specified port.");
}
// Make socket passive
if (listen(serv_fd, BACKLOG) == -1) {
close(serv_fd);
throw std::runtime_error("Server initialization failed (" +
std::string(strerror(errno)) + ")");
}
// Create thread
_acceptor = new acceptor_t;
_acceptor->socket_fd = serv_fd;
_acceptor->new_clients_ready = false;
_acceptor->stop = false;
if (pthread_mutex_init(&_acceptor->mutex, NULL) != 0) {
delete _acceptor;
close(serv_fd);
throw std::runtime_error("Mutex initialization failed");
}
if (pthread_create(&_acceptor->thread, NULL, &Server::thread_accept,
_acceptor) != 0) {
delete _acceptor;
close(serv_fd);
throw std::runtime_error("Acceptor thread failed");
}
}
/**
* \brief Class destructor
*
* Close all sockets and stop and destroy the acceptor.
*/
Server::~Server()
{
// Disconnect connected clients
for (auto &client : _clients) {
close(client.socket);
}
// Stop and destroy acceptor's thread
if (_acceptor) {
_acceptor->stop = true;
pthread_join(_acceptor->thread, NULL);
pthread_mutex_destroy(&_acceptor->mutex);
close(_acceptor->socket_fd);
for (auto &client : _acceptor->new_clients) {
close(client.socket);
}
delete _acceptor;
}
}
/**
* \brief Acceptor's thread function
*
* Wait for new clients and accept them.
* \param[in,out] context Acceptor's structure with configured server socket
* \return Nothing
*/
void *Server::thread_accept(void *context)
{
acceptor_t *acc = (acceptor_t *) context;
int ret_val;
struct timeval tv;
fd_set rfds;
MSG_INFO(msg_module, "Waiting for connections...");
while(1) {
struct sockaddr_storage client_addr;
socklen_t sin_size = sizeof(client_addr);
int new_fd;
// "select()" configuration
FD_ZERO(&rfds);
FD_SET(acc->socket_fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 100000;
ret_val = select(acc->socket_fd + 1, &rfds, NULL, NULL, &tv);
if (ret_val == -1) {
MSG_ERROR(msg_module, "select() - failed (%s)", strerror(errno));
break;
}
if (!FD_ISSET(acc->socket_fd, &rfds)) {
// Timeout
if (acc->stop) {
// End thread
break;
}
continue;
}
new_fd = accept(acc->socket_fd, (struct sockaddr *) &client_addr,
&sin_size);
if (new_fd == -1) {
MSG_ERROR(msg_module, "accept() - failed (%s)", strerror(errno));
continue;
}
MSG_INFO(msg_module, "Client connected: %s",
get_client_desc(client_addr).c_str());
// Further receptions from the socket will be disallowed
shutdown(new_fd, SHUT_RD);
// Add new client to the array of new clients
pthread_mutex_lock(&acc->mutex);
client_t new_client {client_addr, new_fd};
acc->new_clients.push_back(new_client);
acc->new_clients_ready = true;
pthread_mutex_unlock(&acc->mutex);
}
MSG_INFO(msg_module, "Connection acceptor terminated.");
return NULL;
}
/**
* \brief Send a message to a client
*
* Sends the message to the client using prepared socket. When non-blocking mode
* is enabled and only part of the message was sent, the rest of the message is
* stored in the client's profile.
* \param[in] data The message
* \param[in] len The length of the message
* \param[in,out] client Client
* \return Transmission status
*/
enum Server::Send_status Server::msg_send(const char *data, ssize_t len,
client_t &client)
{
ssize_t now;
ssize_t todo = len;
const char *ptr = data;
int flags = MSG_NOSIGNAL;
if (_non_blocking) {
flags |= MSG_DONTWAIT;
}
while (todo > 0) {
now = send(client.socket, ptr, todo, flags);
if (now == -1) {
if (_non_blocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
// Non-blocking mode
break;
}
// Connection failed
MSG_INFO(msg_module, "Client disconnected: %s (%s)",
get_client_desc(client.info).c_str(), strerror(errno));
return SEND_FAILED;
}
ptr += now;
todo -= now;
}
if (todo <= 0) {
return SEND_OK;
}
// Non-blocking mode - (partly) failed to sent the message
if (todo == len) {
// No part of the message was sent
return SEND_WOULDBLOCK;
}
/*
* Partly sent. Store the rest of the message for the next transmission to
* avoid invalid JSON format. Temporary string should be here, because it is
* possible to "data == rest.c_str()".
*/
std::string tmp(ptr, todo);
client.msg_rest.assign(tmp);
return SEND_WOULDBLOCK;
}
/**
* \brief Send record to all connected clients
*
* \param[in] record Record
*/
void Server::ProcessDataRecord(const std::string &record)
{
const char *data = record.c_str();
ssize_t length = record.size();
// Are there new clients?
if (_acceptor->new_clients_ready) {
pthread_mutex_lock(&_acceptor->mutex);
_clients.insert(_clients.end(), _acceptor->new_clients.begin(),
_acceptor->new_clients.end());
_acceptor->new_clients.clear();
_acceptor->new_clients_ready = false;
pthread_mutex_unlock(&_acceptor->mutex);
}
// Send the message to all clients
std::vector<client_t>::iterator iter = _clients.begin();
while (iter != _clients.end()) {
client_t &client = *iter;
enum Send_status ret_val;
// Send the rest part of the last partly sent message
if (_non_blocking && !client.msg_rest.empty()) {
std::string &rest = client.msg_rest;
ret_val = msg_send(rest.c_str(), rest.size(), client);
switch (ret_val) {
case SEND_OK:
// The rest of the message successfully sent
rest.clear();
break;
case SEND_WOULDBLOCK:
// Skip, next client...
++iter;
continue;
case SEND_FAILED:
// Close socket and remove client
close(client.socket);
iter = _clients.erase(iter); // The iterator has new location...
continue;
}
}
// Send new message
ret_val = msg_send(data, length, client);
switch (ret_val) {
case SEND_OK:
case SEND_WOULDBLOCK:
// Next client
++iter;
break;
case SEND_FAILED:
// Close socket and remove client's info
close(client.socket);
iter = _clients.erase(iter); // The iterator has new location...
break;
}
}
}
/**
* \brief Get a brief description about connected client
* \param[in] client Client network info
* \return String with client's IP and port
*/
std::string Server::get_client_desc(const struct sockaddr_storage &client)
{
char ip_str[INET6_ADDRSTRLEN] = {0};
uint16_t port;
switch (client.ss_family) {
case AF_INET: {
// IPv4
const struct sockaddr_in *src_ip = (struct sockaddr_in *) &client;
inet_ntop(client.ss_family, &src_ip->sin_addr, ip_str, sizeof(ip_str));
port = ntohs(src_ip->sin_port);
return std::string(ip_str) + ":" + std::to_string(port);
}
case AF_INET6: {
// IPv6
const struct sockaddr_in6 *src_ip = (struct sockaddr_in6 *) &client;
inet_ntop(client.ss_family, &src_ip->sin6_addr, ip_str, sizeof(ip_str));
port = ntohs(src_ip->sin6_port);
return std::string(ip_str) + ":" + std::to_string(port);
}
default:
return "Unknown";
}
}