core/AdminCache.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Fri Aug 30 14:15:02 2013 -0400 (2013-08-30)
changeset 4102 0eb66c45a884
parent 4081 241d291414e9
child 4139 de7d1cd00703
permissions -rw-r--r--
Reserved slot fixes for OB games when SourceTV or Replay are enabled (bug 5499, r=drifter).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     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 <string.h>
    33 #include <assert.h>
    34 #include <ITextParsers.h>
    35 #include "AdminCache.h"
    36 #include "ForwardSys.h"
    37 #include "PlayerManager.h"
    38 #include "ConCmdManager.h"
    39 #include "Logger.h"
    40 #include "sourcemod.h"
    41 #include "sm_stringutil.h"
    42 #include "sourcemm_api.h"
    43 #include "sm_srvcmds.h"
    44 #include "logic_bridge.h"
    45 
    46 #define LEVEL_STATE_NONE		0
    47 #define LEVEL_STATE_LEVELS		1
    48 #define LEVEL_STATE_FLAGS		2
    49 
    50 AdminCache g_Admins;
    51 char g_ReverseFlags[26];
    52 AdminFlag g_FlagLetters[26];
    53 bool g_FlagSet[26];
    54 
    55 ConVar sm_immunity_mode("sm_immunity_mode", "1", FCVAR_SPONLY, "Mode for deciding immunity protection");
    56 
    57 /* Default flags */
    58 AdminFlag g_DefaultFlags[26] = 
    59 {
    60 	Admin_Reservation, Admin_Generic, Admin_Kick, Admin_Ban, Admin_Unban,
    61 	Admin_Slay, Admin_Changemap, Admin_Convars, Admin_Config, Admin_Chat,
    62 	Admin_Vote, Admin_Password, Admin_RCON, Admin_Cheats, Admin_Custom1, 
    63 	Admin_Custom2, Admin_Custom3, Admin_Custom4, Admin_Custom5, Admin_Custom6,
    64 	Admin_Generic, Admin_Generic, Admin_Generic, Admin_Generic, Admin_Generic,
    65 	Admin_Root
    66 };
    67 
    68 
    69 class FlagReader : public ITextListener_SMC
    70 {
    71 public:
    72 	void LoadLevels()
    73 	{
    74 		if (!Parse())
    75 		{
    76 			memcpy(g_FlagLetters, g_DefaultFlags, sizeof(AdminFlag) * 26);
    77 			for (unsigned int i=0; i<20; i++)
    78 			{
    79 				g_FlagSet[i] = true;
    80 			}
    81 			g_FlagSet[25] = true;
    82 		}
    83 	}
    84 private:
    85 	bool Parse()
    86 	{
    87 		SMCStates states;
    88 		SMCError error;
    89 
    90 		m_bFileNameLogged = false;
    91 		g_SourceMod.BuildPath(Path_SM, m_File, sizeof(m_File), "configs/admin_levels.cfg");
    92 
    93 		if ((error = textparsers->ParseFile_SMC(m_File, this, &states))
    94 			!= SMCError_Okay)
    95 		{
    96 			const char *err_string = textparsers->GetSMCErrorString(error);
    97 			if (!err_string)
    98 			{
    99 				err_string = "Unknown error";
   100 			}
   101 			ParseError(NULL, "Error %d (%s)", error, err_string);
   102 			return false;
   103 		}
   104 
   105 		return true;
   106 	}
   107 	void ReadSMC_ParseStart()
   108 	{
   109 		m_LevelState = LEVEL_STATE_NONE;
   110 		m_IgnoreLevel = 0;
   111 		memset(g_FlagSet, 0, sizeof(g_FlagSet));
   112 	}
   113 	SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
   114 	{
   115 		if (m_IgnoreLevel)
   116 		{
   117 			m_IgnoreLevel++;
   118 			return SMCResult_Continue;
   119 		}
   120 
   121 		if (m_LevelState == LEVEL_STATE_NONE)
   122 		{
   123 			if (strcmp(name, "Levels") == 0)
   124 			{
   125 				m_LevelState = LEVEL_STATE_LEVELS;
   126 			} 
   127 			else 
   128 			{
   129 				m_IgnoreLevel++;
   130 			}
   131 		} else if (m_LevelState == LEVEL_STATE_LEVELS) {
   132 			if (strcmp(name, "Flags") == 0)
   133 			{
   134 				m_LevelState = LEVEL_STATE_FLAGS;
   135 			} 
   136 			else 
   137 			{
   138 				m_IgnoreLevel++;
   139 			}
   140 		} 
   141 		else 
   142 		{
   143 			m_IgnoreLevel++;
   144 		}
   145 
   146 		return SMCResult_Continue;
   147 	}
   148 	SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   149 	{
   150 		if (m_LevelState != LEVEL_STATE_FLAGS || m_IgnoreLevel)
   151 		{
   152 			return SMCResult_Continue;
   153 		}
   154 
   155 		unsigned char c = (unsigned)value[0];
   156 
   157 		if (c < (unsigned)'a' || c > (unsigned)'z')
   158 		{
   159 			ParseError(states, "Flag \"%c\" is not a lower-case ASCII letter", c);
   160 			return SMCResult_Continue;
   161 		}
   162 
   163 		c -= (unsigned)'a';
   164 
   165 		if (!g_Admins.FindFlag(key, &g_FlagLetters[c]))
   166 		{
   167 			ParseError(states, "Unrecognized admin level \"%s\"", key);
   168 			return SMCResult_Continue;
   169 		}
   170 
   171 		g_FlagSet[c] = true;
   172 
   173 		return SMCResult_Continue;
   174 	}
   175 	SMCResult ReadSMC_LeavingSection(const SMCStates *states)
   176 	{
   177 		if (m_IgnoreLevel)
   178 		{
   179 			m_IgnoreLevel--;
   180 			return SMCResult_Continue;
   181 		}
   182 
   183 		if (m_LevelState == LEVEL_STATE_FLAGS)
   184 		{
   185 			m_LevelState = LEVEL_STATE_LEVELS;
   186 			return SMCResult_Halt;
   187 		} 
   188 		else if (m_LevelState == LEVEL_STATE_LEVELS) 
   189 		{
   190 			m_LevelState = LEVEL_STATE_NONE;
   191 		}
   192 
   193 		return SMCResult_Continue;
   194 	}
   195 	void ParseError(const SMCStates *states, const char *message, ...)
   196 	{
   197 		va_list ap;
   198 		char buffer[256];
   199 
   200 		va_start(ap, message);
   201 		UTIL_FormatArgs(buffer, sizeof(buffer), message, ap);
   202 		va_end(ap);
   203 
   204 		if (!m_bFileNameLogged)
   205 		{
   206 			g_Logger.LogError("[SM] Parse error(s) detected in file \"%s\":", m_File);
   207 			m_bFileNameLogged = true;
   208 		}
   209 
   210 		g_Logger.LogError("[SM] (Line %d): %s", states ? states->line : 0, buffer);
   211 	}
   212 private:
   213 	bool m_bFileNameLogged;
   214 	char m_File[PLATFORM_MAX_PATH];
   215 	int m_LevelState;
   216 	int m_IgnoreLevel;
   217 } s_FlagReader;
   218 
   219 AdminCache::AdminCache()
   220 {
   221 	m_pStrings = new BaseStringTable(1024);
   222 	m_pMemory = m_pStrings->GetMemTable();
   223 	m_FreeGroupList = m_FirstGroup = m_LastGroup = INVALID_GROUP_ID;
   224 	m_FreeUserList = m_FirstUser = m_LastUser = INVALID_ADMIN_ID;
   225 	m_pCacheFwd = NULL;
   226 	m_FirstGroup = -1;
   227 	m_InvalidatingAdmins = false;
   228 	m_destroying = false;
   229 }
   230 
   231 AdminCache::~AdminCache()
   232 {
   233 	m_destroying = true;
   234 	DumpAdminCache(AdminCache_Overrides, false);
   235 	DumpAdminCache(AdminCache_Groups, false);
   236 
   237 	List<AuthMethod *>::iterator iter;
   238 	for (iter=m_AuthMethods.begin();
   239 		 iter!=m_AuthMethods.end();
   240 		 iter++)
   241 	{
   242 		delete *iter;
   243 	}
   244 
   245 	delete m_pStrings;
   246 }
   247 
   248 void AdminCache::OnSourceModStartup(bool late)
   249 {
   250 	RegisterAuthIdentType("steam");
   251 	RegisterAuthIdentType("name");
   252 	RegisterAuthIdentType("ip");
   253 
   254 	NameFlag("reservation", Admin_Reservation);
   255 	NameFlag("kick", Admin_Kick);
   256 	NameFlag("generic", Admin_Generic);
   257 	NameFlag("ban", Admin_Ban);
   258 	NameFlag("unban", Admin_Unban);
   259 	NameFlag("slay", Admin_Slay);
   260 	NameFlag("changemap", Admin_Changemap);
   261 	NameFlag("cvars", Admin_Convars);
   262 	NameFlag("config", Admin_Config);
   263 	NameFlag("chat", Admin_Chat);
   264 	NameFlag("vote", Admin_Vote);
   265 	NameFlag("password", Admin_Password);
   266 	NameFlag("rcon", Admin_RCON);
   267 	NameFlag("cheats", Admin_Cheats);
   268 	NameFlag("root", Admin_Root);
   269 	NameFlag("custom1", Admin_Custom1);
   270 	NameFlag("custom2", Admin_Custom2);
   271 	NameFlag("custom3", Admin_Custom3);
   272 	NameFlag("custom4", Admin_Custom4);
   273 	NameFlag("custom5", Admin_Custom5);
   274 	NameFlag("custom6", Admin_Custom6);
   275 }
   276 
   277 void AdminCache::OnSourceModAllInitialized()
   278 {
   279 	m_pCacheFwd = g_Forwards.CreateForward("OnRebuildAdminCache", ET_Ignore, 1, NULL, Param_Cell);
   280 	sharesys->AddInterface(NULL, this);
   281 }
   282 
   283 void AdminCache::OnSourceModLevelChange(const char *mapName)
   284 {
   285 	int i;
   286 	AdminFlag flag;
   287 
   288 	/* For now, we only read these once per level. */
   289 	s_FlagReader.LoadLevels();
   290 
   291 	for (i = 0; i < 26; i++)
   292 	{
   293 		if (FindFlag('a' + i, &flag))
   294 		{
   295 			g_ReverseFlags[flag] = 'a' + i;
   296 		}
   297 		else
   298 		{
   299 			g_ReverseFlags[flag] = '?';
   300 		}
   301 	}
   302 }
   303 
   304 void AdminCache::OnSourceModShutdown()
   305 {
   306 	g_Forwards.ReleaseForward(m_pCacheFwd);
   307 	m_pCacheFwd = NULL;
   308 }
   309 
   310 void AdminCache::OnSourceModPluginsLoaded()
   311 {
   312 	DumpAdminCache(AdminCache_Overrides, true);
   313 	DumpAdminCache(AdminCache_Groups, true);
   314 }
   315 
   316 void AdminCache::NameFlag(const char *str, AdminFlag flag)
   317 {
   318 	m_LevelNames.insert(str, flag);
   319 }
   320 
   321 bool AdminCache::FindFlag(const char *str, AdminFlag *pFlag)
   322 {
   323 	return m_LevelNames.retrieve(str, pFlag);
   324 }
   325 
   326 void AdminCache::AddCommandOverride(const char *cmd, OverrideType type, FlagBits flags)
   327 {
   328 	FlagMap *map;
   329 	if (type == Override_Command)
   330 		map = &m_CmdOverrides;
   331 	else if (type == Override_CommandGroup)
   332 		map = &m_CmdGrpOverrides;
   333 	else
   334 		return;
   335 
   336 	map->insert(cmd, flags);
   337 	g_ConCmds.UpdateAdminCmdFlags(cmd, type, flags, false);
   338 }
   339 
   340 bool AdminCache::GetCommandOverride(const char *cmd, OverrideType type, FlagBits *pFlags)
   341 {
   342 	FlagMap *map;
   343 	if (type == Override_Command)
   344 		map = &m_CmdOverrides;
   345 	else if (type == Override_CommandGroup)
   346 		map = &m_CmdGrpOverrides;
   347 	else
   348 		return false;
   349 
   350 	return map->retrieve(cmd, pFlags);
   351 }
   352 
   353 void AdminCache::UnsetCommandOverride(const char *cmd, OverrideType type)
   354 {
   355 	if (type == Override_Command)
   356 	{
   357 		return _UnsetCommandOverride(cmd);
   358 	} else if (type == Override_CommandGroup) {
   359 		return _UnsetCommandGroupOverride(cmd);
   360 	}
   361 }
   362 
   363 void AdminCache::_UnsetCommandGroupOverride(const char *group)
   364 {
   365 	m_CmdGrpOverrides.remove(group);
   366 	g_ConCmds.UpdateAdminCmdFlags(group, Override_CommandGroup, 0, true);
   367 }
   368 
   369 void AdminCache::_UnsetCommandOverride(const char *cmd)
   370 {
   371 	m_CmdOverrides.remove(cmd);
   372 	g_ConCmds.UpdateAdminCmdFlags(cmd, Override_Command, 0, true);
   373 }
   374 
   375 void AdminCache::DumpCommandOverrideCache(OverrideType type)
   376 {
   377 	if (type == Override_Command)
   378 		m_CmdOverrides.clear();
   379 	else if (type == Override_CommandGroup)
   380 		m_CmdGrpOverrides.clear();
   381 }
   382 
   383 AdminId AdminCache::CreateAdmin(const char *name)
   384 {
   385 	AdminId id;
   386 	AdminUser *pUser;
   387 
   388 	if (m_FreeUserList != INVALID_ADMIN_ID)
   389 	{
   390 		pUser = (AdminUser *)m_pMemory->GetAddress(m_FreeUserList);
   391 		assert(pUser->magic == USR_MAGIC_UNSET);
   392 		id = m_FreeUserList;
   393 		m_FreeUserList = pUser->next_user;
   394 	}
   395 	else
   396 	{
   397 		id = m_pMemory->CreateMem(sizeof(AdminUser), (void **)&pUser);
   398 		pUser->grp_size = 0;
   399 		pUser->grp_table = -1;
   400 	}
   401 
   402 	pUser->flags = 0;
   403 	pUser->eflags = 0;
   404 	pUser->grp_count = 0;
   405 	pUser->password = -1;
   406 	pUser->magic = USR_MAGIC_SET;
   407 	pUser->auth.identidx = -1;
   408 	pUser->auth.index = 0;
   409 	pUser->immunity_level = 0;
   410 	pUser->serialchange = 1;
   411 
   412 	if (m_FirstUser == INVALID_ADMIN_ID)
   413 	{
   414 		m_FirstUser = id;
   415 		m_LastUser = id;
   416 	}
   417 	else
   418 	{
   419 		AdminUser *pPrev = (AdminUser *)m_pMemory->GetAddress(m_LastUser);
   420 		pPrev->next_user = id;
   421 		pUser->prev_user = m_LastUser;
   422 		m_LastUser = id;
   423 	}
   424 
   425 	/* Since we always append to the tail, we should invalidate their next */
   426 	pUser->next_user = -1;
   427 
   428 	if (name && name[0] != '\0')
   429 	{
   430 		int nameidx = m_pStrings->AddString(name);
   431 		pUser = (AdminUser *)m_pMemory->GetAddress(id);
   432 		pUser->nameidx = nameidx;
   433 	}
   434 	else
   435 	{
   436 		pUser->nameidx = -1;
   437 	}
   438 
   439 	return id;
   440 }
   441 
   442 GroupId AdminCache::AddGroup(const char *group_name)
   443 {
   444 	if (m_Groups.contains(group_name))
   445 		return INVALID_GROUP_ID;
   446 
   447 	GroupId id;
   448 	AdminGroup *pGroup;
   449 	if (m_FreeGroupList != INVALID_GROUP_ID)
   450 	{
   451 		pGroup = (AdminGroup *)m_pMemory->GetAddress(m_FreeGroupList);
   452 		assert(pGroup->magic == GRP_MAGIC_UNSET);
   453 		id = m_FreeGroupList;
   454 		m_FreeGroupList = pGroup->next_grp;
   455 	} else {
   456 		id = m_pMemory->CreateMem(sizeof(AdminGroup), (void **)&pGroup);
   457 	}
   458 
   459 	pGroup->immunity_level = 0;
   460 	pGroup->immune_table = -1;
   461 	pGroup->magic = GRP_MAGIC_SET;
   462 	pGroup->next_grp = INVALID_GROUP_ID;
   463 	pGroup->pCmdGrpTable = NULL;
   464 	pGroup->pCmdTable = NULL;
   465 	pGroup->addflags = 0;
   466 
   467 	if (m_FirstGroup == INVALID_GROUP_ID)
   468 	{
   469 		m_FirstGroup = id;
   470 		m_LastGroup = id;
   471 		pGroup->prev_grp = INVALID_GROUP_ID;
   472 	} else {
   473 		AdminGroup *pPrev = (AdminGroup *)m_pMemory->GetAddress(m_LastGroup);
   474 		assert(pPrev->magic == GRP_MAGIC_SET);
   475 		pPrev->next_grp = id;
   476 		pGroup->prev_grp = m_LastGroup;
   477 		m_LastGroup = id;
   478 	}
   479 
   480 	int nameidx = m_pStrings->AddString(group_name);
   481 	pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   482 	pGroup->nameidx = nameidx;
   483 
   484 	m_Groups.insert(group_name, id);
   485 	return id;
   486 }
   487 
   488 GroupId AdminCache::FindGroupByName(const char *group_name)
   489 {
   490 	GroupId id;
   491 	if (!m_Groups.retrieve(group_name, &id))
   492 		return INVALID_GROUP_ID;
   493 
   494 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   495 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   496 		return INVALID_GROUP_ID;
   497 
   498 	return id;
   499 }
   500 
   501 void AdminCache::SetGroupAddFlag(GroupId id, AdminFlag flag, bool enabled)
   502 {
   503 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   504 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   505 	{
   506 		return;
   507 	}
   508 
   509 	if (flag < Admin_Reservation || flag >= AdminFlags_TOTAL)
   510 	{
   511 		return;
   512 	}
   513 
   514 	FlagBits bits = (1<<(FlagBits)flag);
   515 
   516 	if (enabled)
   517 	{
   518 		pGroup->addflags |= bits;
   519 	} else {
   520 		pGroup->addflags &= ~bits;
   521 	}
   522 }
   523 
   524 bool AdminCache::GetGroupAddFlag(GroupId id, AdminFlag flag)
   525 {
   526 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   527 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   528 	{
   529 		return false;
   530 	}
   531 
   532 	if (flag < Admin_Reservation || flag >= AdminFlags_TOTAL)
   533 	{
   534 		return false;
   535 	}
   536 
   537 	FlagBits bit = 1<<(FlagBits)flag;
   538 	return ((pGroup->addflags & bit) == bit);
   539 }
   540 
   541 FlagBits AdminCache::GetGroupAddFlags(GroupId id)
   542 {
   543 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   544 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   545 	{
   546 		return 0;
   547 	}
   548 
   549 	return pGroup->addflags;
   550 }
   551 
   552 const char *AdminCache::GetGroupName(GroupId gid)
   553 {
   554 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid);
   555 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   556 	{
   557 		return NULL;
   558 	}
   559 
   560 	return m_pStrings->GetString(pGroup->nameidx);
   561 }
   562 
   563 void AdminCache::SetGroupGenericImmunity(GroupId id, ImmunityType type, bool enabled)
   564 {
   565 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   566 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   567 	{
   568 		return;
   569 	}
   570 
   571 	unsigned int level = 0;
   572 
   573 	if (enabled)
   574 	{
   575 		if (type == Immunity_Default)
   576 		{
   577 			level = 1;
   578 		} else if (type == Immunity_Global) {
   579 			level = 2;
   580 		}
   581 		if (level > pGroup->immunity_level)
   582 		{
   583 			pGroup->immunity_level = level;
   584 		}
   585 	} else {
   586 		pGroup->immunity_level = 0;
   587 	}
   588 }
   589 
   590 bool AdminCache::GetGroupGenericImmunity(GroupId id, ImmunityType type)
   591 {
   592 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   593 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   594 	{
   595 		return false;
   596 	}
   597 
   598 	if (type == Immunity_Default && pGroup->immunity_level >= 1)
   599 	{
   600 		return true;
   601 	} else if (type == Immunity_Global && pGroup->immunity_level >= 2) {
   602 		return true;
   603 	}
   604 
   605 	return false;
   606 }
   607 
   608 void AdminCache::AddGroupImmunity(GroupId id, GroupId other_id)
   609 {
   610 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(other_id);
   611 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   612 	{
   613 		return;
   614 	}
   615 
   616 	pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   617 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   618 	{
   619 		return;
   620 	}
   621 
   622 	/* We always need to resize the immunity table */
   623 	int *table, tblidx;
   624 	if (pGroup->immune_table == -1)
   625 	{
   626 		tblidx = m_pMemory->CreateMem(sizeof(int) * 2, (void **)&table);
   627 		pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   628 		table[0] = 0;
   629 	} else {
   630 		int *old_table = (int *)m_pMemory->GetAddress(pGroup->immune_table);
   631 		/* Break out if this group is already in the list */
   632 		for (int i=0; i<old_table[0]; i++)
   633 		{
   634 			if (old_table[1+i] == other_id)
   635 			{
   636 				return;
   637 			}
   638 		}
   639 		tblidx = m_pMemory->CreateMem(sizeof(int) * (old_table[0] + 2), (void **)&table);
   640 		/* Get the old address again in case of resize */
   641 		pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   642 		old_table = (int *)m_pMemory->GetAddress(pGroup->immune_table);
   643 		table[0] = old_table[0];
   644 		for (unsigned int i=1; i<=(unsigned int)old_table[0]; i++)
   645 		{
   646 			table[i] = old_table[i];
   647 		}
   648 	}
   649 
   650 	/* Assign */
   651 	pGroup->immune_table = tblidx;
   652 
   653 	/* Add to the array */
   654 	table[0]++;
   655 	table[table[0]] = other_id;
   656 }
   657 
   658 unsigned int AdminCache::GetGroupImmunityCount(GroupId id)
   659 {
   660 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   661 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   662 	{
   663 		return 0;
   664 	}
   665 
   666 	if (pGroup->immune_table == -1)
   667 	{
   668 		return 0;
   669 	}
   670 
   671 	int *table = (int *)m_pMemory->GetAddress(pGroup->immune_table);
   672 
   673 	return table[0];
   674 }
   675 
   676 GroupId AdminCache::GetGroupImmunity(GroupId id, unsigned int number)
   677 {
   678 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   679 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   680 	{
   681 		return INVALID_GROUP_ID;
   682 	}
   683 
   684 	if (pGroup->immune_table == -1)
   685 	{
   686 		return INVALID_GROUP_ID;
   687 	}
   688 
   689 	int *table = (int *)m_pMemory->GetAddress(pGroup->immune_table);
   690 	if (number >= (unsigned int)table[0])
   691 	{
   692 		return INVALID_GROUP_ID;
   693 	}
   694 
   695 	return table[1 + number];
   696 }
   697 
   698 void AdminCache::AddGroupCommandOverride(GroupId id, const char *name, OverrideType type, OverrideRule rule)
   699 {
   700 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   701 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   702 	{
   703 		return;
   704 	}
   705 
   706 	OverrideMap *map;
   707 	if (type == Override_Command)
   708 	{
   709 		if (pGroup->pCmdTable == NULL)
   710 			pGroup->pCmdTable = new OverrideMap();
   711 		map = pGroup->pCmdTable;
   712 	} else if (type == Override_CommandGroup) {
   713 		if (pGroup->pCmdGrpTable == NULL)
   714 			pGroup->pCmdGrpTable = new OverrideMap();
   715 		map = pGroup->pCmdGrpTable;
   716 	} else {
   717 		return;
   718 	}
   719 
   720 	map->insert(name, rule);
   721 }
   722 
   723 bool AdminCache::GetGroupCommandOverride(GroupId id, const char *name, OverrideType type, OverrideRule *pRule)
   724 {
   725 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   726 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   727 	{
   728 		return false;
   729 	}
   730 
   731 	OverrideMap *map;
   732 	if (type == Override_Command)
   733 	{
   734 		if (pGroup->pCmdTable == NULL)
   735 			return false;
   736 		map = pGroup->pCmdTable;
   737 	} else if (type == Override_CommandGroup) {
   738 		if (pGroup->pCmdGrpTable == NULL)
   739 			return false;
   740 		map = pGroup->pCmdGrpTable;
   741 	} else {
   742 		return false;
   743 	}
   744 
   745 	return map->retrieve(name, pRule);
   746 }
   747 
   748 AuthMethod *AdminCache::GetMethodByIndex(unsigned int index)
   749 {
   750 	List<AuthMethod *>::iterator iter;
   751 	for (iter=m_AuthMethods.begin();
   752 		 iter!=m_AuthMethods.end();
   753 		 iter++)
   754 	{
   755 		if (index-- == 0)
   756 		{
   757 			return *iter;
   758 		}
   759 	}
   760 
   761 	return NULL;
   762 }
   763 
   764 bool AdminCache::InvalidateAdmin(AdminId id)
   765 {
   766 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
   767 	AdminUser *pOther;
   768 	if (!pUser || pUser->magic != USR_MAGIC_SET)
   769 	{
   770 		return false;
   771 	}
   772 
   773 	if (!m_InvalidatingAdmins && !m_destroying)
   774 	{
   775 		g_Players.ClearAdminId(id);
   776 	}
   777 
   778 	/* Unlink from the dbl link list */
   779 	if (id == m_FirstUser && id == m_LastUser)
   780 	{
   781 		m_FirstUser = INVALID_ADMIN_ID;
   782 		m_LastUser = INVALID_ADMIN_ID;
   783 	} else if (id == m_FirstUser) {
   784 		m_FirstUser = pUser->next_user;
   785 		pOther = (AdminUser *)m_pMemory->GetAddress(m_FirstUser);
   786 		pOther->prev_user = INVALID_ADMIN_ID;
   787 	} else if (id == m_LastUser) {
   788 		m_LastUser = pUser->prev_user;
   789 		pOther = (AdminUser *)m_pMemory->GetAddress(m_LastUser);
   790 		pOther->next_user = INVALID_ADMIN_ID;
   791 	} else {
   792 		pOther = (AdminUser *)m_pMemory->GetAddress(pUser->prev_user);
   793 		pOther->next_user = pUser->next_user;
   794 		pOther = (AdminUser *)m_pMemory->GetAddress(pUser->next_user);
   795 		pOther->prev_user = pUser->prev_user;
   796 	}
   797 
   798 	/* Unlink from auth tables */
   799 	if (pUser->auth.identidx != -1)
   800 	{
   801 		AuthMethod *method = GetMethodByIndex(pUser->auth.index);
   802 		if (method)
   803 			method->identities.remove(m_pStrings->GetString(pUser->auth.identidx));
   804 	}
   805 
   806 	/* Clear table counts */
   807 	pUser->grp_count = 0;
   808 	
   809 	/* Link into free list */
   810 	pUser->magic = USR_MAGIC_UNSET;
   811 	pUser->next_user = m_FreeUserList;
   812 	m_FreeUserList = id;
   813 
   814 	/* Unset serial change */
   815 	pUser->serialchange = 0;
   816 
   817 	return true;
   818 }
   819 
   820 
   821 void AdminCache::InvalidateGroup(GroupId id)
   822 {
   823 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id);
   824 	AdminGroup *pOther;
   825 
   826 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
   827 	{
   828 		return;
   829 	}
   830 
   831 	const char *str = m_pStrings->GetString(pGroup->nameidx);
   832 	m_Groups.remove(str);
   833 
   834 	/* Unlink from the live dbllink list */
   835 	if (id == m_FirstGroup && id == m_LastGroup)
   836 	{
   837 		m_LastGroup = INVALID_GROUP_ID;
   838 		m_FirstGroup = INVALID_GROUP_ID;
   839 	} else if (id == m_FirstGroup) {
   840 		m_FirstGroup = pGroup->next_grp;
   841 		pOther = (AdminGroup *)m_pMemory->GetAddress(m_FirstGroup);
   842 		pOther->prev_grp = INVALID_GROUP_ID;
   843 	} else if (id == m_LastGroup) {
   844 		m_LastGroup = pGroup->prev_grp;
   845 		pOther = (AdminGroup *)m_pMemory->GetAddress(m_LastGroup);
   846 		pOther->next_grp = INVALID_GROUP_ID;
   847 	} else {
   848 		pOther = (AdminGroup *)m_pMemory->GetAddress(pGroup->prev_grp);
   849 		pOther->next_grp = pGroup->next_grp;
   850 		pOther = (AdminGroup *)m_pMemory->GetAddress(pGroup->next_grp);
   851 		pOther->prev_grp = pGroup->prev_grp;
   852 	}
   853 
   854 	/* Free any used memory */
   855 	delete pGroup->pCmdGrpTable;
   856 	pGroup->pCmdGrpTable = NULL;
   857 	delete pGroup->pCmdTable;
   858 	pGroup->pCmdTable = NULL;
   859 
   860 	/* Link into the free list */
   861 	pGroup->magic = GRP_MAGIC_UNSET;
   862 	pGroup->next_grp = m_FreeGroupList;
   863 	m_FreeGroupList = id;
   864 
   865 	int idx = m_FirstUser;
   866 	AdminUser *pUser;
   867 	int *table;
   868 	while (idx != INVALID_ADMIN_ID)
   869 	{
   870 		pUser = (AdminUser *)m_pMemory->GetAddress(idx);
   871 		if (pUser->grp_count > 0)
   872 		{
   873 			table = (int *)m_pMemory->GetAddress(pUser->grp_table);
   874 			for (unsigned int i=0; i<pUser->grp_count; i++)
   875 			{
   876 				if (table[i] == id)
   877 				{
   878 					/* We have to remove this entry */
   879 					for (unsigned int j=i+1; j<pUser->grp_count; j++)
   880 					{
   881 						/* Move everything down by one */
   882 						table[j-1] = table[j];
   883 					}
   884 					/* Decrease count */
   885 					pUser->grp_count--;
   886 					/* Recalculate effective flags */
   887 					pUser->eflags = pUser->flags;
   888 					for (unsigned int j=0; j<pUser->grp_count; j++)
   889 					{
   890 						pOther = (AdminGroup *)m_pMemory->GetAddress(table[j]);
   891 						pUser->eflags |= pOther->addflags;
   892 					}
   893 					/* Mark as changed */
   894 					pUser->serialchange++;
   895 					/* Break now, duplicates aren't allowed */
   896 					break;
   897 				}
   898 			}
   899 		}
   900 		idx = pUser->next_user;
   901 	}
   902 }
   903 
   904 void AdminCache::InvalidateGroupCache()
   905 {
   906 	/* Nuke the free list */
   907 	m_FreeGroupList = -1;
   908 
   909 	/* Nuke reverse lookups */
   910 	m_Groups.clear();
   911 
   912 	/* Free memory on groups */
   913 	GroupId cur = m_FirstGroup;
   914 	AdminGroup *pGroup;
   915 	while (cur != INVALID_GROUP_ID)
   916 	{
   917 		pGroup = (AdminGroup *)m_pMemory->GetAddress(cur);
   918 		assert(pGroup->magic == GRP_MAGIC_SET);
   919 		delete pGroup->pCmdGrpTable;
   920 		delete pGroup->pCmdTable;
   921 		cur = pGroup->next_grp;
   922 	}
   923 
   924 	m_FirstGroup = INVALID_GROUP_ID;
   925 	m_LastGroup = INVALID_GROUP_ID;
   926 
   927 	InvalidateAdminCache(false);
   928 
   929 	/* Reset the memory table */
   930 	m_pMemory->Reset();
   931 }
   932 
   933 void AdminCache::AddAdminListener(IAdminListener *pListener)
   934 {
   935 	m_hooks.push_back(pListener);
   936 }
   937 
   938 void AdminCache::RemoveAdminListener(IAdminListener *pListener)
   939 {
   940 	m_hooks.remove(pListener);
   941 }
   942 
   943 void AdminCache::RegisterAuthIdentType(const char *name)
   944 {
   945 	if (m_AuthTables.contains(name))
   946 		return;
   947 
   948 	AuthMethod *method = new AuthMethod(name);
   949 	m_AuthMethods.push_back(method);
   950 	m_AuthTables.insert(name, method);
   951 }
   952 
   953 void AdminCache::InvalidateAdminCache(bool unlink_admins)
   954 {
   955 	m_InvalidatingAdmins = true;
   956 	if (!m_destroying)
   957 	{
   958 		g_Players.ClearAllAdmins();
   959 	}
   960 	/* Wipe the identity cache first */
   961 	List<AuthMethod *>::iterator iter;
   962 	for (iter=m_AuthMethods.begin();
   963 		 iter!=m_AuthMethods.end();
   964 		 iter++)
   965 	{
   966 		(*iter)->identities.clear();
   967 	}
   968 	
   969 	if (unlink_admins)
   970 	{
   971 		while (m_FirstUser != INVALID_ADMIN_ID)
   972 		{
   973 			InvalidateAdmin(m_FirstUser);
   974 		}
   975 	} else {
   976 		m_FirstUser = -1;
   977 		m_LastUser = -1;
   978 		m_FreeUserList = -1;
   979 	}
   980 	m_InvalidatingAdmins = false;
   981 }
   982 
   983 void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
   984 {
   985 	List<IAdminListener *>::iterator iter;
   986 	IAdminListener *pListener;
   987 	cell_t result;
   988 
   989 	if (part == AdminCache_Overrides)
   990 	{
   991 		DumpCommandOverrideCache(Override_Command);
   992 		DumpCommandOverrideCache(Override_CommandGroup);
   993 		if (rebuild && !m_destroying)
   994 		{
   995 			for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   996 			{
   997 				pListener = (*iter);
   998 				pListener->OnRebuildOverrideCache();
   999 			}
  1000 			m_pCacheFwd->PushCell(part);
  1001 			m_pCacheFwd->Execute(&result);
  1002 		}
  1003 	} else if (part == AdminCache_Groups || part == AdminCache_Admins) {
  1004 		if (part == AdminCache_Groups)
  1005 		{
  1006 			InvalidateGroupCache();
  1007 			if (rebuild && !m_destroying)
  1008 			{
  1009 				for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1010 				{
  1011 					pListener = (*iter);
  1012 					pListener->OnRebuildGroupCache();
  1013 				}
  1014 				m_pCacheFwd->PushCell(part);
  1015 				m_pCacheFwd->Execute(&result);
  1016 			}
  1017 		}
  1018 		InvalidateAdminCache(true);
  1019 		if (rebuild && !m_destroying)
  1020 		{
  1021 			for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1022 			{
  1023 				pListener = (*iter);
  1024 				pListener->OnRebuildAdminCache((part == AdminCache_Groups));
  1025 			}
  1026 			m_pCacheFwd->PushCell(AdminCache_Admins);
  1027 			m_pCacheFwd->Execute(&result);
  1028 			g_Players.RecheckAnyAdmins();
  1029 		}
  1030 	}
  1031 }
  1032 
  1033 const char *AdminCache::GetAdminName(AdminId id)
  1034 {
  1035 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1036 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1037 	{
  1038 		return NULL;
  1039 	}
  1040 
  1041 	return m_pStrings->GetString(pUser->nameidx);
  1042 }
  1043 
  1044 bool AdminCache::GetMethodIndex(const char *name, unsigned int *_index)
  1045 {
  1046 	List<AuthMethod *>::iterator iter;
  1047 	unsigned int index = 0;
  1048 	for (iter=m_AuthMethods.begin();
  1049 		 iter!=m_AuthMethods.end();
  1050 		 iter++,index++)
  1051 	{
  1052 		if ((*iter)->name.compare(name) == 0)
  1053 		{
  1054 			*_index = index;
  1055 			return true;
  1056 		}
  1057 	}
  1058 
  1059 	return false;
  1060 }
  1061 
  1062 bool AdminCache::BindAdminIdentity(AdminId id, const char *auth, const char *ident)
  1063 {
  1064 	if (ident[0] == '\0')
  1065 	{
  1066 		return false;
  1067 	}
  1068 
  1069 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1070 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1071 	{
  1072 		return false;
  1073 	}
  1074 
  1075 	AuthMethod *method;
  1076 	if (!m_AuthTables.retrieve(auth, &method))
  1077 		return false;
  1078 
  1079 	/* If the id was a steam id strip off the STEAM_*: part */
  1080 	if (strcmp(auth, "steam") == 0 && strncmp(ident, "STEAM_", 6) == 0)
  1081 	{
  1082 		ident += 8;
  1083 	}
  1084 
  1085 	if (method->identities.contains(ident))
  1086 		return false;
  1087 
  1088 	int i_ident = m_pStrings->AddString(ident);
  1089 
  1090 	pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1091 	pUser->auth.identidx = i_ident;
  1092 	GetMethodIndex(auth, &pUser->auth.index);
  1093 
  1094 	return method->identities.insert(ident, id);
  1095 }
  1096 
  1097 AdminId AdminCache::FindAdminByIdentity(const char *auth, const char *identity)
  1098 {
  1099 	AuthMethod *method;
  1100 	if (!m_AuthTables.retrieve(auth, &method))
  1101 		return INVALID_ADMIN_ID;
  1102 
  1103 	/* If the id was a steam id strip off the STEAM_*: part */
  1104 	if (strcmp(auth, "steam") == 0 && strncmp(identity, "STEAM_", 6) == 0)
  1105 	{
  1106 		identity += 8;
  1107 	}
  1108 
  1109 	AdminId id;
  1110 	if (!method->identities.retrieve(identity, &id))
  1111 		return INVALID_ADMIN_ID;
  1112 	return id;
  1113 }
  1114 
  1115 void AdminCache::SetAdminFlag(AdminId id, AdminFlag flag, bool enabled)
  1116 {
  1117 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1118 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1119 	{
  1120 		return;
  1121 	}
  1122 
  1123 	if (flag < Admin_Reservation
  1124 		|| flag >= AdminFlags_TOTAL)
  1125 	{
  1126 		return;
  1127 	}
  1128 	
  1129 	FlagBits bits = (1<<(FlagBits)flag);
  1130 
  1131 	if (enabled)
  1132 	{
  1133 		pUser->flags |= bits;
  1134 		pUser->eflags |= bits;
  1135 	} else {
  1136 		pUser->flags &= ~bits;
  1137 		pUser->eflags &= ~bits;
  1138 	}
  1139 
  1140 	pUser->serialchange++;
  1141 }
  1142 
  1143 bool AdminCache::GetAdminFlag(AdminId id, AdminFlag flag, AccessMode mode)
  1144 {
  1145 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1146 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1147 	{
  1148 		return false;
  1149 	}
  1150 
  1151 	if (flag < Admin_Reservation
  1152 		|| flag >= AdminFlags_TOTAL)
  1153 	{
  1154 		return false;
  1155 	}
  1156 
  1157 	FlagBits bit = (1<<(FlagBits)flag);
  1158 
  1159 	if (mode == Access_Real)
  1160 	{
  1161 		return ((pUser->flags & bit) == bit);
  1162 	} else if (mode == Access_Effective) {
  1163 		bool has_bit = ((pUser->eflags & bit) == bit);
  1164 		if (!has_bit && flag != Admin_Root && ((pUser->eflags & ADMFLAG_ROOT) == ADMFLAG_ROOT))
  1165 		{
  1166 			has_bit = true;
  1167 		}
  1168 		return has_bit;
  1169 	}
  1170 
  1171 	return false;
  1172 }
  1173 
  1174 FlagBits AdminCache::GetAdminFlags(AdminId id, AccessMode mode)
  1175 {
  1176 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1177 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1178 	{
  1179 		return 0;
  1180 	}
  1181 
  1182 	if (mode == Access_Real)
  1183 	{
  1184 		return pUser->flags;
  1185 	} else if (mode == Access_Effective) {
  1186 		return pUser->eflags;
  1187 	}
  1188 
  1189 	return 0;
  1190 }
  1191 
  1192 void AdminCache::SetAdminFlags(AdminId id, AccessMode mode, FlagBits bits)
  1193 {
  1194 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1195 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1196 	{
  1197 		return;
  1198 	}
  1199 
  1200 	if (mode == Access_Real)
  1201 	{
  1202 		pUser->flags = bits;
  1203 		pUser->eflags = bits;
  1204 	} else if (mode == Access_Effective) {
  1205 		pUser->eflags = bits;
  1206 	}
  1207 
  1208 	pUser->serialchange++;
  1209 }
  1210 
  1211 bool AdminCache::AdminInheritGroup(AdminId id, GroupId gid)
  1212 {
  1213 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1214 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1215 	{
  1216 		return false;
  1217 	}
  1218 
  1219 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid);
  1220 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
  1221 	{
  1222 		return false;
  1223 	}
  1224 
  1225 	/* First check for duplicates */
  1226 	if (pUser->grp_count != 0)
  1227 	{
  1228 		int *temp_table = (int *)m_pMemory->GetAddress(pUser->grp_table);
  1229 		for (unsigned int i=0; i<pUser->grp_count; i++)
  1230 		{
  1231 			if (temp_table[i] == gid)
  1232 			{
  1233 				return false;
  1234 			}
  1235 		}
  1236 	}
  1237 
  1238 	int *table;
  1239 	if (pUser->grp_count + 1 > pUser->grp_size)
  1240 	{
  1241 		int new_size = 0;
  1242 		int tblidx;
  1243 		
  1244 		if (pUser->grp_size == 0)
  1245 		{
  1246 			new_size = 2;
  1247 		} else {
  1248 			new_size = pUser->grp_size * 2;
  1249 		}
  1250 		
  1251 		/* Create and refresh pointers */
  1252 		tblidx = m_pMemory->CreateMem(new_size * sizeof(int), (void **)&table);
  1253 		pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1254 		pGroup = (AdminGroup *)m_pMemory->GetAddress(gid);
  1255 
  1256 		/* Copy old data if necessary */
  1257 		if (pUser->grp_table != -1)
  1258 		{
  1259 			int *old_table = (int *)m_pMemory->GetAddress(pUser->grp_table);
  1260 			memcpy(table, old_table, sizeof(int) * pUser->grp_count);
  1261 		}
  1262 		pUser->grp_table = tblidx;
  1263 		pUser->grp_size = new_size;
  1264 	} else {
  1265 		table = (int *)m_pMemory->GetAddress(pUser->grp_table);
  1266 	}
  1267 
  1268 	table[pUser->grp_count] = gid;
  1269 	pUser->grp_count++;
  1270 
  1271 	/* Compute new effective permissions */
  1272 	pUser->eflags |= pGroup->addflags;
  1273 
  1274 	if (pGroup->immunity_level > pUser->immunity_level)
  1275 	{
  1276 		pUser->immunity_level = pGroup->immunity_level;
  1277 	}
  1278 
  1279 	pUser->serialchange++;
  1280 
  1281 	return true;
  1282 }
  1283 
  1284 bool AdminCache::IsValidAdmin(AdminId id)
  1285 {
  1286 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1287 	return (pUser != NULL && pUser->magic == USR_MAGIC_SET);
  1288 }
  1289 
  1290 unsigned int AdminCache::GetAdminGroupCount(AdminId id)
  1291 {
  1292 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1293 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1294 	{
  1295 		return 0;
  1296 	}
  1297 
  1298 	return pUser->grp_count;
  1299 }
  1300 
  1301 GroupId AdminCache::GetAdminGroup(AdminId id, unsigned int index, const char **name)
  1302 {
  1303 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1304 	if (!pUser || pUser->magic != USR_MAGIC_SET || index >= pUser->grp_count)
  1305 	{
  1306 		return INVALID_GROUP_ID;
  1307 	}
  1308 
  1309 	int *table = (int *)m_pMemory->GetAddress(pUser->grp_table);
  1310 
  1311 	GroupId gid = table[index];
  1312 
  1313 	if (name)
  1314 	{
  1315 		*name = GetGroupName(gid);
  1316 	}
  1317 
  1318 	return gid;
  1319 }
  1320 
  1321 const char *AdminCache::GetAdminPassword(AdminId id)
  1322 {
  1323 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1324 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1325 	{
  1326 		return NULL;
  1327 	}
  1328 
  1329 	return m_pStrings->GetString(pUser->password);
  1330 }
  1331 
  1332 void AdminCache::SetAdminPassword(AdminId id, const char *password)
  1333 {	
  1334 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1335 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1336 	{
  1337 		return;
  1338 	}
  1339 
  1340 	if (password[0] == '\0')
  1341 	{
  1342 		pUser->password = -1;
  1343 		return;
  1344 	}
  1345 
  1346 	int i_password = m_pStrings->AddString(password);
  1347 	pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1348 	pUser->password = i_password;
  1349 }
  1350 
  1351 unsigned int AdminCache::FlagBitsToBitArray(FlagBits bits, bool array[], unsigned int maxSize)
  1352 {
  1353 	unsigned int i;
  1354 	for (i=0; i<maxSize && i<AdminFlags_TOTAL; i++)
  1355 	{
  1356 		array[i] = ((bits & (1<<i)) == (unsigned)(1<<i));
  1357 	}
  1358 
  1359 	return i;
  1360 }
  1361 
  1362 FlagBits AdminCache::FlagBitArrayToBits(const bool array[], unsigned int maxSize)
  1363 {
  1364 	FlagBits bits = 0;
  1365 	for (unsigned int i=0; i<maxSize && i<AdminFlags_TOTAL; i++)
  1366 	{
  1367 		if (array[i])
  1368 		{
  1369 			bits |= (1<<i);
  1370 		}
  1371 	}
  1372 
  1373 	return bits;
  1374 }
  1375 
  1376 FlagBits AdminCache::FlagArrayToBits(const AdminFlag array[], unsigned int numFlags)
  1377 {
  1378 	FlagBits bits = 0;
  1379 	for (unsigned int i=0; i<numFlags && i<AdminFlags_TOTAL; i++)
  1380 	{
  1381 		bits |= (1 << (FlagBits)array[i]);
  1382 	}
  1383 
  1384 	return bits;
  1385 }
  1386 
  1387 unsigned int AdminCache::FlagBitsToArray(FlagBits bits, AdminFlag array[], unsigned int maxSize)
  1388 {
  1389 	unsigned int i, num=0;
  1390 	for (i=0; num<maxSize && i<AdminFlags_TOTAL; i++)
  1391 	{
  1392 		if ((bits & (1<<i)) == (unsigned)(1<<i))
  1393 		{
  1394 			array[num++] = (AdminFlag)i;
  1395 		}
  1396 	}
  1397 
  1398 	return num;
  1399 }
  1400 
  1401 bool AdminCache::CheckAdminFlags(AdminId id, FlagBits bits)
  1402 {
  1403 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1404 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1405 	{
  1406 		return false;
  1407 	}
  1408 
  1409 	return ((pUser->eflags & bits) == bits);
  1410 }
  1411 
  1412 bool AdminCache::CanAdminTarget(AdminId id, AdminId target)
  1413 {
  1414 	/** 
  1415 	 * Zeroth, if the targeting AdminId is INVALID_ADMIN_ID, targeting fails.
  1416 	 * First, if the targeted AdminId is INVALID_ADMIN_ID, targeting succeeds.
  1417 	 */
  1418 
  1419 	if (id == INVALID_ADMIN_ID)
  1420 	{
  1421 		return false;
  1422 	}
  1423 
  1424 	if (target == INVALID_ADMIN_ID)
  1425 	{
  1426 		return true;
  1427 	}
  1428 
  1429 	if (id == target)
  1430 	{
  1431 		return true;
  1432 	}
  1433 
  1434 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1435 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1436 	{
  1437 		return false;
  1438 	}
  1439 
  1440 	AdminUser *pTarget = (AdminUser *)m_pMemory->GetAddress(target);
  1441 	if (!pTarget || pTarget->magic != USR_MAGIC_SET)
  1442 	{
  1443 		return false;
  1444 	}
  1445 
  1446 	/** 
  1447 	 * Second, if the targeting admin is root, targeting succeeds.
  1448 	 */
  1449 	if (pUser->eflags & ADMFLAG_ROOT)
  1450 	{
  1451 		return true;
  1452 	}
  1453 
  1454 	/** Fourth, if the targeted admin is immune from targeting admin. */
  1455 	int mode = sm_immunity_mode.GetInt();
  1456 	switch (mode)
  1457 	{
  1458 		case 1:
  1459 		{
  1460 			if (pTarget->immunity_level > pUser->immunity_level)
  1461 			{
  1462 				return false;
  1463 			}
  1464 			break;
  1465 		}
  1466 		case 3:
  1467 		{
  1468 			/* If neither has any immunity, let this pass. */
  1469 			if (!pUser->immunity_level && !pTarget->immunity_level)
  1470 			{
  1471 				return true;
  1472 			}
  1473 			/* Don't break, go to the next case. */
  1474 		}
  1475 		case 2:
  1476 		{
  1477 			if (pTarget->immunity_level >= pUser->immunity_level)
  1478 			{
  1479 				return false;
  1480 			}
  1481 			break;
  1482 		}
  1483 	}
  1484 
  1485 	/** 
  1486 	 * Fifth, if the targeted admin has specific immunity from the
  1487 	 *  targeting admin via group immunities, targeting fails.
  1488 	 */
  1489 	//:TODO: speed this up... maybe with trie hacks.
  1490 	//idea is to insert %d.%d in the trie after computing this and use it as a cache lookup.
  1491 	//problem is the trie cannot delete prefixes, so we'd have a problem with invalidations.
  1492 	if (pTarget->grp_count > 0 && pUser->grp_count > 0)
  1493 	{
  1494 		int *grp_table = (int *)m_pMemory->GetAddress(pTarget->grp_table);
  1495 		int *src_table = (int *)m_pMemory->GetAddress(pUser->grp_table);
  1496 		GroupId id, other;
  1497 		unsigned int num;
  1498 		for (unsigned int i=0; i<pTarget->grp_count; i++)
  1499 		{
  1500 			id = grp_table[i];
  1501 			num = GetGroupImmunityCount(id);
  1502 			for (unsigned int j=0; j<num; i++)
  1503 			{
  1504 				other = GetGroupImmunity(id, j);
  1505 				for (unsigned int k=0; k<pUser->grp_count; k++)
  1506 				{
  1507 					if (other == src_table[k])
  1508 					{
  1509 						return false;
  1510 					}
  1511 				}
  1512 			}
  1513 		}
  1514 	}
  1515 	
  1516 	return true;
  1517 }
  1518 
  1519 bool AdminCache::FindFlag(char c, AdminFlag *pAdmFlag)
  1520 {
  1521 	if (c < 'a' 
  1522 		|| c > 'z'
  1523 		|| !g_FlagSet[(unsigned)c - (unsigned)'a'])
  1524 	{
  1525 		return false;
  1526 	}
  1527 
  1528 	if (pAdmFlag)
  1529 	{
  1530 		*pAdmFlag = g_FlagLetters[(unsigned)c - (unsigned)'a'];
  1531 	}
  1532 
  1533 	return true;
  1534 }
  1535 
  1536 bool AdminCache::FindFlagChar(AdminFlag flag, char *c)
  1537 {
  1538 	if (!g_FlagSet[flag])
  1539 	{
  1540 		return false;
  1541 	}
  1542 
  1543 	if (c)
  1544 	{
  1545 		*c = g_ReverseFlags[flag];
  1546 	}
  1547 
  1548 	return true;
  1549 }
  1550 
  1551 FlagBits AdminCache::ReadFlagString(const char *flags, const char **end)
  1552 {
  1553 	FlagBits bits = 0;
  1554 
  1555 	while (flags && (*flags != '\0'))
  1556 	{
  1557 		AdminFlag flag;
  1558 		if (!FindFlag(*flags, &flag))
  1559 		{
  1560 			break;
  1561 		}
  1562 		bits |= FlagArrayToBits(&flag, 1);
  1563 		flags++;
  1564 	}
  1565 
  1566 	if (end)
  1567 	{
  1568 		*end = flags;
  1569 	}
  1570 
  1571 	return bits;
  1572 }
  1573 
  1574 unsigned int AdminCache::GetAdminSerialChange(AdminId id)
  1575 {
  1576 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1577 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1578 	{
  1579 		return 0;
  1580 	}
  1581 
  1582 	return pUser->serialchange;
  1583 }
  1584 
  1585 bool AdminCache::CanAdminUseCommand(int client, const char *cmd)
  1586 {
  1587 	FlagBits bits;
  1588 	OverrideType otype = Override_Command;
  1589 
  1590 	if (cmd[0] == '@')
  1591 	{
  1592 		otype = Override_CommandGroup;
  1593 		cmd++;
  1594 	}
  1595 
  1596 	if (!g_ConCmds.LookForCommandAdminFlags(cmd, &bits))
  1597 	{
  1598 		if (!GetCommandOverride(cmd, otype, &bits))
  1599 		{
  1600 			bits = 0;
  1601 		}
  1602 	}
  1603 
  1604 	return g_ConCmds.CheckClientCommandAccess(client, cmd, bits);
  1605 }
  1606 
  1607 unsigned int AdminCache::SetGroupImmunityLevel(GroupId gid, unsigned int level)
  1608 {
  1609 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid);
  1610 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
  1611 	{
  1612 		return 0;
  1613 	}
  1614 
  1615 	unsigned int old_level = pGroup->immunity_level;
  1616 
  1617 	pGroup->immunity_level = level;
  1618 
  1619 	return old_level;
  1620 }
  1621 
  1622 unsigned int AdminCache::GetGroupImmunityLevel(GroupId gid)
  1623 {
  1624 	AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid);
  1625 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
  1626 	{
  1627 		return 0;
  1628 	}
  1629 
  1630 	return pGroup->immunity_level;
  1631 }
  1632 
  1633 unsigned int AdminCache::SetAdminImmunityLevel(AdminId id, unsigned int level)
  1634 {
  1635 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1636 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1637 	{
  1638 		return 0;
  1639 	}
  1640 
  1641 	unsigned int old_level = pUser->immunity_level;
  1642 
  1643 	pUser->immunity_level = level;
  1644 
  1645 	return old_level;
  1646 }
  1647 
  1648 unsigned int AdminCache::GetAdminImmunityLevel(AdminId id)
  1649 {
  1650 	AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id);
  1651 	if (!pUser || pUser->magic != USR_MAGIC_SET)
  1652 	{
  1653 		return 0;
  1654 	}
  1655 
  1656 	return pUser->immunity_level;
  1657 }
  1658 
  1659 bool AdminCache::CheckAccess(int client, const char *cmd, FlagBits flags, bool override_only)
  1660 {
  1661 	if (client == 0)
  1662 	{
  1663 		return true;
  1664 	}
  1665 
  1666 	/* Auto-detect a command if we can */
  1667 	FlagBits bits = flags;
  1668 	bool found_command = false;
  1669 	if (!override_only)
  1670 	{
  1671 		found_command = g_ConCmds.LookForCommandAdminFlags(cmd, &bits);
  1672 	}
  1673 
  1674 	if (!found_command)
  1675 	{
  1676 		GetCommandOverride(cmd, Override_Command, &bits);
  1677 	}
  1678 
  1679 	return g_ConCmds.CheckClientCommandAccess(client, cmd, bits) ? 1 : 0;
  1680 }
  1681 
  1682 void iterator_glob_basic_override(FILE *fp, const char *key, FlagBits flags)
  1683 {
  1684 	char flagstr[64];
  1685 	g_Admins.FillFlagString(flags, flagstr, sizeof(flagstr));
  1686 	fprintf(fp, "\t\"%s\"\t\t\"%s\"\n", key, flagstr);
  1687 }
  1688 
  1689 void iterator_glob_grp_override(FILE *fp, const char *key, FlagBits flags)
  1690 {
  1691 	char flagstr[64];
  1692 	g_Admins.FillFlagString(flags, flagstr, sizeof(flagstr));
  1693 	fprintf(fp, "\t\"@%s\"\t\t\"%s\"\n", key, flagstr);
  1694 }
  1695 
  1696 void iterator_group_basic_override(FILE *fp, const char *key, OverrideRule rule)
  1697 {
  1698 	const char *str = (rule == Command_Allow) ? "allow" : "deny";
  1699 	fprintf(fp, "\t\t\t\"%s\"\t\t\"%s\"\n", key, str);
  1700 }
  1701 
  1702 void iterator_group_grp_override(FILE *fp, const char *key, OverrideRule rule)
  1703 {
  1704 	const char *str = (rule == Command_Allow) ? "allow" : "deny";
  1705 	fprintf(fp, "\t\t\t\"@%s\"\t\t\"%s\"\n", key, str);
  1706 }
  1707 
  1708 void AdminCache::DumpCache(FILE *fp)
  1709 {
  1710 	int *itable;
  1711 	AdminId aid;
  1712 	GroupId gid;
  1713 	char flagstr[64];
  1714 	unsigned int num;
  1715 	AdminUser *pAdmin;
  1716 	AdminGroup *pGroup;
  1717 	char name_buffer[512];
  1718 
  1719 	fprintf(fp, "\"Groups\"\n{\n");
  1720 	
  1721 	num = 0;
  1722 	gid = m_FirstGroup;
  1723 	while (gid != INVALID_GROUP_ID
  1724 			&& (pGroup = GetGroup(gid)) != NULL)
  1725 	{
  1726 		num++;
  1727 		FillFlagString(pGroup->addflags, flagstr, sizeof(flagstr));
  1728 
  1729 		fprintf(fp, "\t/* num = %d, gid = 0x%X */\n", num, gid);
  1730 		fprintf(fp, "\t\"%s\"\n\t{\n", GetString(pGroup->nameidx));
  1731 		fprintf(fp, "\t\t\"flags\"\t\t\t\"%s\"\n", flagstr);
  1732 		fprintf(fp, "\t\t\"immunity\"\t\t\"%d\"\n", pGroup->immunity_level);
  1733 		
  1734 		if (pGroup->immune_table != -1
  1735 			&& (itable = (int *)m_pMemory->GetAddress(pGroup->immune_table)) != NULL)
  1736 		{
  1737 			AdminGroup *pAltGroup;
  1738 			const char *gname, *mod;
  1739 
  1740 			for (int i = 1; i <= itable[0]; i++)
  1741 			{
  1742 				if ((pAltGroup = GetGroup(itable[i])) == NULL)
  1743 				{
  1744 					/* Assume the rest of the table is corrupt */
  1745 					break;
  1746 				}
  1747 				gname = GetString(pAltGroup->nameidx);
  1748 				if (atoi(gname) != 0)
  1749 				{
  1750 					mod = "@";
  1751 				}
  1752 				else
  1753 				{
  1754 					mod = "";
  1755 				}
  1756 				fprintf(fp, "\t\t\"immunity\"\t\t\"%s%s\"\n", mod, gname);
  1757 			}
  1758 		}
  1759 
  1760 		fprintf(fp, "\n\t\t\"Overrides\"\n\t\t{\n");
  1761 		if (pGroup->pCmdGrpTable != NULL)
  1762 		{
  1763 			for (OverrideMap::iterator iter = pGroup->pCmdTable->iter(); !iter.empty(); iter.next())
  1764 				iterator_group_grp_override(fp, iter->key.chars(), iter->value);
  1765 		}
  1766 		if (pGroup->pCmdTable != NULL)
  1767 		{
  1768 			for (OverrideMap::iterator iter = pGroup->pCmdTable->iter(); !iter.empty(); iter.next())
  1769 				iterator_group_basic_override(fp, iter->key.chars(), iter->value);
  1770 		}
  1771 		fprintf(fp, "\t\t}\n");
  1772 
  1773 		fprintf(fp, "\t}\n");
  1774 
  1775 		if ((gid = pGroup->next_grp) != INVALID_GROUP_ID)
  1776 		{
  1777 			fprintf(fp, "\n");
  1778 		}
  1779 	}
  1780 
  1781 	fprintf(fp, "}\n\n");
  1782 	fprintf(fp, "\"Admins\"\n{\n");
  1783 
  1784 	num = 0;
  1785 	aid = m_FirstUser;
  1786 	while (aid != INVALID_ADMIN_ID
  1787 			&& (pAdmin = GetUser(aid)) != NULL)
  1788 	{
  1789 		num++;
  1790 		FillFlagString(pAdmin->flags, flagstr, sizeof(flagstr));
  1791 
  1792 		fprintf(fp, "\t/* num = %d, aid = 0x%X, serialno = 0x%X*/\n", num, aid, pAdmin->serialchange);
  1793 
  1794 		if (pAdmin->nameidx != -1)
  1795 		{
  1796 			fprintf(fp, "\t\"%s\"\n\t{\n", GetString(pAdmin->nameidx));
  1797 		}
  1798 		else
  1799 		{
  1800 			fprintf(fp, "\t\"\"\n\t{\n");
  1801 		}
  1802 
  1803 		if (pAdmin->auth.identidx != -1)
  1804 		{
  1805 			fprintf(fp, "\t\t\"auth\"\t\t\t\"%s\"\n", GetMethodName(pAdmin->auth.index));
  1806 			fprintf(fp, "\t\t\"identity\"\t\t\"%s\"\n", GetString(pAdmin->auth.identidx));
  1807 		}
  1808 		if (pAdmin->password != -1)
  1809 		{
  1810 			fprintf(fp, "\t\t\"password\"\t\t\"%s\"\n", GetString(pAdmin->password));
  1811 		}
  1812 		fprintf(fp, "\t\t\"flags\"\t\t\t\"%s\"\n", flagstr);
  1813 		fprintf(fp, "\t\t\"immunity\"\t\t\"%d\"\n", pAdmin->immunity_level);
  1814 
  1815 		if (pAdmin->grp_count != 0 
  1816 			&& pAdmin->grp_table != -1 
  1817 			&& (itable = (int *)m_pMemory->GetAddress(pAdmin->grp_table)) != NULL)
  1818 		{
  1819 			unsigned int i;
  1820 
  1821 			for (i = 0; i < pAdmin->grp_count; i++)
  1822 			{
  1823 				if ((pGroup = GetGroup(itable[i])) == NULL)
  1824 				{
  1825 					/* Assume the rest of the table is corrupt */
  1826 					break;
  1827 				}
  1828 				fprintf(fp, "\t\t\"group\"\t\t\t\"%s\"\n", GetString(pGroup->nameidx));
  1829 			}
  1830 		}
  1831 
  1832 		fprintf(fp, "\t}\n");
  1833 
  1834 		if ((aid = pAdmin->next_user) != INVALID_ADMIN_ID)
  1835 		{
  1836 			fprintf(fp, "\n");
  1837 		}
  1838 	}
  1839 
  1840 	fprintf(fp, "}\n\n");
  1841 
  1842 	fprintf(fp, "\"Overrides\"\n{\n");
  1843 	for (FlagMap::iterator iter = m_CmdGrpOverrides.iter(); !iter.empty(); iter.next())
  1844 		iterator_glob_grp_override(fp, iter->key.chars(), iter->value);
  1845 	for (FlagMap::iterator iter = m_CmdOverrides.iter(); !iter.empty(); iter.next())
  1846 		iterator_glob_basic_override(fp, iter->key.chars(), iter->value);
  1847 	fprintf(fp, "}\n");
  1848 }
  1849 
  1850 AdminGroup *AdminCache::GetGroup(GroupId gid)
  1851 {
  1852 	AdminGroup *pGroup;
  1853 	
  1854 	pGroup = (AdminGroup *)m_pMemory->GetAddress(gid);
  1855 	if (!pGroup || pGroup->magic != GRP_MAGIC_SET)
  1856 	{
  1857 		return NULL;
  1858 	}
  1859 
  1860 	return pGroup;
  1861 }
  1862 
  1863 AdminUser *AdminCache::GetUser(AdminId aid)
  1864 {
  1865 	AdminUser *pAdmin;
  1866 
  1867 	pAdmin = (AdminUser *)m_pMemory->GetAddress(aid);
  1868 	if (!pAdmin || pAdmin->magic != USR_MAGIC_SET)
  1869 	{
  1870 		return NULL;
  1871 	}
  1872 
  1873 	return pAdmin;
  1874 }
  1875 
  1876 const char *AdminCache::GetMethodName(unsigned int index)
  1877 {
  1878 	List<AuthMethod *>::iterator iter;
  1879 	for (iter=m_AuthMethods.begin();
  1880 		iter!=m_AuthMethods.end();
  1881 		iter++)
  1882 	{
  1883 		if (index-- == 0)
  1884 		{
  1885 			return (*iter)->name.c_str();
  1886 		}
  1887 	}
  1888 
  1889 	return NULL;
  1890 }
  1891 
  1892 const char *AdminCache::GetString(int idx)
  1893 {
  1894 	return m_pStrings->GetString(idx);
  1895 }
  1896 
  1897 size_t AdminCache::FillFlagString(FlagBits bits, char *buffer, size_t maxlen)
  1898 {
  1899 	size_t pos;
  1900 	unsigned int i, num_flags;
  1901 	AdminFlag flags[AdminFlags_TOTAL];
  1902 
  1903 	num_flags = FlagBitsToArray(bits, flags, AdminFlags_TOTAL);
  1904 
  1905 	pos = 0;
  1906 	for (i = 0; pos < maxlen && i < num_flags; i++)
  1907 	{
  1908 		if (FindFlagChar(flags[i], &buffer[pos]))
  1909 		{
  1910 			pos++;
  1911 		}
  1912 	}
  1913 	buffer[pos] = '\0';
  1914 
  1915 	return pos;
  1916 }
  1917 
  1918 CON_COMMAND(sm_dump_admcache, "Dumps the admin cache for debugging")
  1919 {
  1920 	FILE *fp;
  1921 	char buffer[PLATFORM_MAX_PATH];
  1922 
  1923 	g_SourceMod.BuildPath(Path_SM, buffer, sizeof(buffer), "data/admin_cache_dump.txt");
  1924 
  1925 	if ((fp = fopen(buffer, "wt")) == NULL)
  1926 	{
  1927 		g_RootMenu.ConsolePrint("Could not open file for writing: %s", buffer);
  1928 		return;
  1929 	}
  1930 
  1931 	g_Admins.DumpCache(fp);
  1932 
  1933 	g_RootMenu.ConsolePrint("Admin cache dumped to: %s", buffer);
  1934 
  1935 	fclose(fp);
  1936 }