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