Repository navigation
Expand file tree
/
Copy pathrustcmd.cpp
More file actions
1365 lines (1188 loc) · 45.4 KB
/
Copy pathrustcmd.cpp
File metadata and controls
1365 lines (1188 loc) · 45.4 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
/*
* rustcmd
*
* WebRCON tool for RustDedicated WebSocket interface
*
* Standalone C++17 WebRCON tool with no third-party dependencies.
* Runtime configuration is read from rustcmd-cpp.conf.
*
* BUILD:
*
* g++ -std=c++17 -O2 -Wall -Wextra -Wpedantic -o rustcmd rustcmd.cpp
*
* USER CONFIGURATION:
*
* mkdir -p ~/.config/rustcmd
* cp rustcmd-cpp.conf ~/.config/rustcmd/rustcmd-cpp.conf
* chmod 600 ~/.config/rustcmd/rustcmd-cpp.conf
*
* rustcmd first checks:
*
* $XDG_CONFIG_HOME/rustcmd/rustcmd-cpp.conf
*
* If XDG_CONFIG_HOME is not set, it checks:
*
* $HOME/.config/rustcmd/rustcmd-cpp.conf
*
* If no user configuration exists, it falls back to:
*
* /etc/rustcmd/rustcmd-cpp.conf
*
* EXAMPLE CONFIGURATION:
*
* RUST_RCON_IP=127.0.0.1
* RUST_RCON_PORT=28016
* RUST_RCON_PASSWORD=your-RCON-passwd
*
* RUST_SERVICE_UNIT=/etc/systemd/system/rustserver.service
*
* USAGE:
*
* rustcmd say "Hello World!"
* rustcmd status
*
* MIT License:
*
* Copyright 2026 Exaga - penthux.net
*
* 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 <array>
#include <cerrno>
#include <cctype>
#include <cstdint>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <fcntl.h>
#include <netdb.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
namespace fs = std::filesystem;
// Runtime configuration
struct RconConfig {
std::string ip;
std::string port;
std::string password;
std::string service_unit;
};
// Error details for verbose output
class DiagnosticError : public std::runtime_error {
public:
DiagnosticError(const std::string& message, const std::string& detail)
: std::runtime_error(message), detail_(detail) {}
const std::string& detail() const noexcept { return detail_; }
private:
std::string detail_;
};
static std::string errno_detail(int error_number)
{
return "[errno " + std::to_string(error_number) + "] " +
std::strerror(error_number);
}
static std::string trim(const std::string& value)
{
const auto first = value.find_first_not_of(" \t\r\n");
if (first == std::string::npos) {
return {};
}
const auto last = value.find_last_not_of(" \t\r\n");
return value.substr(first, last - first + 1);
}
// Configuration file lookup
static fs::path user_config_path()
{
if (const char* xdg = std::getenv("XDG_CONFIG_HOME"); xdg && *xdg) {
return fs::path(xdg) / "rustcmd" / "rustcmd-cpp.conf";
}
if (const char* home = std::getenv("HOME"); home && *home) {
return fs::path(home) / ".config" / "rustcmd" / "rustcmd-cpp.conf";
}
return {};
}
static fs::path find_config_path()
{
const fs::path user_path = user_config_path();
std::error_code ec;
if (!user_path.empty() && fs::is_regular_file(user_path, ec)) {
return user_path;
}
const fs::path system_path = "/etc/rustcmd/rustcmd-cpp.conf";
ec.clear();
if (fs::is_regular_file(system_path, ec)) {
return system_path;
}
if (!user_path.empty()) {
throw std::runtime_error(
"configuration file not found at " + user_path.string() +
" or /etc/rustcmd/rustcmd-cpp.conf");
}
throw std::runtime_error(
"configuration file not found at /etc/rustcmd/rustcmd-cpp.conf and no user "
"configuration directory could be determined");
}
static RconConfig read_config(const fs::path& path)
{
std::ifstream file(path);
if (!file.is_open()) {
throw std::runtime_error("unable to read configuration file: " +
path.string());
}
RconConfig config;
std::string line;
while (std::getline(file, line)) {
line = trim(line);
if (line.empty() || line.front() == '#') {
continue;
}
const auto separator = line.find('=');
if (separator == std::string::npos) {
continue;
}
const std::string key = trim(line.substr(0, separator));
const std::string value = trim(line.substr(separator + 1));
if (key == "RUST_RCON_IP") {
config.ip = value;
} else if (key == "RUST_RCON_PORT") {
config.port = value;
} else if (key == "RUST_RCON_PASSWORD") {
config.password = value;
} else if (key == "RUST_SERVICE_UNIT") {
config.service_unit = value;
}
}
if (file.bad()) {
throw std::runtime_error("error while reading configuration file: " +
path.string());
}
if (config.ip.empty()) {
throw std::runtime_error("RUST_RCON_IP not found in " + path.string());
}
if (config.port.empty()) {
throw std::runtime_error("RUST_RCON_PORT not found in " + path.string());
}
if (config.password.empty()) {
throw std::runtime_error("RUST_RCON_PASSWORD not found in " +
path.string());
}
return config;
}
// Program information and help output
static constexpr const char* VERSION = "1.3.8";
static constexpr const char* PROJECT_URL = "https://github.com/Exaga/rustcmd";
static void print_url()
{
std::cout << "rustcmd project (GitHub) URL: \n"
<< PROJECT_URL << '\n';
}
static void print_license()
{
std::cout
<< "MIT License\n\n"
<< "Copyright 2026 Exaga - penthux.net\n\n"
<< "Permission is hereby granted, free of charge, to any person obtaining a copy\n"
<< "of this software and associated documentation files (the \"Software\"), to deal\n"
<< "in the Software without restriction, including without limitation the rights\n"
<< "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"
<< "copies of the Software, and to permit persons to whom the Software is furnished\n"
<< "to do so, subject to the following conditions:\n\n"
<< "The above copyright notice and this permission notice shall be included in all\n"
<< "copies or substantial portions of the Software.\n\n"
<< "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
<< "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
<< "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
<< "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
<< "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
<< "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n"
<< "SOFTWARE.\n";
}
static void print_version()
{
std::cout << "rustcmd v" << VERSION << " [C++]\n"
<< "WebRCON command-line tool for (RustDedicated) WebSocket interface\n"
<< PROJECT_URL << '\n'
<< "(c) 2026 penthux.net\n\n";
}
static void print_help()
{
std::cout
<< "rustcmd v" << VERSION << " [C++]\n"
<< "WebRCON command-line tool for (RustDedicated) WebSocket interface\n\n"
<< "Usage:\n"
<< " rustcmd <command> [arguments]\n"
<< " rustcmd [options]\n\n"
<< "Examples:\n"
<< " rustcmd status\n"
<< " rustcmd status --verbose\n"
<< " rustcmd serverinfo\n"
<< " rustcmd say \"Hello World!\"\n"
<< " rustcmd server.save\n"
<< " rustcmd server start\n"
<< " rustcmd server stop\n"
<< " rustcmd server restart\n"
<< " rustcmd server status\n\n"
<< "Options:\n"
<< " -h, -?, --help Show this help\n"
<< " -v, --version Show version information\n"
<< " -U, --url Show official rustcmd project URL\n"
<< " -L, --license Show license information\n"
<< " -c, --config <file> Use an alternative configuration file\n"
<< " <command> --verbose Show detailed errors for the command\n\n";
}
// WebRCON JSON command payload
static std::string json_escape(const std::string& value)
{
static constexpr char hex[] = "0123456789abcdef";
std::string escaped;
escaped.reserve(value.size());
for (const unsigned char ch : value) {
switch (ch) {
case '\"': escaped += "\\\""; break;
case '\\': escaped += "\\\\"; break;
case '\b': escaped += "\\b"; break;
case '\f': escaped += "\\f"; break;
case '\n': escaped += "\\n"; break;
case '\r': escaped += "\\r"; break;
case '\t': escaped += "\\t"; break;
default:
if (ch < 0x20) {
escaped += "\\u00";
escaped += hex[(ch >> 4) & 0x0f];
escaped += hex[ch & 0x0f];
} else {
escaped += static_cast<char>(ch);
}
}
}
return escaped;
}
static std::string build_web_rcon_payload(const std::string& command)
{
return "{\"Identifier\":1,\"Message\":\"" + json_escape(command) +
"\",\"Name\":\"WebRCON\"}";
}
// SHA-1 hashing for the WebSocket handshake
static std::uint32_t rotate_left(std::uint32_t value, unsigned int bits)
{
return (value << bits) | (value >> (32U - bits));
}
[[maybe_unused]] static std::array<std::uint8_t, 20> sha1(const std::string& input)
{
std::vector<std::uint8_t> message(input.begin(), input.end());
const std::uint64_t bit_length = static_cast<std::uint64_t>(message.size()) * 8U;
message.push_back(0x80U);
while ((message.size() % 64U) != 56U) {
message.push_back(0x00U);
}
for (int shift = 56; shift >= 0; shift -= 8) {
message.push_back(static_cast<std::uint8_t>((bit_length >> shift) & 0xffU));
}
std::uint32_t h0 = 0x67452301U;
std::uint32_t h1 = 0xefcdab89U;
std::uint32_t h2 = 0x98badcfeU;
std::uint32_t h3 = 0x10325476U;
std::uint32_t h4 = 0xc3d2e1f0U;
for (std::size_t offset = 0; offset < message.size(); offset += 64U) {
std::array<std::uint32_t, 80> words{};
for (std::size_t i = 0; i < 16U; ++i) {
const std::size_t base = offset + (i * 4U);
words[i] = (static_cast<std::uint32_t>(message[base]) << 24U) |
(static_cast<std::uint32_t>(message[base + 1U]) << 16U) |
(static_cast<std::uint32_t>(message[base + 2U]) << 8U) |
static_cast<std::uint32_t>(message[base + 3U]);
}
for (std::size_t i = 16U; i < 80U; ++i) {
words[i] = rotate_left(words[i - 3U] ^ words[i - 8U] ^
words[i - 14U] ^ words[i - 16U], 1U);
}
std::uint32_t a = h0;
std::uint32_t b = h1;
std::uint32_t c = h2;
std::uint32_t d = h3;
std::uint32_t e = h4;
for (std::size_t i = 0; i < 80U; ++i) {
std::uint32_t f = 0;
std::uint32_t k = 0;
if (i < 20U) {
f = (b & c) | ((~b) & d);
k = 0x5a827999U;
} else if (i < 40U) {
f = b ^ c ^ d;
k = 0x6ed9eba1U;
} else if (i < 60U) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdcU;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6U;
}
const std::uint32_t temp = rotate_left(a, 5U) + f + e + k + words[i];
e = d;
d = c;
c = rotate_left(b, 30U);
b = a;
a = temp;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
}
std::array<std::uint8_t, 20> digest{};
const std::array<std::uint32_t, 5> hash = {h0, h1, h2, h3, h4};
for (std::size_t i = 0; i < hash.size(); ++i) {
digest[(i * 4U)] = static_cast<std::uint8_t>((hash[i] >> 24U) & 0xffU);
digest[(i * 4U) + 1U] = static_cast<std::uint8_t>((hash[i] >> 16U) & 0xffU);
digest[(i * 4U) + 2U] = static_cast<std::uint8_t>((hash[i] >> 8U) & 0xffU);
digest[(i * 4U) + 3U] = static_cast<std::uint8_t>(hash[i] & 0xffU);
}
return digest;
}
// Base64 encoding for the WebSocket handshake
[[maybe_unused]] static std::string base64_encode(const std::uint8_t* data,
std::size_t length)
{
static constexpr char alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string output;
output.reserve(((length + 2U) / 3U) * 4U);
for (std::size_t i = 0; i < length; i += 3U) {
const std::uint32_t octet_a = data[i];
const std::uint32_t octet_b = (i + 1U < length) ? data[i + 1U] : 0U;
const std::uint32_t octet_c = (i + 2U < length) ? data[i + 2U] : 0U;
const std::uint32_t triple = (octet_a << 16U) | (octet_b << 8U) | octet_c;
output.push_back(alphabet[(triple >> 18U) & 0x3fU]);
output.push_back(alphabet[(triple >> 12U) & 0x3fU]);
output.push_back((i + 1U < length) ? alphabet[(triple >> 6U) & 0x3fU] : '=');
output.push_back((i + 2U < length) ? alphabet[triple & 0x3fU] : '=');
}
return output;
}
[[maybe_unused]] static std::string websocket_accept_key(const std::string& client_key)
{
static constexpr char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const auto digest = sha1(client_key + websocket_guid);
return base64_encode(digest.data(), digest.size());
}
// TCP connection to the RCON server
static int connect_tcp(const std::string& host, const std::string& port)
{
static constexpr int connect_timeout_ms = 5000;
static constexpr long io_timeout_seconds = 5;
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo* addresses = nullptr;
const int lookup_result = getaddrinfo(host.c_str(), port.c_str(), &hints, &addresses);
if (lookup_result != 0) {
throw DiagnosticError(
"Connection failed: Unable to resolve RCON address.",
"[getaddrinfo " + std::to_string(lookup_result) + "] " +
gai_strerror(lookup_result));
}
int connected_socket = -1;
bool timed_out = false;
bool refused = false;
int last_socket_error = 0;
for (addrinfo* address = addresses; address != nullptr; address = address->ai_next) {
const int socket_fd = socket(address->ai_family, address->ai_socktype,
address->ai_protocol);
if (socket_fd < 0) {
last_socket_error = errno;
continue;
}
const int original_flags = fcntl(socket_fd, F_GETFL, 0);
if (original_flags < 0 ||
fcntl(socket_fd, F_SETFL, original_flags | O_NONBLOCK) < 0) {
close(socket_fd);
continue;
}
int result = connect(socket_fd, address->ai_addr, address->ai_addrlen);
if (result < 0 && errno == EINPROGRESS) {
pollfd descriptor{};
descriptor.fd = socket_fd;
descriptor.events = POLLOUT;
do {
result = poll(&descriptor, 1, connect_timeout_ms);
} while (result < 0 && errno == EINTR);
if (result == 0) {
timed_out = true;
last_socket_error = ETIMEDOUT;
close(socket_fd);
continue;
}
if (result < 0) {
last_socket_error = errno;
close(socket_fd);
continue;
}
int socket_error = 0;
socklen_t error_length = sizeof(socket_error);
if (getsockopt(socket_fd, SOL_SOCKET, SO_ERROR,
&socket_error, &error_length) < 0) {
last_socket_error = errno;
close(socket_fd);
continue;
}
if (socket_error != 0) {
last_socket_error = socket_error;
if (socket_error == ECONNREFUSED) {
refused = true;
} else if (socket_error == ETIMEDOUT) {
timed_out = true;
}
close(socket_fd);
continue;
}
} else if (result < 0) {
last_socket_error = errno;
if (errno == ECONNREFUSED) {
refused = true;
} else if (errno == ETIMEDOUT) {
timed_out = true;
}
close(socket_fd);
continue;
}
if (fcntl(socket_fd, F_SETFL, original_flags) < 0) {
close(socket_fd);
continue;
}
const timeval io_timeout{io_timeout_seconds, 0};
if (setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO,
&io_timeout, sizeof(io_timeout)) < 0 ||
setsockopt(socket_fd, SOL_SOCKET, SO_SNDTIMEO,
&io_timeout, sizeof(io_timeout)) < 0) {
close(socket_fd);
continue;
}
connected_socket = socket_fd;
break;
}
freeaddrinfo(addresses);
if (connected_socket >= 0) {
return connected_socket;
}
if (timed_out) {
const int detail_error = last_socket_error != 0 ? last_socket_error : ETIMEDOUT;
throw DiagnosticError(
"Connection failed: RCON server timed out or is unreachable.",
errno_detail(detail_error));
}
if (refused) {
const int detail_error = last_socket_error != 0 ? last_socket_error : ECONNREFUSED;
throw DiagnosticError(
"Connection failed: Server is offline or RCON IP/port is misconfigured.",
errno_detail(detail_error));
}
if (last_socket_error != 0) {
throw DiagnosticError(
"Connection failed: Unable to connect to RCON server.",
errno_detail(last_socket_error));
}
throw std::runtime_error("Connection failed: Unable to connect to RCON server.");
}
// WebSocket handshake key
static std::string generate_websocket_key()
{
std::array<std::uint8_t, 16> random_bytes{};
std::ifstream random_source("/dev/urandom", std::ios::in | std::ios::binary);
if (!random_source.read(reinterpret_cast<char*>(random_bytes.data()),
static_cast<std::streamsize>(random_bytes.size()))) {
throw std::runtime_error("WebSocket handshake failed: unable to generate handshake key.");
}
return base64_encode(random_bytes.data(), random_bytes.size());
}
// Send the complete HTTP Upgrade request
static void send_all(int socket_fd, const std::string& data)
{
std::size_t sent = 0;
while (sent < data.size()) {
const ssize_t result = send(socket_fd, data.data() + sent,
data.size() - sent, 0);
if (result > 0) {
sent += static_cast<std::size_t>(result);
continue;
}
if (result < 0 && errno == EINTR) {
continue;
}
if (result < 0 && (errno == EAGAIN || errno == EWOULDBLOCK ||
errno == ETIMEDOUT)) {
throw std::runtime_error("WebSocket handshake failed: server timed out.");
}
throw std::runtime_error("WebSocket handshake failed: unable to send upgrade request.");
}
}
// HTTP Upgrade response and any WebSocket data already received
struct HttpUpgradeResponse {
std::string headers;
std::vector<std::uint8_t> leftover;
};
static HttpUpgradeResponse receive_http_headers(int socket_fd)
{
static constexpr std::size_t max_header_size = 16384;
std::string response;
std::array<char, 2048> buffer{};
while (response.find("\r\n\r\n") == std::string::npos) {
const ssize_t result = recv(socket_fd, buffer.data(), buffer.size(), 0);
if (result > 0) {
response.append(buffer.data(), static_cast<std::size_t>(result));
if (response.size() > max_header_size) {
throw std::runtime_error("WebSocket handshake failed: response headers are too large.");
}
continue;
}
if (result == 0) {
throw std::runtime_error("WebSocket handshake failed: server closed the connection.");
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ETIMEDOUT) {
throw std::runtime_error("WebSocket handshake failed: server timed out.");
}
throw std::runtime_error("WebSocket handshake failed: unable to read upgrade response.");
}
const std::size_t header_end = response.find("\r\n\r\n") + 4U;
HttpUpgradeResponse result;
result.headers = response.substr(0, header_end);
result.leftover.assign(response.begin() + static_cast<std::ptrdiff_t>(header_end),
response.end());
return result;
}
static std::string lowercase(std::string value)
{
for (char& ch : value) {
ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
return value;
}
// WebSocket HTTP Upgrade handshake
static std::vector<std::uint8_t> websocket_handshake(int socket_fd, const RconConfig& config)
{
const std::string client_key = generate_websocket_key();
const std::string expected_accept = websocket_accept_key(client_key);
std::ostringstream request;
request << "GET /" << config.password << " HTTP/1.1\r\n"
<< "Host: " << config.ip << ':' << config.port << "\r\n"
<< "Upgrade: websocket\r\n"
<< "Connection: Upgrade\r\n"
<< "Sec-WebSocket-Key: " << client_key << "\r\n"
<< "Sec-WebSocket-Version: 13\r\n\r\n";
send_all(socket_fd, request.str());
const HttpUpgradeResponse response = receive_http_headers(socket_fd);
std::istringstream stream(response.headers);
std::string status_line;
if (!std::getline(stream, status_line)) {
throw std::runtime_error("WebSocket handshake failed: invalid HTTP response.");
}
if (!status_line.empty() && status_line.back() == '\r') {
status_line.pop_back();
}
std::istringstream status_stream(status_line);
std::string http_version;
int status_code = 0;
status_stream >> http_version >> status_code;
if (http_version.rfind("HTTP/", 0) != 0 || status_code != 101) {
throw std::runtime_error("WebSocket handshake failed: RCON endpoint rejected the upgrade.");
}
bool upgrade_ok = false;
bool connection_ok = false;
bool accept_ok = false;
std::string line;
while (std::getline(stream, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (line.empty()) {
break;
}
const auto colon = line.find(':');
if (colon == std::string::npos) {
continue;
}
const std::string name = lowercase(trim(line.substr(0, colon)));
const std::string value = trim(line.substr(colon + 1U));
const std::string lower_value = lowercase(value);
if (name == "upgrade" && lower_value == "websocket") {
upgrade_ok = true;
} else if (name == "connection") {
std::istringstream tokens(lower_value);
std::string token;
while (std::getline(tokens, token, ',')) {
if (trim(token) == "upgrade") {
connection_ok = true;
break;
}
}
} else if (name == "sec-websocket-accept" && value == expected_accept) {
accept_ok = true;
}
}
if (!upgrade_ok || !connection_ok || !accept_ok) {
throw std::runtime_error("WebSocket handshake failed: invalid upgrade response.");
}
return response.leftover;
}
// Send a masked WebSocket text frame
static void send_websocket_text_frame(int socket_fd, const std::string& payload)
{
std::array<std::uint8_t, 4> mask{};
std::ifstream random_source("/dev/urandom", std::ios::in | std::ios::binary);
if (!random_source.read(reinterpret_cast<char*>(mask.data()),
static_cast<std::streamsize>(mask.size()))) {
throw std::runtime_error("WebSocket send failed: unable to generate masking key.");
}
std::vector<std::uint8_t> frame;
frame.reserve(payload.size() + 14U);
// FIN=1, opcode=0x1 (text frame).
frame.push_back(0x81U);
const std::uint64_t payload_length = static_cast<std::uint64_t>(payload.size());
if (payload_length <= 125U) {
frame.push_back(static_cast<std::uint8_t>(0x80U | payload_length));
} else if (payload_length <= 65535U) {
frame.push_back(0x80U | 126U);
frame.push_back(static_cast<std::uint8_t>((payload_length >> 8U) & 0xffU));
frame.push_back(static_cast<std::uint8_t>(payload_length & 0xffU));
} else {
frame.push_back(0x80U | 127U);
for (int shift = 56; shift >= 0; shift -= 8) {
frame.push_back(static_cast<std::uint8_t>((payload_length >> shift) & 0xffU));
}
}
frame.insert(frame.end(), mask.begin(), mask.end());
for (std::size_t i = 0; i < payload.size(); ++i) {
frame.push_back(static_cast<std::uint8_t>(payload[i]) ^ mask[i % mask.size()]);
}
std::size_t sent = 0;
while (sent < frame.size()) {
const ssize_t result = send(socket_fd, frame.data() + sent,
frame.size() - sent, 0);
if (result > 0) {
sent += static_cast<std::size_t>(result);
continue;
}
if (result < 0 && errno == EINTR) {
continue;
}
if (result < 0 && (errno == EAGAIN || errno == EWOULDBLOCK ||
errno == ETIMEDOUT)) {
throw std::runtime_error("WebSocket send failed: server timed out.");
}
throw std::runtime_error("WebSocket send failed: unable to send command frame.");
}
}
// Read enough socket data to complete a WebSocket frame
static void receive_exact(int socket_fd, std::vector<std::uint8_t>& buffer,
std::size_t required)
{
std::array<std::uint8_t, 4096> chunk{};
while (buffer.size() < required) {
const ssize_t result = recv(socket_fd, chunk.data(), chunk.size(), 0);
if (result > 0) {
buffer.insert(buffer.end(), chunk.begin(),
chunk.begin() + static_cast<std::ptrdiff_t>(result));
continue;
}
if (result == 0) {
throw std::runtime_error("WebSocket receive failed: server closed the connection.");
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ETIMEDOUT) {
throw std::runtime_error("WebSocket receive failed: server timed out.");
}
throw std::runtime_error("WebSocket receive failed: unable to read response frame.");
}
}
// Decoded WebSocket frame
struct WebSocketFrame {
std::uint8_t opcode = 0U;
std::vector<std::uint8_t> payload;
};
// Receive and decode a WebSocket frame
static WebSocketFrame receive_websocket_frame(int socket_fd,
std::vector<std::uint8_t>& buffer)
{
receive_exact(socket_fd, buffer, 2U);
const std::uint8_t first = buffer[0];
const std::uint8_t second = buffer[1];
const bool final_frame = (first & 0x80U) != 0U;
const std::uint8_t opcode = first & 0x0fU;
const bool masked = (second & 0x80U) != 0U;
if (!final_frame || masked || (first & 0x70U) != 0U) {
throw std::runtime_error("WebSocket receive failed: unsupported response frame.");
}
std::uint64_t payload_length = second & 0x7fU;
std::size_t header_length = 2U;
if (payload_length == 126U) {
receive_exact(socket_fd, buffer, 4U);
payload_length = (static_cast<std::uint64_t>(buffer[2]) << 8U) |
static_cast<std::uint64_t>(buffer[3]);
header_length = 4U;
} else if (payload_length == 127U) {
receive_exact(socket_fd, buffer, 10U);
payload_length = 0U;
for (std::size_t i = 2U; i < 10U; ++i) {
payload_length = (payload_length << 8U) | buffer[i];
}
header_length = 10U;
}
const bool control_frame = opcode >= 0x08U;
if (control_frame && payload_length > 125U) {
throw std::runtime_error("WebSocket receive failed: invalid control frame.");
}
static constexpr std::uint64_t max_response_size = 16U * 1024U * 1024U;
if (payload_length > max_response_size) {
throw std::runtime_error("WebSocket receive failed: response is too large.");
}
const std::size_t total_length = header_length + static_cast<std::size_t>(payload_length);
receive_exact(socket_fd, buffer, total_length);
WebSocketFrame frame;
frame.opcode = opcode;
frame.payload.assign(buffer.begin() + static_cast<std::ptrdiff_t>(header_length),
buffer.begin() + static_cast<std::ptrdiff_t>(total_length));
buffer.erase(buffer.begin(), buffer.begin() + static_cast<std::ptrdiff_t>(total_length));
return frame;
}
// Send a masked WebSocket control frame
static void send_websocket_control_frame(int socket_fd, std::uint8_t opcode,
const std::vector<std::uint8_t>& payload)
{
if (payload.size() > 125U) {
throw std::runtime_error("WebSocket send failed: control payload is too large.");
}
std::array<std::uint8_t, 4> mask{};
std::ifstream random_source("/dev/urandom", std::ios::in | std::ios::binary);
if (!random_source.read(reinterpret_cast<char*>(mask.data()),
static_cast<std::streamsize>(mask.size()))) {
throw std::runtime_error("WebSocket send failed: unable to generate masking key.");
}
std::vector<std::uint8_t> frame;
frame.reserve(payload.size() + 6U);
frame.push_back(static_cast<std::uint8_t>(0x80U | opcode));
frame.push_back(static_cast<std::uint8_t>(0x80U | payload.size()));
frame.insert(frame.end(), mask.begin(), mask.end());
for (std::size_t i = 0; i < payload.size(); ++i) {
frame.push_back(payload[i] ^ mask[i % mask.size()]);
}
std::size_t sent = 0U;
while (sent < frame.size()) {
const ssize_t result = send(socket_fd, frame.data() + sent, frame.size() - sent, 0);
if (result > 0) {
sent += static_cast<std::size_t>(result);
continue;
}
if (result < 0 && errno == EINTR) continue;
if (result < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == ETIMEDOUT)) {
throw std::runtime_error("WebSocket send failed: server timed out.");
}
throw std::runtime_error("WebSocket send failed: unable to send control frame.");
}
}
// Wait for the WebRCON text response and handle control frames
static std::string receive_websocket_text_frame(int socket_fd,
std::vector<std::uint8_t>& buffer)
{
for (;;) {
WebSocketFrame frame = receive_websocket_frame(socket_fd, buffer);
if (frame.opcode == 0x01U) {
return std::string(frame.payload.begin(), frame.payload.end());
}
if (frame.opcode == 0x09U) {
send_websocket_control_frame(socket_fd, 0x0aU, frame.payload);
continue;
}
if (frame.opcode == 0x0aU) {
continue;
}
if (frame.opcode == 0x08U) {
send_websocket_control_frame(socket_fd, 0x08U, frame.payload);
throw std::runtime_error("WebSocket receive failed: server closed before sending a response.");
}
throw std::runtime_error("WebSocket receive failed: unsupported response frame.");
}
}
// Close the WebSocket without delaying command completion
static void close_websocket(int socket_fd, std::vector<std::uint8_t>& buffer)
{
send_websocket_control_frame(socket_fd, 0x08U, {});
const int flags = fcntl(socket_fd, F_GETFL, 0);
if (flags >= 0) {
(void)fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);
}
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(1);
for (;;) {
try {
if (buffer.size() >= 2U) {
WebSocketFrame frame = receive_websocket_frame(socket_fd, buffer);
if (frame.opcode == 0x08U) return;
if (frame.opcode == 0x09U) {
send_websocket_control_frame(socket_fd, 0x0aU, frame.payload);
}
continue;
}
} catch (...) {
return;
}
const auto now = std::chrono::steady_clock::now();
if (now >= deadline) return;
const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
pollfd descriptor{};
descriptor.fd = socket_fd;
descriptor.events = POLLIN;
int result;
do {
result = poll(&descriptor, 1, static_cast<int>(remaining.count()));
} while (result < 0 && errno == EINTR && std::chrono::steady_clock::now() < deadline);
if (result <= 0) return;