-
-
Notifications
You must be signed in to change notification settings - Fork 517
/
stdinreader.cpp
1202 lines (1120 loc) · 30.9 KB
/
stdinreader.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
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
/*
This file is part of Warzone 2100.
Copyright (C) 2020-2021 Warzone 2100 Project
Warzone 2100 is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Warzone 2100 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "stdinreader.h"
#include "lib/framework/wzglobal.h" // required for config.h
#include "lib/framework/wzapp.h"
#include "lib/netplay/netplay.h"
#include "multiint.h"
#include "multistat.h"
#include "multilobbycommands.h"
#include "clparse.h"
#include <string>
#include <atomic>
#include <functional>
#include <memory>
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wcast-align"
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
#endif
#include <3rdparty/readerwriterqueue/readerwriterqueue.h>
#if defined(__clang__)
# pragma clang diagnostic pop
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
typedef std::vector<char> CmdInterfaceMessageBuffer;
static std::unique_ptr<moodycamel::BlockingReaderWriterQueue<CmdInterfaceMessageBuffer>> cmdInterfaceOutputQueue;
static CmdInterfaceMessageBuffer latestWriteBuffer;
constexpr size_t maxReserveMessageBufferSize = 2048;
#if defined(WZ_OS_UNIX)
# include <fcntl.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <sys/un.h>
# include <sys/param.h>
#endif
#if defined(HAVE_POLL_H)
# include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
# include <sys/poll.h>
#endif
#if (defined(HAVE_POLL_H) || defined(HAVE_SYS_POLL_H)) && !defined(__APPLE__) // Do not use poll on macOS - ref: https://daniel.haxx.se/blog/2016/10/11/poll-on-mac-10-12-is-broken/
# define HAVE_WORKING_POLL
#endif
#if defined(HAVE_SYS_EVENTFD_H)
# include <sys/eventfd.h>
#elif defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#define strncmpl(a, b) strncmp(a, b, strlen(b))
#define errlog(...) do { fprintf(stderr, __VA_ARGS__); fflush(stderr); } while(0);
#define wz_command_interface_output_onmainthread(...) \
wzAsyncExecOnMainThread([]{ \
wz_command_interface_output(__VA_ARGS__); \
});
static WZ_Command_Interface wz_cmd_interface = WZ_Command_Interface::None;
static std::string wz_cmd_interface_param;
WZ_Command_Interface wz_command_interface()
{
return wz_cmd_interface;
}
static WZ_THREAD *cmdInputThread = nullptr;
static WZ_THREAD *cmdOutputThread = nullptr;
static std::atomic<bool> cmdInputThreadQuit;
static std::atomic<bool> cmdOutputThreadQuit;
int readFd = -1;
bool readFdIsSocket = false;
int writeFd = -1;
bool writeFdIsNonBlocking = false;
std::function<void()> cleanupIOFunc;
#if defined(HAVE_SYS_EVENTFD_H)
int quitSignalEventFd = -1;
#elif defined(HAVE_UNISTD_H)
int quitSignalPipeFds[2] = {-1, -1};
#endif
#if !defined(_WIN32) && (defined(HAVE_SYS_EVENTFD_H) || defined(HAVE_UNISTD_H))
# define WZ_STDIN_READER_SUPPORTED
#endif
#if defined(WZ_STDIN_READER_SUPPORTED)
static std::vector<char> stdInReadBuffer;
constexpr size_t readChunkSize = 1024;
static size_t newlineSearchStart = 0;
static size_t actualAvailableBytes = 0;
enum class CmdIOReadyStatus
{
Error,
NotReady,
ReadyRead,
ReadyWrite,
Exit,
};
static CmdIOReadyStatus cmdIOIsReady(optional<int> inputFd, optional<int> outputFd, int quitSignalFd, int msTimeout = 2000)
{
#if defined(_WIN32)
# error "Not supported on Windows"
#endif
#if defined(HAVE_WORKING_POLL)
struct pollfd pfds[3];
nfds_t nfds = 0;
optional<size_t> readIdx;
optional<size_t> writeIdx;
optional<size_t> quitIdx;
if (inputFd.has_value())
{
pfds[nfds].fd = inputFd.value();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
readIdx = nfds;
nfds++;
}
if (outputFd.has_value())
{
pfds[nfds].fd = outputFd.value();
pfds[nfds].events = POLLOUT;
pfds[nfds].revents = 0;
writeIdx = nfds;
nfds++;
}
if (quitSignalFd >= 0)
{
pfds[nfds].fd = quitSignalFd;
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
quitIdx = nfds;
nfds++;
}
int timeoutValue = (quitSignalFd >= 0) ? -1 : msTimeout;
int retval = poll(pfds, nfds, timeoutValue);
if (retval < 0)
{
return CmdIOReadyStatus::Error;
}
if (retval > 0)
{
if (quitIdx.has_value())
{
if (pfds[quitIdx.value()].revents & POLLIN)
{
return CmdIOReadyStatus::Exit;
}
}
if (readIdx.has_value())
{
if (pfds[readIdx.value()].revents & POLLIN)
{
return CmdIOReadyStatus::ReadyRead;
}
}
if (writeIdx.has_value())
{
if (pfds[writeIdx.value()].revents & POLLOUT)
{
return CmdIOReadyStatus::ReadyWrite;
}
}
}
#else
fd_set readset;
fd_set writeset;
FD_ZERO(&readset);
FD_ZERO(&writeset);
if (inputFd.has_value())
{
FD_SET(inputFd.value(), &readset);
}
if (outputFd.has_value())
{
FD_SET(outputFd.value(), &writeset);
}
if (quitSignalFd >= 0)
{
FD_SET(quitSignalFd, &readset);
}
int maxFd = std::max<int>({inputFd.value_or(-1), outputFd.value_or(-1), quitSignalFd});
struct timeval tv;
tv.tv_sec = msTimeout / 1000;
tv.tv_usec = (msTimeout % 1000) * 1000;
int retval = select(maxFd+1, &readset, (outputFd.has_value()) ? &writeset : NULL, NULL, (quitSignalFd >= 0) ? NULL : &tv);
if (retval == -1)
{
return CmdIOReadyStatus::Error;
}
if (retval > 0 && quitSignalFd >= 0 && FD_ISSET(quitSignalFd, &readset))
{
return CmdIOReadyStatus::Exit;
}
if (inputFd.has_value())
{
if (retval > 0 && FD_ISSET(inputFd.value(), &readset))
{
return CmdIOReadyStatus::ReadyRead;
}
}
if (outputFd.has_value())
{
if (retval > 0 && FD_ISSET(outputFd.value(), &writeset))
{
return CmdIOReadyStatus::ReadyWrite;
}
}
#endif
return CmdIOReadyStatus::NotReady;
}
optional<std::string> getNextLineFromBuffer()
{
for (size_t idx = newlineSearchStart; idx < actualAvailableBytes; ++idx)
{
if (stdInReadBuffer[idx] == '\n')
{
std::string nextLine(stdInReadBuffer.data(), idx);
std::vector<decltype(stdInReadBuffer)::value_type>(stdInReadBuffer.begin()+(idx+1), stdInReadBuffer.end()).swap(stdInReadBuffer);
newlineSearchStart = 0;
actualAvailableBytes -= (idx + 1);
return nextLine;
}
}
newlineSearchStart = actualAvailableBytes;
return nullopt;
}
// Returns true if read was successful, sets nextLine to the next available line (if any)
// Returns false if there was an unrecoverable error reading (such as a socket peer closing the socket), and no more reads should be attempted
bool getInputLine(int fd, bool isSocketFd, optional<std::string> &nextLine)
{
// read more data from STDIN
stdInReadBuffer.resize((((stdInReadBuffer.size() + readChunkSize - 1) / readChunkSize) + 1) * readChunkSize);
ssize_t bytesRead = -1;
if (!isSocketFd)
{
bytesRead = read(fd, stdInReadBuffer.data() + actualAvailableBytes, readChunkSize);
}
else
{
do {
bytesRead = recv(fd, stdInReadBuffer.data() + actualAvailableBytes, readChunkSize, 0);
} while (bytesRead == -1 && errno == EINTR);
if (bytesRead == 0)
{
// stream socket peers will cause a return of "0" when there is an orderly shutdown
return false;
}
}
if (bytesRead < 0)
{
int errno_cpy = errno;
errlog("Failed to read/recv with errno: %d\n", errno_cpy);
return false;
}
if (bytesRead == 0)
{
return true;
}
actualAvailableBytes += static_cast<size_t>(bytesRead);
nextLine = getNextLineFromBuffer();
return true;
}
static void convertEscapedNewlines(std::string& input)
{
// convert \\n -> \n
size_t index = input.find("\\n");
while (index != std::string::npos)
{
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 12
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wrestrict"
#endif
input.replace(index, 2, "\n");
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 12
#pragma GCC diagnostic pop
#endif
index = input.find("\\n", index + 1);
}
}
int cmdOutputThreadFunc(void *)
{
if (!cmdInterfaceOutputQueue)
{
errlog("WZCMD FAILURE: No output queue?\n");
return 1;
}
int quitSignalFd = -1;
#if defined(HAVE_SYS_EVENTFD_H)
quitSignalFd = quitSignalEventFd;
#elif defined(HAVE_UNISTD_H)
quitSignalFd = quitSignalPipeFds[0];
#endif
#if defined(MSG_NOSIGNAL) && !defined(__APPLE__)
int writeFlags = MSG_NOSIGNAL;
#else
int writeFlags = 0;
#endif
// Returns true if it wrote, false if it didn't (and the caller should wait until writing is possible)
// Returns nullopt if an unrecoverable error occurred
auto tryWrite = [](int writeFd, const CmdInterfaceMessageBuffer& msg, int writeFlags) -> optional<bool> {
// Attempt to write
ssize_t outputBytes = -1;
do {
outputBytes = send(writeFd, msg.data(), msg.size(), writeFlags);
} while (outputBytes == -1 && errno == EINTR);
if (outputBytes == -1)
{
switch (errno)
{
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
// Must wait to be ready to write
return false;
case EPIPE:
// Other end died / closed connection
errlog("WZCMD NOTICE: Other end closed connection\n");
return nullopt;
default:
// Unrecoverable
errlog("WZCMD FAILURE: Unrecoverable error trying to send data\n");
return nullopt;
}
}
else
{
// wrote it
return true;
}
};
CmdInterfaceMessageBuffer msg;
while (true)
{
if (!cmdInterfaceOutputQueue->wait_dequeue_timed(msg, std::chrono::milliseconds(2000)))
{
// no messages to write - check if signaled to quit
auto result = cmdIOIsReady(nullopt, writeFd, quitSignalFd);
if (result == CmdIOReadyStatus::Exit)
{
// quit thread
return 0;
}
else if (result == CmdIOReadyStatus::NotReady)
{
if (cmdOutputThreadQuit.load())
{
// quit thread
return 0;
}
}
// loop and check for a msg again
continue;
}
// Have a message to write
if (writeFdIsNonBlocking)
{
// Attempt to write
auto writeResult = tryWrite(writeFd, msg, writeFlags);
if (!writeResult.has_value())
{
// unrecoverable error
return 1;
}
if (writeResult.value())
{
// write succeeded - continue
continue;
}
else
{
// write failed - need to wait to be ready to write
// fall-through
}
}
bool successfullyWroteMsg = false;
do {
// Wait to be ready to write
auto result = cmdIOIsReady(nullopt, writeFd, quitSignalFd);
if (result == CmdIOReadyStatus::Exit)
{
// quit thread
return 0;
}
else if (result == CmdIOReadyStatus::NotReady)
{
if (cmdOutputThreadQuit.load())
{
// quit thread
return 0;
}
}
else if (result == CmdIOReadyStatus::ReadyWrite)
{
// Attempt to write
// Can still fail, so need to handle if it does
auto writeResult = tryWrite(writeFd, msg, writeFlags);
if (!writeResult.has_value())
{
// unrecoverable error
return 1;
}
if (writeResult.value())
{
// write succeeded
successfullyWroteMsg = true;
}
else
{
// write failed - need to wait to be ready to write
// loop again
continue;
}
}
else
{
return 1;
}
} while (!successfullyWroteMsg);
}
return 0;
}
int cmdInputThreadFunc(void *)
{
fseek(stdin, 0, SEEK_END);
wz_command_interface_output_onmainthread("WZCMD: stdinReadReady\n");
bool inexit = false;
int quitSignalFd = -1;
#if defined(HAVE_SYS_EVENTFD_H)
quitSignalFd = quitSignalEventFd;
#elif defined(HAVE_UNISTD_H)
quitSignalFd = quitSignalPipeFds[0];
#endif
while (!inexit)
{
optional<std::string> nextLine = getNextLineFromBuffer();
while (!nextLine.has_value())
{
auto result = cmdIOIsReady(readFd, nullopt, quitSignalFd);
if (result == CmdIOReadyStatus::Exit)
{
// quit thread
return 0;
}
else if (result == CmdIOReadyStatus::NotReady)
{
if (cmdInputThreadQuit.load())
{
// quit thread
return 0;
}
}
else if (result == CmdIOReadyStatus::ReadyRead)
{
if (!getInputLine(readFd, readFdIsSocket, nextLine))
{
errlog("WZCMD FAILURE: get input line failed! (did peer close the connection?)\n");
return 1;
}
break;
}
else
{
errlog("WZCMD FAILURE: getline failed!\n");
return 1;
}
}
if (!nextLine.has_value())
{
// continue & wait until we read a full line
continue;
}
const char *line = nextLine.value().c_str();
if(!strncmpl(line, "exit"))
{
wz_command_interface_output_onmainthread("WZCMD info: exit command received - stdin reader will now stop procesing commands\n");
inexit = true;
}
else if(!strncmpl(line, "admin add-hash "))
{
char newadmin[1024] = {0};
int r = sscanf(line, "admin add-hash %1023[^\n]s", newadmin);
if (r != 1)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to add room admin hash! (Expecting one parameter)\n");
}
else
{
std::string newAdminStrCopy(newadmin);
wzAsyncExecOnMainThread([newAdminStrCopy]{
wz_command_interface_output("WZCMD info: Room admin hash added: %s\n", newAdminStrCopy.c_str());
addLobbyAdminIdentityHash(newAdminStrCopy);
auto roomAdminMessage = astringf("Room admin assigned to: %s", newAdminStrCopy.c_str());
sendRoomSystemMessage(roomAdminMessage.c_str());
});
}
}
else if(!strncmpl(line, "admin add-public-key "))
{
char newadmin[1024] = {0};
int r = sscanf(line, "admin add-public-key %1023[^\n]s", newadmin);
if (r != 1)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to add room admin public key! (Expecting one parameter)\n");
}
else
{
std::string newAdminStrCopy(newadmin);
wzAsyncExecOnMainThread([newAdminStrCopy]{
wz_command_interface_output("WZCMD info: Room admin public key added: %s\n", newAdminStrCopy.c_str());
addLobbyAdminPublicKey(newAdminStrCopy);
auto roomAdminMessage = astringf("Room admin assigned to: %s", newAdminStrCopy.c_str());
sendRoomSystemMessage(roomAdminMessage.c_str());
});
}
}
else if(!strncmpl(line, "admin remove "))
{
char newadmin[1024] = {0};
int r = sscanf(line, "admin remove %1023[^\n]s", newadmin);
if (r != 1)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to remove room admin! (Expecting one parameter)\n");
}
else
{
std::string newAdminStrCopy(newadmin);
wzAsyncExecOnMainThread([newAdminStrCopy]{
if (removeLobbyAdminPublicKey(newAdminStrCopy))
{
wz_command_interface_output("WZCMD info: Room admin public key removed: %s\n", newAdminStrCopy.c_str());
auto roomAdminMessage = astringf("Room admin removed: %s", newAdminStrCopy.c_str());
sendRoomSystemMessage(roomAdminMessage.c_str());
}
else if (removeLobbyAdminIdentityHash(newAdminStrCopy))
{
wz_command_interface_output("WZCMD info: Room admin hash removed: %s\n", newAdminStrCopy.c_str());
auto roomAdminMessage = astringf("Room admin removed: %s", newAdminStrCopy.c_str());
sendRoomSystemMessage(roomAdminMessage.c_str());
}
else
{
wz_command_interface_output("WZCMD info: Failed to remove room admin! (Provided parameter not found as either admin hash or public key)\n");
}
});
}
}
else if(!strncmpl(line, "kick identity "))
{
char playeridentitystring[1024] = {0};
char kickreasonstr[1024] = {0};
int r = sscanf(line, "kick identity %1023s %1023[^\n]s", playeridentitystring, kickreasonstr);
if (r != 1 && r != 2)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to get player public key or hash!\n");
}
else
{
std::string playerIdentityStrCopy(playeridentitystring);
std::string kickReasonStrCopy = (r >= 2) ? kickreasonstr : "You have been kicked by the administrator.";
convertEscapedNewlines(kickReasonStrCopy);
wzAsyncExecOnMainThread([playerIdentityStrCopy, kickReasonStrCopy] {
bool foundActivePlayer = false;
for (int i = 0; i < MAX_CONNECTED_PLAYERS; i++)
{
auto player = NetPlay.players[i];
if (!isHumanPlayer(i))
{
continue;
}
bool kickThisPlayer = false;
auto& identity = getMultiStats(i).identity;
if (identity.empty())
{
if (playerIdentityStrCopy == "0") // special case for empty identity, in case that happens...
{
kickThisPlayer = true;
}
else
{
continue;
}
}
if (!kickThisPlayer)
{
// Check playerIdentityStrCopy versus both the (b64) public key and the public hash
std::string checkIdentityHash = identity.publicHashString();
std::string checkPublicKeyB64 = base64Encode(identity.toBytes(EcKey::Public));
if (playerIdentityStrCopy == checkPublicKeyB64 || playerIdentityStrCopy == checkIdentityHash)
{
kickThisPlayer = true;
}
}
if (kickThisPlayer)
{
if (i == NetPlay.hostPlayer)
{
wz_command_interface_output("WZCMD error: Can't kick host!\n");
continue;
}
kickPlayer(i, kickReasonStrCopy.c_str(), ERROR_KICKED, false);
auto KickMessage = astringf("Player %s was kicked by the administrator.", player.name);
sendRoomSystemMessage(KickMessage.c_str());
foundActivePlayer = true;
}
}
if (!foundActivePlayer)
{
wz_command_interface_output("WZCMD error: Failed to find currently-connected player with matching public key or hash?\n");
}
});
}
}
else if(!strncmpl(line, "ban ip "))
{
char tobanip[1024] = {0};
char banreasonstr[1024] = {0};
int r = sscanf(line, "ban ip %1023s %1023[^\n]s", tobanip, banreasonstr);
if (r != 1 && r != 2)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to get ban ip!\n");
}
else
{
std::string banIPStrCopy(tobanip);
std::string banReasonStrCopy = (r >= 2) ? banreasonstr : "You have been banned from joining by the administrator.";
convertEscapedNewlines(banReasonStrCopy);
wzAsyncExecOnMainThread([banIPStrCopy, banReasonStrCopy] {
bool foundActivePlayer = false;
for (int i = 0; i < MAX_CONNECTED_PLAYERS; i++)
{
auto player = NetPlay.players[i];
if (!isHumanPlayer(i))
{
continue;
}
if (!strcmp(player.IPtextAddress, banIPStrCopy.c_str()))
{
kickPlayer(i, banReasonStrCopy.c_str(), ERROR_INVALID, true);
auto KickMessage = astringf("Player %s was banned by the administrator.", player.name);
sendRoomSystemMessage(KickMessage.c_str());
foundActivePlayer = true;
}
}
if (!foundActivePlayer)
{
// add the IP to the ban list anyway
addIPToBanList(banIPStrCopy.c_str(), "Banned player");
}
});
}
}
else if(!strncmpl(line, "unban ip "))
{
char tounbanip[1024] = {0};
int r = sscanf(line, "unban ip %1023[^\n]s", tounbanip);
if (r != 1)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to get unban ip!\n");
}
else
{
std::string unbanIPStrCopy(tounbanip);
wzAsyncExecOnMainThread([unbanIPStrCopy] {
if (!removeIPFromBanList(unbanIPStrCopy.c_str()))
{
wz_command_interface_output("WZCMD error: IP was not on the ban list!\n");
}
});
}
}
else if(!strncmpl(line, "chat bcast "))
{
char chatmsg[1024] = {0};
int r = sscanf(line, "chat bcast %1023[^\n]s", chatmsg);
if (r != 1)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to get bcast message!\n");
}
else
{
std::string chatmsgstr(chatmsg);
wzAsyncExecOnMainThread([chatmsgstr] {
if (!NetPlay.isHostAlive)
{
// can't send this message when the host isn't alive
wz_command_interface_output("WZCMD error: Failed to send bcast message because host isn't yet hosting!\n");
}
sendRoomSystemMessage(chatmsgstr.c_str());
});
}
}
else if(!strncmpl(line, "chat direct "))
{
char playeridentitystring[1024] = {0};
char chatmsg[1024] = {0};
int r = sscanf(line, "chat direct %1023s %1023[^\n]s", playeridentitystring, chatmsg);
if (r != 2)
{
wz_command_interface_output_onmainthread("WZCMD error: Failed to get chat receiver or message!\n");
}
else
{
std::string playerIdentityStrCopy(playeridentitystring);
std::string chatmsgstr(chatmsg);
wzAsyncExecOnMainThread([playerIdentityStrCopy, chatmsgstr] {
if (!NetPlay.isHostAlive)
{
// can't send this message when the host isn't alive
wz_command_interface_output("WZCMD error: Failed to send chat direct message because host isn't yet hosting!\n");
}
bool foundActivePlayer = false;
for (uint32_t i = 0; i < MAX_CONNECTED_PLAYERS; i++)
{
auto player = NetPlay.players[i];
if (!isHumanPlayer(i))
{
continue;
}
bool msgThisPlayer = false;
auto& identity = getMultiStats(i).identity;
if (identity.empty())
{
if (playerIdentityStrCopy == "0") // special case for empty identity, in case that happens...
{
msgThisPlayer = true;
}
else
{
continue;
}
}
if (!msgThisPlayer)
{
// Check playerIdentityStrCopy versus both the (b64) public key and the public hash
std::string checkIdentityHash = identity.publicHashString();
std::string checkPublicKeyB64 = base64Encode(identity.toBytes(EcKey::Public));
if (playerIdentityStrCopy == checkPublicKeyB64 || playerIdentityStrCopy == checkIdentityHash)
{
msgThisPlayer = true;
}
}
if (msgThisPlayer)
{
sendRoomSystemMessageToSingleReceiver(chatmsgstr.c_str(), i);
foundActivePlayer = true;
}
}
if (!foundActivePlayer)
{
wz_command_interface_output("WZCMD error: Failed to find currently-connected player with matching public key or hash?\n");
}
});
}
}
else if(!strncmpl(line, "shutdown now"))
{
inexit = true;
wzAsyncExecOnMainThread([] {
wz_command_interface_output("WZCMD info: shutdown now command received - shutting down\n");
wzQuit(0);
});
}
}
return 0;
}
static void sockBlockSIGPIPE(const int fd, bool block_sigpipe)
{
#if defined(SO_NOSIGPIPE)
const int no_sigpipe = block_sigpipe ? 1 : 0;
if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe)) != 0)
{
errlog("WZCMD INFO: Failed to set SO_NOSIGPIPE on socket, SIGPIPE might be raised when connection gets broken.\n");
}
#else
// Prevent warnings
(void)fd;
(void)block_sigpipe;
#endif
}
bool cmdInterfaceCreateUnixSocket(const std::string& local_path)
{
if (local_path.empty())
{
errlog("WZCMD FAILURE: Requested socket path is empty - cancelling\n");
return false;
}
int socket_type = SOCK_STREAM;
#if defined(SOCK_CLOEXEC)
socket_type |= SOCK_CLOEXEC;
#endif
int cmdSockFd = socket(AF_UNIX, socket_type, 0);
if (cmdSockFd == -1)
{
int errno_cpy = errno;
errlog("WZCMD FAILURE: socket() call failed with errno: %d\n", errno_cpy);
return false;
}
sockBlockSIGPIPE(cmdSockFd, true);
sockaddr_un addr;
socklen_t sockLen = sizeof(addr);
memset(&addr, 0, sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", local_path.c_str());
if (strlen(addr.sun_path) != local_path.length())
{
errlog("WZCMD FAILURE: Requested socket path %s would be truncated to %s - cancelling\n", local_path.c_str(), addr.sun_path);
return false;
}
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) || defined(__NetBSD__)
addr.sun_len = SUN_LEN(&addr);
sockLen = addr.sun_len;
#endif
unlink(addr.sun_path);
if (bind(cmdSockFd, reinterpret_cast<sockaddr*>(&addr), sockLen) != 0)
{
int errno_cpy = errno;
errlog("WZCMD FAILURE: bind() failed with errno: %d\n", errno_cpy);
return false;
}
auto listenResult = listen(cmdSockFd, 1);
if (listenResult != 0)
{
int errno_cpy = errno;
errlog("WZCMD FAILURE: listen() failed with errno: %d\n", errno_cpy);
return false;
}
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
int cmdPeerFd = -1;
do {
#if defined(SOCK_CLOEXEC)
cmdPeerFd = accept4(cmdSockFd, (struct sockaddr*)&ss, &slen, SOCK_CLOEXEC);
#else
cmdPeerFd = accept(cmdSockFd, (struct sockaddr*)&ss, &slen);
#endif
} while (cmdPeerFd == -1 && errno == EINTR);
if (cmdPeerFd == -1)
{
int errno_cpy = errno;
errlog("WZCMD FAILURE: accept() failed with errno: %d\n", errno_cpy);
close(cmdSockFd);
return false;
}
if (fcntl(cmdPeerFd, F_SETFL, O_NONBLOCK) == 0)
{
writeFdIsNonBlocking = true;
}
else
{
int errno_cpy = errno;
errlog("WZCMD NOTICE: Attempt to set non-blocking flag failed with errno: %d\n", errno_cpy);
writeFdIsNonBlocking = false;
}
sockBlockSIGPIPE(cmdPeerFd, true);
readFd = cmdPeerFd;
readFdIsSocket = true;
writeFd = cmdPeerFd;
cleanupIOFunc = [cmdPeerFd, cmdSockFd, addr](){
close(cmdPeerFd);
close(cmdSockFd);
unlink(addr.sun_path);
};
return true;
}
void cmdInterfaceThreadInit()
{
if (wz_command_interface() == WZ_Command_Interface::None)
{
return;
}
#if defined(HAVE_SYS_EVENTFD_H)
if (quitSignalEventFd == -1)
{
int flags = 0;
# if defined(EFD_CLOEXEC)
flags = EFD_CLOEXEC;
# endif
quitSignalEventFd = eventfd(0, flags);
}
#elif defined(HAVE_UNISTD_H)
if (quitSignalPipeFds[0] == -1 && quitSignalPipeFds[1] == -1)
{
int result = -1;
# if defined(HAVE_PIPE2) && defined(O_CLOEXEC)
result = pipe2(quitSignalPipeFds, O_CLOEXEC);
# else
result = pipe(quitSignalPipeFds);
# endif
if (result == -1)
{
quitSignalPipeFds[0] = -1;
quitSignalPipeFds[1] = -1;
}
}
#endif
// initialize output queue (if used)
if (wz_command_interface() != WZ_Command_Interface::StdIn_Interface)
{
cmdInterfaceOutputQueue = std::make_unique<moodycamel::BlockingReaderWriterQueue<CmdInterfaceMessageBuffer>>(1024);
latestWriteBuffer.reserve(maxReserveMessageBufferSize);
}
switch (wz_command_interface())
{
case WZ_Command_Interface::StdIn_Interface:
readFd = STDIN_FILENO;
readFdIsSocket = false;
writeFd = STDERR_FILENO;
writeFdIsNonBlocking = false;
break;
case WZ_Command_Interface::Unix_Socket:
// sets readFd, writeFd, etc as appropriate
if (!cmdInterfaceCreateUnixSocket(wz_cmd_interface_param))
{
// failed (and logged a failure to stderr)
return;
}
break;
default:
return;
}
if (!cmdInputThread)
{
cmdInputThreadQuit.store(false);
cmdInputThread = wzThreadCreate(cmdInputThreadFunc, nullptr, "wzCmdInterfaceInputThread");
wzThreadStart(cmdInputThread);
}