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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
|
/*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP 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.
RTCW SP 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 RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP 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 RTCW SP 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 "server.h"
#ifdef USE_VOIP
cvar_t *sv_voip;
cvar_t *sv_voipProtocol;
#endif
serverStatic_t svs; // persistant server info
server_t sv; // local server
vm_t *gvm = NULL; // game virtual machine
cvar_t *sv_fps = NULL; // time rate for running non-clients
cvar_t *sv_timeout; // seconds without any message
cvar_t *sv_zombietime; // seconds to sink messages after disconnect
cvar_t *sv_rconPassword; // password for remote server commands
cvar_t *sv_privatePassword; // password for the privateClient slots
cvar_t *sv_allowDownload;
cvar_t *sv_maxclients;
cvar_t *sv_privateClients; // number of clients reserved for password
cvar_t *sv_hostname;
cvar_t *sv_master[MAX_MASTER_SERVERS]; // master server ip address
cvar_t *sv_reconnectlimit; // minimum seconds between connect messages
cvar_t *sv_showloss; // report when usercmds are lost
cvar_t *sv_padPackets; // add nop bytes to messages
cvar_t *sv_killserver; // menu system can set to 1 to shut server down
cvar_t *sv_mapname;
cvar_t *sv_mapChecksum;
cvar_t *sv_serverid;
cvar_t *sv_minRate;
cvar_t *sv_maxRate;
cvar_t *sv_dlRate;
cvar_t *sv_minPing;
cvar_t *sv_maxPing;
cvar_t *sv_gametype;
cvar_t *sv_pure;
cvar_t *sv_floodProtect;
cvar_t *sv_lanForceRate; // dedicated 1 (LAN) server forces local client rates to 99999 (bug #491)
cvar_t *sv_allowAnonymous;
cvar_t *sv_banFile;
serverBan_t serverBans[SERVER_MAXBANS];
int serverBansCount = 0;
// Rafael gameskill
cvar_t *sv_gameskill;
// done
cvar_t *sv_reloading; //----(SA) added
/*
=============================================================================
EVENT MESSAGES
=============================================================================
*/
/*
===============
SV_ExpandNewlines
Converts newlines to "\n" so a line prints nicer
===============
*/
static char *SV_ExpandNewlines( char *in ) {
static char string[1024];
int l;
l = 0;
while ( *in && l < sizeof( string ) - 3 ) {
if ( *in == '\n' ) {
string[l++] = '\\';
string[l++] = 'n';
} else {
string[l++] = *in;
}
in++;
}
string[l] = 0;
return string;
}
/*
======================
SV_ReplacePendingServerCommands
FIXME: This is ugly
======================
*/
#if 0 // RF, not used anymore
static int SV_ReplacePendingServerCommands( client_t *client, const char *cmd ) {
int i, index, csnum1, csnum2;
for ( i = client->reliableSent + 1; i <= client->reliableSequence; i++ ) {
index = i & ( MAX_RELIABLE_COMMANDS - 1 );
//
//if ( !Q_strncmp(cmd, client->reliableCommands[ index ], strlen("cs")) ) {
if ( !Q_strncmp( cmd, SV_GetReliableCommand( client, index ), strlen( "cs" ) ) ) {
sscanf( cmd, "cs %i", &csnum1 );
//sscanf(client->reliableCommands[ index ], "cs %i", &csnum2);
sscanf( SV_GetReliableCommand( client, index ), "cs %i", &csnum2 );
if ( csnum1 == csnum2 ) {
//Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) );
/*
if ( client->netchan.remoteAddress.type != NA_BOT ) {
Com_Printf( "WARNING: client %i removed double pending config string %i: %s\n", client-svs.clients, csnum1, cmd );
}
*/
return qtrue;
}
}
}
return qfalse;
}
#endif
/*
======================
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;
// do not send commands until the gamestate has been sent
if( client->state < CS_PRIMED )
return;
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 ) {
Com_Printf( "===== pending server commands =====\n" );
for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
//Com_Printf( "cmd %5d: %s\n", i, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
Com_Printf( "cmd %5d: %s\n", i, SV_GetReliableCommand( client, i & ( MAX_RELIABLE_COMMANDS - 1 ) ) );
}
Com_Printf( "cmd %5d: %s\n", 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_AddReliableCommand( client, index, cmd );
}
/*
=================
SV_SendServerCommand
Sends a reliable command string to be interpreted by
the client game module: "cp", "print", "chat", etc
A NULL client will broadcast to all clients
=================
*/
void QDECL 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 );
// Fix to http://aluigi.altervista.org/adv/q3msgboom-adv.txt
// The actual cause of the bug is probably further downstream
// and should maybe be addressed later, but this certainly
// fixes the problem for now
if ( strlen ((char *)message) > 1022 ) {
return;
}
if ( cl != NULL ) {
SV_AddServerCommand( cl, (char *)message );
return;
}
// hack to echo broadcast prints to console
if ( com_dedicated->integer && !strncmp( (char *)message, "print", 5 ) ) {
Com_Printf( "broadcast: %s\n", SV_ExpandNewlines( (char *)message ) );
}
// send the data to all relevent clients
for ( j = 0, client = svs.clients; j < sv_maxclients->integer ; j++, client++ ) {
// Ridah, don't need to send messages to AI
if ( client->gentity && client->gentity->r.svFlags & SVF_CASTAI ) {
continue;
}
// done.
SV_AddServerCommand( client, (char *)message );
}
}
/*
==============================================================================
MASTER SERVER FUNCTIONS
==============================================================================
*/
/*
================
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.
================
*/
#define HEARTBEAT_MSEC 300 * 1000
#define MASTERDNS_MSEC 24 * 60 * 60 * 1000
void SV_MasterHeartbeat(const char *message)
{
static netadr_t adr[MAX_MASTER_SERVERS][2]; // [2] for v4 and v6 address for the same address string.
int i;
int res;
int netenabled;
static qboolean firstRes = qtrue;
netenabled = Cvar_VariableIntegerValue("net_enabled");
// "dedicated 1" is for lan play, "dedicated 2" is for inet public play
if (!com_dedicated || com_dedicated->integer != 2 || !(netenabled & (NET_ENABLEV4 | NET_ENABLEV6)))
return; // only dedicated servers send heartbeats
// if not time yet, don't send anything
if ( svs.time < svs.nextHeartbeatTime )
return;
if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
message = LEGACY_HEARTBEAT_FOR_MASTER;
svs.nextHeartbeatTime = svs.time + HEARTBEAT_MSEC;
// send to group masters
for (i = 0; i < MAX_MASTER_SERVERS; i++)
{
if(!sv_master[i]->string[0])
continue;
// if server resolves on first attempt, attempt resolution on subsequent heartbeats
// if server does not resolve on first attempt, do not attempt another dns lookup for 24 hours
if(sv_master[i]->modified || svs.time > svs.masterResolveTime[i])
{
sv_master[i]->modified = qfalse;
if(svs.time > svs.masterResolveTime[i])
{
svs.masterResolveTime[i] = svs.time + MASTERDNS_MSEC;
firstRes = qtrue;
}
if(netenabled & NET_ENABLEV4)
{
if(firstRes || adr[i][0].type != NA_BAD) {
Com_Printf("Resolving %s (IPv4)\n", sv_master[i]->string);
res = NET_StringToAdr(sv_master[i]->string, &adr[i][0], NA_IP);
if(res == 2)
{
// if no port was specified, use the default master port
adr[i][0].port = BigShort(PORT_MASTER);
}
if(res) {
Com_Printf( "%s resolved to %s\n", sv_master[i]->string, NET_AdrToStringwPort(adr[i][0]));
if(adr[i][0].type != NA_BAD) {
Com_Printf ("Sending heartbeat to %s (IPv4)\n", sv_master[i]->string );
NET_OutOfBandPrint( NS_SERVER, adr[i][0], "heartbeat %s\n", message);
}
sv_master[i]->modified = qtrue;
} else {
Com_Printf( "%s has no IPv4 address.\n", sv_master[i]->string);
}
}
}
if(netenabled & NET_ENABLEV6)
{
if(firstRes || adr[i][1].type != NA_BAD) {
Com_Printf("Resolving %s (IPv6)\n", sv_master[i]->string);
res = NET_StringToAdr(sv_master[i]->string, &adr[i][1], NA_IP6);
if(res == 2)
{
// if no port was specified, use the default master port
adr[i][1].port = BigShort(PORT_MASTER);
}
if(res) {
Com_Printf( "%s resolved to %s\n", sv_master[i]->string, NET_AdrToStringwPort(adr[i][1]));
if(adr[i][1].type != NA_BAD) {
Com_Printf ("Sending heartbeat to %s (IPv6)\n", sv_master[i]->string );
NET_OutOfBandPrint( NS_SERVER, adr[i][1], "heartbeat %s\n", message);
}
sv_master[i]->modified = qtrue;
} else {
Com_Printf( "%s has no IPv6 address.\n", sv_master[i]->string);
}
}
}
if(adr[i][0].type == NA_BAD && adr[i][1].type == NA_BAD)
{
Com_Printf("Couldn't resolve address: %s\n", sv_master[i]->string);
continue;
}
}
}
firstRes = qfalse;
}
/*
=================
SV_MasterShutdown
Informs all masters that this server is going down
=================
*/
void SV_MasterShutdown( void ) {
// send a heartbeat right now
svs.nextHeartbeatTime = -9999;
SV_MasterHeartbeat(FLATLINE_FOR_MASTER);
// send it again to minimize chance of drops
// svs.nextHeartbeatTime = -9999;
// SV_MasterHeartbeat(FLATLINE_FOR_MASTER);
// when the master tries to poll the server, it won't respond, so
// it will be removed from the list
}
/*
==============================================================================
CONNECTIONLESS COMMANDS
==============================================================================
*/
// This is deliberately quite large to make it more of an effort to DoS
#define MAX_BUCKETS 16384
#define MAX_HASHES 1024
static leakyBucket_t buckets[ MAX_BUCKETS ];
static leakyBucket_t *bucketHashes[ MAX_HASHES ];
leakyBucket_t outboundLeakyBucket;
/*
================
SVC_HashForAddress
================
*/
static long SVC_HashForAddress( netadr_t address ) {
byte *ip = NULL;
size_t size = 0;
int i;
long hash = 0;
switch ( address.type ) {
case NA_IP: ip = address.ip; size = 4; break;
case NA_IP6: ip = address.ip6; size = 16; break;
default: break;
}
for ( i = 0; i < size; i++ ) {
hash += (long)( ip[ i ] ) * ( i + 119 );
}
hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
hash &= ( MAX_HASHES - 1 );
return hash;
}
/*
================
SVC_BucketForAddress
Find or allocate a bucket for an address
================
*/
static leakyBucket_t *SVC_BucketForAddress( netadr_t address, int burst, int period ) {
leakyBucket_t *bucket = NULL;
int i;
long hash = SVC_HashForAddress( address );
int now = Sys_Milliseconds();
for ( bucket = bucketHashes[ hash ]; bucket; bucket = bucket->next ) {
switch ( bucket->type ) {
case NA_IP:
if ( memcmp( bucket->ipv._4, address.ip, 4 ) == 0 ) {
return bucket;
}
break;
case NA_IP6:
if ( memcmp( bucket->ipv._6, address.ip6, 16 ) == 0 ) {
return bucket;
}
break;
default:
break;
}
}
for ( i = 0; i < MAX_BUCKETS; i++ ) {
int interval;
bucket = &buckets[ i ];
interval = now - bucket->lastTime;
// Reclaim expired buckets
if ( bucket->lastTime > 0 && ( interval > ( burst * period ) ||
interval < 0 ) ) {
if ( bucket->prev != NULL ) {
bucket->prev->next = bucket->next;
} else {
bucketHashes[ bucket->hash ] = bucket->next;
}
if ( bucket->next != NULL ) {
bucket->next->prev = bucket->prev;
}
Com_Memset( bucket, 0, sizeof( leakyBucket_t ) );
}
if ( bucket->type == NA_BAD ) {
bucket->type = address.type;
switch ( address.type ) {
case NA_IP: Com_Memcpy( bucket->ipv._4, address.ip, 4 ); break;
case NA_IP6: Com_Memcpy( bucket->ipv._6, address.ip6, 16 ); break;
default: break;
}
bucket->lastTime = now;
bucket->burst = 0;
bucket->hash = hash;
// Add to the head of the relevant hash chain
bucket->next = bucketHashes[ hash ];
if ( bucketHashes[ hash ] != NULL ) {
bucketHashes[ hash ]->prev = bucket;
}
bucket->prev = NULL;
bucketHashes[ hash ] = bucket;
return bucket;
}
}
// Couldn't allocate a bucket for this address
return NULL;
}
/*
================
SVC_RateLimit
================
*/
qboolean SVC_RateLimit( leakyBucket_t *bucket, int burst, int period ) {
if ( bucket != NULL ) {
int now = Sys_Milliseconds();
int interval = now - bucket->lastTime;
int expired = interval / period;
int expiredRemainder = interval % period;
if ( expired > bucket->burst || interval < 0 ) {
bucket->burst = 0;
bucket->lastTime = now;
} else {
bucket->burst -= expired;
bucket->lastTime = now - expiredRemainder;
}
if ( bucket->burst < burst ) {
bucket->burst++;
return qfalse;
}
}
return qtrue;
}
/*
================
SVC_RateLimitAddress
Rate limit for a particular address
================
*/
qboolean SVC_RateLimitAddress( netadr_t from, int burst, int period ) {
leakyBucket_t *bucket = SVC_BucketForAddress( from, burst, period );
return SVC_RateLimit( bucket, burst, period );
}
/*
================
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( netadr_t from ) {
char player[1024];
char status[MAX_MSGLEN];
int i;
client_t *cl;
playerState_t *ps;
int statusLength;
int playerLength;
char infostring[MAX_INFO_STRING];
// ignore if we are in single player
if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")) {
return;
}
// Prevent using getstatus as an amplifier
if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
Com_DPrintf( "SVC_Status: rate limit from %s exceeded, dropping request\n",
NET_AdrToString( from ) );
return;
}
// Allow getstatus to be DoSed relatively easily, but prevent
// excess outbound bandwidth usage when being flooded inbound
if ( SVC_RateLimit( &outboundLeakyBucket, 10, 100 ) ) {
Com_DPrintf( "SVC_Status: rate limit exceeded, dropping request\n" );
return;
}
// A maximum challenge length of 128 should be more than plenty.
if(strlen(Cmd_Argv(1)) > 128)
return;
strcpy( infostring, Cvar_InfoString( CVAR_SERVERINFO ) );
// 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_SetValueForKey( infostring, "challenge", Cmd_Argv( 1 ) );
status[0] = 0;
statusLength = 0;
for ( i = 0 ; i < sv_maxclients->integer ; i++ ) {
cl = &svs.clients[i];
if ( cl->state >= CS_CONNECTED ) {
ps = SV_GameClientNum( i );
Com_sprintf( player, sizeof( player ), "%i %i \"%s\"\n",
ps->persistant[PERS_SCORE], cl->ping, cl->name );
playerLength = strlen( player );
if ( statusLength + playerLength >= sizeof( status ) ) {
break; // can't hold any more
}
strcpy( status + statusLength, player );
statusLength += playerLength;
}
}
NET_OutOfBandPrint( NS_SERVER, from, "statusResponse\n%s\n%s", infostring, 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
================
*/
void SVC_Info( netadr_t from ) {
int i, count, humans;
char *gamedir;
char infostring[MAX_INFO_STRING];
// ignore if we are in single player
if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER ) {
return;
}
// Prevent using getinfo as an amplifier
if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
Com_DPrintf( "SVC_Info: rate limit from %s exceeded, dropping request\n",
NET_AdrToString( from ) );
return;
}
// Allow getinfo to be DoSed relatively easily, but prevent
// excess outbound bandwidth usage when being flooded inbound
if ( SVC_RateLimit( &outboundLeakyBucket, 10, 100 ) ) {
Com_DPrintf( "SVC_Info: rate limit exceeded, dropping request\n" );
return;
}
/*
* Check whether Cmd_Argv(1) has a sane length. This was not done in the original Quake3 version which led
* to the Infostring bug discovered by Luigi Auriemma. See http://aluigi.altervista.org/ for the advisory.
*/
// A maximum challenge length of 128 should be more than plenty.
if(strlen(Cmd_Argv(1)) > 128)
return;
// don't count privateclients
count = humans = 0;
for ( i = sv_privateClients->integer ; i < sv_maxclients->integer ; i++ ) {
if ( svs.clients[i].state >= CS_CONNECTED ) {
count++;
if (svs.clients[i].netchan.remoteAddress.type != NA_BOT) {
humans++;
}
}
}
infostring[0] = 0;
// echo back the parameter to status. so servers can use it as a challenge
// to prevent timed spoofed reply packets that add ghost servers
Info_SetValueForKey( infostring, "challenge", Cmd_Argv( 1 ) );
Info_SetValueForKey( infostring, "gamename", com_gamename->string );
#ifdef LEGACY_PROTOCOL
if(com_legacyprotocol->integer > 0)
Info_SetValueForKey(infostring, "protocol", va("%i", com_legacyprotocol->integer));
else
#endif
Info_SetValueForKey(infostring, "protocol", va("%i", com_protocol->integer));
Info_SetValueForKey( infostring, "hostname", sv_hostname->string );
Info_SetValueForKey( infostring, "mapname", sv_mapname->string );
Info_SetValueForKey( infostring, "clients", va( "%i", count ) );
Info_SetValueForKey( infostring, "g_humanplayers", va( "%i", humans ) );
Info_SetValueForKey( infostring, "sv_maxclients",
va( "%i", sv_maxclients->integer - sv_privateClients->integer ) );
Info_SetValueForKey( infostring, "gametype", va( "%i", sv_gametype->integer ) );
Info_SetValueForKey( infostring, "pure", va( "%i", sv_pure->integer ) );
Info_SetValueForKey( infostring, "g_needpass", va( "%d", Cvar_VariableIntegerValue( "g_needpass" ) ) );
#ifdef USE_VOIP
if (sv_voipProtocol->string && *sv_voipProtocol->string) {
Info_SetValueForKey( infostring, "voip", sv_voipProtocol->string );
}
#endif
if ( sv_minPing->integer ) {
Info_SetValueForKey( infostring, "minPing", va( "%i", sv_minPing->integer ) );
}
if ( sv_maxPing->integer ) {
Info_SetValueForKey( infostring, "maxPing", va( "%i", sv_maxPing->integer ) );
}
gamedir = Cvar_VariableString( "fs_game" );
if ( *gamedir ) {
Info_SetValueForKey( infostring, "game", gamedir );
}
Info_SetValueForKey( infostring, "sv_allowAnonymous", va( "%i", sv_allowAnonymous->integer ) );
// Rafael gameskill
Info_SetValueForKey( infostring, "gameskill", va( "%i", sv_gameskill->integer ) );
// done
NET_OutOfBandPrint( NS_SERVER, from, "infoResponse\n%s", infostring );
}
/*
==============
SV_FlushRedirect
==============
*/
static void SV_FlushRedirect( char *outputbuf ) {
NET_OutOfBandPrint( NS_SERVER, svs.redirectAddress, "print\n%s", outputbuf );
}
/*
===============
SVC_RemoteCommand
An rcon packet arrived from the network.
Shift down the remaining args
Redirect all printfs
===============
*/
static void SVC_RemoteCommand( netadr_t from, msg_t *msg ) {
qboolean valid;
char remaining[1024];
#define SV_OUTPUTBUF_LENGTH ( MAX_MSGLEN - 16 )
char sv_outputbuf[SV_OUTPUTBUF_LENGTH];
char *cmd_aux;
if ( !strlen( sv_rconPassword->string ) ||
strcmp( Cmd_Argv( 1 ), sv_rconPassword->string ) ) {
static leakyBucket_t bucket;
// Make DoS via rcon impractical
if ( SVC_RateLimit( &bucket, 10, 1000 ) ) {
Com_DPrintf( "SVC_RemoteCommand: rate limit exceeded, dropping request\n" );
return;
}
valid = qfalse;
Com_DPrintf( "Bad rcon from %s:\n%s\n", NET_AdrToString( from ), Cmd_Argv( 2 ) );
} else {
valid = qtrue;
Com_DPrintf( "Rcon from %s:\n%s\n", NET_AdrToString( from ), Cmd_Argv( 2 ) );
}
// start redirecting all print outputs to the packet
svs.redirectAddress = from;
Com_BeginRedirect( sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect );
// Prevent using rcon as an amplifier and make dictionary attacks impractical
if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
Com_DPrintf( "SVC_RemoteCommand: rate limit from %s exceeded, dropping request\n",
NET_AdrToString( from ) );
return;
}
if ( !strlen( sv_rconPassword->string ) ) {
Com_Printf( "No rconpassword set.\n" );
} else if ( !valid ) {
Com_Printf( "Bad rconpassword.\n" );
} else {
remaining[0] = 0;
// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
// get the command directly, "rcon <pass> <command>" to avoid quoting issues
// extract the command by walking
// since the cmd formatting can fuckup (amount of spaces), using a dumb step by step parsing
cmd_aux = Cmd_Cmd();
cmd_aux+=4;
while(cmd_aux[0]==' ')
cmd_aux++;
while(cmd_aux[0] && cmd_aux[0]!=' ') // password
cmd_aux++;
while(cmd_aux[0]==' ')
cmd_aux++;
Q_strcat( remaining, sizeof(remaining), cmd_aux);
Cmd_ExecuteString (remaining);
}
Com_EndRedirect();
}
/*
=================
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( netadr_t from, msg_t *msg ) {
char *s;
char *c;
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // skip the -1 marker
if (!Q_strncmp("connect", (char *) &msg->data[4], 7)) {
Huff_Decompress( msg, 12 );
}
s = MSG_ReadStringLine( msg );
Cmd_TokenizeString( s );
c = Cmd_Argv( 0 );
Com_DPrintf( "SV packet %s : %s\n", NET_AdrToString( from ), c );
if ( !Q_stricmp( c,"getstatus" ) ) {
SVC_Status( from );
} else if ( !Q_stricmp( c,"getinfo" ) ) {
SVC_Info( from );
} else if ( !Q_stricmp( c,"getchallenge" ) ) {
SV_GetChallenge( from );
} else if ( !Q_stricmp( c,"connect" ) ) {
SV_DirectConnect( from );
#ifndef STANDALONE
#ifdef USE_AUTHORIZE_SERVER
} else if ( !Q_stricmp( c,"ipAuthorize" ) ) {
SV_AuthorizeIpPacket( from );
#endif
#endif
} else if ( !Q_stricmp( c, "rcon" ) ) {
SVC_RemoteCommand( from, msg );
} else if ( !Q_stricmp( c,"disconnect" ) ) {
// if a client starts up a local server, we may see some spurious
// server disconnect messages when their new server sees our final
// sequenced messages to the old client
} else {
Com_DPrintf ("bad connectionless packet from %s:\n%s\n",
NET_AdrToString (from), s);
}
}
//============================================================================
/*
=================
SV_PacketEvent
=================
*/
void SV_PacketEvent( netadr_t from, msg_t *msg ) {
int i;
client_t *cl;
int qport;
// check for connectionless packet (0xffffffff) first
if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
SV_ConnectionlessPacket( from, msg );
return;
}
// read the qport out of the message so we can fix up
// stupid address translating routers
MSG_BeginReadingOOB( msg );
MSG_ReadLong( msg ); // sequence number
qport = MSG_ReadShort( msg ) & 0xffff;
// find which client the message is from
for ( i = 0, cl = svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) {
if ( cl->state == CS_FREE ) {
continue;
}
if ( !NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) ) {
continue;
}
// it is possible to have multiple clients from a single IP
// address, so they are differentiated by the qport variable
if ( cl->netchan.qport != qport ) {
continue;
}
// the IP port can't be used to differentiate them, because
// some address translating routers periodically change UDP
// port assignments
if ( cl->netchan.remoteAddress.port != from.port ) {
Com_Printf( "SV_ReadPackets: fixing up a translated port\n" );
cl->netchan.remoteAddress.port = from.port;
}
// make sure it is a valid, in sequence packet
if ( SV_Netchan_Process( cl, msg ) ) {
// zombie clients still need to do the Netchan_Process
// to make sure they don't need to retransmit the final
// reliable message, but they don't do any other processing
if ( cl->state != CS_ZOMBIE ) {
cl->lastPacketTime = svs.time; // don't timeout
SV_ExecuteClientMessage( cl, msg );
}
}
return;
}
}
/*
===================
SV_CalcPings
Updates the cl->ping variables
===================
*/
static void SV_CalcPings( void ) {
int i, j;
client_t *cl;
int total, count;
int delta;
playerState_t *ps;
for ( i = 0 ; i < sv_maxclients->integer ; i++ ) {
cl = &svs.clients[i];
if ( cl->state != CS_ACTIVE ) {
cl->ping = 999;
continue;
}
if ( !cl->gentity ) {
cl->ping = 999;
continue;
}
if ( cl->gentity->r.svFlags & SVF_BOT ) {
cl->ping = 0;
continue;
}
total = 0;
count = 0;
for ( j = 0 ; j < PACKET_BACKUP ; j++ ) {
if ( cl->frames[j].messageAcked <= 0 ) {
continue;
}
delta = cl->frames[j].messageAcked - cl->frames[j].messageSent;
count++;
total += delta;
}
if ( !count ) {
cl->ping = 999;
} else {
cl->ping = total / count;
if ( cl->ping > 999 ) {
cl->ping = 999;
}
}
// let the game dll know about the ping
ps = SV_GameClientNum( i );
ps->ping = cl->ping;
}
}
/*
==================
SV_CheckTimeouts
If a packet has not been received from a client for timeout->integer
seconds, drop the conneciton. Server time is used instead of
realtime to avoid dropping the local client while debugging.
When a client is normally dropped, the client_t goes into a zombie state
for a few seconds to make sure any final reliable message gets resent
if necessary
==================
*/
static void SV_CheckTimeouts( void ) {
int i;
client_t *cl;
int droppoint;
int zombiepoint;
droppoint = svs.time - 1000 * sv_timeout->integer;
zombiepoint = svs.time - 1000 * sv_zombietime->integer;
for ( i = 0,cl = svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) {
// message times may be wrong across a changelevel
if ( cl->lastPacketTime > svs.time ) {
cl->lastPacketTime = svs.time;
}
if ( cl->state == CS_ZOMBIE
&& cl->lastPacketTime < zombiepoint ) {
Com_DPrintf( "Going from CS_ZOMBIE to CS_FREE for %s\n", cl->name );
cl->state = CS_FREE; // can now be reused
continue;
}
// Ridah, AI's don't time out
if ( cl->gentity && !( cl->gentity->r.svFlags & SVF_CASTAI ) ) {
if ( cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint ) {
// wait several frames so a debugger session doesn't
// cause a timeout
if ( ++cl->timeoutCount > 5 ) {
SV_DropClient( cl, "timed out" );
cl->state = CS_FREE; // don't bother with zombie state
}
} else {
cl->timeoutCount = 0;
}
}
}
}
/*
==================
SV_CheckPaused
==================
*/
static qboolean SV_CheckPaused( void ) {
int count;
client_t *cl;
int i;
if ( !cl_paused->integer ) {
return qfalse;
}
// only pause if there is just a single client connected
count = 0;
for ( i = 0,cl = svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) {
if ( cl->state >= CS_CONNECTED && cl->netchan.remoteAddress.type != NA_BOT ) {
count++;
}
}
if ( count > 1 ) {
// don't pause
sv_paused->integer = 0;
return qfalse;
}
sv_paused->integer = 1;
return qtrue;
}
/*
==================
SV_FrameMsec
Return time in millseconds until processing of the next server frame.
==================
*/
int SV_FrameMsec()
{
if(sv_fps)
{
int frameMsec;
frameMsec = 1000.0f / sv_fps->value;
if(frameMsec < sv.timeResidual)
return 0;
else
return frameMsec - sv.timeResidual;
}
else
return 1;
}
/*
==================
SV_Frame
Player movement occurs as a result of packet events, which
happen before SV_Frame is called
==================
*/
void SV_Frame( int msec ) {
int frameMsec;
int startTime;
// the menu kills the server with this cvar
if ( sv_killserver->integer ) {
SV_Shutdown( "Server was killed" );
Cvar_Set( "sv_killserver", "0" );
return;
}
if (!com_sv_running->integer)
{
// Running as a server, but no map loaded
#ifdef DEDICATED
// Block until something interesting happens
Sys_Sleep(-1);
#endif
return;
}
// allow pause if only the local client is connected
if ( SV_CheckPaused() ) {
return;
}
// if it isn't time for the next frame, do nothing
if ( sv_fps->integer < 1 ) {
Cvar_Set( "sv_fps", "10" );
}
frameMsec = 1000 / sv_fps->integer * com_timescale->value;
// don't let it scale below 1ms
if(frameMsec < 1)
{
Cvar_Set("timescale", va("%f", sv_fps->integer / 1000.0f));
frameMsec = 1;
}
sv.timeResidual += msec;
if (!com_dedicated->integer) SV_BotFrame (sv.time + sv.timeResidual);
// if time is about to hit the 32nd bit, kick all clients
// and clear sv.time, rather
// than checking for negative time wraparound everywhere.
// 2giga-milliseconds = 23 days, so it won't be too often
if ( svs.time > 0x70000000 ) {
SV_Shutdown( "Restarting server due to time wrapping" );
Cbuf_AddText( va( "spmap %s\n", Cvar_VariableString( "mapname" ) ) );
return;
}
// this can happen considerably earlier when lots of clients play and the map doesn't change
if ( svs.nextSnapshotEntities >= 0x7FFFFFFE - svs.numSnapshotEntities ) {
SV_Shutdown( "Restarting server due to numSnapshotEntities wrapping" );
Cbuf_AddText( va( "spmap %s\n", Cvar_VariableString( "mapname" ) ) );
return;
}
if( sv.restartTime && sv.time >= sv.restartTime ) {
sv.restartTime = 0;
Cbuf_AddText( "map_restart 0\n" );
return;
}
// update infostrings if anything has been changed
if ( cvar_modifiedFlags & CVAR_SERVERINFO ) {
SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) );
cvar_modifiedFlags &= ~CVAR_SERVERINFO;
}
if ( cvar_modifiedFlags & CVAR_SYSTEMINFO ) {
SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString_Big( CVAR_SYSTEMINFO ) );
cvar_modifiedFlags &= ~CVAR_SYSTEMINFO;
}
if ( com_speeds->integer ) {
startTime = Sys_Milliseconds();
} else {
startTime = 0; // quiet a compiler warning
}
// update ping based on the all received frames
SV_CalcPings();
if ( com_dedicated->integer ) {
SV_BotFrame( sv.time );
}
// run the game simulation in chunks
while ( sv.timeResidual >= frameMsec ) {
sv.timeResidual -= frameMsec;
svs.time += frameMsec;
sv.time += frameMsec;
// let everything in the world think and move
VM_Call( gvm, GAME_RUN_FRAME, sv.time );
}
if ( com_speeds->integer ) {
time_game = Sys_Milliseconds() - startTime;
}
// check timeouts
SV_CheckTimeouts();
// send messages back to the clients
SV_SendClientMessages();
// send a heartbeat to the master if needed
SV_MasterHeartbeat(HEARTBEAT_FOR_MASTER);
}
/*
====================
SV_RateMsec
Return the number of msec until another message can be sent to
a client based on its rate settings
====================
*/
#define UDPIP_HEADER_SIZE 28
#define UDPIP6_HEADER_SIZE 48
int SV_RateMsec(client_t *client)
{
int rate, rateMsec;
int messageSize;
messageSize = client->netchan.lastSentSize;
rate = client->rate;
if(sv_maxRate->integer)
{
if(sv_maxRate->integer < 1000)
Cvar_Set( "sv_MaxRate", "1000" );
if(sv_maxRate->integer < rate)
rate = sv_maxRate->integer;
}
if(sv_minRate->integer)
{
if(sv_minRate->integer < 1000)
Cvar_Set("sv_minRate", "1000");
if(sv_minRate->integer > rate)
rate = sv_minRate->integer;
}
if(client->netchan.remoteAddress.type == NA_IP6)
messageSize += UDPIP6_HEADER_SIZE;
else
messageSize += UDPIP_HEADER_SIZE;
rateMsec = messageSize * 1000 / ((int) (rate * com_timescale->value));
rate = Sys_Milliseconds() - client->netchan.lastSentTime;
if(rate > rateMsec)
return 0;
else
return rateMsec - rate;
}
/*
====================
SV_SendQueuedPackets
Send download messages and queued packets in the time that we're idle, i.e.
not computing a server frame or sending client snapshots.
Return the time in msec until we expect to be called next
====================
*/
int SV_SendQueuedPackets()
{
int numBlocks;
int dlStart, deltaT, delayT;
static int dlNextRound = 0;
int timeVal = INT_MAX;
// Send out fragmented packets now that we're idle
delayT = SV_SendQueuedMessages();
if(delayT >= 0)
timeVal = delayT;
if(sv_dlRate->integer)
{
// Rate limiting. This is very imprecise for high
// download rates due to millisecond timedelta resolution
dlStart = Sys_Milliseconds();
deltaT = dlNextRound - dlStart;
if(deltaT > 0)
{
if(deltaT < timeVal)
timeVal = deltaT + 1;
}
else
{
numBlocks = SV_SendDownloadMessages();
if(numBlocks)
{
// There are active downloads
deltaT = Sys_Milliseconds() - dlStart;
delayT = 1000 * numBlocks * MAX_DOWNLOAD_BLKSIZE;
delayT /= sv_dlRate->integer * 1024;
if(delayT <= deltaT + 1)
{
// Sending the last round of download messages
// took too long for given rate, don't wait for
// next round, but always enforce a 1ms delay
// between DL message rounds so we don't hog
// all of the bandwidth. This will result in an
// effective maximum rate of 1MB/s per user, but the
// low download window size limits this anyways.
if(timeVal > 2)
timeVal = 2;
dlNextRound = dlStart + deltaT + 1;
}
else
{
dlNextRound = dlStart + delayT;
delayT -= deltaT;
if(delayT < timeVal)
timeVal = delayT;
}
}
}
}
else
{
if(SV_SendDownloadMessages())
timeVal = 0;
}
return timeVal;
}
|