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