Debian Codegraph @

code/server/sv_client.c

raw symbols SCIP
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 // sv_client.c -- server code for dealing with clients
23
24 #include "server.h"
25
26 static void SV_CloseDownload( client_t *cl );
27
28 /*
29 =================
30 SV_GetChallenge
31
32 A "getchallenge" OOB command has been received
33 Returns a challenge number that can be used
34 in a subsequent connectResponse command.
35 We do this to prevent denial of service attacks that
36 flood the server with invalid connection IPs. With a
37 challenge, they must give a valid IP address.
38
39 If we are authorizing, a challenge request will cause a packet
40 to be sent to the authorize server.
41
42 When an authorizeip is returned, a challenge response will be
43 sent to that ip.
44
45 ioquake3: we added a possibility for clients to add a challenge
46 to their packets, to make it more difficult for malicious servers
47 to hi-jack client connections.
48 Also, the auth stuff is completely disabled for com_standalone games
49 as well as IPv6 connections, since there is no way to use the
50 v4-only auth server for these new types of connections.
51 =================
52 */
53 void SV_GetChallenge(netadr_t from)
54 {
55 int i;
56 int oldest;
57 int oldestTime;
58 int oldestClientTime;
59 int clientChallenge;
60 challenge_t *challenge;
61 qboolean wasfound = qfalse;
62 char *gameName;
63 qboolean gameMismatch;
64
65 // ignore if we are in single player
66 if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")) {
67 return;
68 }
69
70 // Prevent using getchallenge as an amplifier
71 if ( SVC_RateLimitAddress( from, 10, 1000 ) ) {
72 Com_DPrintf( "SV_GetChallenge: rate limit from %s exceeded, dropping request\n",
73 NET_AdrToString( from ) );
74 return;
75 }
76
77 // Allow getchallenge to be DoSed relatively easily, but prevent
78 // excess outbound bandwidth usage when being flooded inbound
79 if ( SVC_RateLimit( &outboundLeakyBucket, 10, 100 ) ) {
80 Com_DPrintf( "SV_GetChallenge: rate limit exceeded, dropping request\n" );
81 return;
82 }
83
84 gameName = Cmd_Argv(2);
85
86 #ifdef LEGACY_PROTOCOL
87 // gamename is optional for legacy protocol
88 if (com_legacyprotocol->integer && !*gameName)
89 gameMismatch = qfalse;
90 else
91 #endif
92 gameMismatch = !*gameName || strcmp(gameName, com_gamename->string) != 0;
93
94 // reject client if the gamename string sent by the client doesn't match ours
95 if (gameMismatch)
96 {
97 NET_OutOfBandPrint(NS_SERVER, from, "print\nGame mismatch: This is a %s server\n",
98 com_gamename->string);
99 return;
100 }
101
102 oldest = 0;
103 oldestClientTime = oldestTime = 0x7fffffff;
104
105 // see if we already have a challenge for this ip
106 challenge = &svs.challenges[0];
107 clientChallenge = atoi(Cmd_Argv(1));
108
109 for(i = 0 ; i < MAX_CHALLENGES ; i++, challenge++)
110 {
111 if(!challenge->connected && NET_CompareAdr(from, challenge->adr))
112 {
113 wasfound = qtrue;
114
115 if(challenge->time < oldestClientTime)
116 oldestClientTime = challenge->time;
117 }
118
119 if(wasfound && i >= MAX_CHALLENGES_MULTI)
120 {
121 i = MAX_CHALLENGES;
122 break;
123 }
124
125 if(challenge->time < oldestTime)
126 {
127 oldestTime = challenge->time;
128 oldest = i;
129 }
130 }
131
132 if (i == MAX_CHALLENGES)
133 {
134 // this is the first time this client has asked for a challenge
135 challenge = &svs.challenges[oldest];
136 challenge->clientChallenge = clientChallenge;
137 challenge->adr = from;
138 challenge->firstTime = svs.time;
139 challenge->connected = qfalse;
140 }
141
142 // always generate a new challenge number, so the client cannot circumvent sv_maxping
143 challenge->challenge = ( ((unsigned int)rand() << 16) ^ (unsigned int)rand() ) ^ svs.time;
144 challenge->wasrefused = qfalse;
145 challenge->time = svs.time;
146
147 #ifndef STANDALONE
148 // Drop the authorize stuff if this client is coming in via v6 as the auth server does not support ipv6.
149 // Drop also for addresses coming in on local LAN and for stand-alone games independent from id's assets.
150 if(challenge->adr.type == NA_IP && !com_standalone->integer && !Sys_IsLANAddress(from))
151 {
152 // look up the authorize server's IP
153 if (svs.authorizeAddress.type == NA_BAD)
154 {
155 Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
156
157 if (NET_StringToAdr(AUTHORIZE_SERVER_NAME, &svs.authorizeAddress, NA_IP))
158 {
159 svs.authorizeAddress.port = BigShort( PORT_AUTHORIZE );
160 Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
161 svs.authorizeAddress.ip[0], svs.authorizeAddress.ip[1],
162 svs.authorizeAddress.ip[2], svs.authorizeAddress.ip[3],
163 BigShort( svs.authorizeAddress.port ) );
164 }
165 }
166
167 // we couldn't contact the auth server, let them in.
168 if(svs.authorizeAddress.type == NA_BAD)
169 Com_Printf("Couldn't resolve auth server address\n");
170
171 // if they have been challenging for a long time and we
172 // haven't heard anything from the authorize server, go ahead and
173 // let them in, assuming the id server is down
174 else if(svs.time - oldestClientTime > AUTHORIZE_TIMEOUT)
175 Com_DPrintf( "authorize server timed out\n" );
176 else
177 {
178 // otherwise send their ip to the authorize server
179 const char *game;
180
181 Com_DPrintf( "sending getIpAuthorize for %s\n", NET_AdrToString( from ));
182
183 game = Cvar_VariableString( "fs_game" );
184 if (game[0] == 0) {
185 game = BASEGAME;
186 }
187
188 // the 0 is for backwards compatibility with obsolete sv_allowanonymous flags
189 // getIpAuthorize <challenge> <IP> <game> 0 <auth-flag>
190 NET_OutOfBandPrint( NS_SERVER, svs.authorizeAddress,
191 "getIpAuthorize %i %i.%i.%i.%i %s 0 %s", challenge->challenge,
192 from.ip[0], from.ip[1], from.ip[2], from.ip[3], game, sv_strictAuth->string );
193
194 return;
195 }
196 }
197 #endif
198
199 challenge->pingTime = svs.time;
200 NET_OutOfBandPrint(NS_SERVER, challenge->adr, "challengeResponse %d %d %d",
201 challenge->challenge, clientChallenge, com_protocol->integer);
202 }
203
204 #ifndef STANDALONE
205 /*
206 ====================
207 SV_AuthorizeIpPacket
208
209 A packet has been returned from the authorize server.
210 If we have a challenge adr for that ip, send the
211 challengeResponse to it
212 ====================
213 */
214 void SV_AuthorizeIpPacket( netadr_t from ) {
215 int challenge;
216 int i;
217 char *s;
218 char *r;
219 challenge_t *challengeptr;
220
221 if ( !NET_CompareBaseAdr( from, svs.authorizeAddress ) ) {
222 Com_Printf( "SV_AuthorizeIpPacket: not from authorize server\n" );
223 return;
224 }
225
226 challenge = atoi( Cmd_Argv( 1 ) );
227
228 for (i = 0 ; i < MAX_CHALLENGES ; i++) {
229 if ( svs.challenges[i].challenge == challenge ) {
230 break;
231 }
232 }
233 if ( i == MAX_CHALLENGES ) {
234 Com_Printf( "SV_AuthorizeIpPacket: challenge not found\n" );
235 return;
236 }
237
238 challengeptr = &svs.challenges[i];
239
240 // send a packet back to the original client
241 challengeptr->pingTime = svs.time;
242 s = Cmd_Argv( 2 );
243 r = Cmd_Argv( 3 ); // reason
244
245 if ( !Q_stricmp( s, "demo" ) ) {
246 // they are a demo client trying to connect to a real server
247 NET_OutOfBandPrint( NS_SERVER, challengeptr->adr, "print\nServer is not a demo server\n" );
248 // clear the challenge record so it won't timeout and let them through
249 Com_Memset( challengeptr, 0, sizeof( *challengeptr ) );
250 return;
251 }
252 if ( !Q_stricmp( s, "accept" ) ) {
253 NET_OutOfBandPrint(NS_SERVER, challengeptr->adr,
254 "challengeResponse %d %d %d", challengeptr->challenge, challengeptr->clientChallenge, com_protocol->integer);
255 return;
256 }
257 if ( !Q_stricmp( s, "unknown" ) ) {
258 if (!r) {
259 NET_OutOfBandPrint( NS_SERVER, challengeptr->adr, "print\nAwaiting CD key authorization\n" );
260 } else {
261 NET_OutOfBandPrint( NS_SERVER, challengeptr->adr, "print\n%s\n", r);
262 }
263 // clear the challenge record so it won't timeout and let them through
264 Com_Memset( challengeptr, 0, sizeof( *challengeptr ) );
265 return;
266 }
267
268 // authorization failed
269 if (!r) {
270 NET_OutOfBandPrint( NS_SERVER, challengeptr->adr, "print\nSomeone is using this CD Key\n" );
271 } else {
272 NET_OutOfBandPrint( NS_SERVER, challengeptr->adr, "print\n%s\n", r );
273 }
274
275 // clear the challenge record so it won't timeout and let them through
276 Com_Memset( challengeptr, 0, sizeof(*challengeptr) );
277 }
278 #endif
279
280 /*
281 ==================
282 SV_IsBanned
283
284 Check whether a certain address is banned
285 ==================
286 */
287
288 static qboolean SV_IsBanned(netadr_t *from, qboolean isexception)
289 {
290 int index;
291 serverBan_t *curban;
292
293 if(!isexception)
294 {
295 // If this is a query for a ban, first check whether the client is excepted
296 if(SV_IsBanned(from, qtrue))
297 return qfalse;
298 }
299
300 for(index = 0; index < serverBansCount; index++)
301 {
302 curban = &serverBans[index];
303
304 if(curban->isexception == isexception)
305 {
306 if(NET_CompareBaseAdrMask(curban->ip, *from, curban->subnet))
307 return qtrue;
308 }
309 }
310
311 return qfalse;
312 }
313
314 /*
315 ==================
316 SV_DirectConnect
317
318 A "connect" OOB command has been received
319 ==================
320 */
321
322 void SV_DirectConnect( netadr_t from ) {
323 char userinfo[MAX_INFO_STRING];
324 int i;
325 client_t *cl, *newcl;
326 client_t temp;
327 sharedEntity_t *ent;
328 int clientNum;
329 int version;
330 int qport;
331 int challenge;
332 char *password;
333 int startIndex;
334 intptr_t denied;
335 int count;
336 char *ip;
337 #ifdef LEGACY_PROTOCOL
338 qboolean compat = qfalse;
339 #endif
340
341 Com_DPrintf ("SVC_DirectConnect ()\n");
342
343 // Check whether this client is banned.
344 if(SV_IsBanned(&from, qfalse))
345 {
346 NET_OutOfBandPrint(NS_SERVER, from, "print\nYou are banned from this server.\n");
347 return;
348 }
349
350 Q_strncpyz( userinfo, Cmd_Argv(1), sizeof(userinfo) );
351
352 version = atoi(Info_ValueForKey(userinfo, "protocol"));
353
354 #ifdef LEGACY_PROTOCOL
355 if(version > 0 && com_legacyprotocol->integer == version)
356 compat = qtrue;
357 else
358 #endif
359 {
360 if(version != com_protocol->integer)
361 {
362 NET_OutOfBandPrint(NS_SERVER, from, "print\nServer uses protocol version %i "
363 "(yours is %i).\n", com_protocol->integer, version);
364 Com_DPrintf(" rejected connect from version %i\n", version);
365 return;
366 }
367 }
368
369 challenge = atoi( Info_ValueForKey( userinfo, "challenge" ) );
370 qport = atoi( Info_ValueForKey( userinfo, "qport" ) );
371
372 // quick reject
373 for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
374 if ( cl->state == CS_FREE ) {
375 continue;
376 }
377 if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress )
378 && ( cl->netchan.qport == qport
379 || from.port == cl->netchan.remoteAddress.port ) ) {
380 if (( svs.time - cl->lastConnectTime)
381 < (sv_reconnectlimit->integer * 1000)) {
382 Com_DPrintf ("%s:reconnect rejected : too soon\n", NET_AdrToString (from));
383 return;
384 }
385 break;
386 }
387 }
388
389 // don't let "ip" overflow userinfo string
390 if ( NET_IsLocalAddress (from) )
391 ip = "localhost";
392 else
393 ip = (char *)NET_AdrToString( from );
394 if( ( strlen( ip ) + strlen( userinfo ) + 4 ) >= MAX_INFO_STRING ) {
395 NET_OutOfBandPrint( NS_SERVER, from,
396 "print\nUserinfo string length exceeded. "
397 "Try removing setu cvars from your config.\n" );
398 return;
399 }
400 Info_SetValueForKey( userinfo, "ip", ip );
401
402 // see if the challenge is valid (LAN clients don't need to challenge)
403 if (!NET_IsLocalAddress(from))
404 {
405 int ping;
406 challenge_t *challengeptr;
407
408 for (i=0; i<MAX_CHALLENGES; i++)
409 {
410 if (NET_CompareAdr(from, svs.challenges[i].adr))
411 {
412 if(challenge == svs.challenges[i].challenge)
413 break;
414 }
415 }
416
417 if (i == MAX_CHALLENGES)
418 {
419 NET_OutOfBandPrint( NS_SERVER, from, "print\nNo or bad challenge for your address.\n" );
420 return;
421 }
422
423 challengeptr = &svs.challenges[i];
424
425 if(challengeptr->wasrefused)
426 {
427 // Return silently, so that error messages written by the server keep being displayed.
428 return;
429 }
430
431 ping = svs.time - challengeptr->pingTime;
432
433 // never reject a LAN client based on ping
434 if ( !Sys_IsLANAddress( from ) ) {
435 if ( sv_minPing->value && ping < sv_minPing->value ) {
436 NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is for high pings only\n" );
437 Com_DPrintf ("Client %i rejected on a too low ping\n", i);
438 challengeptr->wasrefused = qtrue;
439 return;
440 }
441 if ( sv_maxPing->value && ping > sv_maxPing->value ) {
442 NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is for low pings only\n" );
443 Com_DPrintf ("Client %i rejected on a too high ping\n", i);
444 challengeptr->wasrefused = qtrue;
445 return;
446 }
447 }
448
449 Com_Printf("Client %i connecting with %i challenge ping\n", i, ping);
450 challengeptr->connected = qtrue;
451 }
452
453 newcl = &temp;
454 Com_Memset (newcl, 0, sizeof(client_t));
455
456 // if there is already a slot for this ip, reuse it
457 for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
458 if ( cl->state == CS_FREE ) {
459 continue;
460 }
461 if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress )
462 && ( cl->netchan.qport == qport
463 || from.port == cl->netchan.remoteAddress.port ) ) {
464 Com_Printf ("%s:reconnect\n", NET_AdrToString (from));
465 newcl = cl;
466
467 // this doesn't work because it nukes the players userinfo
468
469 // // disconnect the client from the game first so any flags the
470 // // player might have are dropped
471 // VM_Call( gvm, GAME_CLIENT_DISCONNECT, newcl - svs.clients );
472 //
473 goto gotnewcl;
474 }
475 }
476
477 // find a client slot
478 // if "sv_privateClients" is set > 0, then that number
479 // of client slots will be reserved for connections that
480 // have "password" set to the value of "sv_privatePassword"
481 // Info requests will report the maxclients as if the private
482 // slots didn't exist, to prevent people from trying to connect
483 // to a full server.
484 // This is to allow us to reserve a couple slots here on our
485 // servers so we can play without having to kick people.
486
487 // check for privateClient password
488 password = Info_ValueForKey( userinfo, "password" );
489 if ( *password && !strcmp( password, sv_privatePassword->string ) ) {
490 startIndex = 0;
491 } else {
492 // skip past the reserved slots
493 startIndex = sv_privateClients->integer;
494 }
495
496 newcl = NULL;
497 for ( i = startIndex; i < sv_maxclients->integer ; i++ ) {
498 cl = &svs.clients[i];
499 if (cl->state == CS_FREE) {
500 newcl = cl;
501 break;
502 }
503 }
504
505 if ( !newcl ) {
506 if ( NET_IsLocalAddress( from ) ) {
507 count = 0;
508 for ( i = startIndex; i < sv_maxclients->integer ; i++ ) {
509 cl = &svs.clients[i];
510 if (cl->netchan.remoteAddress.type == NA_BOT) {
511 count++;
512 }
513 }
514 // if they're all bots
515 if (count >= sv_maxclients->integer - startIndex) {
516 SV_DropClient(&svs.clients[sv_maxclients->integer - 1], "only bots on server");
517 newcl = &svs.clients[sv_maxclients->integer - 1];
518 }
519 else {
520 Com_Error( ERR_FATAL, "server is full on local connect" );
521 return;
522 }
523 }
524 else {
525 NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is full\n" );
526 Com_DPrintf ("Rejected a connection.\n");
527 return;
528 }
529 }
530
531 // we got a newcl, so reset the reliableSequence and reliableAcknowledge
532 cl->reliableAcknowledge = 0;
533 cl->reliableSequence = 0;
534
535 gotnewcl:
536 // build a new connection
537 // accept the new client
538 // this is the only place a client_t is ever initialized
539 *newcl = temp;
540 clientNum = newcl - svs.clients;
541 ent = SV_GentityNum( clientNum );
542 newcl->gentity = ent;
543
544 // save the challenge
545 newcl->challenge = challenge;
546
547 // save the address
548 #ifdef LEGACY_PROTOCOL
549 newcl->compat = compat;
550 Netchan_Setup(NS_SERVER, &newcl->netchan, from, qport, challenge, compat);
551 #else
552 Netchan_Setup(NS_SERVER, &newcl->netchan, from, qport, challenge, qfalse);
553 #endif
554 // init the netchan queue
555 newcl->netchan_end_queue = &newcl->netchan_start_queue;
556
557 // save the userinfo
558 Q_strncpyz( newcl->userinfo, userinfo, sizeof(newcl->userinfo) );
559
560 // get the game a chance to reject this connection or modify the userinfo
561 denied = VM_Call( gvm, GAME_CLIENT_CONNECT, clientNum, qtrue, qfalse ); // firstTime = qtrue
562 if ( denied ) {
563 // we can't just use VM_ArgPtr, because that is only valid inside a VM_Call
564 char *str = VM_ExplicitArgPtr( gvm, denied );
565
566 NET_OutOfBandPrint( NS_SERVER, from, "print\n%s\n", str );
567 Com_DPrintf ("Game rejected a connection: %s.\n", str);
568 return;
569 }
570
571 SV_UserinfoChanged( newcl );
572
573 // send the connect packet to the client
574 NET_OutOfBandPrint(NS_SERVER, from, "connectResponse %d", challenge);
575
576 Com_DPrintf( "Going from CS_FREE to CS_CONNECTED for %s\n", newcl->name );
577
578 newcl->state = CS_CONNECTED;
579 newcl->lastSnapshotTime = 0;
580 newcl->lastPacketTime = svs.time;
581 newcl->lastConnectTime = svs.time;
582
583 // when we receive the first packet from the client, we will
584 // notice that it is from a different serverid and that the
585 // gamestate message was not just sent, forcing a retransmit
586 newcl->gamestateMessageNum = -1;
587
588 // if this was the first client on the server, or the last client
589 // the server can hold, send a heartbeat to the master.
590 count = 0;
591 for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
592 if ( svs.clients[i].state >= CS_CONNECTED ) {
593 count++;
594 }
595 }
596 if ( count == 1 || count == sv_maxclients->integer ) {
597 SV_Heartbeat_f();
598 }
599 }
600
601 /*
602 =====================
603 SV_FreeClient
604
605 Destructor for data allocated in a client structure
606 =====================
607 */
608 void SV_FreeClient(client_t *client)
609 {
610 #ifdef USE_VOIP
611 int index;
612
613 for(index = client->queuedVoipIndex; index < client->queuedVoipPackets; index++)
614 {
615 index %= ARRAY_LEN(client->voipPacket);
616
617 Z_Free(client->voipPacket[index]);
618 }
619
620 client->queuedVoipPackets = 0;
621 #endif
622
623 SV_Netchan_FreeQueue(client);
624 SV_CloseDownload(client);
625 }
626
627 /*
628 =====================
629 SV_DropClient
630
631 Called when the player is totally leaving the server, either willingly
632 or unwillingly. This is NOT called if the entire server is quiting
633 or crashing -- SV_FinalMessage() will handle that
634 =====================
635 */
636 void SV_DropClient( client_t *drop, const char *reason ) {
637 int i;
638 challenge_t *challenge;
639 const qboolean isBot = drop->netchan.remoteAddress.type == NA_BOT;
640
641 if ( drop->state == CS_ZOMBIE ) {
642 return; // already dropped
643 }
644
645 if ( !isBot ) {
646 // see if we already have a challenge for this ip
647 challenge = &svs.challenges[0];
648
649 for (i = 0 ; i < MAX_CHALLENGES ; i++, challenge++)
650 {
651 if(NET_CompareAdr(drop->netchan.remoteAddress, challenge->adr))
652 {
653 Com_Memset(challenge, 0, sizeof(*challenge));
654 break;
655 }
656 }
657 }
658
659 // Free all allocated data on the client structure
660 SV_FreeClient(drop);
661
662 // Reset the reliable sequence to the currently acknowledged command
663 // This prevents SV_AddServerCommand() from making another recursive call to SV_DropClient()
664 // if the client lacks sufficient space for another reliable command
665 // it also guarantees that the client receives both the print and disconnect commands
666 drop->reliableSequence = drop->reliableAcknowledge;
667 // Setting the gamestate message number to -1 ensures that SV_AddServerCommand()
668 // will not call SV_DropClient() again, even though it is unlikely the client
669 // will receive many server commands during the drop
670 drop->gamestateMessageNum = -1;
671
672 // tell everyone why they got dropped
673 SV_SendServerCommand( NULL, "print \"%s" S_COLOR_WHITE " %s\n\"", drop->name, reason );
674
675 // call the prog function for removing a client
676 // this will remove the body, among other things
677 VM_Call( gvm, GAME_CLIENT_DISCONNECT, drop - svs.clients );
678
679 // add the disconnect command
680 SV_SendServerCommand( drop, "disconnect \"%s\"", reason);
681
682 if ( isBot ) {
683 SV_BotFreeClient( drop - svs.clients );
684
685 // bots shouldn't go zombie, as there's no real net connection.
686 drop->state = CS_FREE;
687 } else {
688 Com_DPrintf( "Going to CS_ZOMBIE for %s\n", drop->name );
689 drop->state = CS_ZOMBIE; // become free in a few seconds
690 }
691
692 // nuke user info
693 SV_SetUserinfo( drop - svs.clients, "" );
694
695 // if this was the last client on the server, send a heartbeat
696 // to the master so it is known the server is empty
697 // send a heartbeat now so the master will get up to date info
698 // if there is already a slot for this ip, reuse it
699 for (i=0 ; i < sv_maxclients->integer ; i++ ) {
700 if ( svs.clients[i].state >= CS_CONNECTED ) {
701 break;
702 }
703 }
704 if ( i == sv_maxclients->integer ) {
705 SV_Heartbeat_f();
706 }
707 }
708
709 /*
710 ================
711 SV_SendClientGameState
712
713 Sends the first message from the server to a connected client.
714 This will be sent on the initial connection and upon each new map load.
715
716 It will be resent if the client acknowledges a later message but has
717 the wrong gamestate.
718 ================
719 */
720 static void SV_SendClientGameState( client_t *client ) {
721 int start;
722 entityState_t *base, nullstate;
723 msg_t msg;
724 byte msgBuffer[MAX_MSGLEN];
725
726 Com_DPrintf ("SV_SendClientGameState() for %s\n", client->name);
727 Com_DPrintf( "Going from CS_CONNECTED to CS_PRIMED for %s\n", client->name );
728 client->state = CS_PRIMED;
729 client->pureAuthentic = 0;
730 client->gotCP = qfalse;
731
732 // when we receive the first packet from the client, we will
733 // notice that it is from a different serverid and that the
734 // gamestate message was not just sent, forcing a retransmit
735 client->gamestateMessageNum = client->netchan.outgoingSequence;
736
737 MSG_Init( &msg, msgBuffer, sizeof( msgBuffer ) );
738
739 // NOTE, MRE: all server->client messages now acknowledge
740 // let the client know which reliable clientCommands we have received
741 MSG_WriteLong( &msg, client->lastClientCommand );
742
743 // send any server commands waiting to be sent first.
744 // we have to do this cause we send the client->reliableSequence
745 // with a gamestate and it sets the clc.serverCommandSequence at
746 // the client side
747 SV_UpdateServerCommandsToClient( client, &msg );
748
749 // send the gamestate
750 MSG_WriteByte( &msg, svc_gamestate );
751 MSG_WriteLong( &msg, client->reliableSequence );
752
753 // write the configstrings
754 for ( start = 0 ; start < MAX_CONFIGSTRINGS ; start++ ) {
755 if (sv.configstrings[start][0]) {
756 MSG_WriteByte( &msg, svc_configstring );
757 MSG_WriteShort( &msg, start );
758 MSG_WriteBigString( &msg, sv.configstrings[start] );
759 }
760 }
761
762 // write the baselines
763 Com_Memset( &nullstate, 0, sizeof( nullstate ) );
764 for ( start = 0 ; start < MAX_GENTITIES; start++ ) {
765 base = &sv.svEntities[start].baseline;
766 if ( !base->number ) {
767 continue;
768 }
769 MSG_WriteByte( &msg, svc_baseline );
770 MSG_WriteDeltaEntity( &msg, &nullstate, base, qtrue );
771 }
772
773 MSG_WriteByte( &msg, svc_EOF );
774
775 MSG_WriteLong( &msg, client - svs.clients);
776
777 // write the checksum feed
778 MSG_WriteLong( &msg, sv.checksumFeed);
779
780 // deliver this to the client
781 SV_SendMessageToClient( &msg, client );
782 }
783
784
785 /*
786 ==================
787 SV_ClientEnterWorld
788 ==================
789 */
790 void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd ) {
791 int clientNum;
792 sharedEntity_t *ent;
793
794 Com_DPrintf( "Going from CS_PRIMED to CS_ACTIVE for %s\n", client->name );
795 client->state = CS_ACTIVE;
796
797 // resend all configstrings using the cs commands since these are
798 // no longer sent when the client is CS_PRIMED
799 SV_UpdateConfigstrings( client );
800
801 // set up the entity for the client
802 clientNum = client - svs.clients;
803 ent = SV_GentityNum( clientNum );
804 ent->s.number = clientNum;
805 client->gentity = ent;
806
807 client->deltaMessage = -1;
808 client->lastSnapshotTime = 0; // generate a snapshot immediately
809
810 if(cmd)
811 memcpy(&client->lastUsercmd, cmd, sizeof(client->lastUsercmd));
812 else
813 memset(&client->lastUsercmd, '\0', sizeof(client->lastUsercmd));
814
815 // call the game begin function
816 VM_Call( gvm, GAME_CLIENT_BEGIN, client - svs.clients );
817 }
818
819 /*
820 ============================================================
821
822 CLIENT COMMAND EXECUTION
823
824 ============================================================
825 */
826
827 /*
828 ==================
829 SV_CloseDownload
830
831 clear/free any download vars
832 ==================
833 */
834 static void SV_CloseDownload( client_t *cl ) {
835 int i;
836
837 // EOF
838 if (cl->download) {
839 FS_FCloseFile( cl->download );
840 }
841 cl->download = 0;
842 *cl->downloadName = 0;
843
844 // Free the temporary buffer space
845 for (i = 0; i < MAX_DOWNLOAD_WINDOW; i++) {
846 if (cl->downloadBlocks[i]) {
847 Z_Free(cl->downloadBlocks[i]);
848 cl->downloadBlocks[i] = NULL;
849 }
850 }
851
852 }
853
854 /*
855 ==================
856 SV_StopDownload_f
857
858 Abort a download if in progress
859 ==================
860 */
861 static void SV_StopDownload_f( client_t *cl ) {
862 if (*cl->downloadName)
863 Com_DPrintf( "clientDownload: %d : file \"%s\" aborted\n", (int) (cl - svs.clients), cl->downloadName );
864
865 SV_CloseDownload( cl );
866 }
867
868 /*
869 ==================
870 SV_DoneDownload_f
871
872 Downloads are finished
873 ==================
874 */
875 static void SV_DoneDownload_f( client_t *cl ) {
876 if ( cl->state == CS_ACTIVE )
877 return;
878
879 Com_DPrintf( "clientDownload: %s Done\n", cl->name);
880 // resend the game state to update any clients that entered during the download
881 SV_SendClientGameState(cl);
882 }
883
884 /*
885 ==================
886 SV_NextDownload_f
887
888 The argument will be the last acknowledged block from the client, it should be
889 the same as cl->downloadClientBlock
890 ==================
891 */
892 static void SV_NextDownload_f( client_t *cl )
893 {
894 int block = atoi( Cmd_Argv(1) );
895
896 if (block == cl->downloadClientBlock) {
897 Com_DPrintf( "clientDownload: %d : client acknowledge of block %d\n", (int) (cl - svs.clients), block );
898
899 // Find out if we are done. A zero-length block indicates EOF
900 if (cl->downloadBlockSize[cl->downloadClientBlock % MAX_DOWNLOAD_WINDOW] == 0) {
901 Com_Printf( "clientDownload: %d : file \"%s\" completed\n", (int) (cl - svs.clients), cl->downloadName );
902 SV_CloseDownload( cl );
903 return;
904 }
905
906 cl->downloadSendTime = svs.time;
907 cl->downloadClientBlock++;
908 return;
909 }
910 // We aren't getting an acknowledge for the correct block, drop the client
911 // FIXME: this is bad... the client will never parse the disconnect message
912 // because the cgame isn't loaded yet
913 SV_DropClient( cl, "broken download" );
914 }
915
916 /*
917 ==================
918 SV_BeginDownload_f
919 ==================
920 */
921 static void SV_BeginDownload_f( client_t *cl ) {
922
923 // Kill any existing download
924 SV_CloseDownload( cl );
925
926 // cl->downloadName is non-zero now, SV_WriteDownloadToClient will see this and open
927 // the file itself
928 Q_strncpyz( cl->downloadName, Cmd_Argv(1), sizeof(cl->downloadName) );
929 }
930
931 /*
932 ==================
933 SV_WriteDownloadToClient
934
935 Check to see if the client wants a file, open it if needed and start pumping the client
936 Fill up msg with data, return number of download blocks added
937 ==================
938 */
939 int SV_WriteDownloadToClient(client_t *cl, msg_t *msg)
940 {
941 int curindex;
942 int unreferenced = 1;
943 char errorMessage[1024];
944 char pakbuf[MAX_QPATH], *pakptr;
945 int numRefPaks;
946
947 if (!*cl->downloadName)
948 return 0; // Nothing being downloaded
949
950 if(!cl->download)
951 {
952 qboolean idPack = qfalse;
953 #ifndef STANDALONE
954 qboolean missionPack = qfalse;
955 #endif
956
957 // Chop off filename extension.
958 Com_sprintf(pakbuf, sizeof(pakbuf), "%s", cl->downloadName);
959 pakptr = strrchr(pakbuf, '.');
960
961 if(pakptr)
962 {
963 *pakptr = '\0';
964
965 // Check for pk3 filename extension
966 if(!Q_stricmp(pakptr + 1, "pk3"))
967 {
968 const char *referencedPaks = FS_ReferencedPakNames();
969
970 // Check whether the file appears in the list of referenced
971 // paks to prevent downloading of arbitrary files.
972 Cmd_TokenizeStringIgnoreQuotes(referencedPaks);
973 numRefPaks = Cmd_Argc();
974
975 for(curindex = 0; curindex < numRefPaks; curindex++)
976 {
977 if(!FS_FilenameCompare(Cmd_Argv(curindex), pakbuf))
978 {
979 unreferenced = 0;
980
981 // now that we know the file is referenced,
982 // check whether it's legal to download it.
983 #ifndef STANDALONE
984 missionPack = FS_idPak(pakbuf, BASETA, NUM_TA_PAKS);
985 idPack = missionPack;
986 #endif
987 idPack = idPack || FS_idPak(pakbuf, BASEGAME, NUM_ID_PAKS);
988
989 break;
990 }
991 }
992 }
993 }
994
995 cl->download = 0;
996
997 // We open the file here
998 if ( !(sv_allowDownload->integer & DLF_ENABLE) ||
999 (sv_allowDownload->integer & DLF_NO_UDP) ||
1000 idPack || unreferenced ||
1001 ( cl->downloadSize = FS_BaseDir_FOpenFileRead( cl->downloadName, &cl->download ) ) < 0 ) {
1002 // cannot auto-download file
1003 if(unreferenced)
1004 {
1005 Com_Printf("clientDownload: %d : \"%s\" is not referenced and cannot be downloaded.\n", (int) (cl - svs.clients), cl->downloadName);
1006 Com_sprintf(errorMessage, sizeof(errorMessage), "File \"%s\" is not referenced and cannot be downloaded.", cl->downloadName);
1007 }
1008 else if (idPack) {
1009 Com_Printf("clientDownload: %d : \"%s\" cannot download id pk3 files\n", (int) (cl - svs.clients), cl->downloadName);
1010 #ifndef STANDALONE
1011 if(missionPack)
1012 {
1013 Com_sprintf(errorMessage, sizeof(errorMessage), "Cannot autodownload Team Arena file \"%s\"\n"
1014 "The Team Arena mission pack can be found in your local game store.", cl->downloadName);
1015 }
1016 else
1017 #endif
1018 {
1019 Com_sprintf(errorMessage, sizeof(errorMessage), "Cannot autodownload id pk3 file \"%s\"", cl->downloadName);
1020 }
1021 }
1022 else if ( !(sv_allowDownload->integer & DLF_ENABLE) ||
1023 (sv_allowDownload->integer & DLF_NO_UDP) ) {
1024
1025 Com_Printf("clientDownload: %d : \"%s\" download disabled\n", (int) (cl - svs.clients), cl->downloadName);
1026 if (sv_pure->integer) {
1027 Com_sprintf(errorMessage, sizeof(errorMessage), "Could not download \"%s\" because autodownloading is disabled on the server.\n\n"
1028 "You will need to get this file elsewhere before you "
1029 "can connect to this pure server.\n", cl->downloadName);
1030 } else {
1031 Com_sprintf(errorMessage, sizeof(errorMessage), "Could not download \"%s\" because autodownloading is disabled on the server.\n\n"
1032 "The server you are connecting to is not a pure server, "
1033 "set autodownload to No in your settings and you might be "
1034 "able to join the game anyway.\n", cl->downloadName);
1035 }
1036 } else {
1037 // NOTE TTimo this is NOT supposed to happen unless bug in our filesystem scheme?
1038 // if the pk3 is referenced, it must have been found somewhere in the filesystem
1039 Com_Printf("clientDownload: %d : \"%s\" file not found on server\n", (int) (cl - svs.clients), cl->downloadName);
1040 Com_sprintf(errorMessage, sizeof(errorMessage), "File \"%s\" not found on server for autodownloading.\n", cl->downloadName);
1041 }
1042 MSG_WriteByte( msg, svc_download );
1043 MSG_WriteShort( msg, 0 ); // client is expecting block zero
1044 MSG_WriteLong( msg, -1 ); // illegal file size
1045 MSG_WriteString( msg, errorMessage );
1046
1047 *cl->downloadName = 0;
1048
1049 if(cl->download)
1050 FS_FCloseFile(cl->download);
1051
1052 return 1;
1053 }
1054
1055 Com_Printf( "clientDownload: %d : beginning \"%s\"\n", (int) (cl - svs.clients), cl->downloadName );
1056
1057 // Init
1058 cl->downloadCurrentBlock = cl->downloadClientBlock = cl->downloadXmitBlock = 0;
1059 cl->downloadCount = 0;
1060 cl->downloadEOF = qfalse;
1061 }
1062
1063 // Perform any reads that we need to
1064 while (cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW &&
1065 cl->downloadSize != cl->downloadCount) {
1066
1067 curindex = (cl->downloadCurrentBlock % MAX_DOWNLOAD_WINDOW);
1068
1069 if (!cl->downloadBlocks[curindex])
1070 cl->downloadBlocks[curindex] = Z_Malloc(MAX_DOWNLOAD_BLKSIZE);
1071
1072 cl->downloadBlockSize[curindex] = FS_Read( cl->downloadBlocks[curindex], MAX_DOWNLOAD_BLKSIZE, cl->download );
1073
1074 if (cl->downloadBlockSize[curindex] < 0) {
1075 // EOF right now
1076 cl->downloadCount = cl->downloadSize;
1077 break;
1078 }
1079
1080 cl->downloadCount += cl->downloadBlockSize[curindex];
1081
1082 // Load in next block
1083 cl->downloadCurrentBlock++;
1084 }
1085
1086 // Check to see if we have eof condition and add the EOF block
1087 if (cl->downloadCount == cl->downloadSize &&
1088 !cl->downloadEOF &&
1089 cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW) {
1090
1091 cl->downloadBlockSize[cl->downloadCurrentBlock % MAX_DOWNLOAD_WINDOW] = 0;
1092 cl->downloadCurrentBlock++;
1093
1094 cl->downloadEOF = qtrue; // We have added the EOF block
1095 }
1096
1097 if (cl->downloadClientBlock == cl->downloadCurrentBlock)
1098 return 0; // Nothing to transmit
1099
1100 // Write out the next section of the file, if we have already reached our window,
1101 // automatically start retransmitting
1102 if (cl->downloadXmitBlock == cl->downloadCurrentBlock)
1103 {
1104 // We have transmitted the complete window, should we start resending?
1105 if (svs.time - cl->downloadSendTime > 1000)
1106 cl->downloadXmitBlock = cl->downloadClientBlock;
1107 else
1108 return 0;
1109 }
1110
1111 // Send current block
1112 curindex = (cl->downloadXmitBlock % MAX_DOWNLOAD_WINDOW);
1113
1114 MSG_WriteByte( msg, svc_download );
1115 MSG_WriteShort( msg, cl->downloadXmitBlock );
1116
1117 // block zero is special, contains file size
1118 if ( cl->downloadXmitBlock == 0 )
1119 MSG_WriteLong( msg, cl->downloadSize );
1120
1121 MSG_WriteShort( msg, cl->downloadBlockSize[curindex] );
1122
1123 // Write the block
1124 if(cl->downloadBlockSize[curindex])
1125 MSG_WriteData(msg, cl->downloadBlocks[curindex], cl->downloadBlockSize[curindex]);
1126
1127 Com_DPrintf( "clientDownload: %d : writing block %d\n", (int) (cl - svs.clients), cl->downloadXmitBlock );
1128
1129 // Move on to the next block
1130 // It will get sent with next snap shot. The rate will keep us in line.
1131 cl->downloadXmitBlock++;
1132 cl->downloadSendTime = svs.time;
1133
1134 return 1;
1135 }
1136
1137 /*
1138 ==================
1139 SV_SendQueuedMessages
1140
1141 Send one round of fragments, or queued messages to all clients that have data pending.
1142 Return the shortest time interval for sending next packet to client
1143 ==================
1144 */
1145
1146 int SV_SendQueuedMessages(void)
1147 {
1148 int i, retval = -1, nextFragT;
1149 client_t *cl;
1150
1151 for(i=0; i < sv_maxclients->integer; i++)
1152 {
1153 cl = &svs.clients[i];
1154
1155 if(cl->state)
1156 {
1157 nextFragT = SV_RateMsec(cl);
1158
1159 if(!nextFragT)
1160 nextFragT = SV_Netchan_TransmitNextFragment(cl);
1161
1162 if(nextFragT >= 0 && (retval == -1 || retval > nextFragT))
1163 retval = nextFragT;
1164 }
1165 }
1166
1167 return retval;
1168 }
1169
1170
1171 /*
1172 ==================
1173 SV_SendDownloadMessages
1174
1175 Send one round of download messages to all clients
1176 ==================
1177 */
1178
1179 int SV_SendDownloadMessages(void)
1180 {
1181 int i, numDLs = 0, retval;
1182 client_t *cl;
1183 msg_t msg;
1184 byte msgBuffer[MAX_MSGLEN];
1185
1186 for(i=0; i < sv_maxclients->integer; i++)
1187 {
1188 cl = &svs.clients[i];
1189
1190 if(cl->state && *cl->downloadName)
1191 {
1192 MSG_Init(&msg, msgBuffer, sizeof(msgBuffer));
1193 MSG_WriteLong(&msg, cl->lastClientCommand);
1194
1195 retval = SV_WriteDownloadToClient(cl, &msg);
1196
1197 if(retval)
1198 {
1199 MSG_WriteByte(&msg, svc_EOF);
1200 SV_Netchan_Transmit(cl, &msg);
1201 numDLs += retval;
1202 }
1203 }
1204 }
1205
1206 return numDLs;
1207 }
1208
1209 /*
1210 =================
1211 SV_Disconnect_f
1212
1213 The client is going to disconnect, so remove the connection immediately FIXME: move to game?
1214 =================
1215 */
1216 static void SV_Disconnect_f( client_t *cl ) {
1217 SV_DropClient( cl, "disconnected" );
1218 }
1219
1220 /*
1221 =================
1222 SV_VerifyPaks_f
1223
1224 If we are pure, disconnect the client if they do no meet the following conditions:
1225
1226 1. the first two checksums match our view of cgame and ui
1227 2. there are no any additional checksums that we do not have
1228
1229 This routine would be a bit simpler with a goto but i abstained
1230
1231 =================
1232 */
1233 static void SV_VerifyPaks_f( client_t *cl ) {
1234 int nChkSum1, nChkSum2, nClientPaks, nServerPaks, i, j, nCurArg;
1235 int nClientChkSum[1024];
1236 int nServerChkSum[1024];
1237 const char *pPaks, *pArg;
1238 qboolean bGood = qtrue;
1239
1240 // if we are pure, we "expect" the client to load certain things from
1241 // certain pk3 files, namely we want the client to have loaded the
1242 // ui and cgame that we think should be loaded based on the pure setting
1243 //
1244 if ( sv_pure->integer != 0 ) {
1245
1246 nChkSum1 = nChkSum2 = 0;
1247 // we run the game, so determine which cgame and ui the client "should" be running
1248 bGood = (FS_FileIsInPAK("vm/cgame.qvm", &nChkSum1) == 1);
1249 if (bGood)
1250 bGood = (FS_FileIsInPAK("vm/ui.qvm", &nChkSum2) == 1);
1251
1252 nClientPaks = Cmd_Argc();
1253
1254 // start at arg 2 ( skip serverId cl_paks )
1255 nCurArg = 1;
1256
1257 pArg = Cmd_Argv(nCurArg++);
1258 if(!pArg) {
1259 bGood = qfalse;
1260 }
1261 else
1262 {
1263 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475
1264 // we may get incoming cp sequences from a previous checksumFeed, which we need to ignore
1265 // since serverId is a frame count, it always goes up
1266 if (atoi(pArg) < sv.checksumFeedServerId)
1267 {
1268 Com_DPrintf("ignoring outdated cp command from client %s\n", cl->name);
1269 return;
1270 }
1271 }
1272
1273 // we basically use this while loop to avoid using 'goto' :)
1274 while (bGood) {
1275
1276 // must be at least 6: "cl_paks cgame ui @ firstref ... numChecksums"
1277 // numChecksums is encoded
1278 if (nClientPaks < 6) {
1279 bGood = qfalse;
1280 break;
1281 }
1282 // verify first to be the cgame checksum
1283 pArg = Cmd_Argv(nCurArg++);
1284 if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum1 ) {
1285 bGood = qfalse;
1286 break;
1287 }
1288 // verify the second to be the ui checksum
1289 pArg = Cmd_Argv(nCurArg++);
1290 if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum2 ) {
1291 bGood = qfalse;
1292 break;
1293 }
1294 // should be sitting at the delimeter now
1295 pArg = Cmd_Argv(nCurArg++);
1296 if (*pArg != '@') {
1297 bGood = qfalse;
1298 break;
1299 }
1300 // store checksums since tokenization is not re-entrant
1301 for (i = 0; nCurArg < nClientPaks; i++) {
1302 nClientChkSum[i] = atoi(Cmd_Argv(nCurArg++));
1303 }
1304
1305 // store number to compare against (minus one cause the last is the number of checksums)
1306 nClientPaks = i - 1;
1307
1308 // make sure none of the client check sums are the same
1309 // so the client can't send 5 the same checksums
1310 for (i = 0; i < nClientPaks; i++) {
1311 for (j = 0; j < nClientPaks; j++) {
1312 if (i == j)
1313 continue;
1314 if (nClientChkSum[i] == nClientChkSum[j]) {
1315 bGood = qfalse;
1316 break;
1317 }
1318 }
1319 if (bGood == qfalse)
1320 break;
1321 }
1322 if (bGood == qfalse)
1323 break;
1324
1325 // get the pure checksums of the pk3 files loaded by the server
1326 pPaks = FS_LoadedPakPureChecksums();
1327 Cmd_TokenizeString( pPaks );
1328 nServerPaks = Cmd_Argc();
1329 if (nServerPaks > 1024)
1330 nServerPaks = 1024;
1331
1332 for (i = 0; i < nServerPaks; i++) {
1333 nServerChkSum[i] = atoi(Cmd_Argv(i));
1334 }
1335
1336 // check if the client has provided any pure checksums of pk3 files not loaded by the server
1337 for (i = 0; i < nClientPaks; i++) {
1338 for (j = 0; j < nServerPaks; j++) {
1339 if (nClientChkSum[i] == nServerChkSum[j]) {
1340 break;
1341 }
1342 }
1343 if (j >= nServerPaks) {
1344 bGood = qfalse;
1345 break;
1346 }
1347 }
1348 if ( bGood == qfalse ) {
1349 break;
1350 }
1351
1352 // check if the number of checksums was correct
1353 nChkSum1 = sv.checksumFeed;
1354 for (i = 0; i < nClientPaks; i++) {
1355 nChkSum1 ^= nClientChkSum[i];
1356 }
1357 nChkSum1 ^= nClientPaks;
1358 if (nChkSum1 != nClientChkSum[nClientPaks]) {
1359 bGood = qfalse;
1360 break;
1361 }
1362
1363 // break out
1364 break;
1365 }
1366
1367 cl->gotCP = qtrue;
1368
1369 if (bGood) {
1370 cl->pureAuthentic = 1;
1371 }
1372 else {
1373 cl->pureAuthentic = 0;
1374 cl->lastSnapshotTime = 0;
1375 cl->state = CS_ACTIVE;
1376 SV_SendClientSnapshot( cl );
1377 SV_DropClient( cl, "Unpure Client. "
1378 "You may need to enable in-game downloads "
1379 "to connect to this server (set "
1380 "cl_allowDownload 1)" );
1381 }
1382 }
1383 }
1384
1385 /*
1386 =================
1387 SV_ResetPureClient_f
1388 =================
1389 */
1390 static void SV_ResetPureClient_f( client_t *cl ) {
1391 cl->pureAuthentic = 0;
1392 cl->gotCP = qfalse;
1393 }
1394
1395 /*
1396 =================
1397 SV_UserinfoChanged
1398
1399 Pull specific info from a newly changed userinfo string
1400 into a more C friendly form.
1401 =================
1402 */
1403 void SV_UserinfoChanged( client_t *cl ) {
1404 char *val;
1405 char *ip;
1406 int i;
1407 int len;
1408
1409 // name for C code
1410 Q_strncpyz( cl->name, Info_ValueForKey (cl->userinfo, "name"), sizeof(cl->name) );
1411
1412 // rate command
1413
1414 // if the client is on the same subnet as the server and we aren't running an
1415 // internet public server, assume they don't need a rate choke
1416 if ( Sys_IsLANAddress( cl->netchan.remoteAddress ) && com_dedicated->integer != 2 && sv_lanForceRate->integer == 1) {
1417 cl->rate = 99999; // lans should not rate limit
1418 } else {
1419 val = Info_ValueForKey (cl->userinfo, "rate");
1420 if (strlen(val)) {
1421 i = atoi(val);
1422 cl->rate = i;
1423 if (cl->rate < 1000) {
1424 cl->rate = 1000;
1425 } else if (cl->rate > 90000) {
1426 cl->rate = 90000;
1427 }
1428 } else {
1429 cl->rate = 3000;
1430 }
1431 }
1432 val = Info_ValueForKey (cl->userinfo, "handicap");
1433 if (strlen(val)) {
1434 i = atoi(val);
1435 if (i<=0 || i>100 || strlen(val) > 4) {
1436 Info_SetValueForKey( cl->userinfo, "handicap", "100" );
1437 }
1438 }
1439
1440 // snaps command
1441 val = Info_ValueForKey (cl->userinfo, "snaps");
1442
1443 if(strlen(val))
1444 {
1445 i = atoi(val);
1446
1447 if(i < 1)
1448 i = 1;
1449 else if(i > sv_fps->integer)
1450 i = sv_fps->integer;
1451
1452 i = 1000 / i;
1453 }
1454 else
1455 i = 50;
1456
1457 if(i != cl->snapshotMsec)
1458 {
1459 // Reset last sent snapshot so we avoid desync between server frame time and snapshot send time
1460 cl->lastSnapshotTime = 0;
1461 cl->snapshotMsec = i;
1462 }
1463
1464 #ifdef USE_VOIP
1465 #ifdef LEGACY_PROTOCOL
1466 if(cl->compat)
1467 cl->hasVoip = qfalse;
1468 else
1469 #endif
1470 {
1471 val = Info_ValueForKey(cl->userinfo, "cl_voipProtocol");
1472 cl->hasVoip = !Q_stricmp( val, "opus" );
1473 }
1474 #endif
1475
1476 // TTimo
1477 // maintain the IP information
1478 // the banning code relies on this being consistently present
1479 if( NET_IsLocalAddress(cl->netchan.remoteAddress) )
1480 ip = "localhost";
1481 else
1482 ip = (char*)NET_AdrToString( cl->netchan.remoteAddress );
1483
1484 val = Info_ValueForKey( cl->userinfo, "ip" );
1485 if( val[0] )
1486 len = strlen( ip ) - strlen( val ) + strlen( cl->userinfo );
1487 else
1488 len = strlen( ip ) + 4 + strlen( cl->userinfo );
1489
1490 if( len >= MAX_INFO_STRING )
1491 SV_DropClient( cl, "userinfo string length exceeded" );
1492 else
1493 Info_SetValueForKey( cl->userinfo, "ip", ip );
1494
1495 }
1496
1497
1498 /*
1499 ==================
1500 SV_UpdateUserinfo_f
1501 ==================
1502 */
1503 static void SV_UpdateUserinfo_f( client_t *cl ) {
1504 Q_strncpyz( cl->userinfo, Cmd_Argv(1), sizeof(cl->userinfo) );
1505
1506 SV_UserinfoChanged( cl );
1507 // call prog code to allow overrides
1508 VM_Call( gvm, GAME_CLIENT_USERINFO_CHANGED, cl - svs.clients );
1509 }
1510
1511
1512 #ifdef USE_VOIP
1513 static
1514 void SV_UpdateVoipIgnore(client_t *cl, const char *idstr, qboolean ignore)
1515 {
1516 if ((*idstr >= '0') && (*idstr <= '9')) {
1517 const int id = atoi(idstr);
1518 if ((id >= 0) && (id < MAX_CLIENTS)) {
1519 cl->ignoreVoipFromClient[id] = ignore;
1520 }
1521 }
1522 }
1523
1524 /*
1525 ==================
1526 SV_Voip_f
1527 ==================
1528 */
1529 static void SV_Voip_f( client_t *cl ) {
1530 const char *cmd = Cmd_Argv(1);
1531 if (strcmp(cmd, "ignore") == 0) {
1532 SV_UpdateVoipIgnore(cl, Cmd_Argv(2), qtrue);
1533 } else if (strcmp(cmd, "unignore") == 0) {
1534 SV_UpdateVoipIgnore(cl, Cmd_Argv(2), qfalse);
1535 } else if (strcmp(cmd, "muteall") == 0) {
1536 cl->muteAllVoip = qtrue;
1537 } else if (strcmp(cmd, "unmuteall") == 0) {
1538 cl->muteAllVoip = qfalse;
1539 }
1540 }
1541 #endif
1542
1543
1544 typedef struct {
1545 char *name;
1546 void (*func)( client_t *cl );
1547 } ucmd_t;
1548
1549 static ucmd_t ucmds[] = {
1550 {"userinfo", SV_UpdateUserinfo_f},
1551 {"disconnect", SV_Disconnect_f},
1552 {"cp", SV_VerifyPaks_f},
1553 {"vdr", SV_ResetPureClient_f},
1554 {"download", SV_BeginDownload_f},
1555 {"nextdl", SV_NextDownload_f},
1556 {"stopdl", SV_StopDownload_f},
1557 {"donedl", SV_DoneDownload_f},
1558
1559 #ifdef USE_VOIP
1560 {"voip", SV_Voip_f},
1561 #endif
1562
1563 {NULL, NULL}
1564 };
1565
1566 /*
1567 ==================
1568 SV_ExecuteClientCommand
1569
1570 Also called by bot code
1571 ==================
1572 */
1573 void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK ) {
1574 ucmd_t *u;
1575 qboolean bProcessed = qfalse;
1576
1577 Cmd_TokenizeString( s );
1578
1579 // see if it is a server level command
1580 for (u=ucmds ; u->name ; u++) {
1581 if (!strcmp (Cmd_Argv(0), u->name) ) {
1582 u->func( cl );
1583 bProcessed = qtrue;
1584 break;
1585 }
1586 }
1587
1588 if (clientOK) {
1589 // pass unknown strings to the game
1590 if (!u->name && sv.state == SS_GAME && (cl->state == CS_ACTIVE || cl->state == CS_PRIMED)) {
1591 Cmd_Args_Sanitize();
1592 VM_Call( gvm, GAME_CLIENT_COMMAND, cl - svs.clients );
1593 }
1594 }
1595 else if (!bProcessed)
1596 Com_DPrintf( "client text ignored for %s: %s\n", cl->name, Cmd_Argv(0) );
1597 }
1598
1599 /*
1600 ===============
1601 SV_ClientCommand
1602 ===============
1603 */
1604 static qboolean SV_ClientCommand( client_t *cl, msg_t *msg ) {
1605 int seq;
1606 const char *s;
1607 qboolean clientOk = qtrue;
1608
1609 seq = MSG_ReadLong( msg );
1610 s = MSG_ReadString( msg );
1611
1612 // see if we have already executed it
1613 if ( cl->lastClientCommand >= seq ) {
1614 return qtrue;
1615 }
1616
1617 Com_DPrintf( "clientCommand: %s : %i : %s\n", cl->name, seq, s );
1618
1619 // drop the connection if we have somehow lost commands
1620 if ( seq > cl->lastClientCommand + 1 ) {
1621 Com_Printf( "Client %s lost %i clientCommands\n", cl->name,
1622 seq - cl->lastClientCommand + 1 );
1623 SV_DropClient( cl, "Lost reliable commands" );
1624 return qfalse;
1625 }
1626
1627 // malicious users may try using too many string commands
1628 // to lag other players. If we decide that we want to stall
1629 // the command, we will stop processing the rest of the packet,
1630 // including the usercmd. This causes flooders to lag themselves
1631 // but not other people
1632 // We don't do this when the client hasn't been active yet since it's
1633 // normal to spam a lot of commands when downloading
1634 if ( !com_cl_running->integer &&
1635 cl->state >= CS_ACTIVE &&
1636 sv_floodProtect->integer &&
1637 svs.time < cl->nextReliableTime ) {
1638 // ignore any other text messages from this client but let them keep playing
1639 // TTimo - moved the ignored verbose to the actual processing in SV_ExecuteClientCommand, only printing if the core doesn't intercept
1640 clientOk = qfalse;
1641 }
1642
1643 // don't allow another command for one second
1644 cl->nextReliableTime = svs.time + 1000;
1645
1646 SV_ExecuteClientCommand( cl, s, clientOk );
1647
1648 cl->lastClientCommand = seq;
1649 Com_sprintf(cl->lastClientCommandString, sizeof(cl->lastClientCommandString), "%s", s);
1650
1651 return qtrue; // continue procesing
1652 }
1653
1654
1655 //==================================================================================
1656
1657
1658 /*
1659 ==================
1660 SV_ClientThink
1661
1662 Also called by bot code
1663 ==================
1664 */
1665 void SV_ClientThink (client_t *cl, usercmd_t *cmd) {
1666 cl->lastUsercmd = *cmd;
1667
1668 if ( cl->state != CS_ACTIVE ) {
1669 return; // may have been kicked during the last usercmd
1670 }
1671
1672 VM_Call( gvm, GAME_CLIENT_THINK, cl - svs.clients );
1673 }
1674
1675 /*
1676 ==================
1677 SV_UserMove
1678
1679 The message usually contains all the movement commands
1680 that were in the last three packets, so that the information
1681 in dropped packets can be recovered.
1682
1683 On very fast clients, there may be multiple usercmd packed into
1684 each of the backup packets.
1685 ==================
1686 */
1687 static void SV_UserMove( client_t *cl, msg_t *msg, qboolean delta ) {
1688 int i, key;
1689 int cmdCount;
1690 usercmd_t nullcmd;
1691 usercmd_t cmds[MAX_PACKET_USERCMDS];
1692 usercmd_t *cmd, *oldcmd;
1693
1694 if ( delta ) {
1695 cl->deltaMessage = cl->messageAcknowledge;
1696 } else {
1697 cl->deltaMessage = -1;
1698 }
1699
1700 cmdCount = MSG_ReadByte( msg );
1701
1702 if ( cmdCount < 1 ) {
1703 Com_Printf( "cmdCount < 1\n" );
1704 return;
1705 }
1706
1707 if ( cmdCount > MAX_PACKET_USERCMDS ) {
1708 Com_Printf( "cmdCount > MAX_PACKET_USERCMDS\n" );
1709 return;
1710 }
1711
1712 // use the checksum feed in the key
1713 key = sv.checksumFeed;
1714 // also use the message acknowledge
1715 key ^= cl->messageAcknowledge;
1716 // also use the last acknowledged server command in the key
1717 key ^= MSG_HashKey(cl->reliableCommands[ cl->reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ], 32);
1718
1719 Com_Memset( &nullcmd, 0, sizeof(nullcmd) );
1720 oldcmd = &nullcmd;
1721 for ( i = 0 ; i < cmdCount ; i++ ) {
1722 cmd = &cmds[i];
1723 MSG_ReadDeltaUsercmdKey( msg, key, oldcmd, cmd );
1724 oldcmd = cmd;
1725 }
1726
1727 // save time for ping calculation
1728 cl->frames[ cl->messageAcknowledge & PACKET_MASK ].messageAcked = svs.time;
1729
1730 // TTimo
1731 // catch the no-cp-yet situation before SV_ClientEnterWorld
1732 // if CS_ACTIVE, then it's time to trigger a new gamestate emission
1733 // if not, then we are getting remaining parasite usermove commands, which we should ignore
1734 if (sv_pure->integer != 0 && cl->pureAuthentic == 0 && !cl->gotCP) {
1735 if (cl->state == CS_ACTIVE)
1736 {
1737 // we didn't get a cp yet, don't assume anything and just send the gamestate all over again
1738 Com_DPrintf( "%s: didn't get cp command, resending gamestate\n", cl->name);
1739 SV_SendClientGameState( cl );
1740 }
1741 return;
1742 }
1743
1744 // if this is the first usercmd we have received
1745 // this gamestate, put the client into the world
1746 if ( cl->state == CS_PRIMED ) {
1747 SV_ClientEnterWorld( cl, &cmds[0] );
1748 // the moves can be processed normaly
1749 }
1750
1751 // a bad cp command was sent, drop the client
1752 if (sv_pure->integer != 0 && cl->pureAuthentic == 0) {
1753 SV_DropClient( cl, "Cannot validate pure client!");
1754 return;
1755 }
1756
1757 if ( cl->state != CS_ACTIVE ) {
1758 cl->deltaMessage = -1;
1759 return;
1760 }
1761
1762 // usually, the first couple commands will be duplicates
1763 // of ones we have previously received, but the servertimes
1764 // in the commands will cause them to be immediately discarded
1765 for ( i = 0 ; i < cmdCount ; i++ ) {
1766 // if this is a cmd from before a map_restart ignore it
1767 if ( cmds[i].serverTime > cmds[cmdCount-1].serverTime ) {
1768 continue;
1769 }
1770 // extremely lagged or cmd from before a map_restart
1771 //if ( cmds[i].serverTime > svs.time + 3000 ) {
1772 // continue;
1773 //}
1774 // don't execute if this is an old cmd which is already executed
1775 // these old cmds are included when cl_packetdup > 0
1776 if ( cmds[i].serverTime <= cl->lastUsercmd.serverTime ) {
1777 continue;
1778 }
1779 SV_ClientThink (cl, &cmds[ i ]);
1780 }
1781 }
1782
1783
1784 #ifdef USE_VOIP
1785 /*
1786 ==================
1787 SV_ShouldIgnoreVoipSender
1788
1789 Blocking of voip packets based on source client
1790 ==================
1791 */
1792
1793 static qboolean SV_ShouldIgnoreVoipSender(const client_t *cl)
1794 {
1795 if (!sv_voip->integer)
1796 return qtrue; // VoIP disabled on this server.
1797 else if (!cl->hasVoip) // client doesn't have VoIP support?!
1798 return qtrue;
1799
1800 // !!! FIXME: implement player blacklist.
1801
1802 return qfalse; // don't ignore.
1803 }
1804
1805 static
1806 void SV_UserVoip(client_t *cl, msg_t *msg, qboolean ignoreData)
1807 {
1808 int sender, generation, sequence, frames, packetsize;
1809 uint8_t recips[(MAX_CLIENTS + 7) / 8];
1810 int flags;
1811 byte encoded[sizeof(cl->voipPacket[0]->data)];
1812 client_t *client = NULL;
1813 voipServerPacket_t *packet = NULL;
1814 int i;
1815
1816 sender = cl - svs.clients;
1817 generation = MSG_ReadByte(msg);
1818 sequence = MSG_ReadLong(msg);
1819 frames = MSG_ReadByte(msg);
1820 MSG_ReadData(msg, recips, sizeof(recips));
1821 flags = MSG_ReadByte(msg);
1822 packetsize = MSG_ReadShort(msg);
1823
1824 if (msg->readcount > msg->cursize)
1825 return; // short/invalid packet, bail.
1826
1827 if (packetsize > sizeof (encoded)) { // overlarge packet?
1828 int bytesleft = packetsize;
1829 while (bytesleft) {
1830 int br = bytesleft;
1831 if (br > sizeof (encoded))
1832 br = sizeof (encoded);
1833 MSG_ReadData(msg, encoded, br);
1834 bytesleft -= br;
1835 }
1836 return; // overlarge packet, bail.
1837 }
1838
1839 MSG_ReadData(msg, encoded, packetsize);
1840
1841 if (ignoreData || SV_ShouldIgnoreVoipSender(cl))
1842 return; // Blacklisted, disabled, etc.
1843
1844 // !!! FIXME: see if we read past end of msg...
1845
1846 // !!! FIXME: reject if not opus data.
1847 // !!! FIXME: decide if this is bogus data?
1848
1849 // decide who needs this VoIP packet sent to them...
1850 for (i = 0, client = svs.clients; i < sv_maxclients->integer ; i++, client++) {
1851 if (client->state != CS_ACTIVE)
1852 continue; // not in the game yet, don't send to this guy.
1853 else if (i == sender)
1854 continue; // don't send voice packet back to original author.
1855 else if (!client->hasVoip)
1856 continue; // no VoIP support, or unsupported protocol
1857 else if (client->muteAllVoip)
1858 continue; // client is ignoring everyone.
1859 else if (client->ignoreVoipFromClient[sender])
1860 continue; // client is ignoring this talker.
1861 else if (*cl->downloadName) // !!! FIXME: possible to DoS?
1862 continue; // no VoIP allowed if downloading, to save bandwidth.
1863
1864 if(Com_IsVoipTarget(recips, sizeof(recips), i))
1865 flags |= VOIP_DIRECT;
1866 else
1867 flags &= ~VOIP_DIRECT;
1868
1869 if (!(flags & (VOIP_SPATIAL | VOIP_DIRECT)))
1870 continue; // not addressed to this player.
1871
1872 // Transmit this packet to the client.
1873 if (client->queuedVoipPackets >= ARRAY_LEN(client->voipPacket)) {
1874 Com_Printf("Too many VoIP packets queued for client #%d\n", i);
1875 continue; // no room for another packet right now.
1876 }
1877
1878 packet = Z_Malloc(sizeof(*packet));
1879 packet->sender = sender;
1880 packet->frames = frames;
1881 packet->len = packetsize;
1882 packet->generation = generation;
1883 packet->sequence = sequence;
1884 packet->flags = flags;
1885 memcpy(packet->data, encoded, packetsize);
1886
1887 client->voipPacket[(client->queuedVoipIndex + client->queuedVoipPackets) % ARRAY_LEN(client->voipPacket)] = packet;
1888 client->queuedVoipPackets++;
1889 }
1890 }
1891 #endif
1892
1893
1894
1895 /*
1896 ===========================================================================
1897
1898 USER CMD EXECUTION
1899
1900 ===========================================================================
1901 */
1902
1903 /*
1904 ===================
1905 SV_ExecuteClientMessage
1906
1907 Parse a client packet
1908 ===================
1909 */
1910 void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) {
1911 int c;
1912 int serverId;
1913
1914 MSG_Bitstream(msg);
1915
1916 serverId = MSG_ReadLong( msg );
1917 cl->messageAcknowledge = MSG_ReadLong( msg );
1918
1919 if (cl->messageAcknowledge < 0) {
1920 // usually only hackers create messages like this
1921 // it is more annoying for them to let them hanging
1922 #ifndef NDEBUG
1923 SV_DropClient( cl, "DEBUG: illegible client message" );
1924 #endif
1925 return;
1926 }
1927
1928 cl->reliableAcknowledge = MSG_ReadLong( msg );
1929
1930 // NOTE: when the client message is fux0red the acknowledgement numbers
1931 // can be out of range, this could cause the server to send thousands of server
1932 // commands which the server thinks are not yet acknowledged in SV_UpdateServerCommandsToClient
1933 if ((cl->reliableSequence - cl->reliableAcknowledge >= MAX_RELIABLE_COMMANDS) || (cl->reliableSequence - cl->reliableAcknowledge < 0)) {
1934 // usually only hackers create messages like this
1935 // it is more annoying for them to let them hanging
1936 #ifndef NDEBUG
1937 SV_DropClient( cl, "DEBUG: illegible client message" );
1938 #endif
1939 cl->reliableAcknowledge = cl->reliableSequence;
1940 return;
1941 }
1942 // if this is a usercmd from a previous gamestate,
1943 // ignore it or retransmit the current gamestate
1944 //
1945 // if the client was downloading, let it stay at whatever serverId and
1946 // gamestate it was at. This allows it to keep downloading even when
1947 // the gamestate changes. After the download is finished, we'll
1948 // notice and send it a new game state
1949 //
1950 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=536
1951 // don't drop as long as previous command was a nextdl, after a dl is done, downloadName is set back to ""
1952 // but we still need to read the next message to move to next download or send gamestate
1953 // I don't like this hack though, it must have been working fine at some point, suspecting the fix is somewhere else
1954 if ( serverId != sv.serverId && !*cl->downloadName && !strstr(cl->lastClientCommandString, "nextdl") ) {
1955 if ( serverId >= sv.restartedServerId && serverId < sv.serverId ) { // TTimo - use a comparison here to catch multiple map_restart
1956 // they just haven't caught the map_restart yet
1957 Com_DPrintf("%s : ignoring pre map_restart / outdated client message\n", cl->name);
1958 return;
1959 }
1960 // if we can tell that the client has dropped the last
1961 // gamestate we sent them, resend it
1962 if ( cl->state != CS_ACTIVE && cl->messageAcknowledge > cl->gamestateMessageNum ) {
1963 Com_DPrintf( "%s : dropped gamestate, resending\n", cl->name );
1964 SV_SendClientGameState( cl );
1965 }
1966 return;
1967 }
1968
1969 // this client has acknowledged the new gamestate so it's
1970 // safe to start sending it the real time again
1971 if( cl->oldServerTime && serverId == sv.serverId ){
1972 Com_DPrintf( "%s acknowledged gamestate\n", cl->name );
1973 cl->oldServerTime = 0;
1974 }
1975
1976 // read optional clientCommand strings
1977 do {
1978 c = MSG_ReadByte( msg );
1979
1980 if ( c == clc_EOF ) {
1981 break;
1982 }
1983
1984 if ( c != clc_clientCommand ) {
1985 break;
1986 }
1987 if ( !SV_ClientCommand( cl, msg ) ) {
1988 return; // we couldn't execute it because of the flood protection
1989 }
1990 if (cl->state == CS_ZOMBIE) {
1991 return; // disconnect command
1992 }
1993 } while ( 1 );
1994
1995 // skip legacy speex voip data
1996 if ( c == clc_voipSpeex ) {
1997 #ifdef USE_VOIP
1998 SV_UserVoip( cl, msg, qtrue );
1999 c = MSG_ReadByte( msg );
2000 #endif
2001 }
2002
2003 // read optional voip data
2004 if ( c == clc_voipOpus ) {
2005 #ifdef USE_VOIP
2006 SV_UserVoip( cl, msg, qfalse );
2007 c = MSG_ReadByte( msg );
2008 #endif
2009 }
2010
2011 // read the usercmd_t
2012 if ( c == clc_move ) {
2013 SV_UserMove( cl, msg, qtrue );
2014 } else if ( c == clc_moveNoDelta ) {
2015 SV_UserMove( cl, msg, qfalse );
2016 } else if ( c != clc_EOF ) {
2017 Com_Printf( "WARNING: bad command byte for client %i\n", (int) (cl - svs.clients) );
2018 }
2019 // if ( msg->readcount != msg->cursize ) {
2020 // Com_Printf( "WARNING: Junk at end of packet for client %i\n", cl - svs.clients );
2021 // }
2022 }