plugins/admin-sql-threaded.sp
author David Anderson <dvander@alliedmods.net>
Tue Aug 14 01:00:42 2007 +0000 (2007-08-14)
changeset 1324 9d1983bf06c7
parent 1322 84bb2bc248eb
child 1326 d24c8f8a2e07
permissions -rw-r--r--
added SQL_CheckConfig() so sql admin plugins can default back
     1 /**
     2  * admin-sql-threaded.sp
     3  * Fetches admins from an SQL database dynamically.  Groups and overrides 
     4  * are fetched once, but also using threads.
     5  *
     6  * This file is part of SourceMod, Copyright (C) 2004-2007 AlliedModders LLC
     7  *
     8  * This program is free software; you can redistribute it and/or
     9  * modify it under the terms of the GNU General Public License
    10  * as published by the Free Software Foundation; either version 2
    11  * of the License, or (at your option) any later version.
    12  *
    13  * This program is distributed in the hope that it will be useful,
    14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    16  * GNU General Public License for more details.
    17  * 
    18  * You should have received a copy of the GNU General Public License
    19  * along with this program; if not, write to the Free Software
    20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    21  *
    22  * Version: $Id$
    23  */
    24 
    25 /* We like semicolons */
    26 #pragma semicolon 1
    27 
    28 #include <sourcemod>
    29 
    30 public Plugin:myinfo = 
    31 {
    32 	name = "SQL Admins (Threaded)",
    33 	author = "AlliedModders LLC",
    34 	description = "Reads admins from SQL dynamically",
    35 	version = SOURCEMOD_VERSION,
    36 	url = "http://www.sourcemod.net/"
    37 };
    38 
    39 /**
    40  * Notes:
    41  *
    42  * 1) All queries in here are high priority.  This is because the admin stuff 
    43  *    is very important.  Do not take this to mean that in your script, 
    44  *    everything should be high priority.  
    45  *
    46  * 2) All callbacks are locked with "sequence numbers."  This is to make sure 
    47  *    that multiple calls to sm_reloadadmins and the like do not make us 
    48  *    store the results from two or more callbacks accidentally.  Instead, we 
    49  *    check the sequence number in each callback with the current "allowed" 
    50  *    sequence number, and if it doesn't match, the callback is cancelled.
    51  *
    52  * 3) Sequence numbers for groups and overrides are not cleared unless there 
    53  *    was a 100% success in the fetch.  This is so we can potentially implement 
    54  *    connection retries in the future.
    55  *
    56  * 4) Sequence numbers for the admin cache are ignored except for being 
    57  *    non-zero, which means players in-game should be re-checked for admin \
    58  *    powers.
    59  */
    60 
    61 new Handle:hDatabase = INVALID_HANDLE;			/** Database connection */
    62 new g_sequence = 0;								/** Global unique sequence number */
    63 new ConnectLock = 0;							/** Connect sequence number */
    64 new RebuildCachePart[3] = {0};					/** Cache part sequence numbers */
    65 new PlayerSeq[MAXPLAYERS+1];					/** Player-specific sequence numbers */
    66 new bool:PlayerAuth[MAXPLAYERS+1];				/** Whether a player has been "pre-authed" */
    67 
    68 #define _DEBUG
    69 
    70 public OnMapEnd()
    71 {
    72 	/**
    73 	 * Clean up on map end just so we can start a fresh connection when we need it later.
    74 	 */
    75 	if (hDatabase != INVALID_HANDLE)
    76 	{
    77 		CloseHandle(hDatabase);
    78 		hDatabase = INVALID_HANDLE;
    79 	}
    80 }
    81 
    82 public bool:OnClientConnect(client, String:rejectmsg[], maxlen)
    83 {
    84 	PlayerSeq[client] = 0;
    85 	PlayerAuth[client] = false;
    86 	return true;
    87 }
    88 
    89 public OnClientDisconnect(client)
    90 {
    91 	PlayerSeq[client] = 0;
    92 	PlayerAuth[client] = false;
    93 }
    94 
    95 public OnDatabaseConnect(Handle:owner, Handle:hndl, const String:error[], any:data)
    96 {
    97 #if defined _DEBUG
    98 	PrintToServer("OnDatabaseConnect(%x,%x,%d) ConnectLock=%d", owner, hndl, data, ConnectLock);
    99 #endif
   100 
   101 	/**
   102 	 * If this happens to be an old connection request, ignore it.
   103 	 */
   104 	if (data != ConnectLock || hDatabase != INVALID_HANDLE)
   105 	{
   106 		if (hndl != INVALID_HANDLE)
   107 		{
   108 			CloseHandle(hndl);
   109 		}
   110 		return;
   111 	}
   112 	
   113 	ConnectLock = 0;
   114 	hDatabase = hndl;
   115 	
   116 	/**
   117 	 * See if the connection is valid.  If not, don't un-mark the caches
   118 	 * as needing rebuilding, in case the next connection request works.
   119 	 */
   120 	if (hDatabase == INVALID_HANDLE)
   121 	{
   122 		LogError("Failed to connect to database: %s", error);
   123 		return;
   124 	}
   125 	
   126 	/**
   127 	 * See if we need to get any of the cache stuff now.
   128 	 */
   129 	new sequence;
   130 	if ((sequence = RebuildCachePart[_:AdminCache_Overrides]) != 0)
   131 	{
   132 		FetchOverrides(hDatabase, sequence);
   133 	}
   134 	if ((sequence = RebuildCachePart[_:AdminCache_Groups]) != 0)
   135 	{
   136 		FetchGroups(hDatabase, sequence);
   137 	}
   138 	if ((sequence = RebuildCachePart[_:AdminCache_Admins]) != 0)
   139 	{
   140 		FetchUsersWeCan(hDatabase);
   141 	}
   142 }
   143 
   144 RequestDatabaseConnection()
   145 {
   146 	ConnectLock = ++g_sequence;
   147 	if (SQL_CheckConfig("admins"))
   148 	{
   149 		SQL_TConnect(OnDatabaseConnect, "admins", ConnectLock);
   150 	} else {
   151 		SQL_TConnect(OnDatabaseConnect, "default", ConnectLock);
   152 	}
   153 }
   154 
   155 public OnRebuildAdminCache(AdminCachePart:part)
   156 {
   157 	/**
   158 	 * Mark this part of the cache as being rebuilt.  This is used by the 
   159 	 * callback system to determine whether the results should still be 
   160 	 * used.
   161 	 */
   162 	new sequence = ++g_sequence;
   163 	RebuildCachePart[_:part] = sequence;
   164 	
   165 	/**
   166 	 * If we don't have a database connection, we can't do any lookups just yet.
   167 	 */
   168 	if (!hDatabase)
   169 	{
   170 		/**
   171 		 * Ask for a new connection if we need it.
   172 		 */
   173 		if (!ConnectLock)
   174 		{
   175 			RequestDatabaseConnection();
   176 		}
   177 		return;
   178 	}
   179 	
   180 	if (part == AdminCache_Overrides)
   181 	{
   182 		FetchOverrides(hDatabase, sequence);
   183 	} else if (part == AdminCache_Groups) {
   184 		FetchGroups(hDatabase, sequence);
   185 	} else if (part == AdminCache_Admins) {
   186 		FetchUsersWeCan(hDatabase);
   187 	}
   188 }
   189 
   190 public Action:OnClientPreAdminCheck(client)
   191 {
   192 	PlayerAuth[client] = true;
   193 	
   194 	/**
   195 	 * Play nice with other plugins.  If there's no database, don't delay the 
   196 	 * connection process.  Unfortunately, we can't attempt anything else and 
   197 	 * we just have to hope either the database is waiting or someone will type 
   198 	 * sm_reloadadmins.
   199 	 */
   200 	if (hDatabase == INVALID_HANDLE)
   201 	{
   202 		return Plugin_Continue;
   203 	}
   204 	
   205 	/**
   206 	 * Similarly, if the cache is in the process of being rebuilt, don't delay 
   207 	 * the user's normal connection flow.  The database will soon auth the user 
   208 	 * normally.
   209 	 */
   210 	if (RebuildCachePart[_:AdminCache_Admins] != 0)
   211 	{
   212 		return Plugin_Continue;
   213 	}
   214 	
   215 	/**
   216 	 * If someone has already assigned an admin ID (bad bad bad), don't 
   217 	 * bother waiting.
   218 	 */
   219 	if (GetUserAdmin(client) != INVALID_ADMIN_ID)
   220 	{
   221 		return Plugin_Continue;
   222 	}
   223 	
   224 	FetchUser(hDatabase, client);
   225 	
   226 	return Plugin_Handled;
   227 }
   228 
   229 public OnReceiveUserGroups(Handle:owner, Handle:hndl, const String:error[], any:data)
   230 {
   231 	new Handle:pk = Handle:data;
   232 	ResetPack(pk);
   233 	
   234 	new client = ReadPackCell(pk);
   235 	new sequence = ReadPackCell(pk);
   236 	
   237 	/**
   238 	 * Make sure it's the same client.
   239 	 */
   240 	if (PlayerSeq[client] != sequence)
   241 	{
   242 		CloseHandle(pk);
   243 		return;
   244 	}
   245 	
   246 	new AdminId:adm = AdminId:ReadPackCell(pk);
   247 	
   248 	/**
   249 	 * Someone could have sneakily changed the admin id while we waited.
   250 	 */
   251 	if (GetUserAdmin(client) != adm)
   252 	{
   253 		NotifyPostAdminCheck(client);
   254 		CloseHandle(pk);
   255 		return;
   256 	}
   257 	
   258 	/**
   259 	 * See if we got results.
   260 	 */
   261 	if (hndl == INVALID_HANDLE)
   262 	{
   263 		decl String:query[255];
   264 		ReadPackString(pk, query, sizeof(query));
   265 		LogError("SQL error receiving user: %s", error);
   266 		LogError("Query dump: %s", query);
   267 		NotifyPostAdminCheck(client);
   268 		CloseHandle(pk);
   269 		return;
   270 	}
   271 	
   272 	decl String:name[80];
   273 	new GroupId:gid;
   274 	
   275 	while (SQL_FetchRow(hndl))
   276 	{
   277 		SQL_FetchString(hndl, 0, name, sizeof(name));
   278 		
   279 		if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
   280 		{
   281 			continue;
   282 		}
   283 		
   284 #if defined _DEBUG
   285 		PrintToServer("Binding user group (%d, %d, %d, %s, %d)", client, sequence, adm, name, gid);
   286 #endif
   287 		
   288 		AdminInheritGroup(adm, gid);
   289 	}
   290 	
   291 	/**
   292 	 * We're DONE! Omg.
   293 	 */
   294 	NotifyPostAdminCheck(client);
   295 	CloseHandle(pk);
   296 }
   297 
   298 public OnReceiveUser(Handle:owner, Handle:hndl, const String:error[], any:data)
   299 {
   300 	new Handle:pk = Handle:data;
   301 	ResetPack(pk);
   302 	
   303 	new client = ReadPackCell(pk);
   304 	
   305 	/**
   306 	 * Check if this is the latest result request.
   307 	 */
   308 	new sequence = ReadPackCell(pk);
   309 	if (PlayerSeq[client] != sequence)
   310 	{
   311 		/* Discard everything, since we're out of sequence. */
   312 		CloseHandle(pk);
   313 		return;
   314 	}
   315 	
   316 	/**
   317 	 * If we need to use the results, make sure they succeeded.
   318 	 */
   319 	if (hndl == INVALID_HANDLE)
   320 	{
   321 		decl String:query[255];
   322 		ReadPackString(pk, query, sizeof(query));
   323 		LogError("SQL error receiving user: %s", error);
   324 		LogError("Query dump: %s", query);
   325 		RunAdminCacheChecks(client);
   326 		NotifyPostAdminCheck(client);
   327 		CloseHandle(pk);
   328 		return;
   329 	}
   330 	
   331 	new num_accounts = SQL_GetRowCount(hndl);
   332 	if (num_accounts == 0)
   333 	{
   334 		RunAdminCacheChecks(client);
   335 		NotifyPostAdminCheck(client);
   336 		CloseHandle(pk);
   337 		return;
   338 	}
   339 	
   340 	decl String:authtype[16];
   341 	decl String:identity[80];
   342 	decl String:password[80];
   343 	decl String:flags[32];
   344 	decl String:name[80];
   345 	new AdminId:adm, id;
   346 	
   347 	/**
   348 	 * Cache user info -- [0] = db id, [1] = cache id, [2] = groups
   349 	 */
   350 	decl user_lookup[num_accounts][3];
   351 	new total_users = 0;
   352 	
   353 	while (SQL_FetchRow(hndl))
   354 	{
   355 		id = SQL_FetchInt(hndl, 0);
   356 		SQL_FetchString(hndl, 1, authtype, sizeof(authtype));
   357 		SQL_FetchString(hndl, 2, identity, sizeof(identity));
   358 		SQL_FetchString(hndl, 3, password, sizeof(password));
   359 		SQL_FetchString(hndl, 4, flags, sizeof(flags));
   360 		SQL_FetchString(hndl, 5, name, sizeof(name));
   361 		
   362 		/* For dynamic admins we clear anything already in the cache. */
   363 		if ((adm = FindAdminByIdentity(authtype, identity)) != INVALID_ADMIN_ID)
   364 		{
   365 			RemoveAdmin(adm);
   366 		}
   367 		
   368 		adm = CreateAdmin(name);
   369 		if (!BindAdminIdentity(adm, authtype, identity))
   370 		{
   371 			LogError("Could not bind prefetched SQL admin (authtype \"%s\") (identity \"%s\")", authtype, identity);
   372 			continue;
   373 		}
   374 		
   375 		user_lookup[total_users][0] = id;
   376 		user_lookup[total_users][1] = _:adm;
   377 		user_lookup[total_users][2] = SQL_FetchInt(hndl, 6);
   378 		total_users++;
   379 		
   380 #if defined _DEBUG
   381 		PrintToServer("Found SQL admin (%d,%s,%s,%s,%s,%s):%d:%d", id, authtype, identity, password, flags, name, adm, user_lookup[total_users-1][2]);
   382 #endif
   383 		
   384 		/* See if this admin wants a password */
   385 		if (password[0] != '\0')
   386 		{
   387 			SetAdminPassword(adm, password);
   388 		}
   389 		
   390 		/* Apply each flag */
   391 		new len = strlen(flags);
   392 		new AdminFlag:flag;
   393 		for (new i=0; i<len; i++)
   394 		{
   395 			if (!FindFlagByChar(flags[i], flag))
   396 			{
   397 				continue;
   398 			}
   399 			SetAdminFlag(adm, flag, true);
   400 		}
   401 	}
   402 	
   403 	/**
   404 	 * Try binding the user.
   405 	 */	
   406 	new group_count = 0;
   407 	RunAdminCacheChecks(client);
   408 	adm = GetUserAdmin(client);
   409 	id = 0;
   410 	
   411 	
   412 	for (new i=0; i<total_users; i++)
   413 	{
   414 		if (user_lookup[i][1] == _:adm)
   415 		{
   416 			id = user_lookup[i][0];
   417 			group_count = user_lookup[i][2];
   418 			break;
   419 		}
   420 	}
   421 	
   422 #if defined _DEBUG
   423 	PrintToServer("Binding client (%d, %d) resulted in: (%d, %d, %d)", client, sequence, id, adm, group_count);
   424 #endif
   425 	
   426 	/**
   427 	 * If we can't verify that we assigned a database admin, or the user has no 
   428 	 * groups, don't bother doing anything.
   429 	 */
   430 	if (!id || !group_count)
   431 	{
   432 		NotifyPostAdminCheck(client);
   433 		CloseHandle(pk);
   434 		return;
   435 	}
   436 	
   437 	/**
   438 	 * The user has groups -- we need to fetch them!
   439 	 */
   440 	decl String:query[255];
   441 	Format(query, sizeof(query), "SELECT g.name FROM sm_admins_groups ag JOIN sm_groups g ON ag.group_id = g.id WHERE ag.admin_id = %d", id);
   442 	 
   443 	ResetPack(pk);
   444 	WritePackCell(pk, client);
   445 	WritePackCell(pk, sequence);
   446 	WritePackCell(pk, _:adm);
   447 	WritePackString(pk, query);
   448 	
   449 	SQL_TQuery(owner, OnReceiveUserGroups, query, pk, DBPrio_High);
   450 }
   451 
   452 FetchUser(Handle:db, client)
   453 {
   454 	decl String:name[65];
   455 	decl String:safe_name[140];
   456 	decl String:steamid[32];
   457 	decl String:ipaddr[24];
   458 	
   459 	/**
   460 	 * Get authentication information from the client.
   461 	 */
   462 	GetClientName(client, name, sizeof(name));
   463 	GetClientIP(client, ipaddr, sizeof(ipaddr));
   464 	
   465 	steamid[0] = '\0';
   466 	if (GetClientAuthString(client, steamid, sizeof(steamid)))
   467 	{
   468 		if (StrEqual(steamid, "STEAM_ID_LAN"))
   469 		{
   470 			steamid[0] = '\0';
   471 		}
   472 	}
   473 	
   474 	SQL_QuoteString(db, name, safe_name, sizeof(safe_name));
   475 	
   476 	/**
   477 	 * Construct the query using the information the user gave us.
   478 	 */
   479 	decl String:query[512];
   480 	new len = 0;
   481 	
   482 	len += Format(query[len], sizeof(query)-len, "SELECT a.id, a.authtype, a.identity, a.password, a.flags, a.name, COUNT(ag.group_id)");
   483 	len += Format(query[len], sizeof(query)-len, " FROM sm_admins a LEFT JOIN sm_admins_groups ag ON a.id = ag.admin_id WHERE ");
   484 	len += Format(query[len], sizeof(query)-len, " (a.authtype = 'ip' AND a.identity = '%s')", ipaddr);
   485 	len += Format(query[len], sizeof(query)-len, " OR (a.authtype = 'name' AND a.identity = '%s')", safe_name);
   486 	if (steamid[0] != '\0')
   487 	{
   488 		len += Format(query[len], sizeof(query)-len, " OR (a.authtype = 'steam' AND a.identity = '%s')", steamid);
   489 	}
   490 	len += Format(query[len], sizeof(query)-len, " GROUP BY a.id");
   491 	
   492 	/**
   493 	 * Send the actual query.
   494 	 */	
   495 	PlayerSeq[client] = ++g_sequence;
   496 	
   497 	new Handle:pk;
   498 	pk = CreateDataPack();
   499 	WritePackCell(pk, client);
   500 	WritePackCell(pk, PlayerSeq[client]);
   501 	WritePackString(pk, query);
   502 	
   503 #if defined _DEBUG
   504 	PrintToServer("Sending user query: %s", query);
   505 #endif
   506 	
   507 	SQL_TQuery(db, OnReceiveUser, query, pk, DBPrio_High);
   508 }
   509 
   510 FetchUsersWeCan(Handle:db)
   511 {
   512 	new max_clients = GetMaxClients();
   513 	
   514 	for (new i=1; i<=max_clients; i++)
   515 	{
   516 		if (PlayerAuth[i] && GetUserAdmin(i) == INVALID_ADMIN_ID)
   517 		{
   518 			FetchUser(db, i);
   519 		}
   520 	}
   521 	
   522 	/**
   523 	 * This round of updates is done.  Go in peace.
   524 	 */
   525 	RebuildCachePart[_:AdminCache_Admins] = 0;
   526 }
   527 
   528 public OnReceiveGroupOverrides(Handle:owner, Handle:hndl, const String:error[], any:data)
   529 {
   530 	new Handle:pk = Handle:data;
   531 	ResetPack(pk);
   532 	
   533 	/**
   534 	 * Check if this is the latest result request.
   535 	 */
   536 	new sequence = ReadPackCell(pk);
   537 	if (RebuildCachePart[_:AdminCache_Groups] != sequence)
   538 	{
   539 		/* Discard everything, since we're out of sequence. */
   540 		CloseHandle(pk);
   541 		return;
   542 	}
   543 	
   544 	/**
   545 	 * If we need to use the results, make sure they succeeded.
   546 	 */
   547 	if (hndl == INVALID_HANDLE)
   548 	{
   549 		decl String:query[255];
   550 		ReadPackString(pk, query, sizeof(query));		
   551 		LogError("SQL error receiving group overrides: %s", error);
   552 		LogError("Query dump: %s", query);
   553 		CloseHandle(pk);	
   554 		return;
   555 	}
   556 	
   557 	/* We're done with the pack forever. */
   558 	CloseHandle(pk);
   559 	
   560 	/**
   561 	 * Fetch the overrides.
   562 	 */
   563 	decl String:name[80];
   564 	decl String:type[16];
   565 	decl String:command[64];
   566 	decl String:access[16];
   567 	new GroupId:gid;
   568 	while (SQL_FetchRow(hndl))
   569 	{
   570 		SQL_FetchString(hndl, 0, name, sizeof(name));
   571 		SQL_FetchString(hndl, 1, type, sizeof(type));
   572 		SQL_FetchString(hndl, 2, command, sizeof(command));
   573 		SQL_FetchString(hndl, 3, access, sizeof(access));
   574 		
   575 		/* Find the group.  This is actually faster than doing the ID lookup. */
   576 		if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
   577 		{
   578 			/* Oh well, just ignore it. */
   579 			continue;
   580 		}
   581 		
   582 		new OverrideType:o_type = Override_Command;
   583 		if (StrEqual(type, "group"))
   584 		{
   585 			o_type = Override_CommandGroup;
   586 		}
   587 				
   588 		new OverrideRule:o_rule = Command_Deny;
   589 		if (StrEqual(access, "allow"))
   590 		{
   591 			o_rule = Command_Allow;
   592 		}
   593 				
   594 #if defined _DEBUG
   595 		PrintToServer("AddAdmGroupCmdOverride(%d, %s, %d, %d)", gid, command, o_type, o_rule);
   596 #endif
   597 				
   598 		AddAdmGroupCmdOverride(gid, command, o_type, o_rule);
   599 	}
   600 	
   601 	/* Clear the sequence so another connect doesn't refetch */
   602 	RebuildCachePart[_:AdminCache_Groups] = 0;
   603 }
   604 
   605 public OnReceiveGroups(Handle:owner, Handle:hndl, const String:error[], any:data)
   606 {
   607 	new Handle:pk = Handle:data;
   608 	ResetPack(pk);
   609 	
   610 	/**
   611 	 * Check if this is the latest result request.
   612 	 */
   613 	new sequence = ReadPackCell(pk);
   614 	if (RebuildCachePart[_:AdminCache_Groups] != sequence)
   615 	{
   616 		/* Discard everything, since we're out of sequence. */
   617 		CloseHandle(pk);
   618 		return;
   619 	}
   620 	
   621 	/**
   622 	 * If we need to use the results, make sure they succeeded.
   623 	 */
   624 	if (hndl == INVALID_HANDLE)
   625 	{
   626 		decl String:query[255];
   627 		ReadPackString(pk, query, sizeof(query));
   628 		LogError("SQL error receiving groups: %s", error);
   629 		LogError("Query dump: %s", query);
   630 		CloseHandle(pk);
   631 		return;
   632 	}
   633 	
   634 	/* We cache basic group info so we can do reverse lookups */
   635 	new Handle:groups = CreateArray(3);
   636 	
   637 	/**
   638 	 * Now start fetching groups.
   639 	 */
   640 	decl String:immunity[16];
   641 	decl String:flags[32];
   642 	decl String:name[128];
   643 	decl String:grp_immunity[256];
   644 	while (SQL_FetchRow(hndl))
   645 	{
   646 		new id = SQL_FetchInt(hndl, 0);
   647 		SQL_FetchString(hndl, 1, immunity, sizeof(immunity));
   648 		SQL_FetchString(hndl, 2, flags, sizeof(flags));
   649 		SQL_FetchString(hndl, 3, name, sizeof(name));
   650 		SQL_FetchString(hndl, 4, grp_immunity, sizeof(grp_immunity));
   651 		
   652 #if defined _DEBUG
   653 		PrintToServer("Adding group (%d, %s, %s, %s, %s)", id, immunity, flags, name, grp_immunity);
   654 #endif
   655 		
   656 		/* Find or create the group */
   657 		new GroupId:gid;
   658 		if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
   659 		{
   660 			gid = CreateAdmGroup(name);
   661 		}
   662 		
   663 		/* Add flags from the database to the group */
   664 		new num_flag_chars = strlen(flags);
   665 		for (new i=0; i<num_flag_chars; i++)
   666 		{
   667 			decl AdminFlag:flag;
   668 			if (!FindFlagByChar(flags[i], flag))
   669 			{
   670 				continue;
   671 			}
   672 			SetAdmGroupAddFlag(gid, flag, true);
   673 		}
   674 		
   675 		/* Set the immunity level this group has */
   676 		if (StrEqual(immunity, "all"))
   677 		{
   678 			SetAdmGroupImmunity(gid, Immunity_Default, true);
   679 			SetAdmGroupImmunity(gid, Immunity_Global, true);
   680 		} else if (StrEqual(immunity, "default")) {
   681 			SetAdmGroupImmunity(gid, Immunity_Default, true);
   682 		} else if (StrEqual(immunity, "global")) {
   683 			SetAdmGroupImmunity(gid, Immunity_Global, true);
   684 		}
   685 		
   686 		new Handle:immunity_list = UTIL_ExplodeNumberString(grp_immunity);
   687 		
   688 		/* Now, save all this for later */
   689 		decl savedata[3];
   690 		savedata[0] = id;
   691 		savedata[1] = _:gid;
   692 		savedata[2] = _:immunity_list;
   693 		
   694 		PushArrayArray(groups, savedata);
   695 	}
   696 	
   697 	/**
   698 	 * Resolve immunity now in a second pass.
   699 	 */
   700 	new num_groups = GetArraySize(groups);
   701 	for (new i=0; i<num_groups; i++)
   702 	{
   703 		decl savedata[3];
   704 		GetArrayArray(groups, i, savedata);
   705 		
   706 		new id = savedata[0];
   707 		new GroupId:gid = GroupId:savedata[1];
   708 		new Handle:immunity_list = Handle:savedata[2];
   709 	
   710 		if (immunity_list != INVALID_HANDLE)
   711 		{
   712 			new immunity_count = GetArraySize(immunity_list);
   713 			for (new j=0; j<immunity_count; j++)
   714 			{
   715 				new other_id = GetArrayCell(immunity_list, j);
   716 				
   717 				if (other_id == id)
   718 				{
   719 					continue;
   720 				}
   721 				
   722 				/* See if we can find this other ID */
   723 				new GroupId:other_gid;
   724 				if ((other_gid = UTIL_FindGroupInCache(groups, other_id)) != INVALID_GROUP_ID)
   725 				{
   726 #if defined _DEBUG
   727 					PrintToServer("SetAdmGroupImmuneFrom(%d, %d)", gid, other_gid);
   728 #endif
   729 					SetAdmGroupImmuneFrom(gid, other_gid);
   730 				}
   731 			}
   732 			/**
   733 			 * We close the Handle but don't zero it in the parent array... not worth 
   734 			 * the effort.
   735 			 */
   736 			CloseHandle(immunity_list);
   737 		}
   738 	}
   739 	
   740 	CloseHandle(groups);
   741 	
   742 	/**
   743 	 * Now we're done with both passes.  It's time to get the group override list.
   744 	 */
   745 	decl String:query[255];
   746 	Format(query, 
   747 		sizeof(query), 
   748 		"SELECT g.name, og.type, og.name, og.access FROM sm_group_overrides og JOIN sm_groups g ON og.group_id = g.id ORDER BY g.id DESC");
   749 
   750 	ResetPack(pk);
   751 	WritePackCell(pk, sequence);
   752 	WritePackString(pk, query);
   753 	
   754 	SQL_TQuery(owner, OnReceiveGroupOverrides, query, pk, DBPrio_High);
   755 }
   756 
   757 FetchGroups(Handle:db, sequence)
   758 {
   759 	decl String:query[255];
   760 	new Handle:pk;
   761 	
   762 	Format(query, sizeof(query), "SELECT id, immunity, flags, name, groups_immune FROM sm_groups");
   763 
   764 	pk = CreateDataPack();
   765 	WritePackCell(pk, sequence);
   766 	WritePackString(pk, query);
   767 	
   768 	SQL_TQuery(db, OnReceiveGroups, query, pk, DBPrio_High);
   769 }
   770 
   771 public OnReceiveOverrides(Handle:owner, Handle:hndl, const String:error[], any:data)
   772 {
   773 	new Handle:pk = Handle:data;
   774 	ResetPack(pk);
   775 	
   776 	/**
   777 	 * Check if this is the latest result request.
   778 	 */
   779 	new sequence = ReadPackCell(pk);
   780 	if (RebuildCachePart[_:AdminCache_Overrides] != sequence)
   781 	{
   782 		/* Discard everything, since we're out of sequence. */
   783 		CloseHandle(pk);
   784 		return;
   785 	}
   786 	
   787 	/**
   788 	 * If we need to use the results, make sure they succeeded.
   789 	 */
   790 	if (hndl == INVALID_HANDLE)
   791 	{
   792 		decl String:query[255];
   793 		ReadPackString(pk, query, sizeof(query));
   794 		LogError("SQL error receiving overrides: %s", error);
   795 		LogError("Query dump: %s", query);
   796 		CloseHandle(pk);
   797 		return;
   798 	}
   799 	
   800 	/**
   801 	 * We're done with you, now.
   802 	 */
   803 	CloseHandle(pk);
   804 	
   805 	decl String:type[64];
   806 	decl String:name[64];
   807 	decl String:flags[32];
   808 	new flag_bits;
   809 	while (SQL_FetchRow(hndl))
   810 	{
   811 		SQL_FetchString(hndl, 0, type, sizeof(type));
   812 		SQL_FetchString(hndl, 1, name, sizeof(name));
   813 		SQL_FetchString(hndl, 2, flags, sizeof(flags));
   814 		
   815 #if defined _DEBUG
   816 		PrintToServer("Adding override (%s, %s, %s)", type, name, flags);
   817 #endif
   818 		
   819 		flag_bits = ReadFlagString(flags);
   820 		if (StrEqual(type, "command"))
   821 		{
   822 			AddCommandOverride(name, Override_Command, flag_bits);
   823 		} else if (StrEqual(type, "group")) {
   824 			AddCommandOverride(name, Override_CommandGroup, flag_bits);
   825 		}
   826 	}
   827 	
   828 	/* Clear the sequence so another connect doesn't refetch */
   829 	RebuildCachePart[_:AdminCache_Overrides] = 0;
   830 }
   831 
   832 FetchOverrides(Handle:db, sequence)
   833 {
   834 	decl String:query[255];
   835 	new Handle:pk;
   836 	
   837 	Format(query, sizeof(query), "SELECT type, name, flags FROM sm_overrides");
   838 
   839 	pk = CreateDataPack();
   840 	WritePackCell(pk, sequence);
   841 	WritePackString(pk, query);
   842 	
   843 	SQL_TQuery(db, OnReceiveOverrides, query, pk, DBPrio_High);
   844 }
   845 
   846 /**
   847  * Finds an entry in a temporary group list (used by immunity resolver).
   848  * 
   849  * @param group_list		Array(3,n) (0=db id, 1=gid, 2=immunity list)
   850  * @param id				group database id
   851  * @return					GroupId of the database id or INVALID_GROUP_ID.
   852  */
   853 stock GroupId:UTIL_FindGroupInCache(Handle:group_list, id)
   854 {
   855 	new size = GetArraySize(group_list);
   856 	
   857 	for (new i=0; i<size; i++)
   858 	{
   859 		decl data[3];
   860 		GetArrayArray(group_list, i, data);
   861 		
   862 		if (data[0] == id)
   863 		{
   864 			return GroupId:data[1];
   865 		}
   866 	}
   867 	
   868 	return INVALID_GROUP_ID;
   869 }
   870 
   871 /**
   872  * Breaks a comma-delimited string into a list of numbers, returning a new 
   873  * dynamic array.
   874  *
   875  * @param text				The string to split.
   876  * @return					A new array Handle which must be closed, or 
   877  *							INVALID_HANDLE on no strings found.
   878  */
   879 stock Handle:UTIL_ExplodeNumberString(const String:text[])
   880 {
   881 	new Handle:array = INVALID_HANDLE;
   882 	decl String:buffer[32];
   883 	new reloc_idx, idx;
   884 	
   885 	while ((idx = SplitString(text[reloc_idx], ",", buffer, sizeof(buffer))) != -1)
   886 	{
   887 		reloc_idx += idx;
   888 		if (text[reloc_idx] == '\0')
   889 		{
   890 			break;
   891 		}
   892 		if (array == INVALID_HANDLE)
   893 		{
   894 			array = CreateArray();
   895 		}
   896 		PushArrayCell(array, StringToInt(buffer));
   897 	}
   898 	
   899 	if (text[reloc_idx] != '\0')
   900 	{
   901 		if (array == INVALID_HANDLE)
   902 		{
   903 			array = CreateArray();
   904 		}
   905 		PushArrayCell(array, StringToInt(text[reloc_idx]));
   906 	}
   907 	
   908 	return array;
   909 }
   910