-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmcrcond.c
1422 lines (1302 loc) · 37.2 KB
/
mcrcond.c
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
///////////////////////////////////////////////////////////////////////////////
//
// The MIT License
//
// Copyright 2021 0xAA55
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <getopt.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#define EXEC_NAME "mcrcond"
#define LOCK_FILE "/tmp/mcrcond.lock" // PID file name
#define LOG_FILE "mcrcond.log" // log file name
#define CFG_FILE "mcrcond.conf" // configure file name
#define DEFAULT_DAEMON_HOST "localhost"
#define DEFAULT_DAEMON_PORT 25585
#define DEFAULT_DAEMON_BACKLOG 256
#define RCON_HEADER_SIZE 12
#define MAX_RCON_REQUEST 1500
#define MAX_RCON_RESPONSE_WAIT 3
#define MAX_RCON_RESPONSE_PAYLOAD 4096
#define MAX_RCON_RESPONSE (MAX_RCON_RESPONSE_PAYLOAD + RCON_HEADER_SIZE)
#define CLIENT_BUFFER_SIZE 4096
#define SOCKET_BUFFER_SIZE 8192
#define MAX_SERVER_WAIT_INTERVAL (5 * 60)
static int signal_exit_catch = 0;
static void signal_handler(int sig)
{
switch(sig)
{
case SIGINT:
case SIGTERM:
signal_exit_catch = 1;
break;
}
}
// The client's structure, managed by the daemon
typedef struct daemon_client_struct
{
int socket_client;
int request_id;
// The client sends the command to execute.
// Max command length should be limited under 1.5 kb
// The client sends the length of the command first, then the command.
// After the whole command received, the daemon pack up the whole thing and send it to rcon, wait for the response.
char buffer[CLIENT_BUFFER_SIZE];
size_t buffer_received;
size_t buffer_to_receive;
int buffer_sent;
// The rcon server returns a response, with it's response packet size specified.
// However, the server may send multiple response packets.
// The packets are the fragmentation of the output of the command.
// If a packet size is exactly 4 kb, then it's possible to be fragmented, and it's necessary to poke the server with some invalid packets.
char response[MAX_RCON_RESPONSE];
size_t response_size;
int response_received;
int response_sent;
time_t response_time;
}daemon_client_t, *daemon_client_p;
// The daemon's structure
typedef struct daemon_inst_struct
{
// Parsed configurations
char conf_rcon_host[256];
int conf_rcon_port;
char conf_rcon_auth[64];
char conf_daemon_listen[256];
int conf_daemon_port;
int conf_daemon_backlog;
int conf_log_rcon;
int conf_debug;
int conf_response_newline;
FILE* fp_log;
int daemonized;
int socket_to_rcon;
int socket_listen;
int cur_request_id;
size_t client_count;
daemon_client_p clients;
}daemon_inst_t, *daemon_inst_p;
// The RCON protocol packet header
typedef struct rcon_packet_struct
{
int length;
int request_id;
int type;
char payload[0];
}rcon_packet_t, *rcon_packet_p;
static int socket_reuse_addr_port(int sfd)
{
int value = 1;
return
(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &value, sizeof value) >= 0) &
(setsockopt(sfd, SOL_SOCKET, SO_REUSEPORT, &value, sizeof value) >= 0);
}
static void di_logtime(daemon_inst_p di, FILE *stream)
{
time_t t;
struct tm *tmp;
char szTime[128];
t = time(NULL);
tmp = localtime(&t);
if (tmp) strftime(szTime, sizeof szTime, "%H:%M:%S", tmp);
fprintf(stream, "[%s]: ", tmp ? szTime : strerror(errno));
}
void di_printf(daemon_inst_p di, const char *format, ...)
{
va_list ap;
va_start(ap, format);
di_logtime(di, di->fp_log);
vfprintf(di->fp_log, format, ap);
fflush(di->fp_log);
va_end(ap);
if (!di->daemonized)
{
va_start(ap, format);
di_logtime(di, stdout);
vprintf(format, ap);
va_end(ap);
}
}
// Delete the daemon instance
void di_delete(daemon_inst_p di)
{
if(!di) return;
if(di->socket_to_rcon != -1) close(di->socket_to_rcon);
if(di->socket_listen != -1) close(di->socket_listen);
if(di->clients)
{
size_t i;
for (i = 0; i < di->client_count; i++)
{
if(di->clients[i].socket_client != -1)
{
close(di->clients[i].socket_client);
}
}
free(di->clients);
}
if(di->fp_log)
{
di_printf(di, "[TERM] The daemon '"EXEC_NAME"' has been terminated.\n");
fclose(di->fp_log);
}
free(di);
}
// Create the daemon instance
daemon_inst_p di_create(char* log_filepath)
{
daemon_inst_p di = NULL;
if (!log_filepath) return di;
di = malloc(sizeof *di);
if (!di) return di;
memset(di, 0, sizeof *di);
di->socket_to_rcon = -1;
di->socket_listen = -1;
strcpy(di->conf_rcon_host, "localhost");
di->conf_rcon_port = 25575;
strcpy(di->conf_rcon_auth, "EX");
strcpy(di->conf_daemon_listen, "localhost");
di->conf_daemon_port = DEFAULT_DAEMON_PORT;
di->conf_daemon_backlog = DEFAULT_DAEMON_BACKLOG;
di->conf_log_rcon = 0;
di->fp_log = fopen(log_filepath, "a");
if(!di->fp_log)
{
// fprintf(stderr, "Open log file '%s' failed: %s.\n", log_filepath, strerror(errno));
goto FailExit;
}
di_printf(di, "[INIT] Starting daemon '"EXEC_NAME"'.\n");
return di;
FailExit:
di_delete(di);
return NULL;
}
// The default configure file generation
int di_write_default_cfg_file(daemon_inst_p di, char *cfg_filepath)
{
FILE *fp = fopen(cfg_filepath, "w");
if(!fp)
{
di_printf(di, "[FAIL] Writing default configure file '%s' failed: %s.\n", cfg_filepath, strerror(errno));
return 0;
}
di_printf(di, "[FAIL] Generating the default configure file to '%s'.\n", cfg_filepath);
di_printf(di, "[INFO] Please check the generated configure file and restart the daemon.\n");
fprintf(fp, "# The minecraft server RCON address, port, password\n");
fprintf(fp, "rcon-host=%s\n", di->conf_rcon_host);
fprintf(fp, "rcon-port=%d\n", di->conf_rcon_port);
fprintf(fp, "rcon-auth=%s\n", di->conf_rcon_auth);
fprintf(fp, "\n");
fprintf(fp, "# From what addresses can connect the daemon\n");
fprintf(fp, "daemon-listen=%s\n", di->conf_daemon_listen);
fprintf(fp, "\n");
fprintf(fp, "# The port of the daemon\n");
fprintf(fp, "daemon-port=%d\n", di->conf_daemon_port);
fprintf(fp, "\n");
fprintf(fp, "# How many connections to the daemon at the same time\n");
fprintf(fp, "daemon-backlog=%d\n", di->conf_daemon_backlog);
fprintf(fp, "\n");
fprintf(fp, "# Uncomment next line to log all RCON activities\n");
fprintf(fp, "#log-rcon=1\n");
fprintf(fp, "\n");
fprintf(fp, "# Uncomment next line to add a newline ending to responses\n");
fprintf(fp, "#response-add-newline=1\n");
fprintf(fp, "\n");
fclose(fp);
return 1;
}
// Parse existing configure file
int di_parse_cfg_file(daemon_inst_p di, char *cfg_filepath)
{
FILE *fp = fopen(cfg_filepath, "r");
if(!fp)
{
if(errno == ENOENT)
{
di_printf(di, "[FAIL] Configure file '%s' not found.\n", cfg_filepath);
di_write_default_cfg_file(di, cfg_filepath);
return 0;
}
else
{
di_printf(di, "[FAIL] Open configure file '%s' failed: %s.\n", cfg_filepath, strerror(errno));
return 0;
}
}
else
{
int line_no = 0;
int failure = 0;
char line_buf[512];
const char token_delims[] = " =\r\n";
do
{
char *ch;
// Read the configure file line by line, and use 'ch' to parse each line.
ch = fgets(line_buf, sizeof line_buf, fp); line_no++;
if(!ch && !feof(fp))
{
failure = 1;
break;
}
// Remove the comments
ch = strchr(line_buf, '#');
if (ch) *ch = '\0';
// Ignore the leading space
ch = line_buf;
while(isspace(*ch)) ch++;
// Ignore empty line
if (*ch == '\r' ||*ch == '\n' || *ch == '\0') continue;
// Remove the spaces of the line
memmove(line_buf, ch, strlen(ch) + 1);
// Parse the line
ch = strtok(line_buf, token_delims);
if (!ch)
{
failure = 2;
break;
}
if (!strcmp(ch, "rcon-host"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%s", &di->conf_rcon_host[0]) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "rcon-port"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%d", &di->conf_rcon_port) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "rcon-auth"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%s", &di->conf_rcon_auth[0]) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "daemon-listen"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%s", &di->conf_daemon_listen[0]) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "daemon-port"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%d", &di->conf_daemon_port) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "daemon-backlog"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%d", &di->conf_daemon_backlog) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "log-rcon"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%d", &di->conf_log_rcon) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "debug"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%d", &di->conf_debug) != 1)
{
failure = 2;
break;
}
}
else if(!strcmp(ch, "response-add-newline"))
{
ch = strtok(NULL, token_delims);
if(!ch || sscanf(ch, "%d", &di->conf_response_newline) != 1)
{
failure = 2;
break;
}
}
else
{
failure = 2;
break;
}
}while(!feof(fp));
fclose(fp);
switch(failure)
{
case 0:
return 1;
case 1:
di_printf(di, "[FAIL] Error occurs while parsing configure file '%s' at line %d:\n", cfg_filepath, line_no);
di_printf(di, "[FAIL] \t%s.\n", strerror(errno));
return 0;
case 2:
di_printf(di, "[FAIL] Error occurs while parsing configure file '%s' at line %d:\n", cfg_filepath, line_no);
di_printf(di, "[FAIL] Unknown '%s'.\n", line_buf);
return 0;
default:
di_printf(di, "[FAIL] Error occurs while parsing configure file '%s' at line %d:\n", cfg_filepath, line_no);
di_printf(di, "[FAIL] Unknown '%s' because of unknown 'failure' %d.\n", line_buf, failure);
return 0;
}
}
}
// Check if 'struct sockaddr' is an IPv4 address
static int is_v4_addr(struct sockaddr *addr, socklen_t addr_len)
{
return (addr->sa_family == AF_INET && addr_len == sizeof(struct sockaddr_in));
}
static void di_reset_listener_socket(daemon_inst_p di)
{
if(di->socket_listen != -1)
{
close(di->socket_listen);
di->socket_listen = -1;
}
di->client_count = 0;
if(di->clients)
{
size_t i;
for (i = 0; i < di->client_count; i++)
{
if(di->clients[i].socket_client != -1)
{
close(di->clients[i].socket_client);
}
}
free(di->clients);
di->clients = NULL;
}
}
// Create the socket for listening from the clients
static int di_init_listener_socket(daemon_inst_p di)
{
struct addrinfo hints;
struct addrinfo *result = NULL, *rp;
int s, sfd = -1;
char port_buf[8];
size_t i;
di_reset_listener_socket(di);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // Stream socket
hints.ai_flags = AI_NUMERICSERV | AI_PASSIVE; // Numeric port and wildcard IP address
hints.ai_protocol = IPPROTO_TCP; // Only TCP
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
sprintf(port_buf, "%d", di->conf_daemon_port);
s = getaddrinfo(di->conf_daemon_listen, port_buf, &hints, &result);
if (s)
{
di_printf(di, "[FAIL] Listen address '%s:%s' not resolvable: %s\n", di->conf_daemon_listen, port_buf, gai_strerror(s));
goto FailExit;
}
for(rp = result; rp; rp = rp->ai_next)
{
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1) continue;
if (!socket_reuse_addr_port(sfd))
{
di_printf(di, "[WARN] Trying to enable reuse of address and port failed: %s.\n", strerror(s));
}
if (is_v4_addr(rp->ai_addr, rp->ai_addrlen))
{
struct sockaddr_in *v4_addr = (struct sockaddr_in*)rp->ai_addr;
di_printf(di, "[INFO] Binding to resolved address '%s:%d'\n",
inet_ntoa(v4_addr->sin_addr),
ntohs(v4_addr->sin_port));
}
if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
{
di_printf(di, "[INFO] Bind to address '%s:%s' successful\n", di->conf_daemon_listen, port_buf);
break;
}
else if (is_v4_addr(rp->ai_addr, rp->ai_addrlen))
{
struct sockaddr_in *v4_addr = (struct sockaddr_in*)rp->ai_addr;
di_printf(di, "[WARN] Bind to resolved address '%s:%d' failed.\n",
inet_ntoa(v4_addr->sin_addr),
ntohs(v4_addr->sin_port));
}
close(sfd);
}
if (!rp)
{
di_printf(di, "[FAIL] None of the resolved address from '%s:%s' cannot be bound.\n", di->conf_daemon_listen, port_buf);
goto FailExit;
}
freeaddrinfo(result); result = NULL;
di->socket_listen = sfd;
if(listen(di->socket_listen, di->conf_daemon_backlog) < 0)
{
di_printf(di, "[FAIL] Listen to address '%s:%s' with backlog %d failed: %s.\n",
di->conf_daemon_listen, port_buf, di->conf_daemon_backlog, strerror(errno));
goto FailExit;
}
else
{
di_printf(di, "[INFO] Listening to address '%s:%s' with backlog %d\n", di->conf_daemon_listen, port_buf, di->conf_daemon_backlog);
}
di->client_count = di->conf_daemon_backlog;
di->clients = malloc(di->client_count * sizeof di->clients[0]);
if (!di->clients)
{
di_printf(di, "[FAIL] Prepare for incoming %d connections failed: %s.\n",
(int)di->client_count, strerror(errno));
goto FailExit;
}
memset(di->clients, 0, di->client_count * sizeof di->clients[0]);
for(i = 0; i < di->client_count; i++)
{
di->clients[i].socket_client = -1;
}
return 1;
FailExit:
di_reset_listener_socket(di);
if(result) freeaddrinfo(result);
return 0;
}
// Create the socket for listening from the clients
static int di_init_rcon_socket(daemon_inst_p di)
{
struct addrinfo hints;
struct addrinfo *result = NULL, *rp;
int s, sfd = -1;
char port_buf[8];
if(di->socket_to_rcon != -1)
{
close(di->socket_to_rcon);
di->socket_to_rcon = -1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // Stream socket
hints.ai_flags = AI_NUMERICSERV | AI_PASSIVE; // Numeric port and wildcard IP address
hints.ai_protocol = IPPROTO_TCP; // Only TCP
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
sprintf(port_buf, "%d", di->conf_rcon_port);
s = getaddrinfo(di->conf_rcon_host, port_buf, &hints, &result);
if (s)
{
di_printf(di, "[FAIL] RCON address '%s:%s' not resolvable: %s\n", di->conf_rcon_host, port_buf, gai_strerror(s));
goto FailExit;
}
for(rp = result; rp; rp = rp->ai_next)
{
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1) continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) == 0) break;
close(sfd);
}
if (!rp)
{
di_printf(di, "[FAIL] Connect to RCON host '%s:%s' failed\n", di->conf_rcon_host, port_buf);
goto FailExit;
}
freeaddrinfo(result); result = NULL;
di->socket_to_rcon = sfd;
return 1;
FailExit:
if(di->socket_to_rcon != -1)
{
close(di->socket_to_rcon);
di->socket_to_rcon = -1;
}
if(result) freeaddrinfo(result);
return 0;
}
static int di_send_rcon_packet(daemon_inst_p di, int request_id, int type, void *packet, size_t size, size_t *ret_send_len)
{
size_t send_len = RCON_HEADER_SIZE + size + 1;
char send_buf[SOCKET_BUFFER_SIZE];
rcon_packet_p packsend = (rcon_packet_p)&send_buf;
packsend->length = send_len - 4;
packsend->request_id = request_id;
packsend->type = type;
memcpy(packsend->payload, packet, size);
packsend->payload[size] = '\0';
*ret_send_len = send_len;
if (di->conf_log_rcon) di_printf(di, "[RCON] %s\n", packet);
return send(di->socket_to_rcon, send_buf, send_len, 0);
}
static int di_new_request_id(daemon_inst_p di)
{
size_t i;
di->cur_request_id ++;
for(;;)
{
int req_id_inuse = 0;
for(i = 0; i < di->client_count; i++)
{
daemon_client_p c = &di->clients[i];
if (c->socket_client == -1) continue;
if (c->request_id == di->cur_request_id)
{
di->cur_request_id ++;
req_id_inuse = 1;
break;
}
}
if (!req_id_inuse) return di->cur_request_id;
}
}
// Start authentication to the RCON server
static int di_rcon_auth(daemon_inst_p di)
{
char recv_buf[MAX_RCON_RESPONSE];
int nrecv;
rcon_packet_p packrecv = (rcon_packet_p)&recv_buf;
size_t send_len;
int req_id = di_new_request_id(di);
if(di_send_rcon_packet(di, req_id, 3, di->conf_rcon_auth, strlen(di->conf_rcon_auth), &send_len) != send_len)
{
di_printf(di, "[FAIL] Authentication to RCON host '%s:%d' by password '%s' failed: send()\n", di->conf_rcon_host, di->conf_rcon_port, di->conf_rcon_auth);
goto FailExit;
}
nrecv = recv(di->socket_to_rcon, recv_buf, sizeof recv_buf, 0);
if(!nrecv)
{
di_printf(di, "[FAIL] Authentication to RCON host '%s:%d' by password '%s' failed: Connection reset by the peer.\n", di->conf_rcon_host, di->conf_rcon_port, di->conf_rcon_auth);
goto FailExit;
}
if(nrecv < 0)
{
di_printf(di, "[FAIL] Authentication to RCON host '%s:%d' by password '%s' failed: %s\n", di->conf_rcon_host, di->conf_rcon_port, di->conf_rcon_auth, strerror(errno));
goto FailExit;
}
if(packrecv->request_id == req_id)
{
di_printf(di, "[AUTH] Authentication to RCON host '%s:%d' by password '%s' succeeded.\n", di->conf_rcon_host, di->conf_rcon_port, di->conf_rcon_auth);
}
else
{
di_printf(di, "[FAIL] Authentication to RCON host '%s:%d' by password '%s' failed: Wrong password\n", di->conf_rcon_host, di->conf_rcon_port, di->conf_rcon_auth);
goto FailExit;
}
return 1;
FailExit:
return 0;
}
// Run the daemon
int di_run(daemon_inst_p di)
{
fd_set readfds;
fd_set writefds;
struct timeval timeout;
size_t i;
int retval;
char recv_buf[SOCKET_BUFFER_SIZE];
char response_buf[SOCKET_BUFFER_SIZE * 2];
rcon_packet_p packrecv = (rcon_packet_p)response_buf;
size_t cb_to_recv = 0;
size_t cb_recv = 0;
int wait_interval = 0;
di->cur_request_id = (int)time(NULL);
do // while (di->daemonized)
{
if(!di_init_rcon_socket(di))
{
if(di->daemonized && !signal_exit_catch)
{
int wait_value;
if (wait_interval < 1)
wait_interval = 1;
else if (wait_interval < MAX_SERVER_WAIT_INTERVAL)
wait_interval <<= 1;
else
wait_interval = MAX_SERVER_WAIT_INTERVAL;
wait_value = rand() % wait_interval;
if (wait_value < 1) wait_value = 1;
sleep(wait_value);
continue;
}
else
{
return 0;
}
}
if(!di_rcon_auth(di)) return 0;
if(!di_init_listener_socket(di)) return 0;
wait_interval = 1;
while(!signal_exit_catch)
{
int maxfd = 0;
int rcon_ready_to_send = 0;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
// Add active client sockets to the select() file descriptors list
for(i = 0; i < di->client_count; i ++)
{
int sock = di->clients[i].socket_client;
if(sock != -1)
{
FD_SET(sock, &readfds);
FD_SET(sock, &writefds);
maxfd ++;
}
}
// Add the RCON server to the list
FD_SET(di->socket_to_rcon, &readfds);
FD_SET(di->socket_to_rcon, &writefds);
maxfd ++;
// Add the listener server to the list
if(maxfd < di->client_count)
{
FD_SET(di->socket_listen, &readfds);
maxfd ++;
}
// First, wait for any activity of the sockets.
retval = select(FD_SETSIZE, &readfds, &writefds, NULL, &timeout);
if(retval == -1)
{
di_printf(di, "[FAIL] select() failed: %s.\n", strerror(errno));
return 0;
}
// Receive responses from the RCON server
if (!cb_to_recv || cb_recv < cb_to_recv)
{
if (FD_ISSET(di->socket_to_rcon, &readfds))
{
retval = recv(di->socket_to_rcon, recv_buf, sizeof recv_buf, 0);
if (retval <= 0)
{
if (retval < 0)
{
di_printf(di, "[FAIL] Receive responses from the RCON server failed: %s.\n", strerror(errno));
}
else
{
// If too many of the requests had sent in a very short time, the server closes the connection.
di_printf(di, "[INFO] The RCON server closed the connection.\n");
}
goto OnRconReset;
}
if (retval + cb_recv > sizeof response_buf)
{
// This would hardly happen since 'response_buf' is twice big as 'recv_buf' and 'recv_buf' is 8kb and it's twice big as the maximum response payload size
di_printf(di, "[FAIL] The RCON server returned a packet with wrong size (%d) which was too big to fit the buffer.\n", (int)(retval + cb_recv));
goto OnRconReset;
}
memcpy(&response_buf[cb_recv], recv_buf, retval);
cb_recv += retval;
if (!cb_to_recv && cb_recv >= 4) cb_to_recv = packrecv->length + 4;
if (di->conf_debug) di_printf(di, "[DEBUG] RCON response received: packet size = %zu, received size = %zu\n", cb_to_recv, cb_recv);
}
}
// If a complete response had received, redirect it to the specific client
if(cb_to_recv && cb_recv >= cb_to_recv)
{
size_t cb_payload = cb_to_recv - RCON_HEADER_SIZE;
if (packrecv->type != 0)
{
di_printf(di, "[FAIL] The RCON server returned a packet with unknown type (%d).\n", packrecv->type);
goto OnRconReset;
}
// Redirect the packet to the client which have the same request id
for(i = 0; i < di->client_count; i++)
{
daemon_client_p c = &di->clients[i];
// Check if activity or not
if (c->socket_client == -1) continue;
// Check the request id
if (c->request_id != packrecv->request_id) continue;
// Check if it had redirected the response it already got
if (c->response_received && !c->response_sent) break;
memcpy(c->response, packrecv->payload, cb_payload);
c->response_received = 1;
c->response_sent = 0;
c->response_size = cb_payload;
if (di->conf_debug) di_printf(di, "[DEBUG] RCON response copied to %zu: %s\n", i, c->response);
break;
}
// Check if no client matches
if (i >= di->client_count)
{
if (di->conf_log_rcon) di_printf(di, "[RCON] (Not redirected to client) %s\n", packrecv->payload);
di_printf(di, "[INFO] The RCON server returned a packet with a request id (%d) which doesn't belongs to current clients.\n", packrecv->request_id);
}
cb_recv -= cb_to_recv;
if (cb_recv)
{
memmove(response_buf, &response_buf[cb_to_recv], cb_recv);
if (cb_recv >= 4)
{
cb_to_recv = packrecv->length + 4;
if (di->conf_debug) di_printf(di, "[DEBUG] Remaining %zu bytes of response with packet size %zu to redirect.\n", cb_recv, cb_to_recv);
}
else
{
cb_to_recv = 0;
if (di->conf_debug) di_printf(di, "[DEBUG] Remaining %zu bytes of response to redirect.\n", cb_recv);
}
}
else
{
cb_to_recv = 0;
}
}
if (FD_ISSET(di->socket_to_rcon, &writefds))
{
rcon_ready_to_send = 1;
}
for(i = 0; i < di->client_count; i++)
{
daemon_client_p c = &di->clients[i];
int sock = c->socket_client;
if (sock == -1) continue;
if (!c->buffer_to_receive || c->buffer_received < c->buffer_to_receive)
{
if (FD_ISSET(sock, &readfds))
{
retval = recv(sock, recv_buf, sizeof recv_buf, 0);
// Check if error occurs or the client closes the socket
if (retval <= 0)
{
if (retval < 0)
{
di_printf(di, "[WARN] Receive requests from client %zu failed: %s.\n", i, strerror(errno));
}
else
{
if (di->conf_debug) di_printf(di, "[DEBUG] The client %zu closed the connection.\n", i);
}
c->socket_client = -1;
close(sock);
continue;
}
// Copy the received data to the end of the buffer
if (c->buffer_received + retval <= sizeof c->buffer)
{
memcpy(&c->buffer[c->buffer_received], recv_buf, retval);
c->buffer_received += retval;
}
else
{
di_printf(di, "[WARN] The client %zu had sent too many data (%zu bytes) that could not fit the buffer (capacity of %zu bytes).\n",
i, c->buffer_received + retval, sizeof c->buffer);
c->socket_client = -1;
close(sock);
continue;
}
// The first 4 bytes is the length of client's packet length.
if(c->buffer_received >= 4)
{
uint32_t packet_size = *(uint32_t*)&c->buffer[0];
c->buffer_to_receive = packet_size + 4;
// Check the size, it shouldn't exceed MAX_RCON_REQUEST and shouldn't be zero
if (packet_size > MAX_RCON_REQUEST || !packet_size)
{
di_printf(di, "[WARN] Client %zu sent invalid size of request: '%zu' bytes\n",i , c->buffer_to_receive);
c->socket_client = -1;
close(sock);
continue;
}
if (di->conf_debug) di_printf(di, "[DEBUG] Receiving client request %zu of %zu bytes\n", c->buffer_received - 4, c->buffer_to_receive - 4);
}
}
}
// Send the request to RCON server if not sent
if (c->buffer_to_receive && c->buffer_received >= c->buffer_to_receive)
{
if (!c->buffer_sent)
{
if (rcon_ready_to_send)
{
size_t send_len;
retval = di_send_rcon_packet(di, c->request_id, 2, &c->buffer[4], c->buffer_received - 4, &send_len);
// Check if error occurs or the client closes the socket
if (retval <= 0)
{
if (retval < 0)
{
di_printf(di, "[FAIL] Send request to the RCON server failed: %s.\n", strerror(errno));
}
else
{
di_printf(di, "[INFO] The RCON server closed the connection.\n");
}
goto OnRconReset;
}
c->buffer_sent = 1;
if (di->conf_debug) di_printf(di, "[DEBUG] Position %zu, request sent\n", i);
}
}
else if (c->response_received)
{
if (!c->response_sent)
{
if (FD_ISSET(sock, &writefds))
{
// Send the response back to the client
if (di->conf_response_newline && c->response_size < sizeof c->response)
{
c->response[c->response_size++] = '\n';
}
retval = send(sock, c->response, c->response_size, 0);
// Check if error occurs or the client closes the socket
if (retval <= 0)
{
if (retval < 0)
{
di_printf(di, "[WARN] Sending response back to the client %zu failed: %s.\n", i, strerror(errno));
}
c->socket_client = -1;
close(sock);
continue;
}
if (di->conf_log_rcon) di_printf(di, "[RCON] %s\n", c->response);
if (c->response_size >= MAX_RCON_RESPONSE_PAYLOAD)
{
c->response_time = time(NULL);
c->response_sent = 1;
c->response_received = 0; // Process the fragmentation
if (di->conf_debug) di_printf(di, "[DEBUG] Waiting for further response of client %zu.\n", i);