-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathsv_main.cpp
More file actions
1520 lines (1269 loc) · 39.2 KB
/
Copy pathsv_main.cpp
File metadata and controls
1520 lines (1269 loc) · 39.2 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
/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code 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 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include "common/Common.h"
#include "server.h"
#include "CryptoChallenge.h"
#include "framework/Rcon.h"
#include "common/Defs.h"
#include "framework/CommandSystem.h"
#include "framework/CvarSystem.h"
#include "framework/Network.h"
#include "qcommon/sys.h"
// These two structs have the same lifetime... both are cleared when the sgame exits
serverStatic_t svs;
server_t sv;
GameVM gvm; // game virtual machine
// Controls the gamelogic simulation time slice size. The game time always jumps in increments
// of 1000/sv_fps ms. Multiple or (for clients hosting games) no gamelogic frames may be run
// per server frame. Since timescale affects the game clock's rate, if you have sv_fps 40 and
// timescale 5, the number of gamelogic frames per wall second will be 200.
// For the dedicated server this also controls the engine frame rate. The engine framerate
// is based on real time, disregarding timescale.
Cvar::Range<Cvar::Cvar<int>> sv_fps("sv_fps", "sgame and dedicated server frame rate", Cvar::NONE, 40, 1, 1000);
Cvar::Cvar<int> sv_timeout("sv_timeout", "seconds without connectivity after which to drop a client", Cvar::NONE, 240);
Cvar::Cvar<int> sv_zombietime("sv_zombietime", "seconds without messages after which to recycle client slot", Cvar::NONE, 2);
Cvar::Cvar<std::string> sv_privatePassword("sv_privatePassword", "password guarding private server slots", Cvar::NONE, "");
Cvar::Cvar<bool> sv_allowDownload("sv_allowDownload", "let clients download missing paks", Cvar::NONE, true);
Cvar::Range<Cvar::Cvar<int>> sv_maxClients("sv_maxclients",
"max number of players on the server", Cvar::SERVERINFO, 20, 1, MAX_CLIENTS);
Cvar::Range<Cvar::Cvar<int>> sv_privateClients("sv_privateClients",
"number of password-protected client slots", Cvar::SERVERINFO, 0, 0, MAX_CLIENTS);
Cvar::Cvar<std::string> sv_hostname("sv_hostname", "server name for server list", Cvar::SERVERINFO, UNNAMED_SERVER);
Cvar::Cvar<std::string> sv_statsURL("sv_statsURL", "URL for server's gameplay statistics", Cvar::SERVERINFO, "");
Cvar::Cvar<int> sv_reconnectlimit("sv_reconnectlimit", "minimum time (seconds) before client can reconnect", Cvar::NONE, 3);
Cvar::Cvar<int> sv_padPackets("sv_padPackets", "(debugging) add n NOP bytes to each snapshot packet", Cvar::NONE, 0);
cvar_t *sv_killserver; // menu system can set to 1 to shut server down
Cvar::Cvar<std::string> sv_mapname("mapname", "current map on this server", Cvar::SERVERINFO | Cvar::ROM, "nomap");
Cvar::Cvar<int> sv_serverid("sv_serverid", "match ID", Cvar::SYSTEMINFO | Cvar::ROM, 0);
Cvar::Cvar<int> sv_maxRate("sv_maxRate", "max bytes/sec to send to a client (0 = unlimited)", Cvar::SERVERINFO, 0);
Cvar::Cvar<bool> sv_lanForceRate("sv_lanForceRate", "make LAN clients use max network rate", Cvar::NONE, true);
Cvar::Cvar<int> sv_dl_maxRate("sv_dl_maxRate", "max bytes/sec for UDP pak download", Cvar::NONE, 42000);
// fretn
Cvar::Cvar<std::string> sv_fullmsg("sv_fullmsg", "message for clients attempting to join full server", Cvar::NONE, "Server is full.");
Cvar::Range<Cvar::Cvar<int>> sv_networkScope(
"sv_networkScope",
"allowed source networks for incoming packets: 0 = loopback only, 1 = LAN, 2 = Internet",
Cvar::NONE,
#ifdef BUILD_SERVER
2,
#else
1,
#endif
0, 2);
// Network stuff other than communication with connected clients
Log::Logger netLog("server.net", "", Log::Level::NOTICE);
namespace Cvar {
template<>
std::string GetCvarTypeName<ServerPrivate>()
{
return "server private";
}
} // namespace Cvar
bool ParseCvarValue(Str::StringRef value, ServerPrivate& result)
{
int intermediate = 0;
if ( Str::ParseInt(intermediate, value) &&
intermediate >= int(ServerPrivate::Public) &&
intermediate <= int(ServerPrivate::NoStatus) )
{
result = ServerPrivate(intermediate);
return true;
}
return false;
}
std::string SerializeCvarValue(ServerPrivate value)
{
return std::to_string(int(value));
}
Cvar::Cvar<ServerPrivate> isPrivate(
"server.private",
"Controls how much the server advertises: "
"0 - Advertise everything, "
"1 - Don't advertise but reply to status queries, "
"2 - Only accept direct connections. ",
Cvar::NONE,
#if BUILD_GRAPHICAL_CLIENT || BUILD_TTY_CLIENT
ServerPrivate::NoAdvertise
#elif BUILD_SERVER
ServerPrivate::Public
#else
#error
#endif
);
bool SV_Private(ServerPrivate level)
{
return isPrivate.Get() >= level;
}
/*
=============================================================================
EVENT MESSAGES
=============================================================================
*/
/*
======================
SV_AddServerCommand
The given command will be transmitted to the client, and is guaranteed to
not have future snapshot_t executed before it is executed
======================
*/
void SV_AddServerCommand( client_t *client, const char *cmd )
{
int index, i;
client->reliableSequence++;
// if we would be losing an old command that hasn't been acknowledged,
// we must drop the connection
// we check == instead of >= so a broadcast print added by SV_DropClient()
// doesn't cause a recursive drop client
if ( client->reliableSequence - client->reliableAcknowledge == MAX_RELIABLE_COMMANDS + 1 )
{
Log::Debug("===== pending server commands =====");
for ( i = client->reliableAcknowledge + 1; i <= client->reliableSequence; i++ )
{
Log::Debug( "cmd %5d: %s", i, client->reliableCommands[ i & ( MAX_RELIABLE_COMMANDS - 1 ) ] );
}
Log::Debug( "cmd %5d: %s", i, cmd );
SV_DropClient( client, "Server command overflow" );
return;
}
index = client->reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) );
}
/*
=================
SV_SendServerCommand
Sends a reliable command string to be interpreted by
the client game module: "cp", "print", "chat", etc
A nullptr client will broadcast to all clients
=================
*/
void PRINTF_LIKE(2) SV_SendServerCommand( client_t *cl, const char *fmt, ... )
{
va_list argptr;
byte message[ MAX_MSGLEN ];
client_t *client;
int j;
va_start( argptr, fmt );
Q_vsnprintf( ( char * ) message, sizeof( message ), fmt, argptr );
va_end( argptr );
// do not forward server command messages that would be too big to clients
// ( q3infoboom / q3msgboom stuff )
if ( strlen( ( char * ) message ) > 1022 )
{
Log::Warn( "^1Not sending reliable command because it is too long! [%.50s...]", message );
return;
}
if ( cl != nullptr )
{
SV_AddServerCommand( cl, ( char * ) message );
return;
}
if ( Com_IsDedicatedServer() )
{
if ( !strncmp( ( char * ) message, "print_tr_p ", 11 ) )
{
SV_PrintTranslatedText( ( const char * ) message, true, true );
}
else if ( !strncmp( ( char * ) message, "print_tr ", 9 ) )
{
SV_PrintTranslatedText( ( const char * ) message, true, false );
}
// hack to echo broadcast prints to console
else if ( !strncmp( ( char * ) message, "print ", 6 ) )
{
// Don't use "Broadcast: %s" as this format string is too unspecific for log suppression
Log::Notice( std::string("Broadcast: ") + Cmd_UnquoteString( ( const char * ) message + 6 ) );
}
}
// send the data to all relevent clients
for ( j = 0, client = svs.clients; j < sv_maxClients.Get(); j++, client++ )
{
if ( client->state < clientState_t::CS_PRIMED )
{
continue;
}
// Ridah, don't need to send messages to AI
if ( SV_IsBot(client) )
{
continue;
}
// done.
SV_AddServerCommand( client, ( char * ) message );
}
}
/*
==============================================================================
MASTER SERVER FUNCTIONS
==============================================================================
*/
namespace {
struct MasterServer;
extern MasterServer masterServers[MAX_MASTER_SERVERS];
struct MasterServer
{
Net::DNSQueryHandle query = 0;
int nextHeartbeatTime = 0;
std::string challenge;
netadrtype_t challenge_address_type;
Cvar::Modified<Cvar::Cvar<std::string>> addressCvar;
MasterServer(const char* cvarName, const char* defaultHostname)
: addressCvar(cvarName, "address of a master server", Cvar::NONE, defaultHostname )
{}
};
MasterServer masterServers[MAX_MASTER_SERVERS] = {
{"sv_master1", MASTER1_SERVER_NAME},
{"sv_master2", MASTER2_SERVER_NAME},
{"sv_master3", MASTER3_SERVER_NAME},
{"sv_master4", MASTER4_SERVER_NAME},
{"sv_master5", MASTER5_SERVER_NAME},
};
} // namespace
// Enqueue queries for the DNS resolution thread
static void SV_ResolveMasterServers( int netMask )
{
static int oldNetMask = 0;
for ( MasterServer& master : masterServers )
{
Util::optional<std::string> address = master.addressCvar.GetModifiedValue();
if ( !address )
{
if ( netMask == oldNetMask )
{
continue; // Continue if nothing changed
}
address = master.addressCvar.Get();
}
// Something changed, reset the heartbeat timer
master.nextHeartbeatTime = 0;
if ( netMask != 0 && !address->empty() )
{
if ( master.query == 0 )
{
master.query = Net::AllocDNSQuery();
}
Net::SetDNSQuery( master.query, *address, netMask );
}
else
{
if ( master.query != 0 )
{
Net::SetDNSQuery( master.query, "", 0 );
}
}
}
oldNetMask = netMask;
}
/*
================
SV_NET_Config
Network connections being reconfigured. May need to redo some lookups.
================
*/
void SV_NET_Config()
{
SV_ResolveMasterServers( 0 );
}
/*
================
SV_MasterHeartbeat
Send a message to the masters every few minutes to
let it know we are alive, and log information.
We will also have a heartbeat sent when a server
changes from empty to non-empty, and full to non-full,
but not on every player enter or exit.
================
*/
static const int HEARTBEAT_MSEC = (300 * 1000);
#define HEARTBEAT_GAME PRODUCT_NAME
#define HEARTBEAT_DEAD PRODUCT_NAME "-dead"
void SV_MasterHeartbeat( const char *hbname )
{
int netenabled = Cvar_VariableIntegerValue( "net_enabled" );
if ( SV_Private(ServerPrivate::NoAdvertise) )
{
SV_ResolveMasterServers( 0 );
return; // only dedicated servers send heartbeats
}
else if ( sv_networkScope.Get() < 2 )
{
if ( !svs.warnedNetworkScopeNotAdvertisable )
{
netLog.Warn( "Not sending master heartbeat because sv_networkScope is local" );
svs.warnedNetworkScopeNotAdvertisable = true;
}
SV_ResolveMasterServers( 0 );
return;
}
SV_ResolveMasterServers( netenabled );
// send to group masters
for ( MasterServer& master : masterServers )
{
if (svs.time < master.nextHeartbeatTime) {
continue;
}
Net::DNSResult adrs = Net::GetAddresses(master.query);
if (adrs.ipv4.type == netadrtype_t::NA_BAD && adrs.ipv6.type == netadrtype_t::NA_BAD)
{
continue;
}
master.nextHeartbeatTime = svs.time + HEARTBEAT_MSEC;
if ( adrs.ipv4.type != netadrtype_t::NA_BAD )
{
if (adrs.ipv4.port == 0) {
adrs.ipv4.port = UBigShort( PORT_MASTER );
}
netLog.Notice( "Sending heartbeat (IPv4) to %s", master.addressCvar.Get() );
// this command should be changed if the server info / status format
// ever incompatibly changes
Net::OutOfBandPrint( netsrc_t::NS_SERVER, adrs.ipv4, "heartbeat %s\n", hbname );
}
if ( adrs.ipv6.type != netadrtype_t::NA_BAD )
{
if (adrs.ipv6.port == 0) {
adrs.ipv6.port = UBigShort( PORT_MASTER );
}
netLog.Notice( "Sending heartbeat (IPv6) to %s", master.addressCvar.Get() );
// this command should be changed if the server info / status format
// ever incompatibly changes
Net::OutOfBandPrint( netsrc_t::NS_SERVER, adrs.ipv6, "heartbeat %s\n", hbname );
}
}
}
// Also called by SV_DropClient, SV_DirectConnect, and SV_SpawnServer
void SV_Heartbeat_f()
{
for (MasterServer& master : masterServers)
{
master.nextHeartbeatTime = 0;
}
}
/*
=================
SV_MasterShutdown
Informs all masters that this server is going down
=================
*/
void SV_MasterShutdown()
{
// send a heartbeat right now
SV_Heartbeat_f();
SV_MasterHeartbeat( HEARTBEAT_DEAD ); // NERVE - SMF - changed to flatline
// send it again to minimize chance of drops
// SV_Heartbeat_f();
// SV_MasterHeartbeat( HEARTBEAT_DEAD );
// when the master tries to poll the server, it won't respond, so
// it will be removed from the list
}
/*
==============================================================================
CONNECTIONLESS COMMANDS
==============================================================================
*/
/*
================
SVC_Status
Responds with all the info that qplug or qspy can see about the server
and all connected players. Used for getting detailed information after
the simple info query.
================
*/
static void SVC_Status( const netadr_t& from, const Cmd::Args& args )
{
if ( SV_Private(ServerPrivate::NoStatus) )
{
return;
}
InfoMap info_map;
Cvar::PopulateInfoMap(CVAR_SERVERINFO, info_map);
if ( args.Argc() > 1 && InfoValidItem(args.Argv(1)) )
{
// echo back the parameter to status. so master servers can use it as a challenge
// to prevent timed spoofed reply packets that add ghost servers
info_map["challenge"] = args.Argv(1);
}
std::string status;
for ( int i = 0; i < sv_maxClients.Get(); i++ )
{
client_t* cl = &svs.clients[ i ];
if ( cl->state >= clientState_t::CS_CONNECTED )
{
const OpaquePlayerState* ps = SV_GameClientNum( i );
status += Str::Format( "%i %i \"%s\"\n", ps->persistant[ PERS_SCORE ], cl->ping, cl->name );
}
}
Net::OutOfBandPrint( netsrc_t::NS_SERVER, from, "statusResponse\n%s\n%s",
InfoMapToString( info_map ), status );
}
/*
================
SVC_Info
Responds with a short info message that should be enough to determine
if a user is interested in a server to do a full status
================
*/
static void SVC_Info( const netadr_t& from, const Cmd::Args& args )
{
if ( SV_Private(ServerPrivate::NoStatus) || !com_sv_running.Get() )
{
return;
}
int bots = 0; // Bots always use public slots.
int publicSlotHumans = 0;
int privateSlotHumans = 0;
for ( int i = 0; i < sv_maxClients.Get(); i++ )
{
if ( svs.clients[ i ].state >= clientState_t::CS_CONNECTED )
{
if (i < sv_privateClients.Get())
{
++privateSlotHumans;
}
else if ( SV_IsBot(&svs.clients[ i ]) )
{
++bots;
}
else
{
++publicSlotHumans;
}
}
}
InfoMap info_map;
if ( args.Argc() > 1 && InfoValidItem(args.Argv(1)) )
{
std::string challenge = args.Argv(1);
// echo back the parameter to status. so master servers can use it as a challenge
// to prevent timed spoofed reply packets that add ghost servers
info_map["challenge"] = challenge;
// If the master server listens on IPv4 and IPv6, we want to send the
// most recent challenge received from it over the OTHER protocol
for ( MasterServer& master : masterServers )
{
// First, see if the challenge was sent by this master server
Net::DNSResult adrs = Net::GetAddresses( master.query );
if ( !NET_CompareBaseAdr( from, adrs.ipv4 ) && !NET_CompareBaseAdr( from, adrs.ipv6 ) )
{
continue;
}
// It was - if the saved challenge is for the other protocol, send it and record the current one
if ( master.challenge_address_type == netadrtype_t::NA_IP ||
master.challenge_address_type == netadrtype_t::NA_IP6 )
{
if ( master.challenge_address_type != from.type )
{
info_map["challenge2"] = master.challenge;
master.challenge_address_type = from.type;
master.challenge = challenge;
break;
}
}
// Otherwise record the current one regardless and check the next server
master.challenge_address_type = from.type;
master.challenge = challenge;
}
}
info_map["protocol"] = std::to_string( PROTOCOL_VERSION );
info_map["hostname"] = sv_hostname.Get();
info_map["serverload"] = std::to_string( svs.serverLoad );
info_map["mapname"] = sv_mapname.Get();
info_map["clients"] = std::to_string( publicSlotHumans + privateSlotHumans );
info_map["bots"] = std::to_string( bots );
// Satisfies (number of open public slots) = (displayed max clients) - (number of clients).
info_map["sv_maxclients"] = std::to_string(
std::max( 0, sv_maxClients.Get() - sv_privateClients.Get() ) + privateSlotHumans );
if ( !sv_statsURL.Get().empty() )
{
info_map["stats"] = sv_statsURL.Get().c_str();
}
info_map["gamename"] = GAMENAME_STRING; // Arnout: to be able to filter out Quake servers
info_map["abi"] = IPC::AbiVersion();
Net::OutOfBandPrint( netsrc_t::NS_SERVER, from, "infoResponse\n%s", InfoMapToString( info_map ) );
}
/*
* Sends back a simple reply
* Used to check if the server is online without sending any other info
*/
static void SVC_Ping( const netadr_t& from, const Cmd::Args& )
{
if ( SV_Private(ServerPrivate::NoStatus) )
{
return;
}
Net::OutOfBandPrint( netsrc_t::NS_SERVER, from, "ack\n" );
}
/*
=================
SV_CheckDRDoS
DRDoS stands for "Distributed Reflected Denial of Service".
See here: http://www.lemuria.org/security/application-drdos.html
Returns false if we're good. true return value means we need to block.
If the address isn't NA_IP, it's automatically denied.
=================
*/
bool SV_CheckDRDoS( netadr_t from )
{
int i;
int globalCount;
int specificCount;
receipt_t *receipt;
netadr_t exactFrom;
int oldest;
int oldestTime;
static int lastGlobalLogTime = 0;
static int lastSpecificLogTime = 0;
// Usually the network is smart enough to not allow incoming UDP packets
// with a source address being a spoofed LAN address. Even if that's not
// the case, sending packets to other hosts in the LAN is not a big deal.
// NA_LOOPBACK qualifies as a LAN address.
if ( Sys_IsLANAddress( from ) ) { return false; }
exactFrom = from;
if ( from.type == netadrtype_t::NA_IP )
{
from.ip[ 3 ] = 0; // xx.xx.xx.0
}
else if ( from.type == netadrtype_t::NA_IP6 )
{
memset( from.ip6 + 7, 0, 9 ); // mask to /56
}
else
{
// So we got a connectionless packet but it's not IPv4, so
// what is it? I don't care, it doesn't matter, we'll just block it.
// This probably won't even happen.
return true;
}
// Count receipts in last 2 seconds.
globalCount = 0;
specificCount = 0;
receipt = &svs.infoReceipts[ 0 ];
oldest = 0;
oldestTime = 0x7fffffff;
for ( i = 0; i < MAX_INFO_RECEIPTS; i++, receipt++ )
{
if ( receipt->time + 2000 > svs.time )
{
if ( receipt->time )
{
// When the server starts, all receipt times are at zero. Furthermore,
// svs.time is close to zero. We check that the receipt time is already
// set so that during the first two seconds after server starts, queries
// from the master servers don't get ignored. As a consequence a potentially
// unlimited number of getinfo+getstatus responses may be sent during the
// first frame of a server's life.
globalCount++;
}
if ( NET_CompareBaseAdr( from, receipt->adr ) )
{
specificCount++;
}
}
if ( receipt->time < oldestTime )
{
oldestTime = receipt->time;
oldest = i;
}
}
if ( globalCount == MAX_INFO_RECEIPTS ) // All receipts happened in last 2 seconds.
{
if ( lastGlobalLogTime + 1000 <= svs.time ) // Limit one log every second.
{
netLog.Notice( "Detected flood of getinfo/getstatus connectionless packets" );
lastGlobalLogTime = svs.time;
}
return true;
}
if ( specificCount >= 5 ) // Already sent 5 to this IP address in last 2 seconds.
{
if ( lastSpecificLogTime + 1000 <= svs.time ) // Limit one log every second.
{
netLog.Notice( "Possible DRDoS attack to address %i.%i.%i.%i, ignoring getinfo/getstatus connectionless packet",
exactFrom.ip[ 0 ], exactFrom.ip[ 1 ], exactFrom.ip[ 2 ], exactFrom.ip[ 3 ] );
lastSpecificLogTime = svs.time;
}
return true;
}
receipt = &svs.infoReceipts[ oldest ];
receipt->adr = from;
receipt->time = svs.time;
return false;
}
/*
===============
SVC_RemoteCommand
An rcon packet arrived from the network.
Shift down the remaining args
Redirect all printfs
===============
*/
class RconEnvironment: public Cmd::DefaultEnvironment {
public:
RconEnvironment(const netadr_t& from)
: from(from), bufferSize(MAX_MSGLEN - prefix.size() - 1)
{}
virtual void Print(Str::StringRef text) override
{
if (text.size() + buffer.size() > bufferSize - 1)
{
Flush();
}
buffer += text;
buffer += '\n';
}
void Flush()
{
if ( !buffer.empty() )
{
Net::OutOfBandPrint(netsrc_t::NS_SERVER, from, "%s\n%s", prefix, buffer);
buffer.clear();
}
}
static void PrintError(const netadr_t& to, const std::string& message)
{
Net::OutOfBandPrint(netsrc_t::NS_SERVER, to, "error\n%s", message);
}
private:
const netadr_t from;
std::string buffer;
const std::string prefix = "print";
const std::size_t bufferSize;
};
static Cvar::Cvar<std::string> cvar_rcon_server_password(
"rcon.server.password",
"Password used to protect the remote console",
Cvar::NONE,
""
);
static Cvar::Range<Cvar::Cvar<int>> cvar_rcon_server_secure(
"rcon.server.secure",
"How secure the Rcon protocol should be: "
"0: Allow unencrypted rcon, "
"1: Require encryption, "
"2: Require encryption and challenge check",
Cvar::NONE,
0,
0,
2
);
/*
* Checks whether the message is acceptable by the server,
* it must be valid and match the rcon settings and challenges.
*/
static bool RconAcceptable(const Rcon::Message& msg, std::string *invalid_reason = nullptr)
{
auto invalid = [invalid_reason](const char* reason)
{
if ( invalid_reason )
*invalid_reason = reason;
return false;
};
if ( !msg.Valid(invalid_reason) )
{
return false;
}
if ( msg.secure < Rcon::Secure(cvar_rcon_server_secure.Get()) )
{
return invalid("Weak security");
}
if ( cvar_rcon_server_password.Get().empty() )
{
return invalid("No rcon.server.password set on the server.");
}
if ( msg.password != cvar_rcon_server_password.Get() )
{
return invalid("Bad password");
}
if ( msg.secure == Rcon::Secure::EncryptedChallenge )
{
if ( !ChallengeManager::MatchString(msg.remote, msg.challenge) )
{
return invalid("Mismatched challenge");
}
}
return true;
}
/*
* Decodes the arguments of an out of band message received by the server
*/
static Rcon::Message RconDecode(const netadr_t& remote, const Cmd::Args& args)
{
if ( args.size() < 3 || (args[0] != "rcon" && args[0] != "srcon") )
{
return Rcon::Message("Invalid command");
}
if ( cvar_rcon_server_password.Get().empty() )
{
return Rcon::Message("rcon.server.password not set");
}
if ( args[0] == "rcon" )
{
return Rcon::Message(remote, args.EscapedArgs(2), Rcon::Secure::Unencrypted, args[1]);
}
auto authentication = args[1];
Crypto::Data cyphertext = Crypto::FromString(args[2]);
Crypto::Data data;
if ( !Crypto::Encoding::Base64Decode( cyphertext, data ) )
{
return Rcon::Message("Invalid Base64 string");
}
Crypto::Data key = Crypto::Hash::Sha256( Crypto::FromString( cvar_rcon_server_password.Get() ) );
if ( !Crypto::Aes256Decrypt( data, key, data ) )
{
return Rcon::Message("Error during decryption");
}
std::string command = Crypto::ToString( data );
if ( authentication == "CHALLENGE" )
{
std::istringstream stream( command );
std::string challenge_hex;
stream >> challenge_hex;
while ( Str::cisspace( stream.peek() ) )
{
stream.ignore();
}
std::getline( stream, command );
return Rcon::Message(remote, command, Rcon::Secure::EncryptedChallenge,
cvar_rcon_server_password.Get(), challenge_hex);
}
else if ( authentication == "PLAIN" )
{
return Rcon::Message(remote, command, Rcon::Secure::EncryptedPlain,
cvar_rcon_server_password.Get());
}
else
{
return Rcon::Message(remote, command, Rcon::Secure::Invalid,
cvar_rcon_server_password.Get());
}
}
static int RemoteCommandThrottle()
{
static int lasttime = 0;
int time = Com_Milliseconds();
int delta = time - lasttime;
lasttime = time;
return delta;
}
static void SVC_RemoteCommand( const netadr_t& from, const Cmd::Args& args )
{
int throttle_delta = RemoteCommandThrottle();
if ( throttle_delta < 180 )
{
return;
}
Rcon::Message message = RconDecode(from, args);
std::string invalid_reason;
if ( !RconAcceptable(message, &invalid_reason) )
{
// If the rconpassword is bad and one just happened recently, don't spam the log file, just die.
if ( throttle_delta < 600 )
{
return;
}
netLog.Notice( "Bad rcon from %s:\n%s\n%s",
Net::AddressToString( from ),
invalid_reason.c_str(),
args.ConcatArgs(2).c_str() );
if ( !SV_Private(ServerPrivate::NoStatus) )
{
RconEnvironment::PrintError( from, invalid_reason );
}
}
else
{
netLog.Notice( "Rcon from %s:\n%s", Net::AddressToString( from ), message.command.c_str() );
// start redirecting all print outputs to the packet
auto env = RconEnvironment(from);
Cmd::ExecuteCommand(message.command, true, &env);
Cmd::ExecuteCommandBuffer();
env.Flush();
}
}
static void SVC_RconInfo( const netadr_t& from, const Cmd::Args& )
{
if ( SV_Private(ServerPrivate::NoStatus) )
{
return;
}
int duration_seconds = std::chrono::duration_cast<std::chrono::seconds>(Challenge::Timeout()).count();
std::string rcon_info_string = InfoMapToString({
{"secure", std::to_string(cvar_rcon_server_secure.Get())},
{"encryption", "AES256"},
{"key", "SHA256"},
{"challenge", std::to_string(cvar_rcon_server_secure.Get() >= 2)},
{"timeout", std::to_string(duration_seconds)},
});
Net::OutOfBandPrint( netsrc_t::NS_SERVER, from, "rconInfoResponse\n%s\n", rcon_info_string );
}
/*
=================
SV_ConnectionlessPacket
A connectionless packet has four leading 0xff
characters to distinguish it from a game channel.
Clients that are in the game can still send
connectionless packets.
=================
*/
static void SV_ConnectionlessPacket( const netadr_t& from, msg_t *msg )
{
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1 marker
if ( !Q_strncmp( "connect", ( char * ) &msg->data[ 4 ], 7 ) )
{
Huff_Decompress( msg, 12 );
}
Cmd::Args args(MSG_ReadStringLine( msg ));