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