-
-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathNetworkServer.cpp
More file actions
4281 lines (3521 loc) · 173 KB
/
Copy pathNetworkServer.cpp
File metadata and controls
4281 lines (3521 loc) · 173 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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------*\
| NetworkServer.cpp |
| |
| OpenRGB SDK network server |
| |
| Adam Honse (CalcProgrammer1) 09 May 2020 |
| |
| This file is part of the OpenRGB project |
| SPDX-License-Identifier: GPL-2.0-or-later |
\*---------------------------------------------------------*/
#include <cstring>
#include <queue>
#include "i2c_smbus.h"
#include "JsonUtils.h"
#include "LogManager.h"
#include "NetworkServer.h"
#include "StringUtils.h"
#ifndef _WIN32
#include <sys/ioctl.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <arpa/inet.h>
#else
#include <ws2tcpip.h>
#endif
#include <memory.h>
#include <errno.h>
#include <stdlib.h>
#ifdef _WIN32
#include <Windows.h>
#define MSG_NOSIGNAL 0
#else
#include <unistd.h>
#endif
#ifdef __linux__
const int yes = 1;
#else
const char yes = 1;
#endif
using namespace std::chrono_literals;
/*---------------------------------------------------------*\
| Macros for copying data fields from set descriptor buffer |
| while ensuring we don't access out of bounds |
\*---------------------------------------------------------*/
#define COPY_DATA_FIELD(data_ptr, data_start, field) \
if((unsigned)(data_ptr + sizeof(field) - data_start) <= (unsigned)data_size) \
{ \
memcpy(&field, data_ptr, sizeof(field)); \
data_ptr += sizeof(field); \
} \
else \
{ \
return(NET_PACKET_STATUS_ERROR_INVALID_DATA); \
} \
#define COPY_STRING_FIELD(data_ptr, data_start, length, field) \
if((unsigned)(data_ptr + length - data_start) <= (unsigned)data_size) \
{ \
field.assign((char *)data_ptr, length); \
field = StringUtils::remove_null_terminating_chars(field); \
data_ptr += length; \
} \
else \
{ \
return(NET_PACKET_STATUS_ERROR_INVALID_DATA); \
} \
#define COPY_DATA_FIELD_UNLOCK(data_ptr, data_start, field, controller) \
if((unsigned)(data_ptr + sizeof(field) - data_start) <= (unsigned)data_size) \
{ \
memcpy(&field, data_ptr, sizeof(field)); \
data_ptr += sizeof(field); \
} \
else \
{ \
controller->AccessMutex.unlock(); \
return(NET_PACKET_STATUS_ERROR_INVALID_DATA); \
} \
/*---------------------------------------------------------*\
| NetworkServer name for log entries |
\*---------------------------------------------------------*/
const char* NETWORKSERVER = "NetworkServer";
NetworkClientInfo::NetworkClientInfo()
{
client_string = "Client";
client_ip = OPENRGB_SDK_HOST;
client_sock = INVALID_SOCKET;
client_listen_thread = nullptr;
client_protocol_version = 0;
client_is_local = false;
client_is_local_client = false;
}
NetworkClientInfo::~NetworkClientInfo()
{
if(client_sock != INVALID_SOCKET)
{
LOG_INFO("[%s] Closing server connection: %s", NETWORKSERVER, client_ip.c_str());
delete client_listen_thread;
shutdown(client_sock, SD_RECEIVE);
closesocket(client_sock);
}
}
static void RGBController_UpdateCallback(void* this_ptr, unsigned int update_reason, void* controller_ptr)
{
NetworkServer* this_obj = (NetworkServer*)this_ptr;
this_obj->SendRequest_RGBController_SignalUpdate((RGBController*)controller_ptr, update_reason);
}
NetworkServer::NetworkServer()
{
host = OPENRGB_SDK_HOST;
port_num = OPENRGB_SDK_PORT;
server_online = false;
server_listening = false;
legacy_workaround_enabled = false;
controller_next_idx = 0;
controller_updating = false;
server_flags = NET_SERVER_FLAG_SUPPORTS_RGBCONTROLLER
| NET_SERVER_FLAG_SUPPORTS_LOGMANAGER
| NET_SERVER_FLAG_SUPPORTS_PROFILEMANAGER
| NET_SERVER_FLAG_SUPPORTS_PLUGINMANAGER
| NET_SERVER_FLAG_SUPPORTS_SETTINGSMANAGER
| NET_SERVER_FLAG_SUPPORTS_DETECTION
| NET_SERVER_FLAG_SUPPORTS_DEVICE_INFO;
for(int i = 0; i < MAXSOCK; i++)
{
ConnectionThread[i] = nullptr;
}
plugin_manager = nullptr;
profile_manager = nullptr;
settings_manager = nullptr;
}
NetworkServer::~NetworkServer()
{
StopServer();
/*-----------------------------------------------------*\
| Unregister the server's RGBController update handler |
| for each RGBController in the controllers list |
\*-----------------------------------------------------*/
for(std::size_t controller_idx = 0; controller_idx < controllers.size(); controller_idx++)
{
controllers[controller_idx]->UnregisterUpdateCallback(this);
}
}
/*---------------------------------------------------------*\
| Server Information functions |
\*---------------------------------------------------------*/
std::string NetworkServer::GetHost()
{
return(host);
}
unsigned short NetworkServer::GetPort()
{
return(port_num);
}
bool NetworkServer::GetOnline()
{
return(server_online);
}
bool NetworkServer::GetListening()
{
return(server_listening);
}
unsigned int NetworkServer::GetNumClients()
{
return((unsigned int)ServerClients.size());
}
const char * NetworkServer::GetClientString(unsigned int client_num)
{
const char * result;
ServerClientsMutex.lock();
if(client_num < ServerClients.size())
{
result = ServerClients[client_num]->client_string.c_str();
}
else
{
result = "";
}
ServerClientsMutex.unlock();
return(result);
}
const char * NetworkServer::GetClientIP(unsigned int client_num)
{
const char * result;
ServerClientsMutex.lock();
if(client_num < ServerClients.size())
{
result = ServerClients[client_num]->client_ip.c_str();
}
else
{
result = "";
}
ServerClientsMutex.unlock();
return(result);
}
unsigned int NetworkServer::GetClientProtocolVersion(unsigned int client_num)
{
unsigned int result;
ServerClientsMutex.lock();
if(client_num < ServerClients.size())
{
result = ServerClients[client_num]->client_protocol_version;
}
else
{
result = 0;
}
ServerClientsMutex.unlock();
return(result);
}
/*---------------------------------------------------------*\
| Callback functions |
\*---------------------------------------------------------*/
void NetworkServer::SignalLogManagerLoggedEntry(LogMessage& logged_entry)
{
if(ServerClients.size() > 0)
{
/*-------------------------------------------------*\
| Create data buffer for message |
\*-------------------------------------------------*/
unsigned int data_size = 0;
unsigned short filename_size = (unsigned short)strlen(logged_entry.filename.c_str()) + 1;
unsigned short text_size = (unsigned short)strlen(logged_entry.text.c_str()) + 1;
data_size += sizeof(data_size);
data_size += sizeof(logged_entry.level);
data_size += sizeof(logged_entry.line);
data_size += sizeof(logged_entry.timestamp);
data_size += sizeof(filename_size);
data_size += filename_size;
data_size += sizeof(text_size);
data_size += text_size;
unsigned char* data_buf = new unsigned char[data_size];
unsigned char* data_ptr = data_buf;
memcpy(data_ptr, &data_size, sizeof(data_size));
data_ptr += sizeof(data_size);
memcpy(data_ptr, &logged_entry.level, sizeof(logged_entry.level));
data_ptr += sizeof(logged_entry.level);
memcpy(data_ptr, &logged_entry.line, sizeof(logged_entry.line));
data_ptr += sizeof(logged_entry.line);
memcpy(data_ptr, &logged_entry.timestamp, sizeof(logged_entry.timestamp));
data_ptr += sizeof(logged_entry.timestamp);
memcpy(data_ptr, &filename_size, sizeof(filename_size));
data_ptr += sizeof(filename_size);
memcpy(data_ptr, logged_entry.filename.c_str(), filename_size);
data_ptr += filename_size;
memcpy(data_ptr, &text_size, sizeof(text_size));
data_ptr += sizeof(text_size);
memcpy(data_ptr, logged_entry.text.c_str(), text_size);
data_ptr += text_size;
/*-------------------------------------------------*\
| Send Logged Entry request for all clients |
\*-------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
if(ServerClients[client_idx]->client_is_local_client)
{
SendRequest_LoggedEntry(ServerClients[client_idx], data_size, data_buf);
}
}
delete[] data_buf;
}
}
void NetworkServer::SignalProfileManagerUpdate(unsigned int update_reason)
{
switch(update_reason)
{
case PROFILEMANAGER_UPDATE_REASON_PROFILE_LIST_UPDATED:
SignalProfileListUpdated();
break;
case PROFILEMANAGER_UPDATE_REASON_ACTIVE_PROFILE_CHANGED:
SignalActiveProfileChanged();
break;
case PROFILEMANAGER_UPDATE_REASON_PROFILE_ABOUT_TO_LOAD:
ProfileManager_ProfileAboutToLoad();
break;
}
}
void NetworkServer::SignalResourceManagerUpdate(unsigned int update_reason)
{
switch(update_reason)
{
case RESOURCEMANAGER_UPDATE_REASON_DEVICE_LIST_UPDATED:
SignalDeviceListUpdated();
break;
case RESOURCEMANAGER_UPDATE_REASON_DETECTION_STARTED:
SignalDetectionStarted();
break;
case RESOURCEMANAGER_UPDATE_REASON_DETECTION_PROGRESS_CHANGED:
SignalDetectionProgress();
break;
case RESOURCEMANAGER_UPDATE_REASON_DETECTION_COMPLETE:
SignalDetectionCompleted();
break;
}
}
void NetworkServer::RegisterClientInfoChangeCallback(NetServerCallback new_callback, void* new_callback_arg)
{
ClientInfoChangeCallbacks.push_back(new_callback);
ClientInfoChangeCallbackArgs.push_back(new_callback_arg);
}
void NetworkServer::RegisterServerListeningChangeCallback(NetServerCallback new_callback, void* new_callback_arg)
{
ServerListeningChangeCallbacks.push_back(new_callback);
ServerListeningChangeCallbackArgs.push_back(new_callback_arg);
}
/*---------------------------------------------------------*\
| Server Configuration functions |
\*---------------------------------------------------------*/
void NetworkServer::SetHost(std::string new_host)
{
if(server_online == false)
{
host = new_host;
}
}
void NetworkServer::SetLegacyWorkaroundEnable(bool enable)
{
legacy_workaround_enabled = enable;
}
void NetworkServer::SetName(std::string new_name)
{
/*-----------------------------------------------------*\
| Store the server name |
\*-----------------------------------------------------*/
server_name = new_name;
/*-----------------------------------------------------*\
| Send server name to all clients |
\*-----------------------------------------------------*/
for(std::size_t client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
SendReply_ServerString(ServerClients[client_idx]);
}
}
void NetworkServer::SetPort(unsigned short new_port)
{
if(server_online == false)
{
port_num = new_port;
}
}
/*---------------------------------------------------------*\
| Server Control functions |
\*---------------------------------------------------------*/
void NetworkServer::StartServer()
{
int err;
struct addrinfo hints, *res, *result;
/*-----------------------------------------------------*\
| Start a TCP server and launch threads |
\*-----------------------------------------------------*/
char port_str[6];
snprintf(port_str, 6, "%d", port_num);
socket_count = 0;
/*-----------------------------------------------------*\
| Windows requires WSAStartup before using sockets |
\*-----------------------------------------------------*/
#ifdef WIN32
if(WSAStartup(MAKEWORD(2, 2), &wsa) != NO_ERROR)
{
WSACleanup();
return;
}
#endif
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
err = getaddrinfo(host.c_str(), port_str, &hints, &result);
if(err)
{
LOG_ERROR("[%s] Unable to get address.", NETWORKSERVER);
WSACleanup();
return;
}
/*-----------------------------------------------------*\
| Create a server socket for each address returned. |
\*-----------------------------------------------------*/
for(res = result; res && socket_count < MAXSOCK; res = res->ai_next)
{
server_sock[socket_count] = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(server_sock[socket_count] == INVALID_SOCKET)
{
LOG_ERROR("[%s] Network socket could not be created.", NETWORKSERVER);
WSACleanup();
return;
}
/*-------------------------------------------------*\
| Set socket options - reuse addr |
\*-------------------------------------------------*/
setsockopt(server_sock[socket_count], SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
/*-------------------------------------------------*\
| Bind the server socket |
\*-------------------------------------------------*/
if(bind(server_sock[socket_count], res->ai_addr, res->ai_addrlen) == SOCKET_ERROR)
{
if(errno == EADDRINUSE)
{
LOG_ERROR("[%s] Could not bind network socket. Is port %hu already being used?", NETWORKSERVER, GetPort());
}
else if(errno == EACCES)
{
LOG_ERROR("[%s] Could not bind network socket. Access to socket was denied.", NETWORKSERVER);
}
else if(errno == EBADF)
{
LOG_ERROR("[%s] Could not bind network socket. sockfd is not a valid file descriptor.", NETWORKSERVER);
}
else if(errno == EINVAL)
{
LOG_ERROR("[%s] Could not bind network socket. The socket is already bound to an address, or addrlen is wrong, or addr is not a valid address for this socket's domain.", NETWORKSERVER);
}
else if(errno == ENOTSOCK)
{
LOG_ERROR("[%s] Could not bind network socket. The file descriptor sockfd does not refer to a socket.", NETWORKSERVER);
}
else
{
/*---------------------------------------------------------*\
| errno could be a Linux specific error, see: |
| https://man7.org/linux/man-pages/man2/bind.2.html |
\*---------------------------------------------------------*/
LOG_ERROR("[%s] Could not bind network socket. Error code: %d.", NETWORKSERVER, errno);
}
WSACleanup();
return;
}
/*-------------------------------------------------*\
| Set socket options - no delay |
\*-------------------------------------------------*/
setsockopt(server_sock[socket_count], IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
socket_count += 1;
}
freeaddrinfo(result);
server_online = true;
/*-----------------------------------------------------*\
| Start the ProfileManager thread |
\*-----------------------------------------------------*/
profilemanager_thread = new NetworkServerControllerThread;
profilemanager_thread->id = 0;
profilemanager_thread->index = 0;
profilemanager_thread->online = true;
profilemanager_thread->thread = new std::thread(&NetworkServer::ProfileManagerListenThread, this, profilemanager_thread);
/*-----------------------------------------------------*\
| Start the connection thread |
\*-----------------------------------------------------*/
for(int curr_socket = 0; curr_socket < socket_count; curr_socket++)
{
ConnectionThread[curr_socket] = new std::thread(&NetworkServer::ConnectionThreadFunction, this, curr_socket);
ConnectionThread[curr_socket]->detach();
}
}
void NetworkServer::StopServer()
{
int curr_socket;
server_online = false;
ServerClientsMutex.lock();
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
delete ServerClients[client_idx];
}
ServerClients.clear();
for(curr_socket = 0; curr_socket < socket_count; curr_socket++)
{
shutdown(server_sock[curr_socket], SD_RECEIVE);
closesocket(server_sock[curr_socket]);
}
ServerClientsMutex.unlock();
for(curr_socket = 0; curr_socket < socket_count; curr_socket++)
{
if(ConnectionThread[curr_socket])
{
delete ConnectionThread[curr_socket];
ConnectionThread[curr_socket] = nullptr;
}
}
socket_count = 0;
/*-----------------------------------------------------*\
| Close the ProfileManager listen thread |
\*-----------------------------------------------------*/
if(profilemanager_thread->thread)
{
profilemanager_thread->online = false;
profilemanager_thread->start_cv.notify_all();
profilemanager_thread->thread->join();
delete profilemanager_thread->thread;
profilemanager_thread->thread = nullptr;
delete profilemanager_thread;
}
/*-----------------------------------------------------*\
| Client info has changed, call the callbacks |
\*-----------------------------------------------------*/
SignalClientInfoChanged();
}
/*---------------------------------------------------------*\
| Server Interface functions |
\*---------------------------------------------------------*/
void NetworkServer::SetControllers(std::vector<RGBController *> new_controllers)
{
/*-----------------------------------------------------*\
| Set the controller list updating flag to pause the |
| controller packet processing |
\*-----------------------------------------------------*/
controller_updating = true;
/*-----------------------------------------------------*\
| Lock the controller list mutex |
\*-----------------------------------------------------*/
controller_ids_mutex.lock();
/*-----------------------------------------------------*\
| Update the controllers list |
\*-----------------------------------------------------*/
controllers = new_controllers;
/*-----------------------------------------------------*\
| Create a copy of the current controller IDs list |
\*-----------------------------------------------------*/
std::vector<NetworkControllerID> controller_ids_old = controller_ids;
/*-----------------------------------------------------*\
| Clear the current controller IDs list |
\*-----------------------------------------------------*/
controller_ids.clear();
/*-----------------------------------------------------*\
| Resize controller IDs list to be the same size as the |
| controllers list |
\*-----------------------------------------------------*/
controller_ids.resize(controllers.size());
/*-----------------------------------------------------*\
| Loop through the controllers list and find the ID for |
| each controller, adding it to the IDs list. |
\*-----------------------------------------------------*/
for(std::size_t controller_idx = 0; controller_idx < controller_ids.size(); controller_idx++)
{
bool match = false;
for(std::size_t controller_id_idx = 0; controller_id_idx < controller_ids_old.size(); controller_id_idx++)
{
if(controllers[controller_idx] == controller_ids_old[controller_id_idx].controller)
{
controller_ids[controller_idx] = controller_ids_old[controller_id_idx];
match = true;
break;
}
}
/*-------------------------------------------------*\
| If an ID does not already exist, create a new ID |
| for this controller |
\*-------------------------------------------------*/
if(!match)
{
NetworkControllerID new_controller_id;
new_controller_id.controller = controllers[controller_idx];
new_controller_id.id = controller_next_idx;
controller_next_idx++;
controller_ids[controller_idx] = new_controller_id;
}
}
/*-----------------------------------------------------*\
| Lock the controller threads mutex |
\*-----------------------------------------------------*/
controller_threads_mutex.lock();
/*-----------------------------------------------------*\
| Create a copy of the current controller threads list |
\*-----------------------------------------------------*/
std::vector<NetworkServerControllerThread *> controller_threads_old = controller_threads;
/*-----------------------------------------------------*\
| Clear the current controller threads list |
\*-----------------------------------------------------*/
controller_threads.clear();
/*-----------------------------------------------------*\
| Resize the controller threads so that there is one |
| thread per controller ID |
\*-----------------------------------------------------*/
controller_threads.resize(controller_ids.size());
/*-----------------------------------------------------*\
| Loop through the controller IDs list and find the |
| thread for each ID, adding it to the threads list. |
\*-----------------------------------------------------*/
for(std::size_t controller_id_idx = 0; controller_id_idx < controller_ids.size(); controller_id_idx++)
{
std::size_t controller_thread_old_idx = 0;
bool match = false;
for(; controller_thread_old_idx < controller_threads_old.size(); controller_thread_old_idx++)
{
if(controller_ids[controller_id_idx].id == controller_threads_old[controller_thread_old_idx]->id)
{
match = true;
break;
}
}
/*-----------------------------------------------------*\
| If an existing thread was found with this ID, copy it |
| into the new list at the new index. |
\*-----------------------------------------------------*/
if(match)
{
controller_threads[controller_id_idx] = controller_threads_old[controller_thread_old_idx];
controller_threads[controller_id_idx]->index = (unsigned int)controller_id_idx;
controller_threads_old.erase(controller_threads_old.begin() + controller_thread_old_idx);
}
/*-----------------------------------------------------*\
| Otherwise, if an existing thread was not found with |
|this ID, create a new one. |
\*-----------------------------------------------------*/
else
{
NetworkServerControllerThread * new_controller_thread = new NetworkServerControllerThread;
new_controller_thread->id = controller_ids[controller_id_idx].id;
new_controller_thread->index = (unsigned int)controller_id_idx;
new_controller_thread->online = true;
new_controller_thread->thread = new std::thread(&NetworkServer::ControllerListenThread, this, new_controller_thread);
controller_threads[controller_id_idx] = new_controller_thread;
}
}
/*-----------------------------------------------------*\
| Unlock the controller IDs mutex |
\*-----------------------------------------------------*/
controller_ids_mutex.unlock();
/*-----------------------------------------------------*\
| Loop through the remaining threads in the old list |
| and shut them down, their controller IDs are no |
| longer valid. |
\*-----------------------------------------------------*/
for(std::size_t controller_thread_old_idx = 0; controller_thread_old_idx < controller_threads_old.size(); controller_thread_old_idx++)
{
controller_threads_old[controller_thread_old_idx]->online = false;
controller_threads_old[controller_thread_old_idx]->start_cv.notify_all();
controller_threads_old[controller_thread_old_idx]->thread->join();
delete controller_threads_old[controller_thread_old_idx]->thread;
}
/*-----------------------------------------------------*\
| Unlock the controller threads mutex |
\*-----------------------------------------------------*/
controller_threads_mutex.unlock();
/*-----------------------------------------------------*\
| Register the server's RGBController update handler |
| for each RGBController in the controllers list |
\*-----------------------------------------------------*/
for(std::size_t controller_idx = 0; controller_idx < controllers.size(); controller_idx++)
{
controllers[controller_idx]->RegisterUpdateCallback(RGBController_UpdateCallback, this);
}
/*-----------------------------------------------------*\
| Clear the controller list updating flag to resume the |
| controller packet processing |
\*-----------------------------------------------------*/
controller_updating = false;
}
void NetworkServer::SetPluginManager(PluginManagerInterface* plugin_manager_pointer)
{
plugin_manager = plugin_manager_pointer;
}
void NetworkServer::SetProfileManager(ProfileManagerInterface* profile_manager_pointer)
{
profile_manager = profile_manager_pointer;
}
void NetworkServer::SetSettingsManager(SettingsManagerInterface* settings_manager_pointer)
{
settings_manager = settings_manager_pointer;
}
/*---------------------------------------------------------*\
| Server callback signal functions |
\*---------------------------------------------------------*/
void NetworkServer::SignalActiveProfileChanged()
{
if(profile_manager)
{
std::string active_profile = profile_manager->GetActiveProfile();
/*-------------------------------------------------*\
| Indicate to the clients that the profile list has |
| changed |
\*-------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
if(ServerClients[client_idx]->client_flags & NET_CLIENT_FLAG_SUPPORTS_PROFILEMANAGER)
{
SendRequest_ProfileManager_ActiveProfileChanged(ServerClients[client_idx], active_profile);
}
}
}
}
void NetworkServer::SignalClientInfoChanged()
{
ClientInfoChangeMutex.lock();
/*-----------------------------------------------------*\
| Client info has changed, call the callbacks |
\*-----------------------------------------------------*/
for(unsigned int callback_idx = 0; callback_idx < ClientInfoChangeCallbacks.size(); callback_idx++)
{
ClientInfoChangeCallbacks[callback_idx](ClientInfoChangeCallbackArgs[callback_idx]);
}
ClientInfoChangeMutex.unlock();
}
void NetworkServer::SignalDetectionCompleted()
{
/*-----------------------------------------------------*\
| Indicate to the clients that detection has completed |
\*-----------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
SendRequest_DetectionCompleted(ServerClients[client_idx]);
}
}
void NetworkServer::SignalDetectionProgress()
{
unsigned int detection_percent = ResourceManager::get()->GetDetectionPercent();
std::string detection_string = ResourceManager::get()->GetDetectionString();
/*-----------------------------------------------------*\
| Indicate to the clients detection progress changed |
\*-----------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
SendRequest_DetectionProgress(ServerClients[client_idx], detection_percent, detection_string);
}
}
void NetworkServer::SignalDetectionStarted()
{
/*-----------------------------------------------------*\
| Indicate to the clients that detection has started |
\*-----------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
SendRequest_DetectionStarted(ServerClients[client_idx]);
}
}
void NetworkServer::SignalDeviceListUpdated()
{
/*-----------------------------------------------------*\
| Indicate to the clients that the controller list has |
| changed |
\*-----------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
SendRequest_DeviceListChanged(ServerClients[client_idx]);
}
}
void NetworkServer::SignalProfileListUpdated()
{
if(profile_manager)
{
unsigned char* profile_list_description = profile_manager->GetProfileListDescription();
/*-------------------------------------------------*\
| Indicate to the clients that the profile list has |
| changed |
\*-------------------------------------------------*/
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
SendRequest_ProfileManager_ProfileListChanged(ServerClients[client_idx], profile_list_description);
}
delete[] profile_list_description;
}
}
void NetworkServer::SignalServerListeningChanged()
{
ServerListeningChangeMutex.lock();
/*-----------------------------------------------------*\
| Server state has changed, call the callbacks |
\*-----------------------------------------------------*/
for(unsigned int callback_idx = 0; callback_idx < ServerListeningChangeCallbacks.size(); callback_idx++)
{
ServerListeningChangeCallbacks[callback_idx](ServerListeningChangeCallbackArgs[callback_idx]);
}
ServerListeningChangeMutex.unlock();
}
/*---------------------------------------------------------*\
| Server Thread functions |
\*---------------------------------------------------------*/
void NetworkServer::ConnectionThreadFunction(int socket_idx)
{
/*-----------------------------------------------------*\
| This thread handles client connections |
\*-----------------------------------------------------*/
LOG_INFO("[%s] Network connection thread started on port %hu", NETWORKSERVER, GetPort());
while(server_online == true)
{
/*-------------------------------------------------*\
| Create new socket for client connection |
\*-------------------------------------------------*/
NetworkClientInfo * client_info = new NetworkClientInfo();
/*---------------------------------------------------------*\
| Listen for incoming client connection on the server |
| socket. This call blocks until a connection is |
| established |
\*---------------------------------------------------------*/
if(listen(server_sock[socket_idx], 10) < 0)
{
LOG_INFO("[%s] Connection thread closed", NETWORKSERVER);
server_online = false;
return;
}
server_listening = true;
SignalServerListeningChanged();
/*-------------------------------------------------*\
| Accept the client connection |
\*-------------------------------------------------*/
client_info->client_sock = accept_select((int)server_sock[socket_idx]);
if(client_info->client_sock < 0)
{
LOG_INFO("[%s] Connection thread closed", NETWORKSERVER);
server_online = false;
server_listening = false;
SignalServerListeningChanged();
return;
}
/*---------------------------------------------------------*\
| Get the new client socket and store it in the clients |
| vector |
\*---------------------------------------------------------*/
u_long arg = 0;
ioctlsocket(client_info->client_sock, FIONBIO, &arg);
setsockopt(client_info->client_sock, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
/*-------------------------------------------------*\
| Discover the remote hosts IP |
\*-------------------------------------------------*/
struct sockaddr_storage tmp_addr;
char ipstr[INET6_ADDRSTRLEN];
socklen_t len;
len = sizeof(tmp_addr);
getpeername(client_info->client_sock, (struct sockaddr*)&tmp_addr, &len);
if(tmp_addr.ss_family == AF_INET)
{
struct sockaddr_in *s_4 = (struct sockaddr_in *)&tmp_addr;
inet_ntop(AF_INET, &s_4->sin_addr, ipstr, sizeof(ipstr));
client_info->client_ip = ipstr;
if(s_4->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
{
client_info->client_is_local = true;
}
}
else
{
struct sockaddr_in6 *s_6 = (struct sockaddr_in6 *)&tmp_addr;
inet_ntop(AF_INET6, &s_6->sin6_addr, ipstr, sizeof(ipstr));
client_info->client_ip = ipstr;
if(IN6_IS_ADDR_LOOPBACK(&s_6->sin6_addr))
{
client_info->client_is_local = true;
}
}
/*---------------------------------------------------------*\
| We need to lock before the thread could possibly finish |
\*---------------------------------------------------------*/
ServerClientsMutex.lock();
/*---------------------------------------------------------*\
| Start a listener thread for the new client socket |
\*---------------------------------------------------------*/
client_info->client_listen_thread = new std::thread(&NetworkServer::ListenThreadFunction, this, client_info);
client_info->client_listen_thread->detach();
ServerClients.push_back(client_info);