forked from CalcProgrammer1/OpenRGB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkServer.cpp
611 lines (493 loc) · 18 KB
/
NetworkServer.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
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
/*-----------------------------------------*\
| NetworkServer.cpp |
| |
| Server code for OpenRGB SDK |
| |
| Adam Honse (CalcProgrammer1) 5/9/2020 |
\*-----------------------------------------*/
#include "NetworkServer.h"
#include <cstring>
#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>
#include <iostream>
const char yes = 1;
#ifdef WIN32
#include <Windows.h>
#else
#include <unistd.h>
static void Sleep(unsigned int milliseconds)
{
usleep(1000 * milliseconds);
}
#endif
NetworkServer::NetworkServer(std::vector<RGBController *>& control) : controllers(control)
{
port_num = 1337;
server_online = false;
}
void NetworkServer::ClientInfoChanged()
{
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();
}
unsigned short NetworkServer::GetPort()
{
return port_num;
}
bool NetworkServer::GetOnline()
{
return server_online;
}
unsigned int NetworkServer::GetNumClients()
{
return ServerClients.size();
}
const char * NetworkServer::GetClientString(unsigned int client_num)
{
if(client_num < ServerClients.size())
{
return ServerClients[client_num]->client_string.c_str();
}
else
{
return "";
}
}
const char * NetworkServer::GetClientIP(unsigned int client_num)
{
if(client_num < ServerClients.size())
{
return ServerClients[client_num]->client_ip;
}
else
{
return "";
}
}
void NetworkServer::RegisterClientInfoChangeCallback(NetServerCallback new_callback, void * new_callback_arg)
{
ClientInfoChangeCallbacks.push_back(new_callback);
ClientInfoChangeCallbackArgs.push_back(new_callback_arg);
}
void NetworkServer::SetPort(unsigned short new_port)
{
if(server_online == false)
{
port_num = new_port;
}
}
void NetworkServer::StartServer()
{
//Start a TCP server and launch threads
char port_str[6];
snprintf(port_str, 6, "%d", port_num);
sockaddr_in myAddress;
/*-------------------------------------------------*\
| Windows requires WSAStartup before using sockets |
\*-------------------------------------------------*/
#ifdef WIN32
if (WSAStartup(MAKEWORD(2, 2), &wsa) != NO_ERROR)
{
WSACleanup();
return;
}
#endif
/*-------------------------------------------------*\
| Create the server socket |
\*-------------------------------------------------*/
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == INVALID_SOCKET)
{
WSACleanup();
return;
}
/*-------------------------------------------------*\
| Fill in server address info with port value |
\*-------------------------------------------------*/
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr("0.0.0.0");
myAddress.sin_port = htons(atoi(port_str));
/*-------------------------------------------------*\
| Bind the server socket |
\*-------------------------------------------------*/
if (bind(server_sock, (sockaddr*)&myAddress, sizeof(myAddress)) == SOCKET_ERROR)
{
WSACleanup();
return;
}
/*-------------------------------------------------*\
| Set socket options - no delay |
\*-------------------------------------------------*/
setsockopt(server_sock, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
server_online = true;
/*-------------------------------------------------*\
| Start the connection thread |
\*-------------------------------------------------*/
ConnectionThread = new std::thread(&NetworkServer::ConnectionThreadFunction, this);
}
void NetworkServer::StopServer()
{
server_online = false;
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
shutdown(ServerClients[client_idx]->client_sock, SD_RECEIVE);
closesocket(ServerClients[client_idx]->client_sock);
ServerClients[client_idx]->client_listen_thread->join();
}
shutdown(server_sock, SD_RECEIVE);
closesocket(server_sock);
ConnectionThread->join();
for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++)
{
delete ServerClients[client_idx];
}
ServerClients.clear();
/*-------------------------------------------------*\
| Client info has changed, call the callbacks |
\*-------------------------------------------------*/
ClientInfoChanged();
}
void NetworkServer::ConnectionThreadFunction()
{
//This thread handles client connections
printf("Network connection thread started\n");
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, 10) < 0)
{
printf("Connection thread closed\r\n");
server_online = false;
return;
}
/*-------------------------------------------------*\
| Accept the client connection |
\*-------------------------------------------------*/
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
client_info->client_sock = accept_select(server_sock, (struct sockaddr *)&client_addr, &client_addr_len);
if(client_info->client_sock < 0)
{
printf("Connection thread closed\r\n");
server_online = false;
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));
inet_ntop(AF_INET, &client_addr.sin_addr, client_info->client_ip, INET_ADDRSTRLEN);
client_info->client_string = "Client";
//Start a listener thread for the new client socket
client_info->client_listen_thread = new std::thread(&NetworkServer::ListenThreadFunction, this, client_info);
ServerClients.push_back(client_info);
/*-------------------------------------------------*\
| Client info has changed, call the callbacks |
\*-------------------------------------------------*/
ClientInfoChanged();
}
printf("Connection thread closed\r\n");
server_online = false;
}
int NetworkServer::accept_select(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
fd_set set;
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
while(1)
{
FD_ZERO(&set); /* clear the set */
FD_SET(sockfd, &set); /* add our file descriptor to the set */
int rv = select(sockfd + 1, &set, NULL, NULL, &timeout);
if(rv == SOCKET_ERROR || server_online == false)
{
return -1;
}
else if(rv == 0)
{
continue;
}
else
{
// socket has something to read
return(accept(sockfd, addr, addrlen));
}
}
}
int NetworkServer::recv_select(SOCKET s, char *buf, int len, int flags)
{
fd_set set;
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
while(1)
{
FD_ZERO(&set); /* clear the set */
FD_SET(s, &set); /* add our file descriptor to the set */
int rv = select(s + 1, &set, NULL, NULL, &timeout);
if(rv == SOCKET_ERROR || server_online == false)
{
return 0;
}
else if(rv == 0)
{
continue;
}
else
{
// socket has something to read
return(recv(s, buf, len, flags));
}
}
}
void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info)
{
SOCKET client_sock = client_info->client_sock;
printf("Network server started\n");
//This thread handles messages received from clients
while(server_online == true)
{
NetPacketHeader header;
int bytes_read = 0;
char * data = NULL;
//Read first byte of magic
bytes_read = recv_select(client_sock, &header.pkt_magic[0], 1, 0);
if(bytes_read <= 0)
{
goto listen_done;
}
//Test first character of magic - 'O'
if(header.pkt_magic[0] != 'O')
{
continue;
}
//Read second byte of magic
bytes_read = recv_select(client_sock, &header.pkt_magic[1], 1, 0);
if(bytes_read <= 0)
{
goto listen_done;
}
//Test second character of magic - 'R'
if(header.pkt_magic[1] != 'R')
{
continue;
}
//Read third byte of magic
bytes_read = recv_select(client_sock, &header.pkt_magic[2], 1, 0);
if(bytes_read <= 0)
{
goto listen_done;
}
//Test third character of magic - 'G'
if(header.pkt_magic[2] != 'G')
{
continue;
}
//Read fourth byte of magic
bytes_read = recv_select(client_sock, &header.pkt_magic[3], 1, 0);
if(bytes_read <= 0)
{
goto listen_done;
}
//Test fourth character of magic - 'B'
if(header.pkt_magic[3] != 'B')
{
continue;
}
//If we get to this point, the magic is correct. Read the rest of the header
bytes_read = 0;
do
{
int tmp_bytes_read = 0;
tmp_bytes_read = recv_select(client_sock, (char *)&header.pkt_dev_idx + bytes_read, sizeof(header) - sizeof(header.pkt_magic) - bytes_read, 0);
bytes_read += tmp_bytes_read;
if(tmp_bytes_read <= 0)
{
goto listen_done;
}
} while(bytes_read != sizeof(header) - sizeof(header.pkt_magic));
//printf( "Server: Received header, now receiving data of size %d\r\n", header.pkt_size);
//Header received, now receive the data
if(header.pkt_size > 0)
{
bytes_read = 0;
data = new char[header.pkt_size];
do
{
int tmp_bytes_read = 0;
tmp_bytes_read = recv_select(client_sock, &data[bytes_read], header.pkt_size - bytes_read, 0);
if(tmp_bytes_read <= 0)
{
goto listen_done;
}
bytes_read += tmp_bytes_read;
} while (bytes_read < header.pkt_size);
}
//printf( "Server: Received header and data\r\n" );
//printf( "Server: Packet ID: %d \r\n", header.pkt_id);
//Entire request received, select functionality based on request ID
switch(header.pkt_id)
{
case NET_PACKET_ID_REQUEST_CONTROLLER_COUNT:
//printf( "NET_PACKET_ID_REQUEST_CONTROLLER_COUNT\r\n" );
SendReply_ControllerCount(client_sock);
break;
case NET_PACKET_ID_REQUEST_CONTROLLER_DATA:
//printf( "NET_PACKET_ID_REQUEST_CONTROLLER_DATA\r\n" );
SendReply_ControllerData(client_sock, header.pkt_dev_idx);
break;
case NET_PACKET_ID_SET_CLIENT_NAME:
printf( "NET_PACKET_ID_SET_CLIENT_NAME\r\n" );
ProcessRequest_ClientString(client_sock, header.pkt_size, data);
break;
case NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE:
//printf( "NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE\r\n" );
if((header.pkt_dev_idx < controllers.size()) && (header.pkt_size == (2 * sizeof(int))))
{
int zone;
int new_size;
memcpy(&zone, data, sizeof(int));
memcpy(&new_size, data + sizeof(int), sizeof(int));
controllers[header.pkt_dev_idx]->ResizeZone(zone, new_size);
}
break;
case NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS:
//printf( "NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS\r\n" );
if(header.pkt_dev_idx < controllers.size())
{
controllers[header.pkt_dev_idx]->SetColorDescription((unsigned char *)data);
controllers[header.pkt_dev_idx]->UpdateLEDs();
}
break;
case NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS:
//printf( "NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS\r\n" );
if(header.pkt_dev_idx < controllers.size())
{
int zone;
memcpy(&zone, &data[sizeof(unsigned int)], sizeof(int));
controllers[header.pkt_dev_idx]->SetZoneColorDescription((unsigned char *)data);
controllers[header.pkt_dev_idx]->UpdateZoneLEDs(zone);
}
break;
case NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED:
//printf( "NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED\r\n" );
if(header.pkt_dev_idx < controllers.size())
{
int led;
memcpy(&led, data, sizeof(int));
controllers[header.pkt_dev_idx]->SetSingleLEDColorDescription((unsigned char *)data);
controllers[header.pkt_dev_idx]->UpdateSingleLED(led);
}
break;
case NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE:
//printf( "NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE\r\n" );
if(header.pkt_dev_idx < controllers.size())
{
controllers[header.pkt_dev_idx]->SetCustomMode();
}
break;
case NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE:
//printf( "NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE\r\n" );
if(header.pkt_dev_idx < controllers.size())
{
controllers[header.pkt_dev_idx]->SetModeDescription((unsigned char *)data);
controllers[header.pkt_dev_idx]->UpdateMode();
}
break;
}
delete[] data;
}
listen_done:
printf("Server connection closed\r\n");
shutdown(client_info->client_sock, SD_RECEIVE);
closesocket(client_info->client_sock);
for(unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++)
{
if(ServerClients[this_idx] == client_info)
{
ServerClients.erase(ServerClients.begin() + this_idx);
break;
}
}
/*-------------------------------------------------*\
| Client info has changed, call the callbacks |
\*-------------------------------------------------*/
ClientInfoChanged();
}
void NetworkServer::ProcessRequest_ClientString(SOCKET client_sock, unsigned int data_size, char * data)
{
for(unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++)
{
if(ServerClients[this_idx]->client_sock == client_sock)
{
ServerClients[this_idx]->client_string = data;
break;
}
}
/*-------------------------------------------------*\
| Client info has changed, call the callbacks |
\*-------------------------------------------------*/
ClientInfoChanged();
}
void NetworkServer::SendReply_ControllerCount(SOCKET client_sock)
{
NetPacketHeader reply_hdr;
unsigned int reply_data;
reply_hdr.pkt_magic[0] = 'O';
reply_hdr.pkt_magic[1] = 'R';
reply_hdr.pkt_magic[2] = 'G';
reply_hdr.pkt_magic[3] = 'B';
reply_hdr.pkt_dev_idx = 0;
reply_hdr.pkt_id = NET_PACKET_ID_REQUEST_CONTROLLER_COUNT;
reply_hdr.pkt_size = sizeof(unsigned int);
reply_data = controllers.size();
send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0);
send(client_sock, (const char *)&reply_data, sizeof(unsigned int), 0);
}
void NetworkServer::SendReply_ControllerData(SOCKET client_sock, unsigned int dev_idx)
{
if(dev_idx < controllers.size())
{
NetPacketHeader reply_hdr;
unsigned char *reply_data = controllers[dev_idx]->GetDeviceDescription();
unsigned int reply_size;
memcpy(&reply_size, reply_data, sizeof(reply_size));
reply_hdr.pkt_magic[0] = 'O';
reply_hdr.pkt_magic[1] = 'R';
reply_hdr.pkt_magic[2] = 'G';
reply_hdr.pkt_magic[3] = 'B';
reply_hdr.pkt_dev_idx = dev_idx;
reply_hdr.pkt_id = NET_PACKET_ID_REQUEST_CONTROLLER_DATA;
reply_hdr.pkt_size = reply_size;
send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0);
send(client_sock, (const char *)reply_data, reply_size, 0);
}
}