/* sv_main.c (description) Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to: Free Software Foundation, Inc. 59 Temple Place - Suite 330 Boston, MA 02111-1307, USA */ static const char rcsid[] = "$Id$"; #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef HAVE_STRING_H # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_SOCKET_H # include #endif #ifdef HAVE_NETINET_IN_H # include #endif #ifdef HAVE_ARPA_INET_H # include #endif #ifdef HAVE_WINSOCK_H # include #endif #include #include #include #include "QF/cmd.h" #include "QF/console.h" #include "QF/cvar.h" #include "QF/model.h" #include "QF/msg.h" #include "QF/plugin.h" #include "QF/qargs.h" #include "QF/sys.h" #include "QF/va.h" #include "QF/ver_check.h" #include "QF/vfs.h" #include "QF/zone.h" #include "bothdefs.h" #include "buildnum.h" #include "compat.h" #include "client.h" //FIXME needed by cls below (for netchan) #include "crudefile.h" #include "game.h" #include "net.h" #include "pmove.h" #include "server.h" #include "sv_progs.h" SERVER_PLUGIN_PROTOS static plugin_list_t server_plugin_list[] = { SERVER_PLUGIN_LIST }; client_t *host_client; // current client client_static_t cls; //FIXME needed by netchan :/ double sv_frametime; double realtime; // without any filtering or bounding int host_hunklevel; netadr_t master_adr[MAX_MASTERS]; // address of group servers quakeparms_t host_parms; qboolean host_initialized; // true if into command execution qboolean rcon_from_user; // DoS protection // FLOOD_PING, FLOOD_LOG, FLOOD_CONNECT, FLOOD_STATUS, FLOOD_RCON, FLOOD_BAN // FIXME: these default values need to be tweaked after more testing double netdosexpire[DOSFLOODCMDS] = { 1, 1, 2, 0.9, 1, 5 }; double netdosvalues[DOSFLOODCMDS] = { 12, 1, 3, 1, 1, 1 }; cvar_t *fs_globalcfg; cvar_t *fs_usercfg; cvar_t *sv_mem_size; cvar_t *sv_console_plugin; cvar_t *sv_allow_status; cvar_t *sv_allow_log; cvar_t *sv_allow_ping; cvar_t *sv_extensions; // Use the extended protocols cvar_t *sv_mintic; // bound the size of the cvar_t *sv_maxtic; // physics time tic cvar_t *sv_netdosprotect; // tone down DoS from quake servers cvar_t *timeout; // seconds without any message cvar_t *zombietime; // seconds to sink messages after // disconnect cvar_t *rcon_password; // password for remote server cvar_t *admin_password; // password for admin commands cvar_t *password; // password for entering the game cvar_t *spectator_password; // password for entering as a // spectator cvar_t *allow_download; cvar_t *allow_download_skins; cvar_t *allow_download_models; cvar_t *allow_download_sounds; cvar_t *allow_download_maps; cvar_t *sv_highchars; cvar_t *sv_phs; cvar_t *pausable; cvar_t *sv_minqfversion; // Minimum QF version allowed to // connect cvar_t *sv_maxrate; // Maximum allowable rate (silently // capped) cvar_t *sv_timestamps; cvar_t *sv_timefmt; // game rules mirrored in svs.info cvar_t *fraglimit; cvar_t *timelimit; cvar_t *teamplay; cvar_t *samelevel; cvar_t *maxclients; cvar_t *maxspectators; cvar_t *deathmatch; // 0, 1, or 2 cvar_t *spawn; cvar_t *watervis; cvar_t *hostname; VFile *sv_logfile; VFile *sv_fraglogfile; cvar_t *pr_gc; cvar_t *pr_gc_interval; int pr_gc_count = 0; void SV_AcceptClient (netadr_t adr, int userid, char *userinfo); void Master_Shutdown (void); const char *client_info_filters[] = { // Info keys needed by client "name", "topcolor", "bottomcolor", "rate", "msg", "skin", "team", "noaim", "pmodel", "emodel", "spectator", "*spectator", "*ver", NULL }; qboolean ServerPaused (void) { return sv.paused; } /* SV_Shutdown Quake calls this before calling Sys_Quit or Sys_Error */ void SV_Shutdown (void) { Master_Shutdown (); if (sv_logfile) { Qclose (sv_logfile); sv_logfile = NULL; } if (sv_fraglogfile) { Qclose (sv_fraglogfile); sv_logfile = NULL; } NET_Shutdown (); Con_Shutdown (); } /* SV_Error Sends a datagram to all the clients informing them of the server crash, then exits */ void SV_Error (const char *error, va_list argptr) { static char string[1024]; static qboolean inerror = false; if (inerror) return; inerror = true; vsnprintf (string, sizeof (string), error, argptr); SV_FinalMessage (va ("server crashed: %s\n", string)); Sys_Print (stderr, error, argptr); } /* SV_FinalMessage Used by SV_Error and SV_Quit_f to send a final message to all connected clients before the server goes down. The messages are sent immediately, not just stuck on the outgoing message list, because the server is going to totally exit after returning from this function. */ void SV_FinalMessage (const char *message) { client_t *cl; int i; SZ_Clear (net_message->message); MSG_WriteByte (net_message->message, svc_print); MSG_WriteByte (net_message->message, PRINT_HIGH); MSG_WriteString (net_message->message, message); MSG_WriteByte (net_message->message, svc_disconnect); for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) if (cl->state >= cs_spawned) Netchan_Transmit (&cl->netchan, net_message->message->cursize, net_message->message->data); } /* SV_DropClient Called when the player is totally leaving the server, either willingly or unwillingly. This is NOT called if the entire server is quiting or crashing. */ void SV_DropClient (client_t *drop) { SV_SavePenaltyFilter (drop, ft_mute, drop->lockedtill); SV_SavePenaltyFilter (drop, ft_cuff, drop->cuff_time); // add the disconnect MSG_WriteByte (&drop->netchan.message, svc_disconnect); if (drop->state == cs_spawned) { if (!drop->spectator) { // call the prog function for removing a client // this will set the body to a dead frame, among other things *sv_globals.self = EDICT_TO_PROG (&sv_pr_state, drop->edict); PR_ExecuteProgram (&sv_pr_state, sv_funcs.ClientDisconnect); } else if (SpectatorDisconnect) { // call the prog function for removing a client // this will set the body to a dead frame, among other things *sv_globals.self = EDICT_TO_PROG (&sv_pr_state, drop->edict); PR_ExecuteProgram (&sv_pr_state, SpectatorDisconnect); } } if (drop->spectator) SV_Printf ("Spectator %s removed\n", drop->name); else SV_Printf ("Client %s removed\n", drop->name); if (drop->download) { Qclose (drop->download); drop->download = NULL; } if (drop->upload) { Qclose (drop->upload); drop->upload = NULL; } *drop->uploadfn = 0; drop->state = cs_zombie; // become free in a few seconds drop->connection_started = realtime; // for zombie timeout drop->old_frags = 0; SVfloat (drop->edict, frags) = 0; drop->name[0] = 0; if (drop->userinfo) Info_Destroy (drop->userinfo); drop->userinfo = 0; // send notification to all remaining clients SV_FullClientUpdate (drop, &sv.reliable_datagram); } int SV_CalcPing (client_t *cl) { float ping; int count, i; register client_frame_t *frame; ping = 0; count = 0; for (frame = cl->frames, i = 0; i < UPDATE_BACKUP; i++, frame++) { if (frame->ping_time > 0) { ping += frame->ping_time; count++; } } if (!count) return 9999; ping /= count; return ping * 1000; } static int make_info_string_filter (const char *key) { return *key == '_' || !Info_FilterForKey (key, client_info_filters); } /* SV_FullClientUpdate Writes all update values to a sizebuf */ void SV_FullClientUpdate (client_t *client, sizebuf_t *buf) { char *info; int i; i = client - svs.clients; // SV_Printf("SV_FullClientUpdate: Updated frags for client %d\n", i); MSG_WriteByte (buf, svc_updatefrags); MSG_WriteByte (buf, i); MSG_WriteShort (buf, client->old_frags); MSG_WriteByte (buf, svc_updateping); MSG_WriteByte (buf, i); MSG_WriteShort (buf, SV_CalcPing (client)); MSG_WriteByte (buf, svc_updatepl); MSG_WriteByte (buf, i); MSG_WriteByte (buf, client->lossage); MSG_WriteByte (buf, svc_updateentertime); MSG_WriteByte (buf, i); MSG_WriteFloat (buf, realtime - client->connection_started); info = client->userinfo ? Info_MakeString (client->userinfo, make_info_string_filter) : ""; MSG_WriteByte (buf, svc_updateuserinfo); MSG_WriteByte (buf, i); MSG_WriteLong (buf, client->userid); MSG_WriteString (buf, info); } /* SV_FullClientUpdateToClient Writes all update values to a client's reliable stream */ void SV_FullClientUpdateToClient (client_t *client, client_t *cl) { if (client->state < cs_connected) return; ClientReliableCheckBlock (cl, 24 + client->userinfo->cursize); if (cl->num_backbuf) { SV_FullClientUpdate (client, &cl->backbuf); ClientReliable_FinishWrite (cl); } else SV_FullClientUpdate (client, &cl->netchan.message); } /* CONNECTIONLESS COMMANDS */ /* CheckForFlood :: EXPERIMENTAL Makes it more difficult to use Quake servers for DoS attacks against other sites. Bad sides: affects gamespy and spytools somewhat... */ int CheckForFlood (flood_enum_t cmdtype) { double currenttime; double oldestTime; static double lastmessagetime = 0; static flood_t floodstatus[DOSFLOODCMDS][DOSFLOODIP]; int oldest, i; static qboolean firsttime = true; if (!sv_netdosprotect->int_val) return 0; oldestTime = 0x7fffffff; oldest = 0; if (firsttime) { memset (floodstatus, sizeof (flood_t) * DOSFLOODCMDS * DOSFLOODIP, 0); firsttime = false; } currenttime = Sys_DoubleTime (); for (i = 0; i < DOSFLOODIP; i++) { if (NET_CompareBaseAdr (net_from, floodstatus[cmdtype][i].adr)) break; if (floodstatus[cmdtype][i].issued < oldestTime) { oldestTime = floodstatus[cmdtype][i].issued; oldest = i; } } if (i < DOSFLOODIP && floodstatus[cmdtype][i].issued) { if ((floodstatus[cmdtype][i].issued + netdosexpire[cmdtype]) > currenttime) { floodstatus[cmdtype][i].floodcount += 1; if (floodstatus[cmdtype][i].floodcount > netdosvalues[cmdtype]) { if ((lastmessagetime + 5) < currenttime) SV_Printf ("Blocking type %d flood from (or to) %s\n", cmdtype, NET_AdrToString (net_from)); floodstatus[cmdtype][i].floodcount = 0; floodstatus[cmdtype][i].issued = currenttime; floodstatus[cmdtype][i].cmdcount += 1; lastmessagetime = currenttime; return 1; } } else { floodstatus[cmdtype][i].floodcount = 0; } } if (i == DOSFLOODIP) { i = oldest; floodstatus[cmdtype][i].adr = net_from; floodstatus[cmdtype][i].firstseen = currenttime; floodstatus[cmdtype][i].cmdcount = 0; floodstatus[cmdtype][i].floodcount = 0; } floodstatus[cmdtype][i].issued = currenttime; floodstatus[cmdtype][i].cmdcount += 1; return 0; } /* SVC_Status Responds with all the info that qplug or qspy can see This message can be up to around 5k with worst case string lengths. */ void SVC_Status (void) { client_t *cl; int ping, bottom, top, i; if (!sv_allow_status->int_val) return; if (CheckForFlood (FLOOD_STATUS)) return; con_printf_no_log = 1; Cmd_TokenizeString ("status"); SV_BeginRedirect (RD_PACKET); SV_Printf ("%s\n", Info_MakeString (svs.info, 0)); for (i = 0; i < MAX_CLIENTS; i++) { cl = &svs.clients[i]; if ((cl->state == cs_connected || cl->state == cs_spawned) && !cl->spectator) { top = atoi (Info_ValueForKey (cl->userinfo, "topcolor")); bottom = atoi (Info_ValueForKey (cl->userinfo, "bottomcolor")); top = (top < 0) ? 0 : ((top > 13) ? 13 : top); bottom = (bottom < 0) ? 0 : ((bottom > 13) ? 13 : bottom); ping = SV_CalcPing (cl); SV_Printf ("%i %i %i %i \"%s\" \"%s\" %i %i\n", cl->userid, cl->old_frags, (int) (realtime - cl->connection_started) / 60, ping, cl->name, Info_ValueForKey (cl->userinfo, "skin"), top, bottom); } } SV_EndRedirect (); con_printf_no_log = 0; } /* SV_CheckLog */ #define LOG_HIGHWATER 4096 #define LOG_FLUSH 10*60 void SV_CheckLog (void) { sizebuf_t *sz; sz = &svs.log[svs.logsequence & 1]; // bump sequence if allmost full, or ten minutes have passed and // there is something still sitting there if (sz->cursize > LOG_HIGHWATER || (realtime - svs.logtime > LOG_FLUSH && sz->cursize)) { // swap buffers and bump sequence svs.logtime = realtime; svs.logsequence++; sz = &svs.log[svs.logsequence & 1]; sz->cursize = 0; SV_Printf ("beginning fraglog sequence %i\n", svs.logsequence); } } /* SVC_Log Responds with all the logged frags for ranking programs. If a sequence number is passed as a parameter and it is the same as the current sequence, an A2A_NACK will be returned instead of the data. */ void SVC_Log (void) { char data[MAX_DATAGRAM + 64]; int seq; if (!sv_allow_log->int_val) return; if (CheckForFlood (FLOOD_LOG)) return; if (Cmd_Argc () == 2) seq = atoi (Cmd_Argv (1)); else seq = -1; if (seq == svs.logsequence - 1 || !sv_fraglogfile) { // they already have this data, or we aren't logging frags data[0] = A2A_NACK; NET_SendPacket (1, data, net_from); return; } Con_DPrintf ("sending log %i to %s\n", svs.logsequence - 1, NET_AdrToString (net_from)); // snprintf (data, sizeof (data), "stdlog %i\n", svs.logsequence-1); // strncat (data, (char *)svs.log_buf[((svs.logsequence-1)&1)], // sizeof(data) - strlen (data)); snprintf (data, sizeof (data), "stdlog %i\n%s", svs.logsequence - 1, (char *) svs.log_buf[((svs.logsequence - 1) & 1)]); NET_SendPacket (strlen (data) + 1, data, net_from); } /* SVC_Ping Just responds with an acknowledgement */ void SVC_Ping (void) { char data; if (!sv_allow_ping->int_val) return; if (CheckForFlood (FLOOD_PING)) return; data = A2A_ACK; NET_SendPacket (1, &data, net_from); } /* SVC_GetChallenge Returns a challenge number that can be used in a subsequent client_connect command. We do this to prevent denial of service attacks that flood the server with invalid connection IPs. With a challenge, they must give a valid IP address. */ void SVC_GetChallenge (void) { int oldest, oldestTime, i; char *extended = ""; oldest = 0; oldestTime = 0x7fffffff; // see if we already have a challenge for this ip for (i = 0; i < MAX_CHALLENGES; i++) { if (NET_CompareBaseAdr (net_from, svs.challenges[i].adr)) break; if (svs.challenges[i].time < oldestTime) { oldestTime = svs.challenges[i].time; oldest = i; } } if (i == MAX_CHALLENGES) { // overwrite the oldest svs.challenges[oldest].challenge = (rand () << 16) ^ rand (); svs.challenges[oldest].adr = net_from; svs.challenges[oldest].time = realtime; i = oldest; } if (sv_extensions->int_val) { extended = " QF"; } // send it to the client Netchan_OutOfBandPrint (net_from, "%c%i%s", S2C_CHALLENGE, svs.challenges[i].challenge, extended); } /* SVC_DirectConnect A connection request that did not come from the master */ void SVC_DirectConnect (void) { info_t *userinfo = 0; const char *s; client_t *cl, *newcl; client_t temp; edict_t *ent; int challenge, clients, edictnum, qport, spectators, version, i; static int userid; netadr_t adr; qboolean spectator; if (CheckForFlood (FLOOD_CONNECT)) return; version = atoi (Cmd_Argv (1)); if (version != PROTOCOL_VERSION) { Netchan_OutOfBandPrint (net_from, "%c\nServer is version %s.\n", A2C_PRINT, QW_VERSION); SV_Printf ("* rejected connect from version %i\n", version); return; } qport = atoi (Cmd_Argv (2)); challenge = atoi (Cmd_Argv (3)); if (strlen (Cmd_Argv (4)) < MAX_INFO_STRING) userinfo = Info_ParseString (Cmd_Argv (4), 1023); // Validate the userinfo string. if (!userinfo) { Netchan_OutOfBandPrint (net_from, "%c\nInvalid userinfo string.\n", A2C_PRINT); return; } // see if the challenge is valid for (i = 0; i < MAX_CHALLENGES; i++) { if (NET_CompareBaseAdr (net_from, svs.challenges[i].adr)) { if (challenge == svs.challenges[i].challenge) break; // good Netchan_OutOfBandPrint (net_from, "%c\nBad challenge.\n", A2C_PRINT); return; } } if (i == MAX_CHALLENGES) { Netchan_OutOfBandPrint (net_from, "%c\nNo challenge for address.\n", A2C_PRINT); return; } s = Info_ValueForKey (userinfo, "*qf_version"); if ((!s[0]) || sv_minqfversion->string[0]) { // kick old clients? if (ver_compare (s, sv_minqfversion->string) < 0) { SV_Printf ("%s: Version %s is less than minimum version %s.\n", NET_AdrToString (net_from), s, sv_minqfversion->string); Netchan_OutOfBandPrint (net_from, "%c\nserver requires QuakeForge " "v%s or greater. Get it from " "http://www.quakeforge.net/\n", A2C_PRINT, sv_minqfversion->string); return; } } // check for password or spectator_password s = Info_ValueForKey (userinfo, "spectator"); if (s[0] && strcmp (s, "0")) { if (spectator_password->string[0] && !strcaseequal (spectator_password->string, "none") && !strequal (spectator_password->string, s)) { // failed SV_Printf ("%s: spectator password failed\n", NET_AdrToString (net_from)); Netchan_OutOfBandPrint (net_from, "%c\nrequires a spectator password\n\n", A2C_PRINT); return; } Info_RemoveKey (userinfo, "spectator"); // remove passwd Info_SetValueForStarKey (userinfo, "*spectator", "1", !sv_highchars->int_val); spectator = true; } else { s = Info_ValueForKey (userinfo, "password"); if (password->string[0] && !strcaseequal (password->string, "none") && !strequal (password->string, s)) { SV_Printf ("%s:password failed\n", NET_AdrToString (net_from)); Netchan_OutOfBandPrint (net_from, "%c\nserver requires a password\n\n", A2C_PRINT); return; } spectator = false; Info_RemoveKey (userinfo, "password"); // remove passwd } adr = net_from; userid++; // so every client gets a unique id newcl = &temp; memset (newcl, 0, sizeof (client_t)); newcl->userid = userid; // works properly if (!sv_highchars->int_val) { byte *p, *q; for (p = (byte *) newcl->userinfo, q = (byte *) userinfo; *q && p < (byte *) newcl->userinfo + sizeof (newcl->userinfo) - 1; q++) if (*q > 31 && *q <= 127) *p++ = *q; } else newcl->userinfo = userinfo; // if there is allready a slot for this ip, drop it for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (cl->state == cs_free) continue; if (NET_CompareBaseAdr (adr, cl->netchan.remote_address) && (cl->netchan.qport == qport || adr.port == cl->netchan.remote_address.port)) { if (cl->state == cs_connected) { SV_Printf ("%s:dup connect\n", NET_AdrToString (adr)); userid--; return; } SV_Printf ("%s:reconnect\n", NET_AdrToString (adr)); SV_DropClient (cl); break; } } // count up the clients and spectators clients = 0; spectators = 0; for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (cl->state == cs_free) continue; if (cl->spectator) spectators++; else clients++; } // if at server limits, refuse connection if (maxclients->int_val > MAX_CLIENTS) Cvar_SetValue (maxclients, MAX_CLIENTS); if (maxspectators->int_val > MAX_CLIENTS) Cvar_SetValue (maxspectators, MAX_CLIENTS); if (maxspectators->int_val + maxclients->int_val > MAX_CLIENTS) Cvar_SetValue (maxspectators, MAX_CLIENTS - maxclients->int_val); if ((spectator && spectators >= maxspectators->int_val) || (!spectator && clients >= maxclients->int_val)) { SV_Printf ("%s:full connect\n", NET_AdrToString (adr)); Netchan_OutOfBandPrint (adr, "%c\nserver is full\n\n", A2C_PRINT); return; } // find a client slot newcl = NULL; for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (cl->state == cs_free) { newcl = cl; break; } } if (!newcl) { SV_Printf ("WARNING: miscounted available clients\n"); return; } // build a new connection // accept the new client // this is the only place a client_t is ever initialized *newcl = temp; Netchan_OutOfBandPrint (adr, "%c", S2C_CONNECTION); edictnum = (newcl - svs.clients) + 1; Netchan_Setup (&newcl->netchan, adr, qport); newcl->state = cs_connected; newcl->prespawned = false; newcl->spawned = false; svs.num_clients++; newcl->datagram.allowoverflow = true; newcl->datagram.data = newcl->datagram_buf; newcl->datagram.maxsize = sizeof (newcl->datagram_buf); // spectator mode can ONLY be set at join time newcl->spectator = spectator; ent = EDICT_NUM (&sv_pr_state, edictnum); newcl->edict = ent; // parse some info from the info strings SV_ExtractFromUserinfo (newcl); // JACK: Init the floodprot stuff. for (i = 0; i < 10; i++) newcl->whensaid[i] = 0.0; newcl->whensaidhead = 0; newcl->lockedtill = SV_RestorePenaltyFilter(newcl, ft_mute); // call the progs to get default spawn parms for the new client PR_ExecuteProgram (&sv_pr_state, sv_funcs.SetNewParms); for (i = 0; i < NUM_SPAWN_PARMS; i++) newcl->spawn_parms[i] = sv_globals.parms[i]; if (newcl->spectator) SV_Printf ("Spectator %s (%s) connected\n", newcl->name, NET_AdrToString (adr)); else SV_Printf ("Client %s (%s) connected\n", newcl->name, NET_AdrToString (adr)); newcl->sendinfo = true; // QuakeForge stuff. newcl->msecs = 0; newcl->msec_cheating = 0; newcl->last_check = -1; newcl->cuff_time = SV_RestorePenaltyFilter(newcl, ft_cuff); } int Rcon_Validate (cvar_t *pass) { if (!strlen (pass->string)) return 0; if (strcmp (Cmd_Argv (1), pass->string)) return 0; return 1; } char * Name_of_sender (void) { client_t *cl; int i; for (i=0, cl=svs.clients ; istate == cs_free) continue; if (!NET_CompareBaseAdr(net_from, cl->netchan.remote_address)) continue; if (cl->netchan.remote_address.port != net_from.port) continue; return cl->name; } return NULL; } /* SVC_RemoteCommand A client issued an rcon command. Shift down the remaining args Redirect all printfs */ void SVC_RemoteCommand (void) { const char *command; char *name; qboolean admin_cmd = false; qboolean do_cmd = false; if (CheckForFlood (FLOOD_RCON)) return; if (Rcon_Validate (rcon_password)) { do_cmd = true; } else if (Rcon_Validate (admin_password)) { admin_cmd = true; if (strcmp(Cmd_Argv(2), "say") == 0 || strcmp(Cmd_Argv(2), "kick") == 0 || strcmp(Cmd_Argv(2), "ban") == 0 || strcmp(Cmd_Argv(2), "mute") == 0 || strcmp(Cmd_Argv(2), "cuff") == 0 || strcmp(Cmd_Argv(2), "exec") == 0 || strcmp(Cmd_Argv(2), "addip") == 0 || strcmp(Cmd_Argv(2), "listip") == 0 || strcmp(Cmd_Argv(2), "writeip") == 0 || strcmp(Cmd_Argv(2), "removeip") == 0) do_cmd = true; } if ((name = Name_of_sender())) { // log issuer if (do_cmd && admin_cmd) { SV_BroadcastPrintf (PRINT_HIGH, "Admin %s issued %s command:\n", name, Cmd_Argv(2)); } else if (admin_cmd) { SV_Printf ("Admin %s issued %s command:\n", name, Cmd_Argv(2)); } else { SV_Printf("User %s %s rcon command:\n", name, do_cmd? "issued":"attempted"); } } if (do_cmd) { command = Cmd_Args (2); SV_Printf ("Rcon from %s:\n\trcon (hidden) %s\n", NET_AdrToString (net_from), command); SV_BeginRedirect (RD_PACKET); if (name) rcon_from_user = true; Cmd_ExecuteString (command, src_command); rcon_from_user = false; } else { SV_Printf ("Bad rcon from %s:\n%s\n", NET_AdrToString (net_from), net_message->message->data + 4); SV_BeginRedirect (RD_PACKET); if (admin_cmd) { SV_Printf("Command not valid with admin password.\n"); } else { SV_Printf ("Bad rcon_password.\n"); } } SV_EndRedirect (); } /* SV_ConnectionlessPacket A connectionless packet has four leading 0xff characters to distinguish it from a game channel. Clients that are in the game can still send connectionless packets. */ void SV_ConnectionlessPacket (void) { const char *c, *s; MSG_BeginReading (net_message); MSG_ReadLong (net_message); // skip the -1 marker s = MSG_ReadString (net_message); Cmd_TokenizeString (s); c = Cmd_Argv (0); if (!strcmp (c, "ping") || (c[0] == A2A_PING && (c[1] == 0 || c[1] == '\n'))) { SVC_Ping (); return; } if (c[0] == A2A_ACK && (c[1] == 0 || c[1] == '\n')) { SV_Printf ("A2A_ACK from %s\n", NET_AdrToString (net_from)); return; } else if (!strcmp (c, "status")) { SVC_Status (); return; } else if (!strcmp (c, "log")) { SVC_Log (); return; } else if (!strcmp (c, "connect")) { SVC_DirectConnect (); return; } else if (!strcmp (c, "getchallenge")) { SVC_GetChallenge (); return; } else if (!strcmp (c, "rcon")) SVC_RemoteCommand (); else SV_Printf ("bad connectionless packet from %s:\n%s\n", NET_AdrToString (net_from), s); } /* PACKET FILTERING You can add or remove addresses from the filter list with: addip removeip The ip address is specified in dot format, and any unspecified digits will match any value, so you can specify an entire class C network with "addip 192.246.40". Removeip will only remove an address specified exactly the same way. You cannot addip a subnet, then removeip a single host. listip Prints the current list of filters. writeip Dumps "addip " commands to listip.cfg so it can be execed at a later date. The filter lists are not saved and restored by default, because I beleive it would cause too much confusion. filterban <0 or 1> If 1 (the default), then ip addresses matching the current list will be prohibited from entering the game. This is the default setting. If 0, then only addresses matching the list will be allowed. This lets you easily set up a private game, or a game that only allows players from your local network. */ typedef struct { int mask; #ifdef HAVE_IPV6 byte ip[16]; #else byte ip[4]; #endif double time; filtertype_t type; } ipfilter_t; #define MAX_IPFILTERS 1024 cvar_t *filterban; cvar_t *sv_filter_automask; int numipfilters; ipfilter_t ipfilters[MAX_IPFILTERS]; unsigned int ipmasks[33]; // network byte order void SV_GenerateIPMasks (void) { int i; unsigned long int j = 0xFFFFFFFF; for (i = 32; i >= 0; i--) { ipmasks[i] = htonl (j); j = j << 1; } } // Note: this function is non-reentrant and not threadsafe const char * SV_PrintIP (byte *ip) { #ifdef HAVE_IPV6 static char buf[INET6_ADDRSTRLEN]; if (!inet_ntop (AF_INET6, ip, buf, INET6_ADDRSTRLEN)) #else # ifdef WIN32 static char buf[16]; strcpy (buf, inet_ntoa (*(struct in_addr*)ip)); if (0) # else static char buf[INET_ADDRSTRLEN]; if (!inet_ntop (AF_INET, ip, buf, INET_ADDRSTRLEN)) # endif #endif Sys_Error ("SV_CleanIPList: inet_ntop_failed. wtf?\n"); return buf; } static inline void SV_MaskIPTrim (byte *ip, int mask) { int i; #ifdef HAVE_IPV6 int intcount = 4; #else int intcount = 1; #endif for (i = 0; i < intcount; i++) { ((unsigned int *)ip)[i] &= ipmasks[mask > 32 ? 32 : mask]; if ((mask -= 32) < 0) mask = 0; } } // assumes b has already been masked static inline qboolean SV_MaskIPCompare (byte *a, byte *b, int mask) { int i; #ifdef HAVE_IPV6 int intcount = 4; #else int intcount = 1; #endif for (i = 0; i < intcount; i++) { if ((((unsigned int *)a)[i] & ipmasks[mask > 32 ? 32 : mask]) != ((unsigned int *)b)[i]) return false; if ((mask -= 32) < 0) mask = 0; } return true; } static inline qboolean SV_IPCompare (byte *a, byte *b) { int i; #ifdef HAVE_IPV6 int intcount = 4; #else int intcount = 1; #endif for (i = 0; i < intcount; i++) if (((unsigned int *)a)[i] != ((unsigned int *)b)[i]) return false; return true; } static inline void SV_IPCopy (byte *dest, byte *src) { int i; #ifdef HAVE_IPV6 int intcount = 4; #else int intcount = 1; #endif for (i = 0; i < intcount; i++) ((unsigned int *)dest)[i] = ((unsigned int *)src)[i]; } qboolean SV_StringToFilter (const char *address, ipfilter_t *f) { #ifdef HAVE_IPV6 byte b[16] = {}; #else byte b[4] = {}; #endif int mask = 0; int i; char *s; char *slash; char *c; s = strdup (address); if (!s) Sys_Error ("SV_StringToFilter: memory allocation failure\n"); // Parse out the mask (the /8 part) if ((slash = strchr (s, '/'))) { char *endptr; *slash = '\0'; slash++; if (*slash < '0' || *slash > '9' || strchr (slash, '/')) goto bad_address; mask = strtol (slash, &endptr, 10); if (!*slash || *endptr) goto bad_address; } else mask = -1; // parse the ip for ipv6 #ifdef HAVE_IPV6 if (inet_pton (AF_INET6, s, b) != 1) { b[10] = 0xFF; // Prefix bytes for hosts that don't support ipv6 b[11] = 0xFF; // (see RFC 2373, section 2.5.4) i = 12; #else i = 0; #endif c = s; // parse for ipv4, as dotted quad, only we have implicit trailing segments do { int j; if (*c == '.') c++; j = strtol (c, &c, 10); if (j < 0 || j > 255 || i >= sizeof (b)) goto bad_address; b[i++] = j; } while (*c == '.'); if (*c) goto bad_address; // change trailing 0 segments to be a mask, eg 1.2.0.0 gives a /16 mask if (mask == -1) { if (sv_filter_automask->int_val) { mask = sizeof (b) * 8; i = sizeof (b) - 1; while (i >= 0 && !b[i]) { mask -= 8; i--; } } else mask = 0; } #ifdef HAVE_IPV6 } #endif #ifdef HAVE_IPV6 if (mask > 128) #else if (mask > 32) #endif goto bad_address; // incase they did 1.2.3.4/16, change it to 1.2.0.0 for easier comparison SV_MaskIPTrim (b, mask); // yada :) f->mask = mask; SV_IPCopy (f->ip, b); free (s); return true; bad_address: SV_Printf ("Bad filter address: %s\n", address); free (s); return false; } void SV_RemoveIPFilter (int i) { for (; i + 1 < numipfilters; i++) ipfilters[i] = ipfilters[i + 1]; numipfilters--; } void SV_CleanIPList (void) { int i; char *type; for (i = 0; i < numipfilters;) { if (ipfilters[i].time && (ipfilters[i].time <= realtime)) { switch (ipfilters[i].type) { case ft_ban: type = "Ban"; break; case ft_mute: type = "Mute"; break; case ft_cuff: type = "Cuff"; break; default: Sys_Error ("SV_CleanIPList: invalid filter type"); } SV_Printf ("SV_CleanIPList: %s for %s/%d removed\n", type, SV_PrintIP (ipfilters[i].ip), ipfilters[i].mask); SV_RemoveIPFilter (i); } else i++; } } void SV_AddIP_f (void) { int i; double bantime; filtertype_t type; if (Cmd_Argc () < 2 || Cmd_Argc () > 4) { SV_Printf ("Usage: addip / [