plugins/admin-sql-prefetch.sp
author David Anderson <dvander@alliedmods.net>
Tue Aug 14 01:00:42 2007 +0000 (2007-08-14)
changeset 1324 9d1983bf06c7
parent 1319 339dc1f92c44
child 1326 d24c8f8a2e07
permissions -rw-r--r--
added SQL_CheckConfig() so sql admin plugins can default back
     1 /**
     2  * admin-sql-prefetch.sp
     3  * Prefetches admins from an SQL database without threading.
     4  * This file is part of SourceMod, Copyright (C) 2004-2007 AlliedModders LLC
     5  *
     6  * This program is free software; you can redistribute it and/or
     7  * modify it under the terms of the GNU General Public License
     8  * as published by the Free Software Foundation; either version 2
     9  * of the License, or (at your option) any later version.
    10  *
    11  * This program is distributed in the hope that it will be useful,
    12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  * GNU General Public License for more details.
    15  * 
    16  * You should have received a copy of the GNU General Public License
    17  * along with this program; if not, write to the Free Software
    18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    19  *
    20  * Version: $Id$
    21  */
    22 
    23 /* We like semicolons */
    24 #pragma semicolon 1
    25 
    26 #include <sourcemod>
    27 
    28 public Plugin:myinfo = 
    29 {
    30 	name = "SQL Admins (Prefetch)",
    31 	author = "AlliedModders LLC",
    32 	description = "Reads all admins from SQL",
    33 	version = SOURCEMOD_VERSION,
    34 	url = "http://www.sourcemod.net/"
    35 };
    36 
    37 public OnRebuildAdminCache(AdminCachePart:part)
    38 {
    39 	/* First try to get a database connection */
    40 	decl String:error[255];
    41 	new Handle:db;
    42 	
    43 	if (SQL_CheckConfig("admins"))
    44 	{
    45 		db = SQL_Connect("admins", true, error, sizeof(error));
    46 	} else {
    47 		db = SQL_Connect("default", true, error, sizeof(error));
    48 	}
    49 	
    50 	if (db == INVALID_HANDLE)
    51 	{
    52 		LogError("Could not connect to database \"default\": %s", error);
    53 		return;
    54 	}
    55 	
    56 	if (part == AdminCache_Overrides)
    57 	{
    58 		FetchOverrides(db);
    59 	} else if (part == AdminCache_Groups) {
    60 		FetchGroups(db);
    61 	} else if (part == AdminCache_Admins) {
    62 		FetchUsers(db);
    63 	}
    64 	
    65 	CloseHandle(db);
    66 }
    67 
    68 FetchUserGroups(Handle:hQuery, AdminId:adm, id)
    69 {
    70 	SQL_BindParamInt(hQuery, 0, id);
    71 	if (!SQL_Execute(hQuery))
    72 	{
    73 		decl String:error[255];
    74 		SQL_GetError(hQuery, error, sizeof(error));
    75 		LogError("FetchUserGroups() statement execute failed: %s", error);
    76 		return;
    77 	}
    78 	
    79 	decl String:name[80];
    80 	new GroupId:gid;
    81 	while (SQL_FetchRow(hQuery))
    82 	{
    83 		SQL_FetchString(hQuery, 0, name, sizeof(name));
    84 		
    85 		if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
    86 		{
    87 			/* Group wasn't found, don't bother with it.  */
    88 			continue;
    89 		}
    90 		
    91 		#if defined _DEBUG
    92 		PrintToServer("Found admin group (%d, %d, %d)", id, gid, adm);
    93 		#endif
    94 		
    95 		AdminInheritGroup(adm, gid);
    96 	}
    97 }
    98 
    99 FetchUsers(Handle:db)
   100 {
   101 	decl String:query[255], String:error[255];
   102 	new Handle:hQuery, Handle:hGroupQuery;
   103 	
   104 	Format(query, sizeof(query), "SELECT id, authtype, identity, passwd, flags, name FROM sm_admins");
   105 	if ((hQuery = SQL_Query(db, query)) == INVALID_HANDLE)
   106 	{
   107 		SQL_GetError(db, error, sizeof(error));
   108 		LogError("FetchUsers() query failed: %s", query);
   109 		LogError("Query error: %s", error);
   110 		return;
   111 	}
   112 	
   113 	/* If this fails it's non-fatal */
   114 	Format(query,
   115 		sizeof(query), 
   116 		"SELECT g.name FROM sm_admins_groups ag JOIN sm_groups g ON ag.group_id = g.id WHERE ag.admin_id = ? ORDER BY inherit_order ASC");
   117 	if ((hGroupQuery = SQL_PrepareQuery(db, query, error, sizeof(error))) == INVALID_HANDLE)
   118 	{
   119 		LogError("FetchUsers() group query preparation failed: %s", query);
   120 		LogError("Query error: %s", error);
   121 	}
   122 	
   123 	decl String:authtype[16];
   124 	decl String:identity[80];
   125 	decl String:password[80];
   126 	decl String:flags[32];
   127 	decl String:name[80];
   128 	new AdminId:adm, id;
   129 	
   130 	while (SQL_FetchRow(hQuery))
   131 	{
   132 		id = SQL_FetchInt(hQuery, 0);
   133 		SQL_FetchString(hQuery, 1, authtype, sizeof(authtype));
   134 		SQL_FetchString(hQuery, 2, identity, sizeof(identity));
   135 		SQL_FetchString(hQuery, 3, password, sizeof(password));
   136 		SQL_FetchString(hQuery, 4, flags, sizeof(flags));
   137 		SQL_FetchString(hQuery, 5, name, sizeof(name));
   138 		
   139 		/* Use a pre-existing admin if we can */
   140 		if ((adm = FindAdminByIdentity(authtype, identity)) == INVALID_ADMIN_ID)
   141 		{
   142 			adm = CreateAdmin(name);
   143 			if (!BindAdminIdentity(adm, authtype, identity))
   144 			{
   145 				LogError("Could not bind prefetched SQL admin (authtype \"%s\") (identity \"%s\")", authtype, identity);
   146 				continue;
   147 			}
   148 		}
   149 		
   150 		#if defined _DEBUG
   151 		PrintToServer("Found SQL admin (%d,%s,%s,%s,%s,%s):%d", id, authtype, identity, password, flags, name, adm);
   152 		#endif
   153 		
   154 		/* See if this admin wants a password */
   155 		if (password[0] != '\0')
   156 		{
   157 			SetAdminPassword(adm, password);
   158 		}
   159 		
   160 		/* Apply each flag */
   161 		new len = strlen(flags);
   162 		new AdminFlag:flag;
   163 		for (new i=0; i<len; i++)
   164 		{
   165 			if (!FindFlagByChar(flags[i], flag))
   166 			{
   167 				continue;
   168 			}
   169 			SetAdminFlag(adm, flag, true);
   170 		}
   171 		
   172 		/* Look up groups */
   173 		if (hGroupQuery != INVALID_HANDLE)
   174 		{
   175 			FetchUserGroups(hGroupQuery, adm, id);
   176 		}
   177 	}
   178 	
   179 	CloseHandle(hGroupQuery);
   180 	CloseHandle(hQuery);
   181 }
   182 
   183 FetchGroups(Handle:db)
   184 {
   185 	decl String:query[255];
   186 	new Handle:hQuery;
   187 	
   188 	Format(query, sizeof(query), "SELECT id, immunity, flags, name, groups_immune FROM sm_groups");
   189 
   190 	if ((hQuery = SQL_Query(db, query)) == INVALID_HANDLE)
   191 	{
   192 		decl String:error[255];
   193 		SQL_GetError(db, error, sizeof(error));
   194 		LogError("FetchGroups() query failed: %s", query);
   195 		LogError("Query error: %s", error);
   196 		return;
   197 	}
   198 	
   199 	/* We cache basic group info so we can do reverse lookups */
   200 	new Handle:groups = CreateArray(3);
   201 	
   202 	/* Now start fetching groups */
   203 	decl String:immunity[16];
   204 	decl String:flags[32];
   205 	decl String:name[128];
   206 	decl String:grp_immunity[256];
   207 	while (SQL_FetchRow(hQuery))
   208 	{
   209 		new id = SQL_FetchInt(hQuery, 0);
   210 		SQL_FetchString(hQuery, 1, immunity, sizeof(immunity));
   211 		SQL_FetchString(hQuery, 2, flags, sizeof(flags));
   212 		SQL_FetchString(hQuery, 3, name, sizeof(name));
   213 		SQL_FetchString(hQuery, 4, grp_immunity, sizeof(grp_immunity));
   214 		
   215 #if defined _DEBUG
   216 		PrintToServer("Adding group (%d, %s, %s, %s, %s)", id, immunity, flags, name, grp_immunity);
   217 #endif
   218 		
   219 		/* Find or create the group */
   220 		new GroupId:gid;
   221 		if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
   222 		{
   223 			gid = CreateAdmGroup(name);
   224 		}
   225 		
   226 		/* Add flags from the database to the group */
   227 		new num_flag_chars = strlen(flags);
   228 		for (new i=0; i<num_flag_chars; i++)
   229 		{
   230 			decl AdminFlag:flag;
   231 			if (!FindFlagByChar(flags[i], flag))
   232 			{
   233 				continue;
   234 			}
   235 			SetAdmGroupAddFlag(gid, flag, true);
   236 		}
   237 		
   238 		/* Set the immunity level this group has */
   239 		if (StrEqual(immunity, "all"))
   240 		{
   241 			SetAdmGroupImmunity(gid, Immunity_Default, true);
   242 			SetAdmGroupImmunity(gid, Immunity_Global, true);
   243 		} else if (StrEqual(immunity, "default")) {
   244 			SetAdmGroupImmunity(gid, Immunity_Default, true);
   245 		} else if (StrEqual(immunity, "global")) {
   246 			SetAdmGroupImmunity(gid, Immunity_Global, true);
   247 		}
   248 		
   249 		new Handle:immunity_list = UTIL_ExplodeNumberString(grp_immunity);
   250 		
   251 		/* Now, save all this for later */
   252 		decl data[3];
   253 		data[0] = id;
   254 		data[1] = _:gid;
   255 		data[2] = _:immunity_list;
   256 		
   257 		PushArrayArray(groups, data);
   258 	}
   259 	
   260 	CloseHandle(hQuery);
   261 	
   262 	/* Second pass - resolve immunity and group overrides */
   263 	new num_groups = GetArraySize(groups);
   264 	for (new i=0; i<num_groups; i++)
   265 	{
   266 		decl data[3];
   267 		GetArrayArray(groups, i, data);
   268 		
   269 		new id = data[0];
   270 		new GroupId:gid = GroupId:data[1];
   271 		new Handle:immunity_list = Handle:data[2];
   272 		
   273 		/* Query to get per-group override list */
   274 		Format(query, 
   275 			sizeof(query),
   276 			"SELECT type, name, access FROM sm_group_overrides WHERE group_id = %d",
   277 			id);
   278 		
   279 		/* Fetch the override query results */
   280 		if ((hQuery = SQL_Query(db, query)) == INVALID_HANDLE)
   281 		{
   282 			decl String:error[255];
   283 			SQL_GetError(db, error, sizeof(error));
   284 			LogError("FetchOverrides() query failed: %s", query);
   285 			LogError("Query error: %s", error);
   286 		} else {
   287 			decl String:type[16];
   288 			decl String:cmd[64];
   289 			decl String:access[16];
   290 			while (SQL_FetchRow(hQuery))
   291 			{
   292 				SQL_FetchString(hQuery, 0, type, sizeof(type));
   293 				SQL_FetchString(hQuery, 1, cmd, sizeof(cmd));
   294 				SQL_FetchString(hQuery, 2, access, sizeof(access));
   295 				
   296 				new OverrideType:o_type = Override_Command;
   297 				if (StrEqual(type, "group"))
   298 				{
   299 					o_type = Override_CommandGroup;
   300 				}
   301 				
   302 				new OverrideRule:o_rule = Command_Deny;
   303 				if (StrEqual(access, "allow"))
   304 				{
   305 					o_rule = Command_Allow;
   306 				}
   307 				
   308 				#if defined _DEBUG
   309 				PrintToServer("AddAdmGroupCmdOverride(%d, %s, %d, %d)", gid, cmd, o_type, o_rule);
   310 				#endif
   311 				
   312 				AddAdmGroupCmdOverride(gid, cmd, o_type, o_rule);
   313 			}
   314 			CloseHandle(hQuery);
   315 		}
   316 		
   317 		/* Lastly, resolve the immunity list if any */
   318 		new immunity_count;
   319 		if (immunity_list != INVALID_HANDLE 
   320 			&& ((immunity_count = GetArraySize(immunity_list)) > 0))
   321 		{
   322 			for (new j=0; j<immunity_count; j++)
   323 			{
   324 				new other_id = GetArrayCell(immunity_list, j);
   325 				
   326 				if (other_id == id)
   327 				{
   328 					continue;
   329 				}
   330 				
   331 				/* See if we can find this other ID */
   332 				new GroupId:other_gid;
   333 				if ((other_gid = UTIL_FindGroupInCache(groups, other_id)) != INVALID_GROUP_ID)
   334 				{
   335 					#if defined _DEBUG
   336 					PrintToServer("SetAdmGroupImmuneFrom(%d, %d)", gid, other_gid);
   337 					#endif
   338 					SetAdmGroupImmuneFrom(gid, other_gid);
   339 				}
   340 			}
   341 		}
   342 		
   343 		if (immunity_list != INVALID_HANDLE)
   344 		{
   345 			CloseHandle(immunity_list);
   346 		}
   347 	}
   348 	
   349 	CloseHandle(groups);
   350 }
   351 
   352 FetchOverrides(Handle:db)
   353 {
   354 	decl String:query[255];
   355 	new Handle:hQuery;
   356 	
   357 	Format(query, sizeof(query), "SELECT type, name, flags FROM sm_overrides");
   358 
   359 	if ((hQuery = SQL_Query(db, query)) == INVALID_HANDLE)
   360 	{
   361 		decl String:error[255];
   362 		SQL_GetError(db, error, sizeof(error));
   363 		LogError("FetchOverrides() query failed: %s", query);
   364 		LogError("Query error: %s", error);
   365 		return;
   366 	}
   367 	
   368 	decl String:type[64];
   369 	decl String:name[64];
   370 	decl String:flags[32];
   371 	new flag_bits;
   372 	while (SQL_FetchRow(hQuery))
   373 	{
   374 		SQL_FetchString(hQuery, 0, type, sizeof(type));
   375 		SQL_FetchString(hQuery, 1, name, sizeof(name));
   376 		SQL_FetchString(hQuery, 2, flags, sizeof(flags));
   377 		
   378 #if defined _DEBUG
   379 		PrintToServer("Adding override (%s, %s, %s)", type, name, flags);
   380 #endif
   381 		
   382 		flag_bits = ReadFlagString(flags);
   383 		if (StrEqual(type, "command"))
   384 		{
   385 			AddCommandOverride(name, Override_Command, flag_bits);
   386 		} else if (StrEqual(type, "group")) {
   387 			AddCommandOverride(name, Override_CommandGroup, flag_bits);
   388 		}
   389 	}
   390 	
   391 	CloseHandle(hQuery);
   392 }
   393 
   394 stock GroupId:UTIL_FindGroupInCache(Handle:group_list, id)
   395 {
   396 	new size = GetArraySize(group_list);
   397 	
   398 	for (new i=0; i<size; i++)
   399 	{
   400 		decl data[3];
   401 		GetArrayArray(group_list, i, data);
   402 		
   403 		if (data[0] == id)
   404 		{
   405 			return GroupId:data[1];
   406 		}
   407 	}
   408 	
   409 	return INVALID_GROUP_ID;
   410 }
   411 
   412 /**
   413  * Breaks a comma-delimited string into a list of numbers, returning a new 
   414  * dynamic array.
   415  *
   416  * @param text				The string to split.
   417  * @return					A new array Handle which must be closed, or 
   418  *							INVALID_HANDLE on no strings found.
   419  */
   420 stock Handle:UTIL_ExplodeNumberString(const String:text[])
   421 {
   422 	new Handle:array = INVALID_HANDLE;
   423 	decl String:buffer[32];
   424 	new reloc_idx, idx;
   425 	
   426 	while ((idx = SplitString(text[reloc_idx], ",", buffer, sizeof(buffer))) != -1)
   427 	{
   428 		reloc_idx += idx;
   429 		if (text[reloc_idx] == '\0')
   430 		{
   431 			break;
   432 		}
   433 		if (array == INVALID_HANDLE)
   434 		{
   435 			array = CreateArray();
   436 		}
   437 		PushArrayCell(array, StringToInt(buffer));
   438 	}
   439 	
   440 	if (text[reloc_idx] != '\0')
   441 	{
   442 		if (array == INVALID_HANDLE)
   443 		{
   444 			array = CreateArray();
   445 		}
   446 		PushArrayCell(array, StringToInt(text[reloc_idx]));
   447 	}
   448 	
   449 	return array;
   450 }
   451