-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cpp
557 lines (431 loc) · 15.4 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#include "Server.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <iostream>
#include <vector>
#include <algorithm>
typedef struct {
Server* server;
int socket;
SSL* ssl;
bool isUsingSSL;
Server_Client_ID client;
} Accept_Struct;
std::string ssl_error_code_to_string(int error_code)
{
switch (error_code)
{
case SSL_ERROR_NONE:
return "The TLS/SSL I/O operation completed. There was no error.";
case SSL_ERROR_ZERO_RETURN:
return "The TLS/SSL connection has been closed.";
case SSL_ERROR_WANT_READ:
return "The operation did not complete; the same TLS/SSL I/O function should be called again later. If, by then, the underlying BIO has data available for reading, then some TLS/SSL protocol progress will take place, i.e. at least part of an TLS/SSL record will be read.";
case SSL_ERROR_WANT_WRITE:
return "The operation did not complete; the same TLS/SSL I/O function should be called again later. If, by then, the underlying BIO has data available for writing, then some TLS/SSL protocol progress will take place, i.e. at least part of an TLS/SSL record will be written.";
case SSL_ERROR_WANT_CONNECT:
return "The operation did not complete; the same TLS/SSL I/O function should be called again later. The underlying BIO was not connected yet to the peer and the call would block in connect(). The SSL function should be called again when the connection is established.";
case SSL_ERROR_WANT_ACCEPT:
return "The operation did not complete; the same TLS/SSL I/O function should be called again later. The underlying BIO was not connected yet to the peer and the call would block in accept(). The SSL function should be called again when the connection is established.";
case SSL_ERROR_WANT_X509_LOOKUP:
return "The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again. The TLS/SSL I/O function should be called again later.";
case SSL_ERROR_SYSCALL:
return "Some I/O error occurred. The OpenSSL error queue may contain more information on the error. If the error queue is empty (i.e. ERR_get_error() returns 0), ret can be used to find out more about the error: If ret == 0, an EOF was observed that violates the protocol. If ret == -1, the underlying BIO reported an I/O error (for socket I/O on Unix systems, consult errno for details).";
case SSL_ERROR_SSL:
return "A failure in the SSL library occurred, usually a protocol error. The OpenSSL error queue contains more information on the error.";
default:
return "Unknown Error Code.";
}
}
void* server_read_thread_function(void* accept)
{
using namespace std;
Accept_Struct* accept_struct = reinterpret_cast<Accept_Struct*>(accept);
vector<string> messages;
int sock = accept_struct->socket;
Server* server = accept_struct->server;
SSL* ssl = accept_struct->ssl;
bool isUsingSSL = accept_struct->isUsingSSL;
Server_Client_ID client = accept_struct->client;
string message;
while (true)
{
if (message.find('\n') == string::npos)
{
int bytes_recieved = 0;
char buffer[512];
if (!isUsingSSL)
bytes_recieved = recv(sock, buffer, 512, 0);
else
bytes_recieved = SSL_read(ssl, buffer, 512);
if (bytes_recieved <= 0)
{
server->on_client_disconnect(client);
if (server->get_delegate())
server->get_delegate()->on_client_disconnect(client, server);
server->disconnect_client(client);
break;
}
buffer[bytes_recieved] = '\0';
message += buffer;
}
else
{
int length = message.find('\n')+1;
string final_message = message.substr(0, length);
message.erase(message.begin(), message.begin()+length);
server->recieve_message(final_message, client);
if (server->get_delegate())
server->get_delegate()->recieve_message(final_message, client, server);
}
}
delete accept_struct;
pthread_exit(NULL);
}
void server_thread_function(Accept_Struct* accept_struct, bool ipv6)
{
using namespace std;
int server_socket = accept_struct->socket;
Server* server = accept_struct->server;
bool isUsingSSL = accept_struct->isUsingSSL;
int err = 0;
SSL_CTX *ctx;
if (isUsingSSL)
{
if ((err = ERR_get_error()) != 0)
{
cerr << "SSL Library Error (Library Init): " << ERR_error_string(err, NULL) << endl;
return;
}
const SSL_METHOD *method = SSLv3_server_method();
ctx = SSL_CTX_new(method);
if ((err = ERR_get_error()) != 0)
{
cerr << "SSL Library Error (CTX New): " << ERR_error_string(err, NULL) << endl;
return;
}
SSL_CTX_use_certificate_file(ctx, server->get_cert_path().c_str(), SSL_FILETYPE_PEM);
if ((err = ERR_get_error()) != 0)
{
cerr << "SSL Library Error (Cert File): " << ERR_error_string(err, NULL) << endl;
return;
}
SSL_CTX_use_PrivateKey_file(ctx, server->get_key_path().c_str(), SSL_FILETYPE_PEM);
if ((err = ERR_get_error()) != 0)
{
cerr << "SSL Library Error (Key File): " << ERR_error_string(err, NULL) << endl;
return;
}
if (!SSL_CTX_check_private_key(ctx))
{
cerr << "SSL Library Error (Failed to check Key File against cert): " << ERR_error_string(ERR_get_error(), NULL) << endl;
return;
}
}
while (true)
{
int client_sock;
struct sockaddr* from = NULL;
struct sockaddr_in from_ipv4;
struct sockaddr_in6 from_ipv6;
unsigned int length = 0;
if (ipv6)
{
from = (struct sockaddr*)&from_ipv6;
length = sizeof(from_ipv6);
}
else
{
from = (struct sockaddr*)&from_ipv4;
length = sizeof(from_ipv4);
}
client_sock = accept(server_socket, from, &length);
if (client_sock == -1)
{
cerr << "Could not accept on socket: " << strerror(errno) << endl;
cerr << "Exiting server thread IPv" << (ipv6 ? "6" : "4") << endl;
break;
}
Server_Client_ID id = Server::next_id();
SSL* ssl = NULL;
if (isUsingSSL)
{
ssl = SSL_new(ctx);
SSL_set_fd(ssl, client_sock);
err = SSL_accept(ssl);
if (err != 1)
{
cerr << "SSL Library Error (SSL Accept): " << ssl_error_code_to_string(err) << endl;
break;
}
server->accept_client(id, ssl);
}
else
server->accept_client(id, client_sock);
//pthread_t accept_thread;
Accept_Struct* to_pass = new Accept_Struct;
to_pass->server = accept_struct->server;
to_pass->isUsingSSL = isUsingSSL;
to_pass->client = id;
to_pass->socket = client_sock;
if (isUsingSSL)
to_pass->ssl = ssl;
accept_struct->server->on_client_connect(to_pass->client);
if (accept_struct->server->get_delegate())
accept_struct->server->get_delegate()->on_client_connect(to_pass->client, accept_struct->server);
delete to_pass;
//pthread_create(&accept_thread, NULL, server_accept_thread_function, (void*)to_pass);
Accept_Struct* read_to_pass = new Accept_Struct;
read_to_pass->server = accept_struct->server;
read_to_pass->isUsingSSL = isUsingSSL;
read_to_pass->client = id;
read_to_pass->socket = client_sock;
if (isUsingSSL)
read_to_pass->ssl = ssl;
pthread_t read_thread;
pthread_create(&read_thread, NULL, server_read_thread_function, (void*)read_to_pass);
}
}
void* server_thread_function_ipv4(void* accept)
{
Accept_Struct* accept_struct = reinterpret_cast<Accept_Struct*>(accept);
server_thread_function(accept_struct, false);
delete accept_struct;
pthread_exit(NULL);
}
void* server_thread_function_ipv6(void* accept)
{
Accept_Struct* accept_struct = reinterpret_cast<Accept_Struct*>(accept);
server_thread_function(accept_struct, true);
delete accept_struct;
pthread_exit(NULL);
}
Server::Server_Exception Server::IPv4_Initialization_Failure("Failed to initialize IPv4 socket correctly. See cerr for more details");
Server::Server_Exception Server::IPv6_Initialization_Failure("Failed to initialize IPv6 socket correctly. See cerr for more details");
Server::Server_Exception Server::Thread_Initialization_Failure("Failed to initialize the server thread correctly. See cerr for more details");
Server::Server_Exception Server::Sending_Without_Existence("Failed to send a message to a socket because this instance of the class does not have a client socket with that id.");
Server::Server(int port, Server::Server_Type type, Server_Delegate *delegate, bool verbose)
{
pthread_mutex_init(&server_mutex, NULL);
server_type = type;
this->verbose = verbose;
this->delegate = delegate;
this->ssl = false;
create_server(port, type);
}
Server::Server(int port, Server::Server_Type type, bool ssl, std::string cert_path, std::string key_path, Server_Delegate *delegate, bool verbose)
{
pthread_mutex_init(&server_mutex, NULL);
server_type = type;
this->verbose = verbose;
this->delegate = delegate;
this->ssl = ssl;
this->cert_path = cert_path;
this->key_path = key_path;
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
OpenSSL_add_all_ciphers();
OpenSSL_add_all_digests();
create_server(port, type);
}
void Server::create_server(int port, Server::Server_Type server_type)
{
using namespace std;
int status = 0;
bool created_dual_stack = false;
if (server_type == IPv6_Server || server_type == Dual_IPv4_IPv6_Server)
{
struct sockaddr_in6 server_name_ipv6;
server_sock_ipv6 = socket(AF_INET6, SOCK_STREAM, 0);
if (server_sock_ipv6 == -1)
{
cerr << "Failed to create IPv6 socket: " << strerror(errno) << endl;
throw IPv6_Initialization_Failure;
}
if (getsockopt(server_sock_ipv6, IPPROTO_IPV6, IPV6_V6ONLY, NULL, NULL) != 0)
{
int no = 0;
setsockopt(server_sock_ipv6, IPPROTO_IPV6, IPV6_V6ONLY, (void *)no, sizeof(no));
created_dual_stack = true;
}
//server_name_ipv6.sin6_len = sizeof(struct sockaddr_in6);
server_name_ipv6.sin6_family = AF_INET6;
server_name_ipv6.sin6_addr = in6addr_any;
server_name_ipv6.sin6_port = htons(port);
status = bind(server_sock_ipv6, (struct sockaddr*)&server_name_ipv6, sizeof(server_name_ipv6));
if (status == -1)
{
cerr << "Failed to bind to socket (port: " << port << ") with error: " << strerror(errno) << endl;
throw IPv6_Initialization_Failure;
}
status = listen(server_sock_ipv6, 5);
if (status == -1)
{
cerr << "Failed to listen: " << strerror(errno) << endl;
throw IPv6_Initialization_Failure;
}
Accept_Struct* accept_struct = new Accept_Struct;
accept_struct->server = this;
accept_struct->socket = server_sock_ipv6;
accept_struct->isUsingSSL = ssl;
status = pthread_create(&server_thread_ipv6, NULL, server_thread_function_ipv6, accept_struct);
if (status)
{
cerr << "Failed to create server thread with error: " << status << " (\"" << strerror(errno) << "\")" << endl;
throw Thread_Initialization_Failure;
}
}
if ((server_type == IPv4_Server || server_type == Dual_IPv4_IPv6_Server) && !created_dual_stack)
{
struct sockaddr_in server_name_ipv4;
server_sock_ipv4 = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock_ipv4 == -1)
{
cerr << "Failed to create IPv4 socket: " << strerror(errno) << endl;
throw IPv4_Initialization_Failure;
}
server_name_ipv4.sin_family = AF_INET;
server_name_ipv4.sin_addr.s_addr = INADDR_ANY;
server_name_ipv4.sin_port = htons(port);
status = bind(server_sock_ipv4, (struct sockaddr*)&server_name_ipv4, sizeof(server_name_ipv4));
if (status == -1)
{
cerr << "Failed to bind to socket (port: " << port << ") with error: " << strerror(errno) << endl;
throw IPv4_Initialization_Failure;
}
status = listen(server_sock_ipv4, 5);
if (status == -1)
{
cerr << "Failed to listen: " << strerror(errno) << endl;
throw IPv4_Initialization_Failure;
}
Accept_Struct* accept_struct = new Accept_Struct;
accept_struct->server = this;
accept_struct->socket = server_sock_ipv4;
accept_struct->isUsingSSL = ssl;
status = pthread_create(&server_thread_ipv4, NULL, server_thread_function_ipv4, accept_struct);
if (status)
{
cerr << "Failed to create server thread with error: " << status << " (\"" << strerror(errno) << "\")" << endl;
throw Thread_Initialization_Failure;
}
}
}
Server::~Server()
{
using namespace std;
pthread_exit(NULL);
pthread_mutex_destroy(&server_mutex);
for (map<Server_Client_ID, int>::iterator it = clients.begin();it != clients.end();it++)
close(it->second);
for (map<Server_Client_ID, SSL*>::iterator it = ssl_clients.begin();it != ssl_clients.end();it++)
{
int s = SSL_get_fd(it->second);
SSL_free(it->second);
close(s);
}
if (server_type == IPv4_Server || server_type == Dual_IPv4_IPv6_Server)
close(server_sock_ipv4);
if (server_type == IPv6_Server || server_type == Dual_IPv4_IPv6_Server)
close(server_sock_ipv6);
}
void Server::broadcast_message(std::string &message)
{
using namespace std;
const char* c_msg = message.c_str();
size_t size = message.size();
pthread_mutex_lock(&server_mutex);
for (std::map<Server_Client_ID, int>::iterator it = clients.begin();it != clients.end();it++)
write(it->second, c_msg, size);
for (std::map<Server_Client_ID, SSL*>::iterator it = ssl_clients.begin();it != ssl_clients.end();it++)
SSL_write(it->second, c_msg, size);
pthread_mutex_unlock(&server_mutex);
}
void Server::broadcast_message_to_clients(std::string &message, std::set<Server_Client_ID> clients)
{
using namespace std;
for (set<Server_Client_ID>::iterator it = clients.begin();it != clients.end();it++)
send_message(message, *it);
}
void Server::send_message(std::string &message, const Server_Client_ID &client)
{
using namespace std;
pthread_mutex_lock(&server_mutex);
if (clients.find(client) != clients.end())
write(clients[client], message.c_str(), message.size());
else if (ssl_clients.find(client) != ssl_clients.end())
SSL_write(ssl_clients[client], message.c_str(), message.size());
else
{
pthread_mutex_unlock(&server_mutex);
throw Sending_Without_Existence;
}
pthread_mutex_unlock(&server_mutex);
}
void Server::accept_client(Server_Client_ID &client, SSL* ssl)
{
pthread_mutex_lock(&server_mutex);
ssl_clients[client] = ssl;
pthread_mutex_unlock(&server_mutex);
}
void Server::accept_client(Server_Client_ID &client, int client_socket)
{
pthread_mutex_lock(&server_mutex);
clients[client] = client_socket;
pthread_mutex_unlock(&server_mutex);
}
void Server::disconnect_client(Server_Client_ID &client)
{
pthread_mutex_lock(&server_mutex);
std::map<Server_Client_ID,int>::iterator it = clients.find(client);
if (it != clients.end())
{
on_client_disconnect(client);
if (delegate)
delegate->on_client_disconnect(client, this);
close(it->second);
clients.erase(it);
}
else
{
std::map<Server_Client_ID,SSL*>::iterator s_it = ssl_clients.find(client);
if (s_it != ssl_clients.end())
{
on_client_disconnect(client);
if (delegate)
delegate->on_client_disconnect(client, this);
int s = SSL_get_fd(s_it->second);
SSL_free(s_it->second);
close(s);
ssl_clients.erase(s_it);
}
}
pthread_mutex_unlock(&server_mutex);
}
Server_Client_ID Server::next_id()
{
static Server_Client_ID client_id = 0;
return client_id++;
}
int Server::client_id_to_socket(Server_Client_ID &client)
{
pthread_mutex_lock(&server_mutex);
int socket = -1;
std::map<Server_Client_ID,int>::iterator it = clients.find(client);
if (it != clients.end())
socket = it->second;
else
{
std::map<Server_Client_ID,SSL*>::iterator s_it = ssl_clients.find(client);
if (s_it != ssl_clients.end())
socket = SSL_get_fd(s_it->second);
}
pthread_mutex_unlock(&server_mutex);
return socket;
}