-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGenericConsole.cpp
More file actions
2085 lines (1894 loc) · 78.3 KB
/
GenericConsole.cpp
File metadata and controls
2085 lines (1894 loc) · 78.3 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
/* vim: set noet ts=4 sw=4 sts=4 ft=cpp:
*
* Created by Darkwire Software.
*
* This example server file is available unlicensed; the MIT license of liblacewing/Lacewing Relay does not apply to this file.
*
* This file is used as a template to make OS-specific code. Several preprocessor-level things are parsed and removed here.
* You should not modify this template unless you are writing code for all platforms.
*/
// Includes OS-specific headers
#ifdef _WIN32
#include "WindowsConsole.hpp"
#else // !_WIN32
#include "LinuxConsole.hpp"
#endif // _WIN32
// Includes all global variables and headers that both Windows wchar_t and non-Windows char use.
#include "GenericConsole.hpp"
// Reprints the time and statistics line. Called by lineEnd() and when stats timer ticks.
static void ReprintStatisticsLine()
{
// We don't maintain a stats line if we're not writing to a console.
// We also should not print if the server is pre-startup or currently shutting down.
if (!isConsoleOutput || lastTimeAndStats.empty())
return;
std::cout << gray << lastTimeAndStats << std::flush;
}
// Pads the last output line and inserts newline, appending either just time prefix to next line,
// or reprinting whole statistics line
// @param reprintStatsLine if true, prints the statistics line again; if false, prints time only,
// expecting another line written immediately by caller
template <class _Elem, class _Traits>
static std::basic_ostream<_Elem, _Traits> & operator << (std::basic_ostream<_Elem, _Traits>& str, const lineEndProp & wrp)
{
// If we're not outputting to console, we don't want to pad or recolor, just output time
if (!isConsoleOutput)
{
std::cout << '\n';
if (!wrp.reprintStatsLine)
std::cout << timeBuffer;
return str;
}
#if lw_utf8_console
// Erase current line to end, then move to next line
std::cout << "\x1b[0K\n"sv;
#else // !lw_utf8_console
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
if (GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
// If we wrote a line that's shorter than last statistics line, we clear whatever wasn't overwritten
// from end of last wrote line (cursor x) to end of console via padding an empty string.
const int charsToFill = csbi.dwSize.X - csbi.dwCursorPosition.X;
assert(charsToFill >= 0);
std::cout << std::setw((std::streamsize)charsToFill) << ""sv << std::setw(0);
}
std::cout << '\n';
#endif // lw_utf8_console
if (wrp.reprintStatsLine)
ReprintStatisticsLine();
else // prepare for another line
std::cout << timeBuffer;
return str;
}
// Checks if a port text input by a user is valid or re-used elsewhere.
static void CheckPort(const lw_char * portStr, lw_ui16 * writeTo, std::function<void()> errInv)
{
const std::uint32_t portNum = static_cast<std::uint32_t>(std::strtoul(portStr, nullptr, 10));
// Check port is in valid range. Port 843 is used for Flash policy.
if (portNum == 843 || portNum == 0 || portNum > std::numeric_limits<lw_ui16>::max())
{
std::cout << red;
errInv();
std::cout << " had invalid port number "sv << portStr << '.' << lineEnd();
return;
}
*writeTo = (lw_ui16)portNum;
// Check port does not match others
if ((writeTo != &mainPort && *writeTo == mainPort) ||
(writeTo != &websocketNonSecurePort && *writeTo == websocketNonSecurePort) ||
(writeTo != &websocketSecurePort && *writeTo == websocketSecurePort))
{
errInv();
std::cout << " port number "sv << portStr << " was reused in several ports."sv << lineEnd();
}
}
static lw_string GetConsoleLine(bool password = false)
{
assert(isConsoleOutput);
// Due to outputting to file, running under debugger, or other reasons, we don't prompt user
if (!requestUserInput)
{
#ifdef _DEBUG
std::cout << "(prompting disabled)\n"sv;
#endif
return lw_string();
}
// Set console color for user's response text
std::cout << userresponsecolor;
// Turn off echo of input to output
#ifdef _WIN32
DWORD conMode;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
if (password &&
(!GetConsoleMode(hStdOut, &conMode) || !SetConsoleMode(hStdOut, conMode & ~ENABLE_ECHO_INPUT)))
{
std::abort();
}
#else // !_WIN32
std::cout << "\033 7"sv;
termios oldt, newt;
if (password)
{
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
}
#endif // _WIN32
lw_string consoleInputLine;
std::getline(std::cin, consoleInputLine);
// User aborted reading input e.g. Ctrl-C
if (shutdowned || std::cin.fail())
return lw_string();
// restore cursor pos to previous line if no input to show
if (consoleInputLine.empty())
#ifdef _WIN32
SetConsoleCursorPosition(hStdOut, csbi.dwCursorPosition);
#else // !_WIN32
std::cout << "\033 8"sv;
#endif // _WIN32
// restore echo and generate random asterisk for password
if (password)
{
#ifdef _WIN32
SetConsoleMode(hStdOut, conMode);
SetConsoleCursorPosition(hStdOut, csbi.dwCursorPosition);
#else // !_WIN32
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
#endif // _WIN32
std::cout << lw_string(consoleInputLine.empty() ? 10 + (rand() % 20) : consoleInputLine.size(), TXT('*')) << '\n';
}
else if (consoleInputLine.empty())
std::cout << "(empty input)\n"sv;
return consoleInputLine;
}
// Looks for matching default TLS cert files and uses the first to match
static void GuessCertPath()
{
if (!wsFullChainPath.empty())
return;
// Search app directory for matching files
#ifdef _WIN32
// Windows: PFX file that should have both private and public key
if (lw_file_exists("./tlscert.pfx"))
{
wsPrivKeyPath = wsFullChainPath = "./tlscert.pfx"s;
std::cout << green << "Auto-set cert file to tlscert.pfx from current directory."sv << lineEnd();
return;
}
#endif // _WIN32
if (lw_file_exists("./fullchain.pem") && lw_file_exists("./privkey.pem"))
{
wsPrivKeyPath = "./privkey.pem"s;
wsFullChainPath = "./fullchain.pem"s;
std::cout << green << "Auto-set cert files to privkey.pem and fullchain.pem from current directory."sv << lineEnd();
return;
}
// Not found at all - if websocket insecure was on, they probably want a secure cert
if (websocketNonSecurePort)
{
std::cout << yellow << "Couldn't auto-find TLS certficate files - expecting "sv;
#ifdef _WIN32
std::cout << "either \"tlscert.pfx\" OR "sv;
#endif // _WIN32
std::cout << "\"fullchain.pem\" and \"privkey.pem\" in app folder."sv << lineEnd();
}
}
static bool GetPortFromInput(const lw_string_view req, lw_ui16 * writeTo, bool requireCert, lw_ui16 defaultVal)
{
// Assume defaults will be fine if not prompting for settings
if (!requestUserInput && !requireCert)
{
*writeTo = defaultVal;
return true;
}
// User already aborted reading input
if (shutdowned || (requestUserInput && std::cin.fail()))
return false;
lw_string consoleInputLine;
if (requestUserInput && !requireCert)
std::cout << userpromptcolor << "Enter a "sv << req << " port (leave empty for default " << defaultVal << "):\n"sv;
// else cert is required for this port: guess cert
else
{
GuessCertPath();
if (!requestUserInput)
{
*writeTo = defaultVal;
return true;
}
std::cout << userpromptcolor << "Enter a "sv << req << " port (leave empty for default "sv << defaultVal <<
", or pass 0 to disable secure websocket):\n"sv;
}
consoleInputLine = GetConsoleLine();
bool good = true;
if (consoleInputLine.empty())
{
// User pressed Ctrl-C during input
if (shutdowned || std::cin.fail())
return false;
*writeTo = defaultVal;
}
else
{
CheckPort(consoleInputLine.c_str(), writeTo, [&]() {
std::cout << "Invalid input: "sv << req;
good = false;
});
}
// Cert is required for this port, and we don't have cmdline arg
if (good && requireCert && *writeTo != 0)
{
if (wsFullChainPath.empty())
{
std::cout << userpromptcolor << "Enter a path to TLS certificate file (combined PFX or full chain PEM), or leave empty to disable websocket secure hosting:\n"sv;
consoleInputLine = GetConsoleLine();
if (consoleInputLine.empty())
{
std::cout << green << "Left empty. Will continue webserver with just insecure websocket."sv << lineEnd();
websocketSecurePort = 0;
return true;
}
wsFullChainPath = lw_u8(consoleInputLine);
}
if (wsPrivKeyPath.empty())
{
std::cout << userpromptcolor << "Enter a path to SSL priv key certificate file (PFX or PEM), or leave empty if part of chain file:\n"sv;
consoleInputLine = GetConsoleLine();
wsPrivKeyPath = consoleInputLine.empty() ? wsFullChainPath : lw_u8(consoleInputLine);
}
if (wsPassPhrase.empty())
{
std::cout << userpromptcolor << "Enter a password to the certificate file(s), or leave empty if none:\n"sv;
consoleInputLine = GetConsoleLine(true);
wsPassPhrase = lw_u8(consoleInputLine);
}
}
return good;
}
// Converts time_t to full date-time representation based on local date format
lw_string fulltimetostring(std::time_t timepoint)
{
lw_string buffer(100, TXT('\0'));
std::tm timeinfo = { 0 };
#ifdef _WIN32
if (!localtime_s(&timeinfo, &timepoint))
std::_tcsftime(buffer.data(), buffer.size(), TXT("%I:%M:%S%p %x"), &timeinfo);
#else // !_WIN32
if (localtime_r(&timepoint, &timeinfo))
std::strftime(buffer.data(), buffer.size(), TXT("%I:%M:%S%p %x"), &timeinfo);
#endif // _WIN32
return buffer;
}
/** Prints total statistics, mid-app or at end of app.
* @param endOfApp If true, program is at end; current time is referred to as end time.
* @remarks Does not print user list, ban list, IP list. Those are only accessible via admin commands.
* If such a thing is widely needed, the console app needs to import ncurses or something so that it can
* have on-console subwindows.
*/
static void PrintTotalStatistics(const bool endOfApp)
{
std::cout << green << std::setw(70) << std::setfill(TXT('=')) << ""sv << std::setw(0) << std::setfill(TXT(' ')) << lineEnd(false);
if (endOfApp)
std::cout << "Program completed. Total statistics:"sv << lineEnd(false);
else
std::cout << "Manual statistics request. Statistics since start of server:" << lineEnd(false);
const std::time_t curTime = time(NULL);
const std::uint64_t secondsUp = std::max<std::uint64_t>(1, (std::uint64_t)std::ceil(difftime(curTime, startTime)));
// Division is floor by default
const std::uint64_t hours = secondsUp / (60ULL * 60ULL), minutes = (secondsUp / 60ULL) % 60ULL, seconds = secondsUp % 60ULL;
std::cout
<< " Start time: "sv << fulltimetostring(startTime) << ". "sv << lineEnd(false)
<< (endOfApp ? " End"sv : " Current"sv) << " time: "sv << fulltimetostring(curTime) << ". "sv << lineEnd(false)
<< " Hosting for: "sv << hours << " hrs, "sv << minutes << " mins, "sv << seconds << " seconds ("sv << secondsUp << " seconds total)."sv << lineEnd(false)
<< " Max in 1 sec: "sv << serverstats.in.highestSec.bytes << " bytes in, "sv << serverstats.out.highestSec.bytes << " bytes out."sv << lineEnd(false)
<< " "sv << serverstats.in.highestSec.msg << " msgs in, "sv << serverstats.out.highestSec.msg << " msgs out (may be diff seconds)."sv << lineEnd(false)
<< " Avg per sec: "sv << (serverstats.in.total.bytes / secondsUp) << " bytes in, "sv << (serverstats.out.total.bytes / secondsUp) << " bytes out."sv << lineEnd(false)
<< " "sv << (serverstats.in.total.msg / secondsUp) << " msgs in, "sv << (serverstats.out.total.msg / secondsUp) << " msgs out."sv << lineEnd(false)
<< " Total: "sv << serverstats.in.total.bytes << " bytes in, "sv << serverstats.out.total.bytes << " bytes out."sv << lineEnd(false)
<< " "sv << serverstats.in.total.msg << " msgs in, "sv << serverstats.out.total.msg << " msgs out."sv << lineEnd(false)
<< " Max clients: "sv << serverstats.maxClients << ", max channels: "sv << serverstats.maxChannels << '.' << lineEnd(false);
if (endOfApp)
std::cout << "Current clients: "sv << globalserver->clientcount() << ", current channels: "sv << globalserver->channelcount() << '.' << lineEnd(false);
std::cout
<< std::setw(70) << std::setfill(TXT('=')) << ""sv << std::setw(0) << std::setfill(TXT(' ')) << lineEnd(!endOfApp);
}
/**
* @brief Entry point for the program, where OS starts this program up
* @param argc Number of entries in argv
* @param argv Null-terminated arguments, the first usually the program's full path
* Running "app.exe -thing val" will result in argc = 3, with argv being
* [0] = "...app.exe", [1] = "-thing", [2] = "val"
* @return 0 for success, -1 for error; usually negative is for errors, positive for info,
* but by spec any non-zero is error.
* @remarks Although OSes don't tend to react to error code, you can read it after app exit,
* e.g. in batch via %ERRORLEVEL%, bash via $?, and so on.
*/
int main(const int argcf, lw_char* argv[])
{
const std::size_t argc = static_cast<std::size_t>(argcf);
// If true, cmdline is set to require admin
bool requireAdmin = false;
#ifdef _WIN32
#ifdef _DEBUG
// Enable memory tracking (does nothing in Release)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// If running in debugger, clear the console window
if (IsDebuggerPresent())
system("cls");
#endif // _DEBUG
// UTF-8 console requires Windows 10, 1903+
#if lw_utf8_console
{
OSVERSIONINFO osvi = {};
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
if (osvi.dwMajorVersion < 10 || (osvi.dwMajorVersion == 10 && osvi.dwBuildNumber < 1903))
{
std::cout << "UTF-8 Windows requires Windows 10, 1903 or later. Run the wide-char version of this program.\n"sv;
return ENOTSUP;
}
}
#endif // lw_utf8_console
// Handle closing nicely - Ctrl-C, Ctrl-Break, and pressing the X on console window.
// Registering no handler will result in default behavior, which normally means OS will instantly terminate app.
//
// This is another entry point from OS -> program; OS will start up a thread in this app to call CloseHandler.
// Note that returning from some handlers will lead OS to instantly terminate app anyway,
// as some handlers are more for OS notifying a program to quit, rather than a user notification.
if (!SetConsoleCtrlHandler(CloseHandler, TRUE))
{
std::cout << "Could not set console close handler, error "sv << GetLastError() << ".\n"sv;
return ENOTSUP;
}
#else // !_WIN32
// GDB sometimes takes a while to link to stdout
#ifdef _DEBUG
std::cout << std::flush;
std::cerr << std::flush;
std::this_thread::sleep_for(3s);
#endif
// Handle user and OS interrupts.
//
// This is the other entry point from OS -> program. OS will pick a thread that has a handler
// to call CloseHandler on. We only use one thread in this app.
//
// Registering no handler will result in default OS handling behavior, which may be
// an instant app terminate, a terminate after dumping RAM to a file in a system folder,
// or letting program continue as normal.
// Returning from some signal handlers will result in the signal being called again
// with default handler, so CloseHandler stalls to allow main thread to exit cleanly
// when it can.
//
// All but SIGKILL and SIGSTOP can be intercepted.
struct sigaction act = { };
act.sa_handler = CloseHandler;
sigemptyset(&act.sa_mask);
// SIGINT is a more "friendly" signal caused by Ctrl-C. It is also raised if your code hits a debugger-set breakpoint.
sigaddset(&act.sa_mask, SIGINT);
// SIGQUIT is caused by Ctrl-\, which closes your app and dumps the running state,
// basically requesting exit with a dump of all files your app is currently using.
// Returning from handler is instant app close.
sigaddset(&act.sa_mask, SIGQUIT);
// SIGABRT is caused by abort(), generally raised by internal CRT code for serious issues such as corrupt heap.
// Returning from handler usually causes abort() to reset the handler to OS default and raise it again,
// which causes instant app close.
sigaddset(&act.sa_mask, SIGABRT);
// These are caused by bad memory access (SIGSEGV), unaligned memory access (SIGBUS), or illegal CPU instructions (SIGILL).
// Returning from handler is likely going to crash the app and cause instant app close.
sigaddset(&act.sa_mask, SIGILL);
sigaddset(&act.sa_mask, SIGSEGV);
sigaddset(&act.sa_mask, SIGBUS);
// SIGFPE is floating-point exception, e.g. dividing by zero, float overflow, etc. It can be ignored,
// although it leads the running code in undefined state, so we close down in response.
// Returning from handler is instant app close.
//sigaddset(&act.sa_mask, SIGFPE);
// SIGPIPE is writing to a pipe that no longer exists.
// Returning from handler is instant app close.
sigaddset(&act.sa_mask, SIGPIPE);
// SIGTERM is when OS is requesting app to instantly close. It is "gentle" compared to SIGKILL,
// which is not raised in processes and cannot be intercepted.
// Returning from handler is instant app close.
// On system shutdown, SIGTERM is sent; apps have usually 5s to close down before SIGKILL.
sigaddset(&act.sa_mask, SIGTERM);
if (sigaction(SIGINT, &act, NULL))
{
std::cout << "Could not set console close handler, error "sv << errno << ".\n"sv;
return ENOTSUP;
}
#endif // _WIN32
#ifndef _DEBUG
// We don't use C-style printf(), so desync C++ console output (std::cout) and C (printf, puts).
// It's unclear whether std::cout or printf is faster; and some say std::cout is faster
// only with a fast locale.
// Since Bluewing currently requires C++17, for use of std::string_view and std::shared_ptr,
// we'll stick to C++ console.
std::ios_base::sync_with_stdio(false);
#endif // !_DEBUG
#ifdef _WIN32
// For Unicode text format
#if lw_utf8_console
if (!SetConsoleCP(CP_UTF8) || !SetConsoleOutputCP(CP_UTF8))
{
std::cout << "UTF-8 console not permitted. Run the wide-char version of this program.\n";
return ENOTSUP;
}
#else // !lw_utf8_console
init_locale();
#endif // lw_utf8_console
// Get access to console
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
hStdIn = GetStdHandle(STD_INPUT_HANDLE);
// If running under debugger, we may not care to ask for settings
if (IsDebuggerPresent())
requestUserInput = requestUserInputUnderDebugger;
#endif // _WIN32
// Update timeBuffer for startup output
OnTimerTick(nullptr);
// Get app directory that app is running from, by getting running app full path.
// argv[0] may contain relative path, so it shouldn't be relied on.
{
lw_string filenameBuf;
#ifdef _WIN32
#ifdef _MSC_VER
// MSVC provide a shortcut to get current running app path, but not all compilers have it.
TCHAR* filePath = NULL;
if (_get_tpgmptr(&filePath) == 0)
filenameBuf = filePath;
#endif // _MSC_VER
DWORD pathLen;
// Fall back on manual lookup of EXE path
if (filenameBuf.empty())
{
// We can't get path size via passing null, so we have to repeat with increasing buffer
filenameBuf.resize(1024);
while (true)
{
// Get full path of EXE, including EXE filename + ext.
pathLen = GetModuleFileName(NULL, filenameBuf.data(), (DWORD)filenameBuf.size());
if (pathLen == 0)
{
// Extend the buffer to next power of 2
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
filenameBuf.resize(filenameBuf.size() << 1);
continue;
}
// Some other error, give up
std::cout << red << "Looking up app directory failed. Error "sv << GetLastError() << '.' << lineEnd();
goto cleanup;
}
// If success, trim to number of bytes actually written
if (pathLen < filenameBuf.size())
{
// Null terminator is not guaranteed, remove if exists
if (filenameBuf[pathLen - 1] == _T('\0'))
--pathLen;
filenameBuf.resize(pathLen);
break;
}
} while (true);
}
// Both methods use whatever native used to run this app, so it may be DOS-style 8.3 path or a long path.
// We'll convert it to a long path, which may be a no-op.
pathLen = GetLongPathName(filenameBuf.data(), NULL, 0);
if (pathLen == 0)
{
std::cout << red << "Looking up app directory failed. Error "sv << GetLastError() << '.' << lineEnd();
goto cleanup;
}
filenameBuf.resize(pathLen);
// Reusing same buffer for short and long path is explicitly allowed
// Writing to std::string null terminator with another null is fine in C++17, undefined behavior earlier
pathLen = GetLongPathName(filenameBuf.data(), filenameBuf.data(), (DWORD)filenameBuf.size());
if (pathLen == 0)
{
std::cout << red << "Looking up app directory failed. Error "sv << GetLastError() << '.' << lineEnd();
goto cleanup;
}
filenameBuf.resize(pathLen); // return if success does not include null terminator
#else // !_WIN32
filenameBuf.resize(256);
// Get full path of app, including filename + ext.
for (ssize_t pathLen; true;)
{
pathLen = ::readlink("/proc/self/exe", filenameBuf.data(), filenameBuf.size());
// Sometimes, the OS hasn't made the symlink yet, and returns nothing. Sleep until it's ready.
if (pathLen == 0)
{
std::this_thread::sleep_for(50ms);
continue;
}
if (pathLen == -1)
{
std::cout << "Looking up current app folder failed 2, error "sv << errno << ".\n"sv;
return EINVAL;
}
// Enough written
if ((size_t)pathLen < filenameBuf.size())
{
filenameBuf.resize(pathLen);
break;
}
// Extend the buffer to next power of 2, try again
filenameBuf.resize(filenameBuf.size() << 1);
}
#endif // _WIN32
// Trim to last slash.
const std::size_t lastSlash = filenameBuf.find_last_of(TXT("\\/"sv));
if (lastSlash == lw_string::npos)
{
std::cout << red << "Current app path \""sv << filenameBuf << "\" made no sense."sv << lineEnd();
goto cleanup;
}
appFolder = filenameBuf.substr(0, lastSlash + 1);
}
// Parse passed args
{
bool bad = false;
if (argc > 1)
{
const auto setport = [&](std::size_t argCIdxName, lw_ui16* writeTo) {
if (argCIdxName + 1 >= argc)
{
std::cout << "Invalid cmdline: " << argv[argCIdxName] << " had no following value.\n"sv;
return (bad = true);
}
CheckPort(argv[argCIdxName + 1], writeTo, [&]() {
std::cout << "Invalid cmdline: "sv << argv[argCIdxName];
bad = true;
});
return !bad;
};
const auto setpath = [&](std::size_t argCIdxName, std::string* writeTo) {
if (argCIdxName + 1 >= argc)
{
std::cout << "Invalid cmdline: "sv << argv[argCIdxName] << " had no following value.\n"sv;
return (bad = true);
}
// If flash policy path is specified, it must exist
#if lw_utf8_console
if (!lw_file_exists(argv[argCIdxName + 1]))
#else // !lw_utf8_console
if (!lw_file_exists(WideToUTF8(argv[argCIdxName + 1]).c_str()))
#endif // lw_utf8_console
{
std::cout << "Invalid cmdline: "sv << argv[argCIdxName] << " had invalid path \"" << argv[argCIdxName + 1] << "\".\n"sv;
return (bad = true);
}
*writeTo = lw_u8(argv[argCIdxName + 1]);
// PFX may hold both priv key and full chain, but should only be passed once, as priv key
if (writeTo == &wsFullChainPath && lw_u8str_icmp(*writeTo, wsPrivKeyPath))
{
std::cout << "Invalid cmdline: \""sv << argv[argCIdxName] << "\" cert path \""sv
<< argv[argCIdxName + 1] << "\" was reused for both fullchain and priv key. "
"Only pass it for priv key if you're using a PFX with both.\n"sv;
return (bad = true);
}
if (writeTo == &flashPolicyPath && (lw_u8str_icmp(*writeTo, wsFullChainPath) || lw_u8str_icmp(*writeTo, wsPrivKeyPath)))
{
std::cout << "Invalid cmdline: \""sv << argv[argCIdxName] << "\" policy path \""sv
<< argv[argCIdxName + 1] << "\" was reused for a websocket cert path.\n"sv;
return (bad = true);
}
return !bad;
};
// Assume the first argv[0] is app path, and skip it
// otherwise read all arguments in key-value pairs, or as keys by themselves
for (std::size_t i = 1; i < argc;)
{
// Skip past commandline - or / precursor
if (argv[i][0] == TXT('/') || argv[i][0] == TXT('-'))
++argv[i];
// These only edit the same things
if ((!strcasecmp(argv[i], TXT("mainPort")) && setport(i, &mainPort)) ||
(!strcasecmp(argv[i], TXT("wsPort")) && setport(i, &websocketNonSecurePort)) ||
(!strcasecmp(argv[i], TXT("wssPort")) && setport(i, &websocketSecurePort)) ||
(!strcasecmp(argv[i], TXT("certFullChainPath")) && setpath(i, &wsFullChainPath)) ||
(!strcasecmp(argv[i], TXT("certPrivKeyPath")) && setpath(i, &wsPrivKeyPath)))
{
i += 2;
continue;
}
// Flash policy set: presumably we want flash enabled
if (!strcasecmp(argv[i], TXT("flashPolicyPath")) && setpath(i, &flashPolicyPath))
{
if (flashEnabled)
std::cout << "Warning: cmdline enableFlash does not need passing if you pass the flash policy path.\n"sv;
flashEnabled = true;
i += 2;
continue;
}
// Flash is enabled: assume it is to be generated, or read from app directory
if (!strcasecmp(argv[i], TXT("enableFlash")))
{
// They also passed flash policy, so complain
if (!flashPolicyPath.empty())
std::cout << "Warning: cmdline "sv << argv[i] << " does not need passing if you set the policy path.\n"sv;
flashEnabled = true;
++i;
continue;
}
// If this is true, expects the server program to be run under admin privileges,
// which is necessary for ICMP raw sockets (used for UDP error replies),
// and for privileged hosting (hosting on a port number below 1024)
if (!strcasecmp(argv[i], TXT("requireAdmin")))
{
requireAdmin = true;
++i;
continue;
}
// If this is true, turns off the statistics line and the title bar updates.
// The ability to use cin for statistics, or send report messages, is still usable.
if (!strcasecmp(argv[i], TXT("noRegularOutput")))
{
regularOutputEnabled = false;
++i;
continue;
}
// Sets the TLS certificate private password; note the server does not explicitly store
// this securely, it depends on SChannel or OpenSSL's storage.
if (!strcasecmp(argv[i], TXT("certPassPhrase")))
{
if (i + 1 >= argc)
{
std::cout << "Invalid cmdline: "sv << argv[i] << " had no following value.\n"sv;
bad = true;
break;
}
wsPassPhrase = lw_u8(argv[i + 1]);
if (wsPassPhrase[0] == TXT('"'))
{
wsPassPhrase.erase(0);
wsPassPhrase.erase(wsPassPhrase.cend());
}
i += 2;
continue;
}
if (!strcasecmp(argv[i], TXT("welcomeMsg")))
{
if (i + 1 >= argc)
{
std::cout << "Invalid cmdline: "sv << argv[i] << " had no following value.\n"sv;
bad = true;
break;
}
welcomeMessage = lw_u8(argv[i + 1]);
i += 2;
continue;
}
if (!strcasecmp(argv[i], TXT("tcpClientUploadCap")) || !strcasecmp(argv[i], TXT("totalUploadCap")))
{
if (i + 1 >= argc)
{
std::cout << "Invalid cmdline: "sv << argv[i] << " had no following value.\n"sv;
bad = true;
break;
}
const std::uint32_t capBytes = static_cast<std::uint32_t>(std::strtoul(argv[i + 1], nullptr, 10));
if (capBytes < 0)
{
std::cout << "Invalid cmdline: "sv << argv[i] << " had invalid value "sv << capBytes << " bytes.\n"sv;
bad = true;
break;
}
if (!strcasecmp(argv[i], "tcpClientUploadCap"))
tcpClientUploadCap = (std::size_t)capBytes;
else
totalUploadCap = (std::size_t)capBytes;
i += 2;
continue;
}
// Give help
if (!strcasecmp(argv[i], TXT("?")) || !strcasecmp(argv[i], TXT("help")))
{
std::cout << "==== " PROJECT_NAME " "sv;
# ifdef _DEBUG
std::cout << "debug"sv;
# else // !_DEBUG
std::cout << "release"sv;
# endif // _DEBUG
std::cout << " build "sv << lacewing::relayserver::buildnum << " cmdline options ====\n"
"bluewing-cpp-server /welcomeMsg \"message\" /mainPort 6121\n"
" /enableFlash /flashPolicyPath \"path to xml\"\n"
" /wsPort 80 /wssPort 443 /certFullChainPath \"...full-chain.pem\" /certPrivKeyPath \"...privkey.pem\" /certPassPhrase \"password\"\n"
" /requireAdmin /noRegularOutput /tcpClientUploadCap bytespersec /totalUploadCap bytespersec\n"
"\n"
"Defaults if command-lines and passed, and nothing is specified:\n"
" Main port 6121. Flash and WebSocket not hosting.\n"
" To reply to invalid UDP with ICMP Unreachable, the server app must be running with admin permissions.\n"
" Cert chain will be loaded from fullchain.pem + privkey.pem files, or from tlscert.pfx, in current directory.\n"
" No password is expected, if none is provided by cmdline.\n"
" Flash will be disabled by default. If enabled, it will always host policy on port 843.\n"
" Specifying /enableFlash without /flashPolicyPath will generate a flash policy in current directory.\n"
" Admin will not be required.\n"
" Regular output is on, so a status line is maintained at end of console, and console colors/title set is used.\n"
" TCP caps will be unlimited for both single-client (tcpClientUploadCap) and all-client (totalUploadCap).\n"
" UDP cap is 4/5th of TCP cap, so that UDP will not be the cause of exceeding the client cap.\n"
" Welcome message will contain build number, and if upload caps are active, will warn about automatic bans.\n"
"====\n"sv;
bad = true;
break;
}
if (bad)
break;
std::cout << "Invalid cmdline: "sv << argv[i] << " was not recognised.\n"sv;
bad = true;
break;
}
}
if (bad)
goto cleanup;
}
// Backup current console config for restoring
#ifdef _WIN32
// GetConsoleMode fails if not console (e.g. redirected stdout to file)
isConsoleOutput = regularOutputEnabled && GetConsoleMode(hStdOut, &conOrigOutputMode);
#else // !_WIN32
// A TTY is a normal console; if this is false, not console output (e.g. redirected stdout to file)
isConsoleOutput = regularOutputEnabled && isatty(fileno(stdout));
#endif // _WIN32
if (isConsoleOutput)
{
#ifdef _WIN32
// Save the console details for restoring at end of app
GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &conOrigInputMode);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
conOrigTextAttributes = csbi.wAttributes;
GetConsoleCursorInfo(hStdOut, &conOrigCursorInfo);
#if lw_utf8_console
// Enable ANSI console commands - only supported on Windows consoles that also support UTF-8.
// Allows coloring, cursor hiding, etc, in a cross-platform way.
// For reading: https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
if (!SetConsoleMode(hStdOut, conOrigOutputMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT))
{
isConsoleOutput = false;
std::cout << "Error setting console mode: "sv << GetLastError() << '\n';
goto cleanup;
}
#endif // lw_utf8_console
// Set console icon
{
// GetConsoleWindow() and undoc'd Kernel32 func SetConsoleIcon() doesn't work in Win 11,
// presumably due to psuedoconsole.
// GetForegroundWindow() will grab any app's foreground window, not just this one.
consoleWin = GetActiveWindow();
int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
conSmallIcon = (HICON)LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_ICON1), IMAGE_ICON,
width, height, LR_LOADTRANSPARENT | LR_COLOR | LR_COPYFROMRESOURCE);
conOrigSmallIcon = (HICON)SendMessageW(consoleWin, WM_SETICON, ICON_SMALL, (LPARAM)conSmallIcon);
width = GetSystemMetrics(SM_CXICON);
height = GetSystemMetrics(SM_CYICON);
conBigIcon = (HICON)LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_ICON1), IMAGE_ICON,
width, height, LR_LOADTRANSPARENT | LR_COLOR | LR_COPYFROMRESOURCE);
conOrigBigIcon = (HICON)SendMessageW(consoleWin, WM_SETICON, ICON_BIG, (LPARAM)conBigIcon);
}
#else // !_WIN32
// We restore origTerminalSettings if isConsoleOutput is true, so it must be valid.
if (tcgetattr(STDIN_FILENO, &origTerminalSettings) != 0)
{
std::cout << red << "Failed to get terminal settings (error "sv << errno << "). Aborting server start."sv << lineEnd();
return -1;
}
#endif // _WIN32
// Same as outputting gray but without time buffer
#if lw_utf8_console
std::cout << "\033[37m";
#else // !lw_utf8_console
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif // lw_utf8_console
}
// Check for admin membership, required for ICMP raw sockets, which are used for UDP error replies
// Blue Server does not *require* ICMP replies though; it will silently ignore bad UDP (e.g. from an unrecognised IP)
{
#ifdef _WIN32
BOOL isAdmin;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
isAdmin = AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if (isAdmin)
{
if (!CheckTokenMembership(NULL, AdministratorsGroup, &isAdmin))
isAdmin = FALSE;
FreeSid(AdministratorsGroup);
}
if (!isAdmin)
{
if (requireAdmin)
{
std::cout << red << "Server is set by command-line to require admin, and is not running as admin. Server start aborted.\n"sv;
goto cleanup;
}
std::cout << red << "Warning: server is not running with admin privileges. Resetting UDP connections with ICMP will not be possible.\n"sv;
}
#else // !_WIN32
// Linux-based OSes also require net bind service permission if targeting ports below 1024.
// You can enable both of these by running server under root user, or by adding the perm:
// $ setcap 'cap_net_bind_service,cap_net_raw=+ep' /path/to/bluewing-cpp-server
// Noteably, the websocket server ports are by default port 80 and 443, flash policy 843.
// This perm check will assume admin permissions if it cannot check.
bool isAdmin = true;
#if __has_include(<sys/capabilities.h>)
const cap_t current = cap_get_proc();
if (current == NULL)
{
std::cout << red << "Warning: Failed to get process capabilities (error "sv << errno << "). Assuming raw socket + net bind capabilities are granted.\n"sv;
cap_flag_value_t on;
if (cap_get_flag(current, CAP_NET_BIND_SERVICE, CAP_PERMITTED, &on) != 0) {
std::cout << red << "Warning: Failed to check cap_net_bind_service value (error "sv << errno << "). Assuming it is granted.\n"sv;
}
isAdmin = on == 1;
if (cap_get_flag(current, CAP_NET_RAW, CAP_PERMITTED, &on) != 0) {
std::cout << red << "Warning: Failed to check cap_net_raw capability (error "sv << errno << "). Assuming it is granted.\n"sv;
}
isAdmin &= on == 1;
}
#else // __has_include 0
std::cout << red << "Warning: Server was built without libcap-dev. Checking for raw socket/port bind privileges is not possible. Assuming they are granted.\n"sv;
#endif // __has_include
if (!isAdmin)
{
if (requireAdmin)
{
std::cout << red << "Server is set by command-line to require admin, and is not running as admin. Server start aborted.\n"sv;
goto cleanup;
}
std::cout << red << "Warning: server is not running with admin privileges. Resetting UDP connections with ICMP will not be possible.\n"sv;
}
#endif // _WIN32
}
// If console output, and no cmd args were passed at all, ask user for input
if (argc <= 1)
{
if (!GetPortFromInput("main"sv, &mainPort, false, 6121) ||
!GetPortFromInput("WebSocket insecure"sv, &websocketNonSecurePort, false, 80) ||
!GetPortFromInput("WebSocket secure"sv, &websocketSecurePort, true, 443))
{
goto cleanup;
}
if (welcomeMessage.empty() && requestUserInput)
{
std::cout << userpromptcolor << "Enter a welcome message, or leave blank for the default message with server build:\n"sv;
welcomeMessage = lw_u8(GetConsoleLine());
}
}
else // Set defaults
{
if (!mainPort)
mainPort = 6121;
// Secure port passed but no cert: can we guess it? If not, hard fail
if (websocketSecurePort && wsFullChainPath.empty())
{
GuessCertPath();
if (wsFullChainPath.empty())
{
std::cout << red << "Server was passed secure port but no certificate paths.\n"sv;
goto cleanup;
}
}
}
// Block some IPs by default
//misbehavingIPList.emplace_back(MisbehavingIPEntry("127.0.0.1"sv, 4, "IP banned. Contact Phi on Clickteam Discord."sv, std::string_view(), laceclock::now() + 24h));
misbehavingIPList.emplace_back(MisbehavingIPEntry("176.59.131.111"sv, 4, "IP banned. Contact Phi on Clickteam Discord."sv, std::string_view(), laceclock::now() + 24h));
// Stop echoing std::cin keypresses to std::cout display, and disable line buffering.
// Line buffering is where std::cin will buffer until Enter, resulting in no key registering,
// including in getch().
// This is referred to on Linux as a "cooked" or "canonical" mode.
// Disabling it causes any character to be put straight into std::cin, without buffering.
// This allows various "is input pending" functions to work on single keypress.
if (isConsoleOutput)
{
#ifdef _WIN32
if (SetConsoleMode(hStdIn, conOrigInputMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT)) == FALSE)
{
std::cout << red << "Failed to set stdin to character mode (error "sv << GetLastError() << "). "
"Server may not process console input keypresses."sv << lineEnd();
}
#else // !_WIN32
struct termios curTerminalSettings = origTerminalSettings;
curTerminalSettings.c_lflag &= ~(ECHO | ICANON);
// In Linux, Ctrl-Z results in SIGTSTP signal being raised.
// It is an old design to allow single-task terminal to swap between multiple foreground programs,
// by suspending with Ctrl-Z (raising SIGTSP), and resuming with fg command (raising SIGCONT).
//
// As Bluewing is a real-time server, that's a bad idea.
// Having a SIGTSP signal handler won't stop the enclosing terminal from freezing the server
// anyway, so we instead tell terminal to disable Ctrl-Z handling and treat Ctrl-Z as a
// normal std::cin key, here.
// Ctrl-\ results in SIGQUIT, which is intended for app dump of all live data + exit.
// We prevent that as well.
curTerminalSettings.c_cc[VSUSP] =
curTerminalSettings.c_cc[VQUIT] = _POSIX_VDISABLE;
// A success return may be only partial success. Confirm all were set as we wanted.
if (tcsetattr(STDIN_FILENO, TCSANOW, &curTerminalSettings) != 0 ||
tcgetattr(STDIN_FILENO, &curTerminalSettings) != 0 ||
curTerminalSettings.c_cc[VSUSP] != _POSIX_VDISABLE ||
curTerminalSettings.c_cc[VQUIT] != _POSIX_VDISABLE ||
(curTerminalSettings.c_lflag & (ECHO | ICANON)) != 0)
{
std::cout << red << "Warning: Failed to set stdin terminal settings (error "sv << errno << "). "
"Server may malfunction if user leaves terminal or a special keybind is used."sv << lineEnd();
}
#endif // _WIN32
}
// User input is not echoed to output screen anymore, so we don't need cin and cout sync'd
std::cin.tie(nullptr);
globalpump = lacewing::eventpump_new();
globalserver = new lacewing::relayserver(globalpump);
globalmsgrecvcounttimer = lacewing::timer_new(globalpump, "global message receiving tick-over");
// Update the current time in case host() errors, or try to connect before first tick
OnTimerTick(globalmsgrecvcounttimer);