1 /*
2 Copyright (C) 1997-2001 Id Software, Inc.
3 
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8 
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 
13 See the GNU General Public License for more details.
14 
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 
19 */
20 // server.h
21 
22 
23 //define	PARANOID			// speed sapping error checking
24 
25 #include "qcommon.h"
26 #include "q_list.h"
27 #include "game.h"
28 
29 //=============================================================================
30 
31 #define	MAX_MASTERS	8				// max recipients for heartbeat packets
32 
33 #define SV_Malloc( size )       Z_TagMalloc( size, TAG_SERVER )
34 #define SV_Mallocz( size )      Z_TagMallocz( size, TAG_SERVER )
35 #define SV_CopyString( s )		Z_TagCopyString( s, TAG_SERVER )
36 
37 typedef struct server_s {
38 	server_state_t	state;			// precache commands are only valid during load
39 
40 	attractLoop_t	attractloop;		// running cinematics and demos for the local system only
41 	qboolean	loadgame;			// client begins should reuse existing entity
42 
43 	uint32		time;				// always sv.framenum * 100 msec
44 	int			framenum;
45 
46 	char		name[MAX_QPATH];			// map name, or cinematic name
47 	cm_t		cm;
48 
49 	char		configstrings[MAX_CONFIGSTRINGS][MAX_QPATH];
50 
51 	// demo server information
52 	fileHandle_t	demofile;
53 
54 	uint32			tracecount;
55 } server_t;
56 
57 #define EDICT_NUM(n) ((edict_t *)((byte *)ge->edicts + ge->edict_size*(n)))
58 #define NUM_FOR_EDICT(e) ( ((byte *)(e)-(byte *)ge->edicts ) / ge->edict_size)
59 
60 #define MAX_TOTAL_ENT_LEAFS		128
61 
62 typedef enum clientConnState_e {
63 	cs_free,		// can be reused for a new connection
64 	cs_zombie,		// client has been disconnected, but don't reuse
65 					// connection for a couple seconds
66 	cs_connected,	// has been assigned to a client_t, but not in game yet
67 	cs_primed,		// got gamestate, precaching
68 	cs_ready,		// precached, but not in game yet
69 	cs_spawned		// client is fully in game
70 } clientConnState_t;
71 
72 typedef struct {
73 	uint32			numEntities;
74 	uint32			numPlayers;
75 	uint32			firstEntity;
76 	uint32			firstPlayer;
77 } deltaFrame_t;
78 
79 typedef struct client_frame_s {
80 	deltaFrame_t		delta;
81 	int					areabytes;
82 	byte				areabits[MAX_MAP_AREAS/8];		// portalarea visibility bits
83 	playerStateEx_t		ps;
84 	uint32				senttime;			// for ping calculations
85 } client_frame_t;
86 
87 #define MSGQUEUE_POOLSIZE		1024
88 #define MSGQUEUE_MALLOC_TRESHOLD	( 64 - 24 )		// keep clientMessage_s 64 bytes aligned
89 
90 #define MSG_RELIABLE	1
91 #define MSG_CLEAR		2
92 
93 typedef struct clientMessage_s {
94 	listElem_t	elem;
95 
96 	byte		*data;
97 	int			cursize;
98 
99 	byte		localBuffer[MSGQUEUE_MALLOC_TRESHOLD];
100 
101 	qboolean	reliable;
102 } clientMessage_t;
103 
104 #define	LATENCY_COUNTS	16
105 #define LATENCY_MASK	( LATENCY_COUNTS - 1 )
106 
107 #define	RATE_MESSAGES	10
108 
109 #define SV_BASELINES_SHIFT			6
110 #define SV_BASELINES_PER_CHUNK		( 1 << SV_BASELINES_SHIFT )
111 #define SV_BASELINES_MASK			( SV_BASELINES_PER_CHUNK - 1 )
112 #define SV_BASELINES_CHUNKS			( MAX_EDICTS >> SV_BASELINES_SHIFT )
113 
114 #define FOR_EACH_CLIENT( c ) \
115 	for( c = ( client_t * )svs.clients.first; c != NULL; \
116             c = ( client_t * )c->elem.next )
117 
118 
119 typedef struct client_s {
120     listElem_t      elem;
121 
122 	clientConnState_t	state;
123 
124 	char			userinfo[MAX_INFO_STRING];		// name, etc
125 	char			*versionString;
126 
127 	int				lastframe;			// for delta compression
128 	usercmd_t		lastcmd;			// for filling in big drops
129 
130 	int				commandMsec;		// every seconds this is reset, if user
131 										// commands exhaust it, assume time cheating
132 
133 	int				frame_latency[LATENCY_COUNTS];
134 	int				ping;
135 
136 	int				message_size[RATE_MESSAGES];	// used to rate drop packets
137 	int				rate;
138 	int				surpressCount;		// number of messages rate supressed
139 	uint32			sendTime;			// used to rate drop async packets
140 
141 	edict_t			*edict;				// EDICT_NUM(clientnum+1)
142 	char			name[MAX_CLIENT_NAME];	// extracted from userinfo, high bits masked
143 	int				messagelevel;		// for filtering printed messages
144 	int				clientNum;
145 
146 	clientSetting_t	settings[CLS_MAX];
147 	qboolean		nodata;
148 
149 	client_frame_t	frames[UPDATE_BACKUP];	// updates can be delta'd from here
150 
151 	byte			*download;			// file being downloaded
152 	int				downloadsize;		// total bytes (can't use EOF because of paks)
153 	int				downloadcount;		// bytes sent
154 
155 	uint32			lastmessage;		// svs.realtime when packet was last received
156 	uint32			lastconnect;
157 
158 	int				challenge;			// challenge of this user, randomly generated
159 	int				protocol;
160 
161 	pmoveParams_t	pmp;
162 
163 	list_t			freeMsgList;
164 	list_t			usedMsgList;
165 	clientMessage_t	*msgPool;
166 
167 	sizebuf_t		datagram;
168 	byte			*datagram_buffer;
169 
170 	entity_state_t	*baselines[SV_BASELINES_CHUNKS];
171 
172 	void			(*AddMessage)( struct client_s *, byte *, int, qboolean );
173 	void			(*WriteFrame)( struct client_s * );
174 	void			(*BuildFrame)( struct client_s * );
175 	void			(*WriteDatagram)( struct client_s * );
176 
177     void            (*AddUnicast)( struct client_s *, int );
178     void            (*AddMulticast)( struct client_s *client, const vec3_t,
179                                         multicast_t );
180 
181 	netchan_t		*netchan;
182 } client_t;
183 
184 // a client can leave the server in one of four ways:
185 // dropping properly by quiting or disconnecting
186 // timing out if no valid messages are received for timeout.value seconds
187 // getting kicked off by the server operator
188 // a program error, like an overflowed reliable buffer
189 
190 //=============================================================================
191 
192 // MAX_CHALLENGES is made large to prevent a denial
193 // of service attack that could cycle all of them
194 // out before legitimate users connected
195 #define	MAX_CHALLENGES	1024
196 
197 typedef struct challenge_s {
198 	netadr_t	adr;
199 	int			challenge;
200 	int			time;
201 } challenge_t;
202 
203 typedef struct ratelimit_s {
204 	uint32 limit;
205 	uint32 period;
206 	uint32 time;
207 	uint32 count;
208 } ratelimit_t;
209 
210 typedef struct ucmd_s {
211 	char	*name;
212 	void	(*func)( void );
213 } ucmd_t;
214 
215 typedef struct server_static_s {
216 	qboolean	initialized;				// sv_init has completed
217 	uint32		realtime;					// always increasing, no clamping, etc
218 
219 	char		mapcmd[MAX_TOKEN_CHARS];	// ie: *intro.cin+base
220 
221 	int			spawncount;					// incremented each server start
222 											// used to check late spawns
223 
224 	gametype_t		gametype;
225 
226 	int			    maxGameClients;
227 	client_t	    *clientpool;					// [maxclients->value]
228 	list_t	        clients;
229 	list_t	        freeclients;
230 	uint32			numEntityStates;			// maxclients->value*UPDATE_BACKUP*MAX_PACKET_ENTITIES
231 	uint32			numPlayerStates;
232 	uint32			nextEntityStates;				// next entityState to use
233 	uint32			nextPlayerStates;				// next playerState to use
234 	entity_state_t	*entityStates;		// [numEntityStates]
235 	playerStateEx_t	*playerStates;		// [numPlayerStates]
236 
237 	uint32			last_heartbeat;
238 
239 	ratelimit_t		ratelimit_status;
240 	ratelimit_t		ratelimit_badpass;
241 	ratelimit_t		ratelimit_badrcon;
242 
243 	challenge_t	challenges[MAX_CHALLENGES];	// to prevent invalid IPs from connecting
244 } server_static_t;
245 
246 //=============================================================================
247 
248 extern	netadr_t	net_from;
249 
250 extern	netadr_t	master_adr[MAX_MASTERS];	// address of the master server
251 
252 extern	server_static_t	svs;				// persistant server info
253 extern	server_t		sv;					// local server
254 
255 extern	cvar_t		*sv_maxclients;
256 extern	cvar_t		*sv_mvd_enable;
257 extern	cvar_t		*sv_reserved_slots;
258 extern	cvar_t		*sv_noreload;			// don't reload level state when reentering
259 extern	cvar_t		*sv_airaccelerate;		// development tool
260 extern	cvar_t		*sv_qwmod;				// atu QW Physics modificator
261 extern	cvar_t		*sv_enforcetime;
262 
263 extern	cvar_t		*sv_debug_send;
264 extern	cvar_t		*sv_pad_packets;
265 extern	cvar_t		*sv_lan_force_rate;
266 
267 extern cvar_t		*sv_strafejump_hack;
268 extern cvar_t		*sv_bodyque_hack;
269 #ifndef _WIN32
270 extern cvar_t		*sv_oldgame_hack;
271 #endif
272 
273 extern cvar_t		*sv_status_limit;
274 extern cvar_t		*sv_status_show;
275 extern cvar_t		*sv_badauth_time;
276 
277 extern cvar_t       *sv_nextserver;
278 
279 extern	client_t	*sv_client;
280 extern	edict_t		*sv_player;
281 
282 
283 
284 //===========================================================
285 
286 //
287 // sv_main.c
288 //
289 void SV_DropClient( client_t *drop, const char *reason );
290 void SV_RemoveClient( client_t *client );
291 
292 int SV_ModelIndex( const char *name );
293 int SV_SoundIndex( const char *name );
294 int SV_ImageIndex( const char *name );
295 
296 void SV_InitOperatorCommands (void);
297 
298 void SV_UserinfoChanged (client_t *cl);
299 
300 void SV_UpdateUserinfo( char *userinfo );
301 
302 void SV_SendAsyncPackets( void );
303 
304 qboolean SV_RateLimited( ratelimit_t *r );
305 void SV_RateInit( ratelimit_t *r, int limit, int period );
306 
307 
308 void Master_Heartbeat (void);
309 void Master_Packet (void);
310 
311 //
312 // sv_init.c
313 //
314 void SV_InitGame( int maxPlayers );
315 void SV_Map (attractLoop_t attractloop, char *levelstring, qboolean loadgame);
316 void SV_SpawnServer( char *server, char *spawnpoint, server_state_t serverstate,
317 					attractLoop_t attractloop, qboolean loadgame, qboolean fakemap );
318 
319 
320 //
321 // sv_phys.c
322 //
323 void SV_PrepWorldFrame (void);
324 
325 //
326 // sv_send.c
327 //
328 typedef enum {RD_NONE, RD_CLIENT, RD_PACKET} redirect_t;
329 #define	SV_OUTPUTBUF_LENGTH	(MAX_PACKETLEN - 16)
330 
331 extern	char	sv_outputbuf[SV_OUTPUTBUF_LENGTH];
332 
333 void SV_FlushRedirect (int sv_redirected, char *outputbuf);
334 
335 void SV_DemoCompleted (void);
336 void SV_SendClientMessages (void);
337 
338 void SV_Multicast (vec3_t origin, multicast_t to);
339 void SV_StartSound (vec3_t origin, edict_t *entity, int channel,
340 					int soundindex, float volume,
341 					float attenuation, float timeofs);
342 void SV_ClientPrintf ( client_t *cl, int level, const char *fmt, ... );
343 void SV_BroadcastPrintf( int level, const char *fmt, ... );
344 void SV_BroadcastCommand( const char *fmt, ... );
345 void SV_ClientAddMessage( client_t *client, int flags );
346 
347 void SV_OldClientWriteDatagram( client_t *client );
348 void SV_OldClientAddMessage( client_t *client, byte *data,
349 							  int length, qboolean reliable );
350 void SV_OldClientWriteReliableMessages( client_t *client, int maxSize );
351 void SV_OldClientClearMessages( client_t *client );
352 void SV_OldClientAddUnicast( client_t *client, int clientNum );
353 void SV_OldClientAddMulticast( client_t *client, const vec3_t origin,
354         multicast_t to );
355 
356 void SV_NewClientWriteDatagram( client_t *client );
357 void SV_NewClientAddMessage( client_t *client, byte *data,
358 							  int length, qboolean reliable );
359 void SV_NewClientAddUnicast( client_t *client, int clientNum );
360 void SV_NewClientAddMulticast( client_t *client, const vec3_t origin,
361         multicast_t to );
362 
363 void SV_CalcSendTime( client_t *client, int messageSize );
364 
365 
366 //
367 // sv_user.c
368 //
369 void SV_Nextserver (void);
370 void SV_ExecuteClientMessage (client_t *cl);
371 
372 //
373 // sv_ccmds.c
374 //
375 void SV_ReadLevelFile (void);
376 
377 //
378 // sv_ents.c
379 //
380 void SV_BuildProxyClientFrame( client_t *client );
381 void SV_BuildClientFrame( client_t *client );
382 void SV_BuildMvdFrame( client_t *client );
383 void SV_BuildProxyMvdFrame( client_t *client );
384 void SV_WriteFrameToClient_Default( client_t *client );
385 void SV_WriteFrameToClient_Enhanced( client_t *client );
386 void SV_WriteFrameToClient_Mvd( client_t *client );
387 void SV_RecordDemoMessage( void );
388 
389 void SV_EmitPacketEntities( deltaFrame_t *from, deltaFrame_t *to,
390 						   int clientNum, entity_state_t **baselines );
391 void SV_EmitPacketPlayers( deltaFrame_t *from, deltaFrame_t *to,
392 						  msgPsFlags_t flags );
393 void SV_DeltaBeginFrame( deltaFrame_t *frame );
394 entity_state_t *SV_DeltaAllocEntity( void );
395 playerStateEx_t *SV_DeltaAllocPlayer( void );
396 
397 
398 
399 void SV_Error (char *error, ...);
400 
401 //
402 // sv_game.c
403 //
404 extern	game_export_t	*ge;
405 
406 void SV_InitGameProgs( void );
407 void SV_ShutdownGameProgs (void);
408 void SV_InitEdict (edict_t *e);
409 
410 void PF_Configstring( int index, const char *val );
411 void PF_Pmove( pmove_t *pm );
412 
413 //============================================================
414 
415 //
416 // high level object sorting to reduce interaction tests
417 //
418 
419 void SV_ClearWorld (void);
420 // called after the world model has been loaded, before linking any entities
421 
422 void SV_UnlinkEdict (edict_t *ent);
423 // call before removing an entity, and before trying to move one,
424 // so it doesn't clip against itself
425 
426 void SV_LinkEdict (edict_t *ent);
427 // Needs to be called any time an entity changes origin, mins, maxs,
428 // or solid.  Automatically unlinks if needed.
429 // sets ent->v.absmin and ent->v.absmax
430 // sets ent->leafnums[] for pvs determination even if the entity
431 // is not solid
432 
433 int SV_AreaEdicts (vec3_t mins, vec3_t maxs, edict_t **list, int maxcount, int areatype);
434 // fills in a table of edict pointers with edicts that have bounding boxes
435 // that intersect the given area.  It is possible for a non-axial bmodel
436 // to be returned that doesn't actually intersect the area on an exact
437 // test.
438 // returns the number of pointers filled in
439 // ??? does this always return the world?
440 
441 //===================================================================
442 
443 //
444 // functions that interact with everything apropriate
445 //
446 int SV_PointContents (vec3_t p);
447 // returns the CONTENTS_* value from the world at the given point.
448 // Quake 2 extends this to also check entities, to allow moving liquids
449 
450 typedef trace_t (*sv_trace_t)( vec3_t, vec3_t, vec3_t, vec3_t, edict_t *, int );
451 
452 trace_t SV_Trace (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, edict_t *passedict, int contentmask);
453 trace_t *SV_Trace_Old (trace_t *trace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end,
454 					   edict_t *passedict, int contentmask);
455 // mins and maxs are relative
456 
457 // if the entire move stays in a solid volume, trace.allsolid will be set,
458 // trace.startsolid will be set, and trace.fraction will be 0
459 
460 // if the starting point is in a solid, it will be allowed to move out
461 // to an open area
462 
463 // passedict is explicitly excluded from clipping checks (normally NULL)
464 
465