1 /*
2 ===========================================================================
3 
4 Return to Castle Wolfenstein multiplayer GPL Source Code
5 Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
6 
7 This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (“RTCW MP Source Code”).
8 
9 RTCW MP Source Code is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13 
14 RTCW MP Source Code is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18 
19 You should have received a copy of the GNU General Public License
20 along with RTCW MP Source Code.  If not, see <http://www.gnu.org/licenses/>.
21 
22 In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code.  If not, please request a copy in writing from id Software at the address below.
23 
24 If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
25 
26 ===========================================================================
27 */
28 
29 // server.h
30 
31 #include "../qcommon/q_shared.h"
32 #include "../qcommon/qcommon.h"
33 #include "../game/g_public.h"
34 #include "../game/bg_public.h"
35 
36 //=============================================================================
37 
38 #define PERS_SCORE              0       // !!! MUST NOT CHANGE, SERVER AND
39 										// GAME BOTH REFERENCE !!!
40 
41 #define MAX_ENT_CLUSTERS    16
42 
43 #define MAX_BPS_WINDOW      20          // NERVE - SMF - net debugging
44 
45 #ifdef USE_VOIP
46 #define VOIP_QUEUE_LENGTH 64
47 
48 typedef struct voipServerPacket_s
49 {
50 	int generation;
51 	int sequence;
52 	int frames;
53 	int len;
54 	int sender;
55 	int flags;
56 	byte data[4000];
57 } voipServerPacket_t;
58 #endif
59 
60 typedef struct svEntity_s {
61 	struct worldSector_s *worldSector;
62 	struct svEntity_s *nextEntityInWorldSector;
63 
64 	entityState_t baseline;         // for delta compression of initial sighting
65 	int numClusters;                // if -1, use headnode instead
66 	int clusternums[MAX_ENT_CLUSTERS];
67 	int lastCluster;                // if all the clusters don't fit in clusternums
68 	int areanum, areanum2;
69 	int snapshotCounter;            // used to prevent double adding from portal views
70 } svEntity_t;
71 
72 typedef enum {
73 	SS_DEAD,            // no map loaded
74 	SS_LOADING,         // spawning level entities
75 	SS_GAME             // actively running
76 } serverState_t;
77 
78 typedef struct {
79 	serverState_t state;
80 	qboolean restarting;                // if true, send configstring changes during SS_LOADING
81 	int serverId;                       // changes each server start
82 	int restartedServerId;              // serverId before a map_restart
83 	int checksumFeed;                   // the feed key that we use to compute the pure checksum strings
84 	// show_bug.cgi?id=475
85 	// the serverId associated with the current checksumFeed (always <= serverId)
86 	int checksumFeedServerId;
87 	int snapshotCounter;                // incremented for each snapshot built
88 	int timeResidual;                   // <= 1000 / sv_frame->value
89 	int nextFrameTime;                  // when time > nextFrameTime, process world
90 	char            *configstrings[MAX_CONFIGSTRINGS];
91 	svEntity_t svEntities[MAX_GENTITIES];
92 
93 	char            *entityParsePoint;  // used during game VM init
94 
95 	// the game virtual machine will update these on init and changes
96 	sharedEntity_t  *gentities;
97 	int gentitySize;
98 	int num_entities;                   // current number, <= MAX_GENTITIES
99 
100 	playerState_t   *gameClients;
101 	int gameClientSize;                 // will be > sizeof(playerState_t) due to game private data
102 
103 	int restartTime;
104 	int time;
105 
106 	// NERVE - SMF - net debugging
107 	int bpsWindow[MAX_BPS_WINDOW];
108 	int bpsWindowSteps;
109 	int bpsTotalBytes;
110 	int bpsMaxBytes;
111 
112 	int ubpsWindow[MAX_BPS_WINDOW];
113 	int ubpsTotalBytes;
114 	int ubpsMaxBytes;
115 
116 	float ucompAve;
117 	int ucompNum;
118 	// -NERVE - SMF
119 } server_t;
120 
121 
122 
123 
124 
125 typedef struct {
126 	int areabytes;
127 	byte areabits[MAX_MAP_AREA_BYTES];                  // portalarea visibility bits
128 	playerState_t ps;
129 	int num_entities;
130 	int first_entity;                   // into the circular sv_packet_entities[]
131 										// the entities MUST be in increasing state number
132 										// order, otherwise the delta compression will fail
133 	int messageSent;                    // time the message was transmitted
134 	int messageAcked;                   // time the message was acked
135 	int messageSize;                    // used to rate drop packets
136 } clientSnapshot_t;
137 
138 typedef enum {
139 	CS_FREE,        // can be reused for a new connection
140 	CS_ZOMBIE,      // client has been disconnected, but don't reuse connection for a couple seconds
141 	CS_CONNECTED,   // has been assigned to a client_t, but no gamestate yet
142 	CS_PRIMED,      // gamestate has been sent, but client hasn't sent a usercmd
143 	CS_ACTIVE       // client is fully in game
144 } clientState_t;
145 
146 typedef struct netchan_buffer_s {
147 	msg_t msg;
148 	byte msgBuffer[MAX_MSGLEN];
149 #ifdef LEGACY_PROTOCOL
150 	char		clientCommandString[MAX_STRING_CHARS];	// valid command string for SV_Netchan_Encode
151 #endif
152 	struct netchan_buffer_s *next;
153 } netchan_buffer_t;
154 
155 typedef struct client_s {
156 	clientState_t state;
157 	char userinfo[MAX_INFO_STRING];                 // name, etc
158 
159 	char reliableCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
160 	int reliableSequence;                   // last added reliable message, not necesarily sent or acknowledged yet
161 	int reliableAcknowledge;                // last acknowledged reliable message
162 	int reliableSent;                       // last sent reliable message, not necesarily acknowledged yet
163 	int messageAcknowledge;
164 
165 	int gamestateMessageNum;                // netchan->outgoingSequence of gamestate
166 	int challenge;
167 
168 	usercmd_t lastUsercmd;
169 	int lastMessageNum;                 // for delta compression
170 	int lastClientCommand;              // reliable client message sequence
171 	char lastClientCommandString[MAX_STRING_CHARS];
172 	sharedEntity_t  *gentity;           // SV_GentityNum(clientnum)
173 	char name[MAX_NAME_LENGTH];                     // extracted from userinfo, high bits masked
174 
175 	// downloading
176 	char downloadName[MAX_QPATH];            // if not empty string, we are downloading
177 	fileHandle_t download;              // file being downloaded
178 	int downloadSize;                   // total bytes (can't use EOF because of paks)
179 	int downloadCount;                  // bytes sent
180 	int downloadClientBlock;                // last block we sent to the client, awaiting ack
181 	int downloadCurrentBlock;               // current block number
182 	int downloadXmitBlock;              // last block we xmited
183 	unsigned char   *downloadBlocks[MAX_DOWNLOAD_WINDOW];   // the buffers for the download blocks
184 	int downloadBlockSize[MAX_DOWNLOAD_WINDOW];
185 	qboolean downloadEOF;               // We have sent the EOF block
186 	int downloadSendTime;               // time we last got an ack from the client
187 
188 	int deltaMessage;                   // frame last client usercmd message
189 	int nextReliableTime;               // svs.time when another reliable command will be allowed
190 	int lastPacketTime;                 // svs.time when packet was last received
191 	int lastConnectTime;                // svs.time when connection started
192 	int lastSnapshotTime;			// svs.time of last sent snapshot
193 	qboolean rateDelayed;               // true if nextSnapshotTime was set based on rate instead of snapshotMsec
194 	int timeoutCount;                   // must timeout a few frames in a row so debugging doesn't break
195 	clientSnapshot_t frames[PACKET_BACKUP];     // updates can be delta'd from here
196 	int ping;
197 	int rate;                           // bytes / second
198 	int snapshotMsec;                   // requests a snapshot every snapshotMsec unless rate choked
199 	int pureAuthentic;
200 	qboolean gotCP;  // TTimo - additional flag to distinguish between a bad pure checksum, and no cp command at all
201 	netchan_t netchan;
202 	// TTimo
203 	// queuing outgoing fragmented messages to send them properly, without udp packet bursts
204 	// in case large fragmented messages are stacking up
205 	// buffer them into this queue, and hand them out to netchan as needed
206 	netchan_buffer_t *netchan_start_queue;
207 	netchan_buffer_t **netchan_end_queue;
208 
209 #ifdef USE_VOIP
210 	qboolean hasVoip;
211 	qboolean muteAllVoip;
212 	qboolean ignoreVoipFromClient[MAX_CLIENTS];
213 	voipServerPacket_t *voipPacket[VOIP_QUEUE_LENGTH];
214 	int queuedVoipPackets;
215 	int queuedVoipIndex;
216 #endif
217 
218 	int				oldServerTime;
219 	qboolean		csUpdated[MAX_CONFIGSTRINGS];
220 
221 #ifdef LEGACY_PROTOCOL
222 	qboolean		compat;
223 #endif
224 } client_t;
225 
226 //=============================================================================
227 
228 
229 // MAX_CHALLENGES is made large to prevent a denial
230 // of service attack that could cycle all of them
231 // out before legitimate users connected
232 #define MAX_CHALLENGES  2048
233 // Allow a certain amount of challenges to have the same IP address
234 // to make it a bit harder to DOS one single IP address from connecting
235 // while not allowing a single ip to grab all challenge resources
236 #define MAX_CHALLENGES_MULTI (MAX_CHALLENGES / 2)
237 
238 #define AUTHORIZE_TIMEOUT   5000
239 
240 typedef struct {
241 	netadr_t adr;
242 	int challenge;
243 	int clientChallenge;		// challenge number coming from the client
244 	int time;                       // time the last packet was sent to the autherize server
245 	int pingTime;                   // time the challenge response was sent to client
246 	int firstTime;                  // time the adr was first used, for authorize timeout checks
247 	int firstPing;                  // Used for min and max ping checks
248 	qboolean wasrefused;
249 	qboolean connected;
250 } challenge_t;
251 
252 
253 // this structure will be cleared only when the game dll changes
254 typedef struct {
255 	qboolean initialized;                   // sv_init has completed
256 
257 	int time;                               // will be strictly increasing across level changes
258 
259 	int snapFlagServerBit;                  // ^= SNAPFLAG_SERVERCOUNT every SV_SpawnServer()
260 
261 	client_t    *clients;                   // [sv_maxclients->integer];
262 	int numSnapshotEntities;                // sv_maxclients->integer*PACKET_BACKUP*MAX_SNAPSHOT_ENTITIES
263 	int nextSnapshotEntities;               // next snapshotEntities to use
264 	entityState_t   *snapshotEntities;      // [numSnapshotEntities]
265 	int nextHeartbeatTime;
266 	challenge_t challenges[MAX_CHALLENGES]; // to prevent invalid IPs from connecting
267 	netadr_t redirectAddress;               // for rcon return messages
268 
269 #ifndef STANDALONE
270 	netadr_t authorizeAddress;              // for rcon return messages
271 #endif
272 	int masterResolveTime[MAX_MASTER_SERVERS]; // next svs.time that server should do dns lookup for master server
273 } serverStatic_t;
274 
275 #define SERVER_MAXBANS	1024
276 // Structure for managing bans
277 typedef struct
278 {
279 	netadr_t ip;
280 	// For a CIDR-Notation type suffix
281 	int subnet;
282 
283 	qboolean isexception;
284 } serverBan_t;
285 
286 //================
287 // DHM - Nerve
288 #ifdef UPDATE_SERVER
289 
290 typedef struct {
291 	char version[MAX_QPATH];
292 	char platform[MAX_QPATH];
293 	char installer[MAX_QPATH];
294 } versionMapping_t;
295 
296 
297 #define MAX_UPDATE_VERSIONS 128
298 extern versionMapping_t versionMap[MAX_UPDATE_VERSIONS];
299 extern int numVersions;
300 // Maps client version to appropriate installer
301 
302 #endif
303 // DHM - Nerve
304 
305 //=============================================================================
306 
307 extern serverStatic_t svs;                  // persistant server info across maps
308 extern server_t sv;                         // cleared each map
309 extern vm_t            *gvm;                // game virtual machine
310 
311 extern cvar_t  *sv_fps;
312 extern cvar_t  *sv_timeout;
313 extern cvar_t  *sv_zombietime;
314 extern cvar_t  *sv_rconPassword;
315 extern cvar_t  *sv_privatePassword;
316 extern cvar_t  *sv_allowDownload;
317 extern cvar_t  *sv_friendlyFire;        // NERVE - SMF
318 extern cvar_t  *sv_maxlives;            // NERVE - SMF
319 extern cvar_t  *sv_tourney;             // NERVE - SMF
320 extern cvar_t  *sv_maxclients;
321 
322 extern cvar_t  *sv_privateClients;
323 extern cvar_t  *sv_hostname;
324 extern cvar_t  *sv_master[MAX_MASTER_SERVERS];
325 extern cvar_t  *sv_reconnectlimit;
326 extern cvar_t  *sv_showloss;
327 extern cvar_t  *sv_padPackets;
328 extern cvar_t  *sv_killserver;
329 extern cvar_t  *sv_mapname;
330 extern cvar_t  *sv_mapChecksum;
331 extern cvar_t  *sv_serverid;
332 extern cvar_t  *sv_minRate;
333 extern cvar_t  *sv_maxRate;
334 extern cvar_t  *sv_dlRate;
335 extern cvar_t  *sv_minPing;
336 extern cvar_t  *sv_maxPing;
337 extern cvar_t  *sv_gametype;
338 extern cvar_t  *sv_pure;
339 extern cvar_t  *sv_floodProtect;
340 extern cvar_t  *sv_allowAnonymous;
341 extern cvar_t  *sv_lanForceRate;
342 extern cvar_t  *sv_onlyVisibleClients;
343 
344 extern cvar_t *sv_forceNameUniq;
345 
346 extern	cvar_t	*sv_banFile;
347 
348 extern	serverBan_t serverBans[SERVER_MAXBANS];
349 extern	int serverBansCount;
350 
351 #ifdef USE_VOIP
352 extern	cvar_t	*sv_voip;
353 extern	cvar_t	*sv_voipProtocol;
354 #endif
355 
356 #if defined ANTIWALLHACK
357 extern cvar_t *awh_active;
358 extern cvar_t *awh_bbox_horz;
359 extern cvar_t *awh_bbox_vert;
360 #endif
361 
362 extern cvar_t  *sv_showAverageBPS;          // NERVE - SMF - net debugging
363 
364 // Rafael gameskill
365 extern cvar_t  *sv_gameskill;
366 // done
367 
368 // TTimo - autodl
369 extern cvar_t *sv_dl_maxRate;
370 
371 
372 //===========================================================
373 
374 //
375 // sv_main.c
376 //
377 typedef struct leakyBucket_s leakyBucket_t;
378 struct leakyBucket_s {
379 	netadrtype_t	type;
380 
381 	union {
382 		byte	_4[4];
383 		byte	_6[16];
384 	} ipv;
385 
386 	int						lastTime;
387 	signed char		burst;
388 
389 	long					hash;
390 
391 	leakyBucket_t *prev, *next;
392 };
393 
394 extern leakyBucket_t outboundLeakyBucket;
395 
396 qboolean SVC_RateLimit( leakyBucket_t *bucket, int burst, int period );
397 qboolean SVC_RateLimitAddress( netadr_t from, int burst, int period );
398 
399 void SV_FinalMessage( char *message );
400 void QDECL SV_SendServerCommand( client_t *cl, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
401 
402 
403 void SV_AddOperatorCommands( void );
404 void SV_RemoveOperatorCommands( void );
405 
406 void SV_MasterShutdown( void );
407 
408 int SV_RateMsec(client_t *client);
409 
410 //
411 // sv_init.c
412 //
413 void SV_SetConfigstring( int index, const char *val );
414 void SV_GetConfigstring( int index, char *buffer, int bufferSize );
415 void SV_UpdateConfigstrings( client_t *client );
416 
417 void SV_SetUserinfo( int index, const char *val );
418 void SV_GetUserinfo( int index, char *buffer, int bufferSize );
419 
420 void SV_ChangeMaxClients( void );
421 void SV_SpawnServer( char *server, qboolean killBots );
422 
423 
424 
425 //
426 // sv_client.c
427 //
428 void SV_GetChallenge( netadr_t from );
429 
430 void SV_DirectConnect( netadr_t from );
431 
432 #ifndef STANDALONE
433 void SV_AuthorizeIpPacket( netadr_t from );
434 #endif
435 
436 void SV_ExecuteClientMessage( client_t *cl, msg_t *msg );
437 void SV_UserinfoChanged( client_t *cl );
438 
439 void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd );
440 void SV_FreeClient(client_t *client);
441 void SV_DropClient( client_t *drop, const char *reason );
442 
443 void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK );
444 void SV_ClientThink( client_t *cl, usercmd_t *cmd );
445 
446 int SV_WriteDownloadToClient(client_t *cl , msg_t *msg);
447 int SV_SendDownloadMessages(void);
448 int SV_SendQueuedMessages(void);
449 
450 //
451 // sv_ccmds.c
452 //
453 void SV_Heartbeat_f( void );
454 
455 //
456 // sv_snapshot.c
457 //
458 void SV_AddServerCommand( client_t *client, const char *cmd );
459 void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg );
460 void SV_WriteFrameToClient( client_t *client, msg_t *msg );
461 void SV_SendMessageToClient( msg_t *msg, client_t *client );
462 void SV_SendClientMessages( void );
463 void SV_SendClientSnapshot( client_t *client );
464 
465 //
466 // sv_game.c
467 //
468 int SV_NumForGentity( sharedEntity_t *ent );
469 sharedEntity_t *SV_GentityNum( int num );
470 playerState_t *SV_GameClientNum( int num );
471 svEntity_t  *SV_SvEntityForGentity( sharedEntity_t *gEnt );
472 sharedEntity_t *SV_GEntityForSvEntity( svEntity_t *svEnt );
473 void        SV_InitGameProgs( void );
474 void        SV_ShutdownGameProgs( void );
475 void        SV_RestartGameProgs( void );
476 qboolean    SV_inPVS( const vec3_t p1, const vec3_t p2 );
477 qboolean SV_GetTag( int clientNum, char *tagname, orientation_t * or );
478 
479 //
480 // sv_bot.c
481 //
482 void        SV_BotFrame( int time );
483 int         SV_BotAllocateClient( void );
484 void        SV_BotFreeClient( int clientNum );
485 
486 void        SV_BotInitCvars( void );
487 int         SV_BotLibSetup( void );
488 int         SV_BotLibShutdown( void );
489 int         SV_BotGetSnapshotEntity( int client, int ent );
490 int         SV_BotGetConsoleMessage( int client, char *buf, int size );
491 
492 int BotImport_DebugPolygonCreate( int color, int numPoints, vec3_t *points );
493 void BotImport_DebugPolygonDelete( int id );
494 
495 void SV_BotInitBotLib(void);
496 
497 #if defined ANTIWALLHACK
498 //
499 // sv_wallhack.c
500 //
501 void AWH_Init(void);
502 void AWH_RandomizePos(int player, int other);
503 int AWH_CanSee(int player, int other);
504 int AWH_CanHear(int player, int other);
505 #endif
506 
507 //============================================================
508 //
509 // high level object sorting to reduce interaction tests
510 //
511 
512 void SV_ClearWorld( void );
513 // called after the world model has been loaded, before linking any entities
514 
515 void SV_UnlinkEntity( sharedEntity_t *ent );
516 // call before removing an entity, and before trying to move one,
517 // so it doesn't clip against itself
518 
519 void SV_LinkEntity( sharedEntity_t *ent );
520 // Needs to be called any time an entity changes origin, mins, maxs,
521 // or solid.  Automatically unlinks if needed.
522 // sets ent->r.absmin and ent->r.absmax
523 // sets ent->leafnums[] for pvs determination even if the entity
524 // is not solid
525 
526 
527 clipHandle_t SV_ClipHandleForEntity( const sharedEntity_t *ent );
528 
529 
530 void SV_SectorList_f( void );
531 
532 
533 int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount );
534 // fills in a table of entity numbers with entities that have bounding boxes
535 // that intersect the given area.  It is possible for a non-axial bmodel
536 // to be returned that doesn't actually intersect the area on an exact
537 // test.
538 // returns the number of pointers filled in
539 // The world entity is never returned in this list.
540 
541 
542 int SV_PointContents( const vec3_t p, int passEntityNum );
543 // returns the CONTENTS_* value from the world and all entities at the given point.
544 
545 
546 void SV_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule );
547 // mins and maxs are relative
548 
549 // if the entire move stays in a solid volume, trace.allsolid will be set,
550 // trace.startsolid will be set, and trace.fraction will be 0
551 
552 // if the starting point is in a solid, it will be allowed to move out
553 // to an open area
554 
555 // passEntityNum is explicitly excluded from clipping checks (normally ENTITYNUM_NONE)
556 
557 
558 void SV_ClipToEntity( trace_t *trace, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int entityNum, int contentmask, int capsule );
559 // clip to a specific entity
560 
561 //
562 // sv_net_chan.c
563 //
564 void SV_Netchan_Transmit( client_t *client, msg_t *msg );
565 int SV_Netchan_TransmitNextFragment( client_t *client );
566 qboolean SV_Netchan_Process( client_t *client, msg_t *msg );
567 
568 void SV_Netchan_FreeQueue(client_t *client);
569