core/ChatTriggers.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Mar 27 04:54:56 2008 +0000 (2008-03-27)
changeset 1947 e73a1e51833b
parent 1934 d96a3537067c
child 2289 44045ead61cd
permissions -rw-r--r--
Updated copyright year
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <ITextParsers.h>
    33 #include "ChatTriggers.h"
    34 #include "sm_stringutil.h"
    35 #include "ConCmdManager.h"
    36 #include "PlayerManager.h"
    37 #include "Translator.h"
    38 #include "HalfLife2.h"
    39 
    40 /* :HACKHACK: We can't SH_DECL here because ConCmdManager.cpp does.
    41  * While the OB build only runs on MM:S 1.6.0+ (SH 5+), the older one 
    42  * can technically be compiled against any MM:S version after 1.4.2.
    43  */
    44 #if defined ORANGEBOX_BUILD
    45 extern bool __SourceHook_FHRemoveConCommandDispatch(void *, bool, class fastdelegate::FastDelegate1<const CCommand &, void>);
    46 extern int __SourceHook_FHAddConCommandDispatch(void *, ISourceHook::AddHookMode, bool, class fastdelegate::FastDelegate1<const CCommand &, void>);
    47 #else
    48 extern bool __SourceHook_FHRemoveConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    49 #if SH_IMPL_VERSION >= 5
    50 extern int __SourceHook_FHAddConCommandDispatch(void *, ISourceHook::AddHookMode, bool, class fastdelegate::FastDelegate0<void>);
    51 #elif SH_IMPL_VERSION == 4
    52 extern int __SourceHook_FHAddConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    53 #elif SH_IMPL_VERSION == 3
    54 extern bool __SourceHook_FHAddConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    55 #endif //SH_IMPL_VERSION
    56 #endif //ORANGEBOX_BUILD
    57 
    58 ChatTriggers g_ChatTriggers;
    59 bool g_bSupressSilentFails = false;
    60 CPhraseFile *g_pFloodPhrases = NULL;
    61 
    62 ChatTriggers::ChatTriggers() : m_pSayCmd(NULL), m_bWillProcessInPost(false), 
    63 	m_bTriggerWasSilent(false), m_ReplyTo(SM_REPLY_CONSOLE)
    64 {
    65 	m_PubTrigger = sm_strdup("!");
    66 	m_PrivTrigger = sm_strdup("/");
    67 	m_PubTriggerSize = 1;
    68 	m_PrivTriggerSize = 1;
    69 	m_bIsChatTrigger = false;
    70 }
    71 
    72 ChatTriggers::~ChatTriggers()
    73 {
    74 	delete [] m_PubTrigger;
    75 	m_PubTrigger = NULL;
    76 	delete [] m_PrivTrigger;
    77 	m_PrivTrigger = NULL;
    78 }
    79 
    80 ConfigResult ChatTriggers::OnSourceModConfigChanged(const char *key, 
    81 													const char *value, 
    82 													ConfigSource source,
    83 													char *error, 
    84 													size_t maxlength)
    85 {
    86 	if (strcmp(key, "PublicChatTrigger") == 0)
    87 	{
    88 		delete [] m_PubTrigger;
    89 		m_PubTrigger = sm_strdup(value);
    90 		m_PubTriggerSize = strlen(m_PubTrigger);
    91 		return ConfigResult_Accept;
    92 	}
    93 	else if (strcmp(key, "SilentChatTrigger") == 0)
    94 	{
    95 		delete [] m_PrivTrigger;
    96 		m_PrivTrigger = sm_strdup(value);
    97 		m_PrivTriggerSize = strlen(m_PrivTrigger);
    98 		return ConfigResult_Accept;
    99 	}
   100 	else if (strcmp(key, "SilentFailSuppress") == 0)
   101 	{
   102 		g_bSupressSilentFails = strcmp(value, "yes") == 0;
   103 		return ConfigResult_Accept;
   104 	}
   105 
   106 	return ConfigResult_Ignore;
   107 }
   108 
   109 void ChatTriggers::OnSourceModAllInitialized()
   110 {
   111 	m_pShouldFloodBlock = g_Forwards.CreateForward("OnClientFloodCheck", ET_Event, 1, NULL, Param_Cell);
   112 	m_pDidFloodBlock = g_Forwards.CreateForward("OnClientFloodResult", ET_Event, 2, NULL, Param_Cell, Param_Cell);
   113 }
   114 
   115 void ChatTriggers::OnSourceModAllInitialized_Post()
   116 {
   117 	unsigned int file_id;
   118 	
   119 	file_id = g_Translator.FindOrAddPhraseFile("antiflood.phrases.txt");
   120 	g_pFloodPhrases = g_Translator.GetFileByIndex(file_id);
   121 }
   122 
   123 void ChatTriggers::OnSourceModGameInitialized()
   124 {
   125 	unsigned int total = 2;
   126 	ConCommandBase *pCmd = icvar->GetCommands();
   127 	const char *name;
   128 	while (pCmd)
   129 	{
   130 		if (pCmd->IsCommand())
   131 		{
   132 			name = pCmd->GetName();
   133 			if (!m_pSayCmd && strcmp(name, "say") == 0)
   134 			{
   135 				m_pSayCmd = (ConCommand *)pCmd;
   136 				if (--total == 0)
   137 				{
   138 					break;
   139 				}
   140 			} else if (!m_pSayTeamCmd && strcmp(name, "say_team") == 0) {
   141 				m_pSayTeamCmd = (ConCommand *)pCmd;
   142 				if (--total == 0)
   143 				{
   144 					break;
   145 				}
   146 			}
   147 		}
   148 		pCmd = const_cast<ConCommandBase *>(pCmd->GetNext());
   149 	}
   150 
   151 	if (m_pSayCmd)
   152 	{
   153 		SH_ADD_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayCmd, this, &ChatTriggers::OnSayCommand_Pre, false);
   154 		SH_ADD_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayCmd, this, &ChatTriggers::OnSayCommand_Post, true);
   155 	}
   156 	if (m_pSayTeamCmd)
   157 	{
   158 		SH_ADD_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayTeamCmd, this, &ChatTriggers::OnSayCommand_Pre, false);
   159 		SH_ADD_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayTeamCmd, this, &ChatTriggers::OnSayCommand_Post, true);
   160 	}
   161 }
   162 
   163 void ChatTriggers::OnSourceModShutdown()
   164 {
   165 	if (m_pSayTeamCmd)
   166 	{
   167 		SH_REMOVE_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayTeamCmd, this, &ChatTriggers::OnSayCommand_Post, true);
   168 		SH_REMOVE_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayTeamCmd, this, &ChatTriggers::OnSayCommand_Pre, false);
   169 	}
   170 	if (m_pSayCmd)
   171 	{
   172 		SH_REMOVE_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayCmd, this, &ChatTriggers::OnSayCommand_Post, true);
   173 		SH_REMOVE_HOOK_MEMFUNC(ConCommand, Dispatch, m_pSayCmd, this, &ChatTriggers::OnSayCommand_Pre, false);
   174 	}
   175 
   176 	g_Forwards.ReleaseForward(m_pShouldFloodBlock);
   177 	g_Forwards.ReleaseForward(m_pDidFloodBlock);
   178 }
   179 
   180 #if defined ORANGEBOX_BUILD
   181 void ChatTriggers::OnSayCommand_Pre(const CCommand &command)
   182 {
   183 #else
   184 void ChatTriggers::OnSayCommand_Pre()
   185 {
   186 	CCommand command;
   187 #endif
   188 	int client;
   189 	CPlayer *pPlayer;
   190 	
   191 	client = g_ConCmds.GetCommandClient();
   192 	m_bIsChatTrigger = false;
   193 	m_bWasFloodedMessage = false;
   194 
   195 	/* The server console cannot do this */
   196 	if (client == 0 || (pPlayer = g_Players.GetPlayerByIndex(client)) == NULL)
   197 	{
   198 		RETURN_META(MRES_IGNORED);
   199 	}
   200 
   201 	/* We guarantee the client is connected */
   202 	if (!pPlayer->IsConnected())
   203 	{
   204 		RETURN_META(MRES_IGNORED);
   205 	}
   206 
   207 	const char *args = command.ArgS();
   208 	
   209 	if (!args)
   210 	{
   211 		RETURN_META(MRES_IGNORED);
   212 	}
   213 
   214 	/* Check if we need to block this message from being sent */
   215 	if (ClientIsFlooding(client))
   216 	{
   217 		char buffer[128];
   218 
   219 		/* :TODO: log an error? */
   220 		if (g_Translator.CoreTransEx(g_pFloodPhrases, 
   221 			client, 
   222 			buffer, 
   223 			sizeof(buffer),
   224 			"Flooding the server",
   225 			NULL,
   226 			NULL)
   227 			!= Trans_Okay)
   228 		{
   229 			UTIL_Format(buffer, sizeof(buffer), "You are flooding the server!");
   230 		}
   231 
   232 		/* :TODO: we should probably kick people who spam too much. */
   233 
   234 		char fullbuffer[192];
   235 		UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s", buffer);
   236 		g_HL2.TextMsg(client, HUD_PRINTTALK, fullbuffer);
   237 
   238 		m_bWasFloodedMessage = true;
   239 
   240 		RETURN_META(MRES_SUPERCEDE);
   241 	}
   242 
   243 	/* Handle quoted string sets */
   244 	bool is_quoted = false;
   245 	if (args[0] == '"')
   246 	{
   247 		args++;
   248 		is_quoted = true;
   249 	}
   250 
   251 	bool is_trigger = false;
   252 	bool is_silent = false;
   253 
   254 	/* Check for either trigger */
   255 	if (m_PubTriggerSize && strncmp(args, m_PubTrigger, m_PubTriggerSize) == 0)
   256 	{
   257 		is_trigger = true;
   258 		args = &args[m_PubTriggerSize];
   259 	} 
   260 	else if (m_PrivTriggerSize && strncmp(args, m_PrivTrigger, m_PrivTriggerSize) == 0) 
   261 	{
   262 		is_trigger = true;
   263 		is_silent = true;
   264 		args = &args[m_PrivTriggerSize];
   265 	}
   266 
   267 	if (!is_trigger)
   268 	{
   269 		RETURN_META(MRES_IGNORED);
   270 	}
   271 
   272 	/**
   273 	 * Test if this is actually a command!
   274 	 */
   275 	if (!PreProcessTrigger(engine->PEntityOfEntIndex(client), args, is_quoted))
   276 	{
   277 		CPlayer *pPlayer;
   278 		if (is_silent 
   279 			&& g_bSupressSilentFails 
   280 			&& client != 0
   281 			&& (pPlayer = g_Players.GetPlayerByIndex(client)) != NULL
   282 			&& pPlayer->GetAdminId() != INVALID_ADMIN_ID)
   283 		{
   284 			RETURN_META(MRES_SUPERCEDE);
   285 		}
   286 		RETURN_META(MRES_IGNORED);
   287 	}
   288 
   289 	m_bIsChatTrigger = true;
   290 
   291 	/**
   292 	 * We'll execute it in post.
   293 	 */
   294 	m_bWillProcessInPost = true;
   295 	m_bTriggerWasSilent = is_silent;
   296 
   297 	/* If we're silent, block */
   298 	if (is_silent)
   299 	{
   300 		RETURN_META(MRES_SUPERCEDE);
   301 	}
   302 
   303 	/* Otherwise, let the command continue */
   304 	RETURN_META(MRES_IGNORED);
   305 }
   306 
   307 #if defined ORANGEBOX_BUILD
   308 void ChatTriggers::OnSayCommand_Post(const CCommand &command)
   309 #else
   310 void ChatTriggers::OnSayCommand_Post()
   311 #endif
   312 {
   313 	m_bIsChatTrigger = false;
   314 	m_bWasFloodedMessage = false;
   315 	if (m_bWillProcessInPost)
   316 	{
   317 		/* Reset this for re-entrancy */
   318 		m_bWillProcessInPost = false;
   319 		
   320 		/* Execute the cached command */
   321 		int client = g_ConCmds.GetCommandClient();
   322 		unsigned int old = SetReplyTo(SM_REPLY_CHAT);
   323 		serverpluginhelpers->ClientCommand(engine->PEntityOfEntIndex(client), m_ToExecute);
   324 		SetReplyTo(old);
   325 	}
   326 }
   327 
   328 bool ChatTriggers::PreProcessTrigger(edict_t *pEdict, const char *args, bool is_quoted)
   329 {
   330 	/* Extract a command.  This is kind of sloppy. */
   331 	char cmd_buf[64];
   332 	size_t cmd_len = 0;
   333 	const char *inptr = args;
   334 	while (*inptr != '\0' 
   335 			&& !textparsers->IsWhitespace(inptr) 
   336 			&& *inptr != '"'
   337 			&& cmd_len < sizeof(cmd_buf) - 1)
   338 	{
   339 		cmd_buf[cmd_len++] = *inptr++;
   340 	}
   341 	cmd_buf[cmd_len] = '\0';
   342 
   343 	if (cmd_len == 0)
   344 	{
   345 		return false;
   346 	}
   347 
   348 	/* See if we have this registered */
   349 	bool prepended = false;
   350 	if (!g_ConCmds.LookForSourceModCommand(cmd_buf))
   351 	{
   352 		/* Check if we had an "sm_" prefix */
   353 		if (strncmp(cmd_buf, "sm_", 3) == 0)
   354 		{
   355 			return false;
   356 		}
   357 
   358 		/* Now, prepend.  Don't worry about the buffers.  This will 
   359 		 * work because the sizes are limited from earlier.
   360 		 */
   361 		char new_buf[80];
   362 		strcpy(new_buf, "sm_");
   363 		strncopy(&new_buf[3], cmd_buf, sizeof(new_buf)-3);
   364 
   365 		/* Recheck */
   366 		if (!g_ConCmds.LookForSourceModCommand(new_buf))
   367 		{
   368 			return false;
   369 		}
   370 		
   371 		prepended = true;
   372 	}
   373 
   374 	/* See if we need to do extra string manipulation */
   375 	if (is_quoted || prepended)
   376 	{
   377 		size_t len;
   378 
   379 		/* Check if we need to prepend sm_ */
   380 		if (prepended)
   381 		{
   382 			len = UTIL_Format(m_ToExecute, sizeof(m_ToExecute), "sm_%s", args);
   383 		} else {
   384 			len = strncopy(m_ToExecute, args, sizeof(m_ToExecute));
   385 		}
   386 		
   387 		/* Check if we need to strip a quote */
   388 		if (is_quoted)
   389 		{
   390 			if (m_ToExecute[len-1] == '"')
   391 			{
   392 				m_ToExecute[--len] = '\0';
   393 			}
   394 		}
   395 	} else {
   396 		strncopy(m_ToExecute, args, sizeof(m_ToExecute));
   397 	}
   398 
   399 	return true;
   400 }
   401 
   402 unsigned int ChatTriggers::SetReplyTo(unsigned int reply)
   403 {
   404 	unsigned int old = m_ReplyTo;
   405 
   406 	m_ReplyTo = reply;
   407 
   408 	return old;
   409 }
   410 
   411 unsigned int ChatTriggers::GetReplyTo()
   412 {
   413 	return m_ReplyTo;
   414 }
   415 
   416 bool ChatTriggers::IsChatTrigger()
   417 {
   418 	return m_bIsChatTrigger;
   419 }
   420 
   421 bool ChatTriggers::ClientIsFlooding(int client)
   422 {
   423 	bool is_flooding = false;
   424 
   425 	if (m_pShouldFloodBlock->GetFunctionCount() != 0)
   426 	{
   427 		cell_t res = 0;
   428 
   429 		m_pShouldFloodBlock->PushCell(client);
   430 		m_pShouldFloodBlock->Execute(&res);
   431 
   432 		if (res != 0)
   433 		{
   434 			is_flooding = true;
   435 		}
   436 	}
   437 
   438 	if (m_pDidFloodBlock->GetFunctionCount() != 0)
   439 	{
   440 		m_pDidFloodBlock->PushCell(client);
   441 		m_pDidFloodBlock->PushCell(is_flooding ? 1 : 0);
   442 		m_pDidFloodBlock->Execute(NULL);
   443 	}
   444 
   445 	return is_flooding;
   446 }
   447 
   448 bool ChatTriggers::WasFloodedMessage()
   449 {
   450 	return m_bWasFloodedMessage;
   451 }