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 // server.h
23 
24 #include "../qcommon/q_shared.h"
25 #include "../qcommon/qcommon.h"
26 #include "../game/g_public.h"
27 #include "../game/bg_public.h"
28 
29 //=============================================================================
30 
31 #define	PERS_SCORE				0		// !!! MUST NOT CHANGE, SERVER AND
32 										// GAME BOTH REFERENCE !!!
33 
34 #define	MAX_ENT_CLUSTERS	16
35 
36 typedef struct svEntity_s {
37 	struct worldSector_s *worldSector;
38 	struct svEntity_s *nextEntityInWorldSector;
39 
40 	entityState_t	baseline;		// for delta compression of initial sighting
41 	int			numClusters;		// if -1, use headnode instead
42 	int			clusternums[MAX_ENT_CLUSTERS];
43 	int			lastCluster;		// if all the clusters don't fit in clusternums
44 	int			areanum, areanum2;
45 	int			snapshotCounter;	// used to prevent double adding from portal views
46 } svEntity_t;
47 
48 typedef enum {
49 	SS_DEAD,			// no map loaded
50 	SS_LOADING,			// spawning level entities
51 	SS_GAME				// actively running
52 } serverState_t;
53 
54 typedef struct {
55 	serverState_t	state;
56 	qboolean		restarting;			// if true, send configstring changes during SS_LOADING
57 	int				serverId;			// changes each server start
58 	int				restartedServerId;	// serverId before a map_restart
59 	int				checksumFeed;		// the feed key that we use to compute the pure checksum strings
60 	// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475
61 	// the serverId associated with the current checksumFeed (always <= serverId)
62 	int       checksumFeedServerId;
63 	int				snapshotCounter;	// incremented for each snapshot built
64 	int				timeResidual;		// <= 1000 / sv_frame->value
65 	int				nextFrameTime;		// when time > nextFrameTime, process world
66 	struct cmodel_s	*models[MAX_MODELS];
67 	char			*configstrings[MAX_CONFIGSTRINGS];
68 	svEntity_t		svEntities[MAX_GENTITIES];
69 
70 	char			*entityParsePoint;	// used during game VM init
71 
72 	// the game virtual machine will update these on init and changes
73 	sharedEntity_t	*gentities;
74 	int				gentitySize;
75 	int				num_entities;		// current number, <= MAX_GENTITIES
76 
77 	playerState_t	*gameClients;
78 	int				gameClientSize;		// will be > sizeof(playerState_t) due to game private data
79 
80 	int				restartTime;
81 	int				time;
82 } server_t;
83 
84 
85 
86 
87 
88 typedef struct {
89 	int				areabytes;
90 	byte			areabits[MAX_MAP_AREA_BYTES];		// portalarea visibility bits
91 	playerState_t	ps;
92 	int				num_entities;
93 	int				first_entity;		// into the circular sv_packet_entities[]
94 										// the entities MUST be in increasing state number
95 										// order, otherwise the delta compression will fail
96 	int				messageSent;		// time the message was transmitted
97 	int				messageAcked;		// time the message was acked
98 	int				messageSize;		// used to rate drop packets
99 } clientSnapshot_t;
100 
101 typedef enum {
102 	CS_FREE,		// can be reused for a new connection
103 	CS_ZOMBIE,		// client has been disconnected, but don't reuse
104 					// connection for a couple seconds
105 	CS_CONNECTED,	// has been assigned to a client_t, but no gamestate yet
106 	CS_PRIMED,		// gamestate has been sent, but client hasn't sent a usercmd
107 	CS_ACTIVE		// client is fully in game
108 } clientState_t;
109 
110 typedef struct netchan_buffer_s {
111 	msg_t           msg;
112 	byte            msgBuffer[MAX_MSGLEN];
113 	struct netchan_buffer_s *next;
114 } netchan_buffer_t;
115 
116 typedef struct client_s {
117 	clientState_t	state;
118 	char			userinfo[MAX_INFO_STRING];		// name, etc
119 
120 	char			reliableCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
121 	int				reliableSequence;		// last added reliable message, not necesarily sent or acknowledged yet
122 	int				reliableAcknowledge;	// last acknowledged reliable message
123 	int				reliableSent;			// last sent reliable message, not necesarily acknowledged yet
124 	int				messageAcknowledge;
125 
126 	int				gamestateMessageNum;	// netchan->outgoingSequence of gamestate
127 	int				challenge;
128 
129 	usercmd_t		lastUsercmd;
130 	int				lastMessageNum;		// for delta compression
131 	int				lastClientCommand;	// reliable client message sequence
132 	char			lastClientCommandString[MAX_STRING_CHARS];
133 	sharedEntity_t	*gentity;			// SV_GentityNum(clientnum)
134 	char			name[MAX_NAME_LENGTH];			// extracted from userinfo, high bits masked
135 
136 	// downloading
137 	char			downloadName[MAX_QPATH]; // if not empty string, we are downloading
138 	fileHandle_t	download;			// file being downloaded
139  	int				downloadSize;		// total bytes (can't use EOF because of paks)
140  	int				downloadCount;		// bytes sent
141 	int				downloadClientBlock;	// last block we sent to the client, awaiting ack
142 	int				downloadCurrentBlock;	// current block number
143 	int				downloadXmitBlock;	// last block we xmited
144 	unsigned char	*downloadBlocks[MAX_DOWNLOAD_WINDOW];	// the buffers for the download blocks
145 	int				downloadBlockSize[MAX_DOWNLOAD_WINDOW];
146 	qboolean		downloadEOF;		// We have sent the EOF block
147 	int				downloadSendTime;	// time we last got an ack from the client
148 
149 	int				deltaMessage;		// frame last client usercmd message
150 	int				nextReliableTime;	// svs.time when another reliable command will be allowed
151 	int				lastPacketTime;		// svs.time when packet was last received
152 	int				lastConnectTime;	// svs.time when connection started
153 	int				nextSnapshotTime;	// send another snapshot when svs.time >= nextSnapshotTime
154 	qboolean		rateDelayed;		// true if nextSnapshotTime was set based on rate instead of snapshotMsec
155 	int				timeoutCount;		// must timeout a few frames in a row so debugging doesn't break
156 	clientSnapshot_t	frames[PACKET_BACKUP];	// updates can be delta'd from here
157 	int				ping;
158 	int				rate;				// bytes / second
159 	int				snapshotMsec;		// requests a snapshot every snapshotMsec unless rate choked
160 	int				pureAuthentic;
161 	qboolean  gotCP; // TTimo - additional flag to distinguish between a bad pure checksum, and no cp command at all
162 	netchan_t		netchan;
163 	// TTimo
164 	// queuing outgoing fragmented messages to send them properly, without udp packet bursts
165 	// in case large fragmented messages are stacking up
166 	// buffer them into this queue, and hand them out to netchan as needed
167 	netchan_buffer_t *netchan_start_queue;
168 	netchan_buffer_t **netchan_end_queue;
169 
170 	int				oldServerTime;
171 	qboolean			csUpdated[MAX_CONFIGSTRINGS+1];
172 } client_t;
173 
174 //=============================================================================
175 
176 
177 // MAX_CHALLENGES is made large to prevent a denial
178 // of service attack that could cycle all of them
179 // out before legitimate users connected
180 #define	MAX_CHALLENGES	1024
181 
182 #define	AUTHORIZE_TIMEOUT	5000
183 
184 typedef struct {
185 	netadr_t	adr;
186 	int			challenge;
187 	int			time;				// time the last packet was sent to the autherize server
188 	int			pingTime;			// time the challenge response was sent to client
189 	int			firstTime;			// time the adr was first used, for authorize timeout checks
190 	qboolean	connected;
191 } challenge_t;
192 
193 
194 #define	MAX_MASTERS	8				// max recipients for heartbeat packets
195 
196 
197 // this structure will be cleared only when the game dll changes
198 typedef struct {
199 	qboolean	initialized;				// sv_init has completed
200 
201 	int			time;						// will be strictly increasing across level changes
202 
203 	int			snapFlagServerBit;			// ^= SNAPFLAG_SERVERCOUNT every SV_SpawnServer()
204 
205 	client_t	*clients;					// [sv_maxclients->integer];
206 	int			numSnapshotEntities;		// sv_maxclients->integer*PACKET_BACKUP*MAX_PACKET_ENTITIES
207 	int			nextSnapshotEntities;		// next snapshotEntities to use
208 	entityState_t	*snapshotEntities;		// [numSnapshotEntities]
209 	int			nextHeartbeatTime;
210 	challenge_t	challenges[MAX_CHALLENGES];	// to prevent invalid IPs from connecting
211 	netadr_t	redirectAddress;			// for rcon return messages
212 
213 	netadr_t	authorizeAddress;			// for rcon return messages
214 } serverStatic_t;
215 
216 #define SERVER_MAXBANS	1024
217 #define SERVER_BANFILE	"serverbans.dat"
218 // Structure for managing bans
219 typedef struct
220 {
221 	netadr_t ip;
222 	// For a CIDR-Notation type suffix
223 	int subnet;
224 
225 	qboolean isexception;
226 } serverBan_t;
227 
228 //=============================================================================
229 
230 extern	serverStatic_t	svs;				// persistant server info across maps
231 extern	server_t		sv;					// cleared each map
232 extern	vm_t			*gvm;				// game virtual machine
233 
234 #define	MAX_MASTER_SERVERS	5
235 
236 extern	cvar_t	*sv_fps;
237 extern	cvar_t	*sv_timeout;
238 extern	cvar_t	*sv_zombietime;
239 extern	cvar_t	*sv_rconPassword;
240 extern	cvar_t	*sv_privatePassword;
241 extern	cvar_t	*sv_allowDownload;
242 extern	cvar_t	*sv_maxclients;
243 
244 extern	cvar_t	*sv_privateClients;
245 extern	cvar_t	*sv_hostname;
246 extern	cvar_t	*sv_master[MAX_MASTER_SERVERS];
247 extern	cvar_t	*sv_reconnectlimit;
248 extern	cvar_t	*sv_showloss;
249 extern	cvar_t	*sv_padPackets;
250 extern	cvar_t	*sv_killserver;
251 extern	cvar_t	*sv_mapname;
252 extern	cvar_t	*sv_mapChecksum;
253 extern	cvar_t	*sv_serverid;
254 extern	cvar_t	*sv_minRate;
255 extern	cvar_t	*sv_maxRate;
256 extern	cvar_t	*sv_minPing;
257 extern	cvar_t	*sv_maxPing;
258 extern	cvar_t	*sv_gametype;
259 extern	cvar_t	*sv_pure;
260 extern	cvar_t	*sv_floodProtect;
261 extern	cvar_t	*sv_lanForceRate;
262 extern	cvar_t	*sv_strictAuth;
263 
264 extern	serverBan_t serverBans[SERVER_MAXBANS];
265 extern	int serverBansCount;
266 
267 //===========================================================
268 
269 //
270 // sv_main.c
271 //
272 void SV_FinalMessage (char *message);
273 void QDECL SV_SendServerCommand( client_t *cl, const char *fmt, ...);
274 
275 
276 void SV_AddOperatorCommands (void);
277 void SV_RemoveOperatorCommands (void);
278 
279 
280 void SV_MasterHeartbeat (void);
281 void SV_MasterShutdown (void);
282 
283 
284 
285 
286 //
287 // sv_init.c
288 //
289 void SV_SetConfigstring( int index, const char *val );
290 void SV_GetConfigstring( int index, char *buffer, int bufferSize );
291 void SV_UpdateConfigstrings( client_t *client );
292 
293 void SV_SetUserinfo( int index, const char *val );
294 void SV_GetUserinfo( int index, char *buffer, int bufferSize );
295 
296 void SV_ChangeMaxClients( void );
297 void SV_SpawnServer( char *server, qboolean killBots );
298 
299 
300 
301 //
302 // sv_client.c
303 //
304 void SV_GetChallenge( netadr_t from );
305 
306 void SV_DirectConnect( netadr_t from );
307 
308 #ifndef STANDALONE
309 void SV_AuthorizeIpPacket( netadr_t from );
310 #endif
311 
312 void SV_ExecuteClientMessage( client_t *cl, msg_t *msg );
313 void SV_UserinfoChanged( client_t *cl );
314 
315 void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd );
316 void SV_DropClient( client_t *drop, const char *reason );
317 
318 void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK );
319 void SV_ClientThink (client_t *cl, usercmd_t *cmd);
320 
321 void SV_WriteDownloadToClient( client_t *cl , msg_t *msg );
322 
323 //
324 // sv_ccmds.c
325 //
326 void SV_Heartbeat_f( void );
327 
328 //
329 // sv_snapshot.c
330 //
331 void SV_AddServerCommand( client_t *client, const char *cmd );
332 void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg );
333 void SV_WriteFrameToClient (client_t *client, msg_t *msg);
334 void SV_SendMessageToClient( msg_t *msg, client_t *client );
335 void SV_SendClientMessages( void );
336 void SV_SendClientSnapshot( client_t *client );
337 
338 //
339 // sv_game.c
340 //
341 int	SV_NumForGentity( sharedEntity_t *ent );
342 sharedEntity_t *SV_GentityNum( int num );
343 playerState_t *SV_GameClientNum( int num );
344 svEntity_t	*SV_SvEntityForGentity( sharedEntity_t *gEnt );
345 sharedEntity_t *SV_GEntityForSvEntity( svEntity_t *svEnt );
346 void		SV_InitGameProgs ( void );
347 void		SV_ShutdownGameProgs ( void );
348 void		SV_RestartGameProgs( void );
349 qboolean	SV_inPVS (const vec3_t p1, const vec3_t p2);
350 
351 //
352 // sv_bot.c
353 //
354 void		SV_BotFrame( int time );
355 int			SV_BotAllocateClient(void);
356 void		SV_BotFreeClient( int clientNum );
357 
358 void		SV_BotInitCvars(void);
359 int			SV_BotLibSetup( void );
360 int			SV_BotLibShutdown( void );
361 int			SV_BotGetSnapshotEntity( int client, int ent );
362 int			SV_BotGetConsoleMessage( int client, char *buf, int size );
363 
364 int BotImport_DebugPolygonCreate(int color, int numPoints, vec3_t *points);
365 void BotImport_DebugPolygonDelete(int id);
366 
367 //============================================================
368 //
369 // high level object sorting to reduce interaction tests
370 //
371 
372 void SV_ClearWorld (void);
373 // called after the world model has been loaded, before linking any entities
374 
375 void SV_UnlinkEntity( sharedEntity_t *ent );
376 // call before removing an entity, and before trying to move one,
377 // so it doesn't clip against itself
378 
379 void SV_LinkEntity( sharedEntity_t *ent );
380 // Needs to be called any time an entity changes origin, mins, maxs,
381 // or solid.  Automatically unlinks if needed.
382 // sets ent->v.absmin and ent->v.absmax
383 // sets ent->leafnums[] for pvs determination even if the entity
384 // is not solid
385 
386 
387 clipHandle_t SV_ClipHandleForEntity( const sharedEntity_t *ent );
388 
389 
390 void SV_SectorList_f( void );
391 
392 
393 int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount );
394 // fills in a table of entity numbers with entities that have bounding boxes
395 // that intersect the given area.  It is possible for a non-axial bmodel
396 // to be returned that doesn't actually intersect the area on an exact
397 // test.
398 // returns the number of pointers filled in
399 // The world entity is never returned in this list.
400 
401 
402 int SV_PointContents( const vec3_t p, int passEntityNum );
403 // returns the CONTENTS_* value from the world and all entities at the given point.
404 
405 
406 void SV_Trace( trace_t *results, const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule );
407 // mins and maxs are relative
408 
409 // if the entire move stays in a solid volume, trace.allsolid will be set,
410 // trace.startsolid will be set, and trace.fraction will be 0
411 
412 // if the starting point is in a solid, it will be allowed to move out
413 // to an open area
414 
415 // passEntityNum is explicitly excluded from clipping checks (normally ENTITYNUM_NONE)
416 
417 
418 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 );
419 // clip to a specific entity
420 
421 //
422 // sv_net_chan.c
423 //
424 void SV_Netchan_Transmit( client_t *client, msg_t *msg);
425 void SV_Netchan_TransmitNextFragment( client_t *client );
426 qboolean SV_Netchan_Process( client_t *client, msg_t *msg );
427 
428