Debian Codegraph @

code/server/sv_main.c

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