2 * admin-sql-threaded.sp
3 * Fetches admins from an SQL database dynamically. Groups and overrides
4 * are fetched once, but also using threads.
6 * This file is part of SourceMod, Copyright (C) 2004-2007 AlliedModders LLC
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.
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.
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.
25 /* We like semicolons */
30 public Plugin:myinfo =
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/"
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.
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.
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.
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 \
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" */
73 * Clean up on map end just so we can start a fresh connection when we need it later.
75 if (hDatabase != INVALID_HANDLE)
77 CloseHandle(hDatabase);
78 hDatabase = INVALID_HANDLE;
82 public bool:OnClientConnect(client, String:rejectmsg[], maxlen)
84 PlayerSeq[client] = 0;
85 PlayerAuth[client] = false;
89 public OnClientDisconnect(client)
91 PlayerSeq[client] = 0;
92 PlayerAuth[client] = false;
95 public OnDatabaseConnect(Handle:owner, Handle:hndl, const String:error[], any:data)
98 PrintToServer("OnDatabaseConnect(%x,%x,%d) ConnectLock=%d", owner, hndl, data, ConnectLock);
102 * If this happens to be an old connection request, ignore it.
104 if (data != ConnectLock || hDatabase != INVALID_HANDLE)
106 if (hndl != INVALID_HANDLE)
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.
120 if (hDatabase == INVALID_HANDLE)
122 LogError("Failed to connect to database: %s", error);
127 * See if we need to get any of the cache stuff now.
130 if ((sequence = RebuildCachePart[_:AdminCache_Overrides]) != 0)
132 FetchOverrides(hDatabase, sequence);
134 if ((sequence = RebuildCachePart[_:AdminCache_Groups]) != 0)
136 FetchGroups(hDatabase, sequence);
138 if ((sequence = RebuildCachePart[_:AdminCache_Admins]) != 0)
140 FetchUsersWeCan(hDatabase);
144 RequestDatabaseConnection()
146 ConnectLock = ++g_sequence;
147 if (SQL_CheckConfig("admins"))
149 SQL_TConnect(OnDatabaseConnect, "admins", ConnectLock);
151 SQL_TConnect(OnDatabaseConnect, "default", ConnectLock);
155 public OnRebuildAdminCache(AdminCachePart:part)
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
162 new sequence = ++g_sequence;
163 RebuildCachePart[_:part] = sequence;
166 * If we don't have a database connection, we can't do any lookups just yet.
171 * Ask for a new connection if we need it.
175 RequestDatabaseConnection();
180 if (part == AdminCache_Overrides)
182 FetchOverrides(hDatabase, sequence);
183 } else if (part == AdminCache_Groups) {
184 FetchGroups(hDatabase, sequence);
185 } else if (part == AdminCache_Admins) {
186 FetchUsersWeCan(hDatabase);
190 public Action:OnClientPreAdminCheck(client)
192 PlayerAuth[client] = true;
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
200 if (hDatabase == INVALID_HANDLE)
202 return Plugin_Continue;
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
210 if (RebuildCachePart[_:AdminCache_Admins] != 0)
212 return Plugin_Continue;
216 * If someone has already assigned an admin ID (bad bad bad), don't
219 if (GetUserAdmin(client) != INVALID_ADMIN_ID)
221 return Plugin_Continue;
224 FetchUser(hDatabase, client);
226 return Plugin_Handled;
229 public OnReceiveUserGroups(Handle:owner, Handle:hndl, const String:error[], any:data)
231 new Handle:pk = Handle:data;
234 new client = ReadPackCell(pk);
235 new sequence = ReadPackCell(pk);
238 * Make sure it's the same client.
240 if (PlayerSeq[client] != sequence)
246 new AdminId:adm = AdminId:ReadPackCell(pk);
249 * Someone could have sneakily changed the admin id while we waited.
251 if (GetUserAdmin(client) != adm)
253 NotifyPostAdminCheck(client);
259 * See if we got results.
261 if (hndl == INVALID_HANDLE)
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);
272 decl String:name[80];
275 while (SQL_FetchRow(hndl))
277 SQL_FetchString(hndl, 0, name, sizeof(name));
279 if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
285 PrintToServer("Binding user group (%d, %d, %d, %s, %d)", client, sequence, adm, name, gid);
288 AdminInheritGroup(adm, gid);
294 NotifyPostAdminCheck(client);
298 public OnReceiveUser(Handle:owner, Handle:hndl, const String:error[], any:data)
300 new Handle:pk = Handle:data;
303 new client = ReadPackCell(pk);
306 * Check if this is the latest result request.
308 new sequence = ReadPackCell(pk);
309 if (PlayerSeq[client] != sequence)
311 /* Discard everything, since we're out of sequence. */
317 * If we need to use the results, make sure they succeeded.
319 if (hndl == INVALID_HANDLE)
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);
331 new num_accounts = SQL_GetRowCount(hndl);
332 if (num_accounts == 0)
334 RunAdminCacheChecks(client);
335 NotifyPostAdminCheck(client);
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];
348 * Cache user info -- [0] = db id, [1] = cache id, [2] = groups
350 decl user_lookup[num_accounts][3];
353 while (SQL_FetchRow(hndl))
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));
362 /* For dynamic admins we clear anything already in the cache. */
363 if ((adm = FindAdminByIdentity(authtype, identity)) != INVALID_ADMIN_ID)
368 adm = CreateAdmin(name);
369 if (!BindAdminIdentity(adm, authtype, identity))
371 LogError("Could not bind prefetched SQL admin (authtype \"%s\") (identity \"%s\")", authtype, identity);
375 user_lookup[total_users][0] = id;
376 user_lookup[total_users][1] = _:adm;
377 user_lookup[total_users][2] = SQL_FetchInt(hndl, 6);
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]);
384 /* See if this admin wants a password */
385 if (password[0] != '\0')
387 SetAdminPassword(adm, password);
390 /* Apply each flag */
391 new len = strlen(flags);
393 for (new i=0; i<len; i++)
395 if (!FindFlagByChar(flags[i], flag))
399 SetAdminFlag(adm, flag, true);
404 * Try binding the user.
407 RunAdminCacheChecks(client);
408 adm = GetUserAdmin(client);
412 for (new i=0; i<total_users; i++)
414 if (user_lookup[i][1] == _:adm)
416 id = user_lookup[i][0];
417 group_count = user_lookup[i][2];
423 PrintToServer("Binding client (%d, %d) resulted in: (%d, %d, %d)", client, sequence, id, adm, group_count);
427 * If we can't verify that we assigned a database admin, or the user has no
428 * groups, don't bother doing anything.
430 if (!id || !group_count)
432 NotifyPostAdminCheck(client);
438 * The user has groups -- we need to fetch them!
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);
444 WritePackCell(pk, client);
445 WritePackCell(pk, sequence);
446 WritePackCell(pk, _:adm);
447 WritePackString(pk, query);
449 SQL_TQuery(owner, OnReceiveUserGroups, query, pk, DBPrio_High);
452 FetchUser(Handle:db, client)
454 decl String:name[65];
455 decl String:safe_name[140];
456 decl String:steamid[32];
457 decl String:ipaddr[24];
460 * Get authentication information from the client.
462 GetClientName(client, name, sizeof(name));
463 GetClientIP(client, ipaddr, sizeof(ipaddr));
466 if (GetClientAuthString(client, steamid, sizeof(steamid)))
468 if (StrEqual(steamid, "STEAM_ID_LAN"))
474 SQL_QuoteString(db, name, safe_name, sizeof(safe_name));
477 * Construct the query using the information the user gave us.
479 decl String:query[512];
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')
488 len += Format(query[len], sizeof(query)-len, " OR (a.authtype = 'steam' AND a.identity = '%s')", steamid);
490 len += Format(query[len], sizeof(query)-len, " GROUP BY a.id");
493 * Send the actual query.
495 PlayerSeq[client] = ++g_sequence;
498 pk = CreateDataPack();
499 WritePackCell(pk, client);
500 WritePackCell(pk, PlayerSeq[client]);
501 WritePackString(pk, query);
504 PrintToServer("Sending user query: %s", query);
507 SQL_TQuery(db, OnReceiveUser, query, pk, DBPrio_High);
510 FetchUsersWeCan(Handle:db)
512 new max_clients = GetMaxClients();
514 for (new i=1; i<=max_clients; i++)
516 if (PlayerAuth[i] && GetUserAdmin(i) == INVALID_ADMIN_ID)
523 * This round of updates is done. Go in peace.
525 RebuildCachePart[_:AdminCache_Admins] = 0;
528 public OnReceiveGroupOverrides(Handle:owner, Handle:hndl, const String:error[], any:data)
530 new Handle:pk = Handle:data;
534 * Check if this is the latest result request.
536 new sequence = ReadPackCell(pk);
537 if (RebuildCachePart[_:AdminCache_Groups] != sequence)
539 /* Discard everything, since we're out of sequence. */
545 * If we need to use the results, make sure they succeeded.
547 if (hndl == INVALID_HANDLE)
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);
557 /* We're done with the pack forever. */
561 * Fetch the overrides.
563 decl String:name[80];
564 decl String:type[16];
565 decl String:command[64];
566 decl String:access[16];
568 while (SQL_FetchRow(hndl))
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));
575 /* Find the group. This is actually faster than doing the ID lookup. */
576 if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
578 /* Oh well, just ignore it. */
582 new OverrideType:o_type = Override_Command;
583 if (StrEqual(type, "group"))
585 o_type = Override_CommandGroup;
588 new OverrideRule:o_rule = Command_Deny;
589 if (StrEqual(access, "allow"))
591 o_rule = Command_Allow;
595 PrintToServer("AddAdmGroupCmdOverride(%d, %s, %d, %d)", gid, command, o_type, o_rule);
598 AddAdmGroupCmdOverride(gid, command, o_type, o_rule);
601 /* Clear the sequence so another connect doesn't refetch */
602 RebuildCachePart[_:AdminCache_Groups] = 0;
605 public OnReceiveGroups(Handle:owner, Handle:hndl, const String:error[], any:data)
607 new Handle:pk = Handle:data;
611 * Check if this is the latest result request.
613 new sequence = ReadPackCell(pk);
614 if (RebuildCachePart[_:AdminCache_Groups] != sequence)
616 /* Discard everything, since we're out of sequence. */
622 * If we need to use the results, make sure they succeeded.
624 if (hndl == INVALID_HANDLE)
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);
634 /* We cache basic group info so we can do reverse lookups */
635 new Handle:groups = CreateArray(3);
638 * Now start fetching groups.
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))
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));
653 PrintToServer("Adding group (%d, %s, %s, %s, %s)", id, immunity, flags, name, grp_immunity);
656 /* Find or create the group */
658 if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
660 gid = CreateAdmGroup(name);
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++)
668 if (!FindFlagByChar(flags[i], flag))
672 SetAdmGroupAddFlag(gid, flag, true);
675 /* Set the immunity level this group has */
676 if (StrEqual(immunity, "all"))
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);
686 new Handle:immunity_list = UTIL_ExplodeNumberString(grp_immunity);
688 /* Now, save all this for later */
692 savedata[2] = _:immunity_list;
694 PushArrayArray(groups, savedata);
698 * Resolve immunity now in a second pass.
700 new num_groups = GetArraySize(groups);
701 for (new i=0; i<num_groups; i++)
704 GetArrayArray(groups, i, savedata);
706 new id = savedata[0];
707 new GroupId:gid = GroupId:savedata[1];
708 new Handle:immunity_list = Handle:savedata[2];
710 if (immunity_list != INVALID_HANDLE)
712 new immunity_count = GetArraySize(immunity_list);
713 for (new j=0; j<immunity_count; j++)
715 new other_id = GetArrayCell(immunity_list, j);
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)
727 PrintToServer("SetAdmGroupImmuneFrom(%d, %d)", gid, other_gid);
729 SetAdmGroupImmuneFrom(gid, other_gid);
733 * We close the Handle but don't zero it in the parent array... not worth
736 CloseHandle(immunity_list);
743 * Now we're done with both passes. It's time to get the group override list.
745 decl String:query[255];
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");
751 WritePackCell(pk, sequence);
752 WritePackString(pk, query);
754 SQL_TQuery(owner, OnReceiveGroupOverrides, query, pk, DBPrio_High);
757 FetchGroups(Handle:db, sequence)
759 decl String:query[255];
762 Format(query, sizeof(query), "SELECT id, immunity, flags, name, groups_immune FROM sm_groups");
764 pk = CreateDataPack();
765 WritePackCell(pk, sequence);
766 WritePackString(pk, query);
768 SQL_TQuery(db, OnReceiveGroups, query, pk, DBPrio_High);
771 public OnReceiveOverrides(Handle:owner, Handle:hndl, const String:error[], any:data)
773 new Handle:pk = Handle:data;
777 * Check if this is the latest result request.
779 new sequence = ReadPackCell(pk);
780 if (RebuildCachePart[_:AdminCache_Overrides] != sequence)
782 /* Discard everything, since we're out of sequence. */
788 * If we need to use the results, make sure they succeeded.
790 if (hndl == INVALID_HANDLE)
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);
801 * We're done with you, now.
805 decl String:type[64];
806 decl String:name[64];
807 decl String:flags[32];
809 while (SQL_FetchRow(hndl))
811 SQL_FetchString(hndl, 0, type, sizeof(type));
812 SQL_FetchString(hndl, 1, name, sizeof(name));
813 SQL_FetchString(hndl, 2, flags, sizeof(flags));
816 PrintToServer("Adding override (%s, %s, %s)", type, name, flags);
819 flag_bits = ReadFlagString(flags);
820 if (StrEqual(type, "command"))
822 AddCommandOverride(name, Override_Command, flag_bits);
823 } else if (StrEqual(type, "group")) {
824 AddCommandOverride(name, Override_CommandGroup, flag_bits);
828 /* Clear the sequence so another connect doesn't refetch */
829 RebuildCachePart[_:AdminCache_Overrides] = 0;
832 FetchOverrides(Handle:db, sequence)
834 decl String:query[255];
837 Format(query, sizeof(query), "SELECT type, name, flags FROM sm_overrides");
839 pk = CreateDataPack();
840 WritePackCell(pk, sequence);
841 WritePackString(pk, query);
843 SQL_TQuery(db, OnReceiveOverrides, query, pk, DBPrio_High);
847 * Finds an entry in a temporary group list (used by immunity resolver).
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.
853 stock GroupId:UTIL_FindGroupInCache(Handle:group_list, id)
855 new size = GetArraySize(group_list);
857 for (new i=0; i<size; i++)
860 GetArrayArray(group_list, i, data);
864 return GroupId:data[1];
868 return INVALID_GROUP_ID;
872 * Breaks a comma-delimited string into a list of numbers, returning a new
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.
879 stock Handle:UTIL_ExplodeNumberString(const String:text[])
881 new Handle:array = INVALID_HANDLE;
882 decl String:buffer[32];
885 while ((idx = SplitString(text[reloc_idx], ",", buffer, sizeof(buffer))) != -1)
888 if (text[reloc_idx] == '\0')
892 if (array == INVALID_HANDLE)
894 array = CreateArray();
896 PushArrayCell(array, StringToInt(buffer));
899 if (text[reloc_idx] != '\0')
901 if (array == INVALID_HANDLE)
903 array = CreateArray();
905 PushArrayCell(array, StringToInt(text[reloc_idx]));