Debian Codegraph @

code/server/sv_main.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22
23 #include "server.h"
24
25 #ifdef USE_VOIP
26 cvar_t *sv_voip;
27 cvar_t *sv_voipProtocol;
28 #endif
29
30 serverStatic_t svs; // persistant server info
31 server_t sv; // local server
32 vm_t *gvm = NULL; // game virtual machine
33
34 cvar_t *sv_fps = NULL; // time rate for running non-clients
35 cvar_t *sv_timeout; // seconds without any message
36 cvar_t *sv_zombietime; // seconds to sink messages after disconnect
37 cvar_t *sv_rconPassword; // password for remote server commands
38 cvar_t *sv_privatePassword; // password for the privateClient slots
39 cvar_t *sv_allowDownload;
40 cvar_t *sv_maxclients;
41
42 cvar_t *sv_privateClients; // number of clients reserved for password
43 cvar_t *sv_hostname;
44 cvar_t *sv_master[MAX_MASTER_SERVERS]; // master server ip address
45 cvar_t *sv_reconnectlimit; // minimum seconds between connect messages
46 cvar_t *sv_showloss; // report when usercmds are lost
47 cvar_t *sv_padPackets; // add nop bytes to messages
48 cvar_t *sv_killserver; // menu system can set to 1 to shut server down
49 cvar_t *sv_mapname;
50 cvar_t *sv_mapChecksum;
51 cvar_t *sv_serverid;
52 cvar_t *sv_minRate;
53 cvar_t *sv_maxRate;
54 cvar_t *sv_dlRate;
55 cvar_t *sv_minPing;
56 cvar_t *sv_maxPing;
57 cvar_t *sv_gametype;
•58 cvar_t *sv_dorestart;
59 cvar_t *sv_pure;
60 cvar_t *sv_floodProtect;
61 cvar_t *sv_lanForceRate; // dedicated 1 (LAN) server forces local client rates to 99999 (bug #491)
62 #ifndef STANDALONE
63 cvar_t *sv_strictAuth;
64 #endif
65 cvar_t *sv_banFile;
66
67 serverBan_t serverBans[SERVER_MAXBANS];
68 int serverBansCount = 0;
69
70 /*
71 =============================================================================
72
73 EVENT MESSAGES
74
75 =============================================================================
76 */
77
78 /*
79 ===============
80 SV_ExpandNewlines
81
82 Converts newlines to "\n" so a line prints nicer
83 ===============
84 */
85 static char *SV_ExpandNewlines( char *in ) {
86 static char string[1024];
87 int l;
88
89 l = 0;
90 while ( *in && l < sizeof(string) - 3 ) {
91 if ( *in == '\n' ) {
92 string[l++] = '\\';
93 string[l++] = 'n';
94 } else {
95 string[l++] = *in;
96 }
97 in++;
98 }
99 string[l] = 0;
100
101 return string;
102 }
103
104 /*
105 ======================
106 SV_ReplacePendingServerCommands
107
108 FIXME: This is ugly
109 ======================
110 */
111 #if 0 // unused
112 static int SV_ReplacePendingServerCommands( client_t *client, const char *cmd ) {
113 int i, index, csnum1, csnum2;
114
115 for ( i = client->reliableSent+1; i <= client->reliableSequence; i++ ) {
116 index = i & ( MAX_RELIABLE_COMMANDS - 1 );
117 //
118 if ( !Q_strncmp(cmd, client->reliableCommands[ index ], strlen("cs")) ) {
119 sscanf(cmd, "cs %i", &csnum1);
120 sscanf(client->reliableCommands[ index ], "cs %i", &csnum2);
121 if ( csnum1 == csnum2 ) {
122 Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) );
123 /*
124 if ( client->netchan.remoteAddress.type != NA_BOT ) {
125 Com_Printf( "WARNING: client %i removed double pending config string %i: %s\n", client-svs.clients, csnum1, cmd );
126 }
127 */
128 return qtrue;
129 }
130 }
131 }
132 return qfalse;
133 }
134 #endif
135
136 /*
137 ======================
138 SV_AddServerCommand
139
140 The given command will be transmitted to the client, and is guaranteed to
141 not have future snapshot_t executed before it is executed
142 ======================
143 */
144 void SV_AddServerCommand( client_t *client, const char *cmd ) {
145 int index, i;
146
147 // this is very ugly but it's also a waste to for instance send multiple config string updates
148 // for the same config string index in one snapshot
149 // if ( SV_ReplacePendingServerCommands( client, cmd ) ) {
150 // return;
151 // }
152
153 // do not send commands until the gamestate has been sent
154 if( client->state < CS_PRIMED )
155 return;
156
157 client->reliableSequence++;
158 // if we would be losing an old command that hasn't been acknowledged,
159 // we must drop the connection
160 // we check == instead of >= so a broadcast print added by SV_DropClient()
161 // doesn't cause a recursive drop client
162 if ( client->reliableSequence - client->reliableAcknowledge == MAX_RELIABLE_COMMANDS + 1 ) {
163 if ( client->gamestateMessageNum == -1 ) {
164 // invalid game state message
165 // this can occur in SV_DropClient() to avoid calling it more than once
166 return;
167 }
168
169 Com_Printf( "===== pending server commands =====\n" );
170 for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
171 Com_Printf( "cmd %5d: %s\n", i, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
172 }
173 Com_Printf( "cmd %5d: %s\n", i, cmd );
174 SV_DropClient( client, "Server command overflow" );
175 return;
176 }
177 index = client->reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
178 Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) );
179 }
180
181
182 /*
183 =================
184 SV_SendServerCommand
185
186 Sends a reliable command string to be interpreted by
187 the client game module: "cp", "print", "chat", etc
188 A NULL client will broadcast to all clients
189 =================
190 */
191 void QDECL SV_SendServerCommand(client_t *cl, const char *fmt, ...) {
192 va_list argptr;
193 byte message[MAX_MSGLEN];
194 client_t *client;
195 int j;
196
197 va_start (argptr,fmt);
198 Q_vsnprintf ((char *)message, sizeof(message), fmt,argptr);
199 va_end (argptr);
200
201 // Fix to http://aluigi.altervista.org/adv/q3msgboom-adv.txt
202 // The actual cause of the bug is probably further downstream
203 // and should maybe be addressed later, but this certainly
204 // fixes the problem for now
205 if ( strlen ((char *)message) > 1022 ) {
206 return;
207 }
208
209 if ( cl != NULL ) {
210 SV_AddServerCommand( cl, (char *)message );
211 return;
212 }
213
214 // hack to echo broadcast prints to console
215 if ( com_dedicated->integer && !strncmp( (char *)message, "print", 5) ) {
216 Com_Printf ("broadcast: %s\n", SV_ExpandNewlines((char *)message) );
217 }
218
219 // send the data to all relevant clients
220 for (j = 0, client = svs.clients; j < sv_maxclients->integer ; j++, client++) {
221 SV_AddServerCommand( client, (char *)message );
222 }
223 }
224
225
226 /*
227 ==============================================================================
228
229 MASTER SERVER FUNCTIONS
230
231 ==============================================================================
232 */
233
234 /*
235 ================
236 SV_MasterHeartbeat
237
238 Send a message to the masters every few minutes to
239 let it know we are alive, and log information.
240 We will also have a heartbeat sent when a server
241 changes from empty to non-empty, and full to non-full,
242 but not on every player enter or exit.
243 ================
244 */
245 #define HEARTBEAT_MSEC 300*1000
246 #define MASTERDNS_MSEC 24*60*60*1000
247 void SV_MasterHeartbeat(const char *message)
248 {
249 static netadr_t adr[MAX_MASTER_SERVERS][2]; // [2] for v4 and v6 address for the same address string.
250 int i;
251 int res;
252 int netenabled;
253
254 netenabled = Cvar_VariableIntegerValue("net_enabled");
255
256 // "dedicated 1" is for lan play, "dedicated 2" is for inet public play
257 if (!com_dedicated || com_dedicated->integer != 2 || !(netenabled & (NET_ENABLEV4 | NET_ENABLEV6)))
258 return; // only dedicated servers send heartbeats
259
260 // if not time yet, don't send anything
261 if ( svs.time < svs.nextHeartbeatTime )
262 return;
263
264 if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) )
265 message = LEGACY_HEARTBEAT_FOR_MASTER;
266
267 svs.nextHeartbeatTime = svs.time + HEARTBEAT_MSEC;
268
269 // send to group masters
270 for (i = 0; i < MAX_MASTER_SERVERS; i++)
271 {
272 if(!sv_master[i]->string[0])
273 continue;
274
275 // see if we haven't already resolved the name or if it's been over 24 hours
276 // resolving usually causes hitches on win95, so only do it when needed
277 if (sv_master[i]->modified || svs.time > svs.masterResolveTime[i])
278 {
279 sv_master[i]->modified = qfalse;
280 svs.masterResolveTime[i] = svs.time + MASTERDNS_MSEC;
281
282 if(netenabled & NET_ENABLEV4)
283 {
284 Com_Printf("Resolving %s (IPv4)\n", sv_master[i]->string);
285 res = NET_StringToAdr(sv_master[i]->string, &adr[i][0], NA_IP);
286
287 if(res == 2)
288 {
289 // if no port was specified, use the default master port
290 adr[i][0].port = BigShort(PORT_MASTER);
291 }
292
293 if(res)
294 Com_Printf( "%s resolved to %s\n", sv_master[i]->string, NET_AdrToStringwPort(adr[i][0]));
295 else
296 Com_Printf( "%s has no IPv4 address.\n", sv_master[i]->string);
297 }
298
299 if(netenabled & NET_ENABLEV6)
300 {
301 Com_Printf("Resolving %s (IPv6)\n", sv_master[i]->string);
302 res = NET_StringToAdr(sv_master[i]->string, &adr[i][1], NA_IP6);
303
304 if(res == 2)
305 {
306 // if no port was specified, use the default master port
307 adr[i][1].port = BigShort(PORT_MASTER);
308 }
309
310 if(res)
311 Com_Printf( "%s resolved to %s\n", sv_master[i]->string, NET_AdrToStringwPort(adr[i][1]));
312 else
313 Com_Printf( "%s has no IPv6 address.\n", sv_master[i]->string);
314 }
315 }
316
317 if(adr[i][0].type == NA_BAD && adr[i][1].type == NA_BAD)
318 {
319 continue;
320 }
321
322
323 Com_Printf ("Sending heartbeat to %s\n", sv_master[i]->string );
324
325 // this command should be changed if the server info / status format
326 // ever incompatably changes
327
328 if(adr[i][0].type != NA_BAD)
329 NET_OutOfBandPrint( NS_SERVER, adr[i][0], "heartbeat %s\n", message);
330 if(adr[i][1].type != NA_BAD)
331 NET_OutOfBandPrint( NS_SERVER, adr[i][1], "heartbeat %s\n", message);
332 }
333 }
334
335 /*
336 =================
337 SV_MasterShutdown
338
339 Informs all masters that this server is going down
340 =================
341 */
342 void SV_MasterShutdown( void ) {
343 // send a heartbeat right now
344 svs.nextHeartbeatTime = -9999;
345 SV_MasterHeartbeat(HEARTBEAT_FOR_MASTER);
346
347 // send it again to minimize chance of drops
348 svs.nextHeartbeatTime = -9999;
349 SV_MasterHeartbeat(HEARTBEAT_FOR_MASTER);
350
351 // when the master tries to poll the server, it won't respond, so
352 // it will be removed from the list
353 }
354
355
356 /*
357 ==============================================================================
358
359 CONNECTIONLESS COMMANDS
360
361 ==============================================================================
362 */
363
364 // This is deliberately quite large to make it more of an effort to DoS
365 #define MAX_BUCKETS 16384
366 #define MAX_HASHES 1024
367
368 static leakyBucket_t buckets[ MAX_BUCKETS ];
369 static leakyBucket_t *bucketHashes[ MAX_HASHES ];
370 leakyBucket_t outboundLeakyBucket;
371
372 /*
373 ================
374 SVC_HashForAddress
375 ================
376 */
377 static long SVC_HashForAddress( netadr_t address ) {
378 byte *ip = NULL;
379 size_t size = 0;
380 int i;
381 long hash = 0;
382
383 switch ( address.type ) {
384 case NA_IP: ip = address.ip; size = 4; break;
385 case NA_IP6: ip = address.ip6; size = 16; break;
386 default: break;
387 }
388
389 for ( i = 0; i < size; i++ ) {
390 hash += (long)( ip[ i ] ) * ( i + 119 );
391 }
392
393 hash = ( hash ^ ( hash >> 10 ) ^ ( hash >> 20 ) );
394 hash &= ( MAX_HASHES - 1 );
395
396 return hash;
397 }
398
399 /*
400 ================
401 SVC_BucketForAddress
402
403 Find or allocate a bucket for an address
404 ================
405 */
406 static leakyBucket_t *SVC_BucketForAddress( netadr_t address, int burst, int period ) {
407 leakyBucket_t *bucket = NULL;
408 int i;
409 long hash = SVC_HashForAddress( address );
410 int now = Sys_Milliseconds();
411
412 for ( bucket = bucketHashes[ hash ]; bucket; bucket = bucket->next ) {
413 switch ( bucket->type ) {
414 case NA_IP:
415 if ( memcmp( bucket->ipv._4, address.ip, 4 ) == 0 ) {
416 return bucket;
417 }
418 break;
419
420 case NA_IP6:
421 if ( memcmp( bucket->ipv._6, address.ip6, 16 ) == 0 ) {
422 return bucket;
423 }
424 break;
425
426 default:
427 break;
428 }
429 }
430
431 for ( i = 0; i < MAX_BUCKETS; i++ ) {
432 int interval;
433
434 bucket = &buckets[ i ];
435 interval = now - bucket->lastTime;
436
437 // Reclaim expired buckets
438 if ( bucket->lastTime > 0 && ( interval > ( burst * period ) ||
439 interval < 0 ) ) {
440 if ( bucket->prev != NULL ) {
441 bucket->prev->next = bucket->next;
442 } else {
443 bucketHashes[ bucket->hash ] = bucket->next;
444 }
445
446 if ( bucket->next != NULL ) {
447 bucket->next->prev = bucket->prev;
448 }
449
450 Com_Memset( bucket, 0, sizeof( leakyBucket_t ) );
451 }
452
453 if ( bucket->type == NA_BAD ) {
454 bucket->type = address.type;
455 switch ( address.type ) {
456 case NA_IP: Com_Memcpy( bucket->ipv._4, address.ip, 4 ); break;
457 case NA_IP6: Com_Memcpy( bucket->ipv._6, address.ip6, 16 ); break;
458 default: break;
459 }
460
461 bucket->lastTime = now;
462 bucket->burst = 0;
463 bucket->hash = hash;
464
465 // Add to the head of the relevant hash chain
466 bucket->next = bucketHashes[ hash ];
467 if ( bucketHashes[ hash ] != NULL ) {
468 bucketHashes[ hash ]->prev = bucket;
469 }
470
471 bucket->prev = NULL;
472 bucketHashes[ hash ] = bucket;
473
474 return bucket;
475 }
476 }
477
478 // Couldn't allocate a bucket for this address
479 return NULL;
480 }
481
482 /*
483 ================
484 SVC_RateLimit
485 ================
486 */
487 qboolean SVC_RateLimit( leakyBucket_t *bucket, int burst, int period ) {
488 if ( bucket != NULL ) {
489 int now = Sys_Milliseconds();
490 int interval = now - bucket->lastTime;
491 int expired = interval / period;
492 int expiredRemainder = interval % period;
493
494 if ( expired > bucket->burst || interval < 0 ) {
495 bucket->burst = 0;
496 bucket->lastTime = now;
497 } else {
498 bucket->burst -= expired;
499 bucket->lastTime = now - expiredRemainder;
500 }
501
502 if ( bucket->burst < burst ) {
503 bucket->burst++;
504
505 return qfalse;
506 }
507 }
508
509 return qtrue;
510 }
511
512 /*
513 ================
514 SVC_RateLimitAddress
515
516 Rate limit for a particular address
517 ================
518 */
519 qboolean SVC_RateLimitAddress( netadr_t from, int burst, int period ) {
520 leakyBucket_t *bucket = SVC_BucketForAddress( from, burst, period );
521
522 return SVC_RateLimit( bucket, burst, period );
523 }
524
525 /*
526 ================
527 SVC_Status
528
529 Responds with all the info that qplug or qspy can see about the server
530 and all connected players. Used for getting detailed information after
531 the simple info query.
532 ================
533 */
534 static void SVC_Status( netadr_t from ) {
535 char player[1024];
536 char status[MAX_MSGLEN];
537 int i;
538 client_t *cl;
539 playerState_t *ps;
540 int statusLength;
541 int playerLength;
542 char infostring[MAX_INFO_STRING];
543
544 // ignore if we are in single player
545 if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")) {
546 return;
547 }
548
549 // Prevent using getstatus as an amplifier
550 if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
551 Com_DPrintf( "SVC_Status: rate limit from %s exceeded, dropping request\n",
552 NET_AdrToString( from ) );
553 return;
554 }
555
556 // Allow getstatus to be DoSed relatively easily, but prevent
557 // excess outbound bandwidth usage when being flooded inbound
558 if ( SVC_RateLimit( &outboundLeakyBucket, 10, 100 ) ) {
559 Com_DPrintf( "SVC_Status: rate limit exceeded, dropping request\n" );
560 return;
561 }
562
563 // A maximum challenge length of 128 should be more than plenty.
564 if(strlen(Cmd_Argv(1)) > 128)
565 return;
566
567 strcpy( infostring, Cvar_InfoString( CVAR_SERVERINFO ) );
568
569 // echo back the parameter to status. so master servers can use it as a challenge
570 // to prevent timed spoofed reply packets that add ghost servers
571 Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) );
572
573 status[0] = 0;
574 statusLength = 0;
575
576 for (i=0 ; i < sv_maxclients->integer ; i++) {
577 cl = &svs.clients[i];
578 if ( cl->state >= CS_CONNECTED ) {
579 ps = SV_GameClientNum( i );
580 Com_sprintf (player, sizeof(player), "%i %i \"%s\"\n",
581 ps->persistant[PERS_SCORE], cl->ping, cl->name);
582 playerLength = strlen(player);
583 if (statusLength + playerLength >= sizeof(status) ) {
584 break; // can't hold any more
585 }
586 strcpy (status + statusLength, player);
587 statusLength += playerLength;
588 }
589 }
590
591 NET_OutOfBandPrint( NS_SERVER, from, "statusResponse\n%s\n%s", infostring, status );
592 }
593
594 /*
595 ================
596 SVC_Info
597
598 Responds with a short info message that should be enough to determine
599 if a user is interested in a server to do a full status
600 ================
601 */
602 void SVC_Info( netadr_t from ) {
603 int i, count, humans;
604 char *gamedir;
605 char infostring[MAX_INFO_STRING];
606
607 // ignore if we are in single player
608 if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")) {
609 return;
610 }
611
612 // Prevent using getinfo as an amplifier
613 if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
614 Com_DPrintf( "SVC_Info: rate limit from %s exceeded, dropping request\n",
615 NET_AdrToString( from ) );
616 return;
617 }
618
619 // Allow getinfo to be DoSed relatively easily, but prevent
620 // excess outbound bandwidth usage when being flooded inbound
621 if ( SVC_RateLimit( &outboundLeakyBucket, 10, 100 ) ) {
622 Com_DPrintf( "SVC_Info: rate limit exceeded, dropping request\n" );
623 return;
624 }
625
626 /*
627 * Check whether Cmd_Argv(1) has a sane length. This was not done in the original Quake3 version which led
628 * to the Infostring bug discovered by Luigi Auriemma. See http://aluigi.altervista.org/ for the advisory.
629 */
630
631 // A maximum challenge length of 128 should be more than plenty.
632 if(strlen(Cmd_Argv(1)) > 128)
633 return;
634
635 // don't count privateclients
636 count = humans = 0;
637 for ( i = sv_privateClients->integer ; i < sv_maxclients->integer ; i++ ) {
638 if ( svs.clients[i].state >= CS_CONNECTED ) {
639 count++;
640 if (svs.clients[i].netchan.remoteAddress.type != NA_BOT) {
641 humans++;
642 }
643 }
644 }
645
646 infostring[0] = 0;
647
648 // echo back the parameter to status. so servers can use it as a challenge
649 // to prevent timed spoofed reply packets that add ghost servers
650 Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) );
651
652 Info_SetValueForKey( infostring, "gamename", com_gamename->string );
653
654 #ifdef LEGACY_PROTOCOL
655 if(com_legacyprotocol->integer > 0)
656 Info_SetValueForKey(infostring, "protocol", va("%i", com_legacyprotocol->integer));
657 else
658 #endif
659 Info_SetValueForKey(infostring, "protocol", va("%i", com_protocol->integer));
660
661 Info_SetValueForKey( infostring, "hostname", sv_hostname->string );
662 Info_SetValueForKey( infostring, "mapname", sv_mapname->string );
663 Info_SetValueForKey( infostring, "clients", va("%i", count) );
664 Info_SetValueForKey(infostring, "g_humanplayers", va("%i", humans));
665 Info_SetValueForKey( infostring, "sv_maxclients",
666 va("%i", sv_maxclients->integer - sv_privateClients->integer ) );
667 Info_SetValueForKey( infostring, "gametype", va("%i", sv_gametype->integer ) );
668 Info_SetValueForKey( infostring, "pure", va("%i", sv_pure->integer ) );
669 Info_SetValueForKey(infostring, "g_needpass", va("%d", Cvar_VariableIntegerValue("g_needpass")));
670
671 #ifdef USE_VOIP
672 if (sv_voipProtocol->string && *sv_voipProtocol->string) {
673 Info_SetValueForKey( infostring, "voip", sv_voipProtocol->string );
674 }
675 #endif
676
677 if( sv_minPing->integer ) {
678 Info_SetValueForKey( infostring, "minPing", va("%i", sv_minPing->integer) );
679 }
680 if( sv_maxPing->integer ) {
681 Info_SetValueForKey( infostring, "maxPing", va("%i", sv_maxPing->integer) );
682 }
683 gamedir = Cvar_VariableString( "fs_game" );
684 if( *gamedir ) {
685 Info_SetValueForKey( infostring, "game", gamedir );
686 }
687
688 NET_OutOfBandPrint( NS_SERVER, from, "infoResponse\n%s", infostring );
689 }
690
691 /*
692 ================
693 SVC_FlushRedirect
694
695 ================
696 */
697 static void SV_FlushRedirect( char *outputbuf ) {
698 NET_OutOfBandPrint( NS_SERVER, svs.redirectAddress, "print\n%s", outputbuf );
699 }
700
701 /*
702 ===============
703 SVC_RemoteCommand
704
705 An rcon packet arrived from the network.
706 Shift down the remaining args
707 Redirect all printfs
708 ===============
709 */
710 static void SVC_RemoteCommand( netadr_t from, msg_t *msg ) {
711 qboolean valid;
712 char remaining[1024];
713 // TTimo - scaled down to accumulate, but not overflow anything network wise, print wise etc.
714 // (OOB messages are the bottleneck here)
715 #define SV_OUTPUTBUF_LENGTH (1024 - 16)
716 char sv_outputbuf[SV_OUTPUTBUF_LENGTH];
717 char *cmd_aux;
718
719 // Prevent using rcon as an amplifier and make dictionary attacks impractical
720 if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
721 Com_DPrintf( "SVC_RemoteCommand: rate limit from %s exceeded, dropping request\n",
722 NET_AdrToString( from ) );
723 return;
724 }
725
726 if ( !strlen( sv_rconPassword->string ) ||
727 strcmp (Cmd_Argv(1), sv_rconPassword->string) ) {
728 static leakyBucket_t bucket;
729
730 // Make DoS via rcon impractical
731 if ( SVC_RateLimit( &bucket, 10, 1000 ) ) {
732 Com_DPrintf( "SVC_RemoteCommand: rate limit exceeded, dropping request\n" );
733 return;
734 }
735
736 valid = qfalse;
737 Com_Printf ("Bad rcon from %s: %s\n", NET_AdrToString (from), Cmd_ArgsFrom(2) );
738 } else {
739 valid = qtrue;
740 Com_Printf ("Rcon from %s: %s\n", NET_AdrToString (from), Cmd_ArgsFrom(2) );
741 }
742
743 // start redirecting all print outputs to the packet
744 svs.redirectAddress = from;
745 Com_BeginRedirect (sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect);
746
747 if ( !strlen( sv_rconPassword->string ) ) {
748 Com_Printf ("No rconpassword set on the server.\n");
749 } else if ( !valid ) {
750 Com_Printf ("Bad rconpassword.\n");
751 } else {
752 remaining[0] = 0;
753
754 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
755 // get the command directly, "rcon <pass> <command>" to avoid quoting issues
756 // extract the command by walking
757 // since the cmd formatting can fuckup (amount of spaces), using a dumb step by step parsing
758 cmd_aux = Cmd_Cmd();
759 cmd_aux+=4;
760 while(cmd_aux[0]==' ')
761 cmd_aux++;
762 while(cmd_aux[0] && cmd_aux[0]!=' ') // password
763 cmd_aux++;
764 while(cmd_aux[0]==' ')
765 cmd_aux++;
766
767 Q_strcat( remaining, sizeof(remaining), cmd_aux);
768
769 Cmd_ExecuteString (remaining);
770
771 }
772
773 Com_EndRedirect ();
774 }
775
776 /*
777 =================
778 SV_ConnectionlessPacket
779
780 A connectionless packet has four leading 0xff
781 characters to distinguish it from a game channel.
782 Clients that are in the game can still send
783 connectionless packets.
784 =================
785 */
786 static void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
787 char *s;
788 char *c;
789
790 MSG_BeginReadingOOB( msg );
791 MSG_ReadLong( msg ); // skip the -1 marker
792
793 if (!Q_strncmp("connect", (char *) &msg->data[4], 7)) {
794 Huff_Decompress(msg, 12);
795 }
796
797 s = MSG_ReadStringLine( msg );
798 Cmd_TokenizeString( s );
799
800 c = Cmd_Argv(0);
801 Com_DPrintf ("SV packet %s : %s\n", NET_AdrToString(from), c);
802
803 if (!Q_stricmp(c, "getstatus")) {
804 SVC_Status( from );
805 } else if (!Q_stricmp(c, "getinfo")) {
806 SVC_Info( from );
807 } else if (!Q_stricmp(c, "getchallenge")) {
808 SV_GetChallenge(from);
809 } else if (!Q_stricmp(c, "connect")) {
810 SV_DirectConnect( from );
811 #ifndef STANDALONE
812 } else if (!Q_stricmp(c, "ipAuthorize")) {
813 SV_AuthorizeIpPacket( from );
814 #endif
815 } else if (!Q_stricmp(c, "rcon")) {
816 SVC_RemoteCommand( from, msg );
817 } else if (!Q_stricmp(c, "disconnect")) {
818 // if a client starts up a local server, we may see some spurious
819 // server disconnect messages when their new server sees our final
820 // sequenced messages to the old client
821 } else {
822 Com_DPrintf ("bad connectionless packet from %s:\n%s\n",
823 NET_AdrToString (from), s);
824 }
825 }
826
827 //============================================================================
828
829 /*
830 =================
831 SV_PacketEvent
832 =================
833 */
834 void SV_PacketEvent( netadr_t from, msg_t *msg ) {
835 int i;
836 client_t *cl;
837 int qport;
838
839 // check for connectionless packet (0xffffffff) first
840 if ( msg->cursize >= 4 && *(int *)msg->data == -1) {
841 SV_ConnectionlessPacket( from, msg );
842 return;
843 }
844
845 // read the qport out of the message so we can fix up
846 // stupid address translating routers
847 MSG_BeginReadingOOB( msg );
848 MSG_ReadLong( msg ); // sequence number
849 qport = MSG_ReadShort( msg ) & 0xffff;
850
851 // find which client the message is from
852 for (i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
853 if (cl->state == CS_FREE) {
854 continue;
855 }
856 if ( !NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) ) {
857 continue;
858 }
859 // it is possible to have multiple clients from a single IP
860 // address, so they are differentiated by the qport variable
861 if (cl->netchan.qport != qport) {
862 continue;
863 }
864
865 // the IP port can't be used to differentiate them, because
866 // some address translating routers periodically change UDP
867 // port assignments
868 if (cl->netchan.remoteAddress.port != from.port) {
869 Com_Printf( "SV_PacketEvent: fixing up a translated port\n" );
870 cl->netchan.remoteAddress.port = from.port;
871 }
872
873 // make sure it is a valid, in sequence packet
874 if (SV_Netchan_Process(cl, msg)) {
875 // zombie clients still need to do the Netchan_Process
876 // to make sure they don't need to retransmit the final
877 // reliable message, but they don't do any other processing
878 if (cl->state != CS_ZOMBIE) {
879 cl->lastPacketTime = svs.time; // don't timeout
880 SV_ExecuteClientMessage( cl, msg );
881 }
882 }
883 return;
884 }
885 }
886
887
888 /*
889 ===================
890 SV_CalcPings
891
892 Updates the cl->ping variables
893 ===================
894 */
895 static void SV_CalcPings( void ) {
896 int i, j;
897 client_t *cl;
898 int total, count;
899 int delta;
900 playerState_t *ps;
901
902 for (i=0 ; i < sv_maxclients->integer ; i++) {
903 cl = &svs.clients[i];
904 if ( cl->state != CS_ACTIVE ) {
905 cl->ping = 999;
906 continue;
907 }
908 if ( !cl->gentity ) {
909 cl->ping = 999;
910 continue;
911 }
912 if ( cl->gentity->r.svFlags & SVF_BOT ) {
913 cl->ping = 0;
914 continue;
915 }
916
917 total = 0;
918 count = 0;
919 for ( j = 0 ; j < PACKET_BACKUP ; j++ ) {
920 if ( cl->frames[j].messageAcked <= 0 ) {
921 continue;
922 }
923 delta = cl->frames[j].messageAcked - cl->frames[j].messageSent;
924 count++;
925 total += delta;
926 }
927 if (!count) {
928 cl->ping = 999;
929 } else {
930 cl->ping = total/count;
931 if ( cl->ping > 999 ) {
932 cl->ping = 999;
933 }
934 }
935
936 // let the game dll know about the ping
937 ps = SV_GameClientNum( i );
938 ps->ping = cl->ping;
939 }
940 }
941
942 /*
943 ==================
944 SV_CheckTimeouts
945
946 If a packet has not been received from a client for timeout->integer
947 seconds, drop the conneciton. Server time is used instead of
948 realtime to avoid dropping the local client while debugging.
949
950 When a client is normally dropped, the client_t goes into a zombie state
951 for a few seconds to make sure any final reliable message gets resent
952 if necessary
953 ==================
954 */
955 static void SV_CheckTimeouts( void ) {
956 int i;
957 client_t *cl;
958 int droppoint;
959 int zombiepoint;
960
961 droppoint = svs.time - 1000 * sv_timeout->integer;
962 zombiepoint = svs.time - 1000 * sv_zombietime->integer;
963
964 for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
965 // message times may be wrong across a changelevel
966 if (cl->lastPacketTime > svs.time) {
967 cl->lastPacketTime = svs.time;
968 }
969
970 if (cl->state == CS_ZOMBIE
971 && cl->lastPacketTime < zombiepoint) {
972 // using the client id cause the cl->name is empty at this point
973 Com_DPrintf( "Going from CS_ZOMBIE to CS_FREE for client %d\n", i );
974 cl->state = CS_FREE; // can now be reused
975 continue;
976 }
977 if ( cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint) {
978 // wait several frames so a debugger session doesn't
979 // cause a timeout
980 if ( ++cl->timeoutCount > 5 ) {
981 SV_DropClient (cl, "timed out");
982 cl->state = CS_FREE; // don't bother with zombie state
983 }
984 } else {
985 cl->timeoutCount = 0;
986 }
987 }
988 }
989
990
991 /*
992 ==================
993 SV_CheckPaused
994 ==================
995 */
996 static qboolean SV_CheckPaused( void ) {
997 int count;
998 client_t *cl;
999 int i;
1000
1001 if ( !cl_paused->integer ) {
1002 return qfalse;
1003 }
1004
1005 // only pause if there is just a single client connected
1006 count = 0;
1007 for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
1008 if ( cl->state >= CS_CONNECTED && cl->netchan.remoteAddress.type != NA_BOT ) {
1009 count++;
1010 }
1011 }
1012
1013 if ( count > 1 ) {
1014 // don't pause
1015 if (sv_paused->integer)
1016 Cvar_Set("sv_paused", "0");
1017 return qfalse;
1018 }
1019
1020 if (!sv_paused->integer)
1021 Cvar_Set("sv_paused", "1");
1022 return qtrue;
1023 }
1024
1025 /*
1026 ==================
1027 SV_FrameMsec
1028 Return time in millseconds until processing of the next server frame.
1029 ==================
1030 */
1031 int SV_FrameMsec(void)
1032 {
1033 if(sv_fps)
1034 {
1035 int frameMsec;
1036
1037 frameMsec = 1000.0f / sv_fps->value;
1038
1039 if(frameMsec < sv.timeResidual)
1040 return 0;
1041 else
1042 return frameMsec - sv.timeResidual;
1043 }
1044 else
1045 return 1;
1046 }
1047
1048 /*
1049 ==================
1050 SV_Frame
1051
1052 Player movement occurs as a result of packet events, which
1053 happen before SV_Frame is called
1054 ==================
1055 */
1056 void SV_Frame( int msec ) {
1057 int frameMsec;
1058 int startTime;
1059
1060 // the menu kills the server with this cvar
1061 if ( sv_killserver->integer ) {
1062 SV_Shutdown ("Server was killed");
1063 Cvar_Set( "sv_killserver", "0" );
1064 return;
1065 }
1066
1067 if (!com_sv_running->integer)
1068 {
1069 // Running as a server, but no map loaded
1070 #ifdef DEDICATED
1071 // Block until something interesting happens
1072 Sys_Sleep(-1);
1073 #endif
1074
1075 return;
1076 }
1077
1078 // allow pause if only the local client is connected
1079 if ( SV_CheckPaused() ) {
1080 return;
1081 }
1082
1083 // if it isn't time for the next frame, do nothing
1084 if ( sv_fps->integer < 1 ) {
1085 Cvar_Set( "sv_fps", "10" );
1086 }
1087
1088 frameMsec = 1000 / sv_fps->integer * com_timescale->value;
1089 // don't let it scale below 1ms
1090 if(frameMsec < 1)
1091 {
1092 Cvar_Set("timescale", va("%f", sv_fps->integer / 1000.0f));
1093 frameMsec = 1;
1094 }
1095
1096 sv.timeResidual += msec;
1097
1098 if (!com_dedicated->integer) SV_BotFrame (sv.time + sv.timeResidual);
1099
1100 // if time is about to hit the 32nd bit, kick all clients
1101 // and clear sv.time, rather
1102 // than checking for negative time wraparound everywhere.
1103 // 2giga-milliseconds = 23 days, so it won't be too often
1104 if ( svs.time > 0x70000000 ) {
1105 SV_Shutdown( "Restarting server due to time wrapping" );
1106 Cbuf_AddText( va( "map %s\n", Cvar_VariableString( "mapname" ) ) );
1107 return;
1108 }
1109 // this can happen considerably earlier when lots of clients play and the map doesn't change
1110 if ( svs.nextSnapshotEntities >= 0x7FFFFFFE - svs.numSnapshotEntities ) {
1111 SV_Shutdown( "Restarting server due to numSnapshotEntities wrapping" );
1112 Cbuf_AddText( va( "map %s\n", Cvar_VariableString( "mapname" ) ) );
1113 return;
1114 }
1115
1116 if( sv.restartTime && sv.time >= sv.restartTime ) {
1117 sv.restartTime = 0;
1118 Cbuf_AddText( "map_restart 0\n" );
1119 return;
1120 }
1121
1122 // update infostrings if anything has been changed
1123 if ( cvar_modifiedFlags & CVAR_SERVERINFO ) {
1124 SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) );
1125 cvar_modifiedFlags &= ~CVAR_SERVERINFO;
1126 }
1127 if ( cvar_modifiedFlags & CVAR_SYSTEMINFO ) {
1128 SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString_Big( CVAR_SYSTEMINFO ) );
1129 cvar_modifiedFlags &= ~CVAR_SYSTEMINFO;
1130 }
1131
1132 if ( com_speeds->integer ) {
1133 startTime = Sys_Milliseconds ();
1134 } else {
1135 startTime = 0; // quite a compiler warning
1136 }
1137
1138 // update ping based on the all received frames
1139 SV_CalcPings();
1140
1141 if (com_dedicated->integer) SV_BotFrame (sv.time);
1142
1143 // run the game simulation in chunks
1144 while ( sv.timeResidual >= frameMsec ) {
1145 sv.timeResidual -= frameMsec;
1146 svs.time += frameMsec;
1147 sv.time += frameMsec;
1148
1149 // let everything in the world think and move
1150 VM_Call (gvm, GAME_RUN_FRAME, sv.time);
1151 }
1152
1153 if ( com_speeds->integer ) {
1154 time_game = Sys_Milliseconds () - startTime;
1155 }
1156
1157 // check timeouts
1158 SV_CheckTimeouts();
1159
1160 // send messages back to the clients
1161 SV_SendClientMessages();
1162
1163 // send a heartbeat to the master if needed
1164 SV_MasterHeartbeat(HEARTBEAT_FOR_MASTER);
1165 }
1166
1167 /*
1168 ====================
1169 SV_RateMsec
1170
1171 Return the number of msec until another message can be sent to
1172 a client based on its rate settings
1173 ====================
1174 */
1175
1176 #define UDPIP_HEADER_SIZE 28
1177 #define UDPIP6_HEADER_SIZE 48
1178
1179 int SV_RateMsec(client_t *client)
1180 {
1181 int rate, rateMsec;
1182 int messageSize;
1183
1184 messageSize = client->netchan.lastSentSize;
1185 rate = client->rate;
1186
1187 if(sv_maxRate->integer)
1188 {
1189 if(sv_maxRate->integer < 1000)
1190 Cvar_Set( "sv_MaxRate", "1000" );
1191 if(sv_maxRate->integer < rate)
1192 rate = sv_maxRate->integer;
1193 }
1194
1195 if(sv_minRate->integer)
1196 {
1197 if(sv_minRate->integer < 1000)
1198 Cvar_Set("sv_minRate", "1000");
1199 if(sv_minRate->integer > rate)
1200 rate = sv_minRate->integer;
1201 }
1202
1203 if(client->netchan.remoteAddress.type == NA_IP6)
1204 messageSize += UDPIP6_HEADER_SIZE;
1205 else
1206 messageSize += UDPIP_HEADER_SIZE;
1207
1208 rateMsec = messageSize * 1000 / ((int) (rate * com_timescale->value));
1209 rate = Sys_Milliseconds() - client->netchan.lastSentTime;
1210
1211 if(rate > rateMsec)
1212 return 0;
1213 else
1214 return rateMsec - rate;
1215 }
1216
1217 /*
1218 ====================
1219 SV_SendQueuedPackets
1220
1221 Send download messages and queued packets in the time that we're idle, i.e.
1222 not computing a server frame or sending client snapshots.
1223 Return the time in msec until we expect to be called next
1224 ====================
1225 */
1226
1227 int SV_SendQueuedPackets(void)
1228 {
1229 int numBlocks;
1230 int dlStart, deltaT, delayT;
1231 static int dlNextRound = 0;
1232 int timeVal = INT_MAX;
1233
1234 // Send out fragmented packets now that we're idle
1235 delayT = SV_SendQueuedMessages();
1236 if(delayT >= 0)
1237 timeVal = delayT;
1238
1239 if(sv_dlRate->integer)
1240 {
1241 // Rate limiting. This is very imprecise for high
1242 // download rates due to millisecond timedelta resolution
1243 dlStart = Sys_Milliseconds();
1244 deltaT = dlNextRound - dlStart;
1245
1246 if(deltaT > 0)
1247 {
1248 if(deltaT < timeVal)
1249 timeVal = deltaT + 1;
1250 }
1251 else
1252 {
1253 numBlocks = SV_SendDownloadMessages();
1254
1255 if(numBlocks)
1256 {
1257 // There are active downloads
1258 deltaT = Sys_Milliseconds() - dlStart;
1259
1260 delayT = 1000 * numBlocks * MAX_DOWNLOAD_BLKSIZE;
1261 delayT /= sv_dlRate->integer * 1024;
1262
1263 if(delayT <= deltaT + 1)
1264 {
1265 // Sending the last round of download messages
1266 // took too long for given rate, don't wait for
1267 // next round, but always enforce a 1ms delay
1268 // between DL message rounds so we don't hog
1269 // all of the bandwidth. This will result in an
1270 // effective maximum rate of 1MB/s per user, but the
1271 // low download window size limits this anyways.
1272 if(timeVal > 2)
1273 timeVal = 2;
1274
1275 dlNextRound = dlStart + deltaT + 1;
1276 }
1277 else
1278 {
1279 dlNextRound = dlStart + delayT;
1280 delayT -= deltaT;
1281
1282 if(delayT < timeVal)
1283 timeVal = delayT;
1284 }
1285 }
1286 }
1287 }
1288 else
1289 {
1290 if(SV_SendDownloadMessages())
1291 timeVal = 0;
1292 }
1293
1294 return timeVal;
1295 }