Landed sourcepawn-1.2. The big changes:
1) JIT compilation/optimization now occurs per-function, and only when functions are first used. We're now officially a whole-method JIT rather than an AOT compiler (albiet, still a simple JIT). This has two implications: Functions are now much better abstracted internally, and loading a plugin is now much less expensive. If a function contains calls to other functions, THOSE functions are only compiled when they're invoked as well.
2) I've removed debug mode. We always show full backtraces now, as there was a very cheap way to implement this which really cleaned up everything. This is great for a number of reasons -- there's less code, the JIT is better designed, we don't need to relocate debug tables, and best of all we no longer have to tell users to enable debug mode at their own expense.
3 * =============================================================================
4 * SourceMod SQL Admins Plugin (Threaded)
5 * Fetches admins from an SQL database dynamically.
7 * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
8 * =============================================================================
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.
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
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/>.
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>.
34 /* We like semicolons */
39 public Plugin:myinfo =
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/"
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.
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.
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.
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
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" */
82 * Clean up on map end just so we can start a fresh connection when we need it later.
84 if (hDatabase != INVALID_HANDLE)
86 CloseHandle(hDatabase);
87 hDatabase = INVALID_HANDLE;
91 public bool:OnClientConnect(client, String:rejectmsg[], maxlen)
93 PlayerSeq[client] = 0;
94 PlayerAuth[client] = false;
98 public OnClientDisconnect(client)
100 PlayerSeq[client] = 0;
101 PlayerAuth[client] = false;
104 public OnDatabaseConnect(Handle:owner, Handle:hndl, const String:error[], any:data)
107 PrintToServer("OnDatabaseConnect(%x,%x,%d) ConnectLock=%d", owner, hndl, data, ConnectLock);
111 * If this happens to be an old connection request, ignore it.
113 if (data != ConnectLock || hDatabase != INVALID_HANDLE)
115 if (hndl != INVALID_HANDLE)
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.
129 if (hDatabase == INVALID_HANDLE)
131 LogError("Failed to connect to database: %s", error);
136 * See if we need to get any of the cache stuff now.
139 if ((sequence = RebuildCachePart[_:AdminCache_Overrides]) != 0)
141 FetchOverrides(hDatabase, sequence);
143 if ((sequence = RebuildCachePart[_:AdminCache_Groups]) != 0)
145 FetchGroups(hDatabase, sequence);
147 if ((sequence = RebuildCachePart[_:AdminCache_Admins]) != 0)
149 FetchUsersWeCan(hDatabase);
153 RequestDatabaseConnection()
155 ConnectLock = ++g_sequence;
156 if (SQL_CheckConfig("admins"))
158 SQL_TConnect(OnDatabaseConnect, "admins", ConnectLock);
160 SQL_TConnect(OnDatabaseConnect, "default", ConnectLock);
164 public OnRebuildAdminCache(AdminCachePart:part)
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
171 new sequence = ++g_sequence;
172 RebuildCachePart[_:part] = sequence;
175 * If we don't have a database connection, we can't do any lookups just yet.
180 * Ask for a new connection if we need it.
184 RequestDatabaseConnection();
189 if (part == AdminCache_Overrides)
191 FetchOverrides(hDatabase, sequence);
192 } else if (part == AdminCache_Groups) {
193 FetchGroups(hDatabase, sequence);
194 } else if (part == AdminCache_Admins) {
195 FetchUsersWeCan(hDatabase);
199 public Action:OnClientPreAdminCheck(client)
201 PlayerAuth[client] = true;
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
209 if (hDatabase == INVALID_HANDLE)
211 return Plugin_Continue;
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
219 if (RebuildCachePart[_:AdminCache_Admins] != 0)
221 return Plugin_Continue;
225 * If someone has already assigned an admin ID (bad bad bad), don't
228 if (GetUserAdmin(client) != INVALID_ADMIN_ID)
230 return Plugin_Continue;
233 FetchUser(hDatabase, client);
235 return Plugin_Handled;
238 public OnReceiveUserGroups(Handle:owner, Handle:hndl, const String:error[], any:data)
240 new Handle:pk = Handle:data;
243 new client = ReadPackCell(pk);
244 new sequence = ReadPackCell(pk);
247 * Make sure it's the same client.
249 if (PlayerSeq[client] != sequence)
255 new AdminId:adm = AdminId:ReadPackCell(pk);
258 * Someone could have sneakily changed the admin id while we waited.
260 if (GetUserAdmin(client) != adm)
262 NotifyPostAdminCheck(client);
268 * See if we got results.
270 if (hndl == INVALID_HANDLE)
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);
281 decl String:name[80];
284 while (SQL_FetchRow(hndl))
286 SQL_FetchString(hndl, 0, name, sizeof(name));
288 if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
294 PrintToServer("Binding user group (%d, %d, %d, %s, %d)", client, sequence, adm, name, gid);
297 AdminInheritGroup(adm, gid);
303 NotifyPostAdminCheck(client);
307 public OnReceiveUser(Handle:owner, Handle:hndl, const String:error[], any:data)
309 new Handle:pk = Handle:data;
312 new client = ReadPackCell(pk);
315 * Check if this is the latest result request.
317 new sequence = ReadPackCell(pk);
318 if (PlayerSeq[client] != sequence)
320 /* Discard everything, since we're out of sequence. */
326 * If we need to use the results, make sure they succeeded.
328 if (hndl == INVALID_HANDLE)
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);
340 new num_accounts = SQL_GetRowCount(hndl);
341 if (num_accounts == 0)
343 RunAdminCacheChecks(client);
344 NotifyPostAdminCheck(client);
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];
358 * Cache user info -- [0] = db id, [1] = cache id, [2] = groups
360 decl user_lookup[num_accounts][3];
363 while (SQL_FetchRow(hndl))
365 id = SQL_FetchInt(hndl, 0);
366 SQL_FetchString(hndl, 1, authtype, sizeof(authtype));
367 SQL_FetchString(hndl, 2, identity, sizeof(identity));
368 SQL_FetchString(hndl, 3, password, sizeof(password));
369 SQL_FetchString(hndl, 4, flags, sizeof(flags));
370 SQL_FetchString(hndl, 5, name, sizeof(name));
371 immunity = SQL_FetchInt(hndl, 7);
373 /* For dynamic admins we clear anything already in the cache. */
374 if ((adm = FindAdminByIdentity(authtype, identity)) != INVALID_ADMIN_ID)
379 adm = CreateAdmin(name);
380 if (!BindAdminIdentity(adm, authtype, identity))
382 LogError("Could not bind prefetched SQL admin (authtype \"%s\") (identity \"%s\")", authtype, identity);
386 user_lookup[total_users][0] = id;
387 user_lookup[total_users][1] = _:adm;
388 user_lookup[total_users][2] = SQL_FetchInt(hndl, 6);
392 PrintToServer("Found SQL admin (%d,%s,%s,%s,%s,%s,%d):%d:%d", id, authtype, identity, password, flags, name, immunity, adm, user_lookup[total_users-1][2]);
395 /* See if this admin wants a password */
396 if (password[0] != '\0')
398 SetAdminPassword(adm, password);
401 SetAdminImmunityLevel(adm, immunity);
403 /* Apply each flag */
404 new len = strlen(flags);
406 for (new i=0; i<len; i++)
408 if (!FindFlagByChar(flags[i], flag))
412 SetAdminFlag(adm, flag, true);
417 * Try binding the user.
420 RunAdminCacheChecks(client);
421 adm = GetUserAdmin(client);
425 for (new i=0; i<total_users; i++)
427 if (user_lookup[i][1] == _:adm)
429 id = user_lookup[i][0];
430 group_count = user_lookup[i][2];
436 PrintToServer("Binding client (%d, %d) resulted in: (%d, %d, %d)", client, sequence, id, adm, group_count);
440 * If we can't verify that we assigned a database admin, or the user has no
441 * groups, don't bother doing anything.
443 if (!id || !group_count)
445 NotifyPostAdminCheck(client);
451 * The user has groups -- we need to fetch them!
453 decl String:query[255];
454 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);
457 WritePackCell(pk, client);
458 WritePackCell(pk, sequence);
459 WritePackCell(pk, _:adm);
460 WritePackString(pk, query);
462 SQL_TQuery(owner, OnReceiveUserGroups, query, pk, DBPrio_High);
465 FetchUser(Handle:db, client)
467 decl String:name[65];
468 decl String:safe_name[140];
469 decl String:steamid[32];
470 decl String:ipaddr[24];
473 * Get authentication information from the client.
475 GetClientName(client, name, sizeof(name));
476 GetClientIP(client, ipaddr, sizeof(ipaddr));
479 if (GetClientAuthString(client, steamid, sizeof(steamid)))
481 if (StrEqual(steamid, "STEAM_ID_LAN"))
487 SQL_EscapeString(db, name, safe_name, sizeof(safe_name));
490 * Construct the query using the information the user gave us.
492 decl String:query[512];
495 len += Format(query[len], sizeof(query)-len, "SELECT a.id, a.authtype, a.identity, a.password, a.flags, a.name, COUNT(ag.group_id), immunity");
496 len += Format(query[len], sizeof(query)-len, " FROM sm_admins a LEFT JOIN sm_admins_groups ag ON a.id = ag.admin_id WHERE ");
497 len += Format(query[len], sizeof(query)-len, " (a.authtype = 'ip' AND a.identity = '%s')", ipaddr);
498 len += Format(query[len], sizeof(query)-len, " OR (a.authtype = 'name' AND a.identity = '%s')", safe_name);
499 if (steamid[0] != '\0')
501 len += Format(query[len], sizeof(query)-len, " OR (a.authtype = 'steam' AND a.identity = '%s')", steamid);
503 len += Format(query[len], sizeof(query)-len, " GROUP BY a.id");
506 * Send the actual query.
508 PlayerSeq[client] = ++g_sequence;
511 pk = CreateDataPack();
512 WritePackCell(pk, client);
513 WritePackCell(pk, PlayerSeq[client]);
514 WritePackString(pk, query);
517 PrintToServer("Sending user query: %s", query);
520 SQL_TQuery(db, OnReceiveUser, query, pk, DBPrio_High);
523 FetchUsersWeCan(Handle:db)
525 new max_clients = GetMaxClients();
527 for (new i=1; i<=max_clients; i++)
529 if (PlayerAuth[i] && GetUserAdmin(i) == INVALID_ADMIN_ID)
536 * This round of updates is done. Go in peace.
538 RebuildCachePart[_:AdminCache_Admins] = 0;
542 public OnReceiveGroupImmunity(Handle:owner, Handle:hndl, const String:error[], any:data)
544 new Handle:pk = Handle:data;
548 * Check if this is the latest result request.
550 new sequence = ReadPackCell(pk);
551 if (RebuildCachePart[_:AdminCache_Groups] != sequence)
553 /* Discard everything, since we're out of sequence. */
559 * If we need to use the results, make sure they succeeded.
561 if (hndl == INVALID_HANDLE)
563 decl String:query[255];
564 ReadPackString(pk, query, sizeof(query));
565 LogError("SQL error receiving group immunity: %s", error);
566 LogError("Query dump: %s", query);
571 /* We're done with the pack forever. */
574 while (SQL_FetchRow(hndl))
576 decl String:group1[80];
577 decl String:group2[80];
578 new GroupId:gid1, GroupId:gid2;
580 SQL_FetchString(hndl, 0, group1, sizeof(group1));
581 SQL_FetchString(hndl, 1, group2, sizeof(group2));
583 if (((gid1 = FindAdmGroup(group1)) == INVALID_GROUP_ID)
584 || (gid2 = FindAdmGroup(group2)) == INVALID_GROUP_ID)
589 SetAdmGroupImmuneFrom(gid1, gid2);
591 PrintToServer("SetAdmGroupImmuneFrom(%d, %d)", gid1, gid2);
595 /* Clear the sequence so another connect doesn't refetch */
596 RebuildCachePart[_:AdminCache_Groups] = 0;
599 public OnReceiveGroupOverrides(Handle:owner, Handle:hndl, const String:error[], any:data)
601 new Handle:pk = Handle:data;
605 * Check if this is the latest result request.
607 new sequence = ReadPackCell(pk);
608 if (RebuildCachePart[_:AdminCache_Groups] != sequence)
610 /* Discard everything, since we're out of sequence. */
616 * If we need to use the results, make sure they succeeded.
618 if (hndl == INVALID_HANDLE)
620 decl String:query[255];
621 ReadPackString(pk, query, sizeof(query));
622 LogError("SQL error receiving group overrides: %s", error);
623 LogError("Query dump: %s", query);
629 * Fetch the overrides.
631 decl String:name[80];
632 decl String:type[16];
633 decl String:command[64];
634 decl String:access[16];
636 while (SQL_FetchRow(hndl))
638 SQL_FetchString(hndl, 0, name, sizeof(name));
639 SQL_FetchString(hndl, 1, type, sizeof(type));
640 SQL_FetchString(hndl, 2, command, sizeof(command));
641 SQL_FetchString(hndl, 3, access, sizeof(access));
643 /* Find the group. This is actually faster than doing the ID lookup. */
644 if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
646 /* Oh well, just ignore it. */
650 new OverrideType:o_type = Override_Command;
651 if (StrEqual(type, "group"))
653 o_type = Override_CommandGroup;
656 new OverrideRule:o_rule = Command_Deny;
657 if (StrEqual(access, "allow"))
659 o_rule = Command_Allow;
663 PrintToServer("AddAdmGroupCmdOverride(%d, %s, %d, %d)", gid, command, o_type, o_rule);
666 AddAdmGroupCmdOverride(gid, command, o_type, o_rule);
670 * It's time to get the group immunity list.
673 decl String:query[256];
674 len += Format(query[len], sizeof(query)-len, "SELECT g1.name, g2.name FROM sm_group_immunity gi");
675 len += Format(query[len], sizeof(query)-len, " LEFT JOIN sm_groups g1 ON g1.id = gi.group_id ");
676 len += Format(query[len], sizeof(query)-len, " LEFT JOIN sm_groups g2 ON g2.id = gi.other_id");
679 WritePackCell(pk, sequence);
680 WritePackString(pk, query);
682 SQL_TQuery(owner, OnReceiveGroupImmunity, query, pk, DBPrio_High);
685 public OnReceiveGroups(Handle:owner, Handle:hndl, const String:error[], any:data)
687 new Handle:pk = Handle:data;
691 * Check if this is the latest result request.
693 new sequence = ReadPackCell(pk);
694 if (RebuildCachePart[_:AdminCache_Groups] != sequence)
696 /* Discard everything, since we're out of sequence. */
702 * If we need to use the results, make sure they succeeded.
704 if (hndl == INVALID_HANDLE)
706 decl String:query[255];
707 ReadPackString(pk, query, sizeof(query));
708 LogError("SQL error receiving groups: %s", error);
709 LogError("Query dump: %s", query);
715 * Now start fetching groups.
717 decl String:flags[32];
718 decl String:name[128];
720 while (SQL_FetchRow(hndl))
722 SQL_FetchString(hndl, 0, flags, sizeof(flags));
723 SQL_FetchString(hndl, 1, name, sizeof(name));
724 immunity = SQL_FetchInt(hndl, 2);
727 PrintToServer("Adding group (%d, %s, %s)", immunity, flags, name);
730 /* Find or create the group */
732 if ((gid = FindAdmGroup(name)) == INVALID_GROUP_ID)
734 gid = CreateAdmGroup(name);
737 /* Add flags from the database to the group */
738 new num_flag_chars = strlen(flags);
739 for (new i=0; i<num_flag_chars; i++)
742 if (!FindFlagByChar(flags[i], flag))
746 SetAdmGroupAddFlag(gid, flag, true);
749 SetAdmGroupImmunityLevel(gid, immunity);
753 * It's time to get the group override list.
755 decl String:query[255];
758 "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");
761 WritePackCell(pk, sequence);
762 WritePackString(pk, query);
764 SQL_TQuery(owner, OnReceiveGroupOverrides, query, pk, DBPrio_High);
767 FetchGroups(Handle:db, sequence)
769 decl String:query[255];
772 Format(query, sizeof(query), "SELECT flags, name, immunity_level FROM sm_groups");
774 pk = CreateDataPack();
775 WritePackCell(pk, sequence);
776 WritePackString(pk, query);
778 SQL_TQuery(db, OnReceiveGroups, query, pk, DBPrio_High);
781 public OnReceiveOverrides(Handle:owner, Handle:hndl, const String:error[], any:data)
783 new Handle:pk = Handle:data;
787 * Check if this is the latest result request.
789 new sequence = ReadPackCell(pk);
790 if (RebuildCachePart[_:AdminCache_Overrides] != sequence)
792 /* Discard everything, since we're out of sequence. */
798 * If we need to use the results, make sure they succeeded.
800 if (hndl == INVALID_HANDLE)
802 decl String:query[255];
803 ReadPackString(pk, query, sizeof(query));
804 LogError("SQL error receiving overrides: %s", error);
805 LogError("Query dump: %s", query);
811 * We're done with you, now.
815 decl String:type[64];
816 decl String:name[64];
817 decl String:flags[32];
819 while (SQL_FetchRow(hndl))
821 SQL_FetchString(hndl, 0, type, sizeof(type));
822 SQL_FetchString(hndl, 1, name, sizeof(name));
823 SQL_FetchString(hndl, 2, flags, sizeof(flags));
826 PrintToServer("Adding override (%s, %s, %s)", type, name, flags);
829 flag_bits = ReadFlagString(flags);
830 if (StrEqual(type, "command"))
832 AddCommandOverride(name, Override_Command, flag_bits);
833 } else if (StrEqual(type, "group")) {
834 AddCommandOverride(name, Override_CommandGroup, flag_bits);
838 /* Clear the sequence so another connect doesn't refetch */
839 RebuildCachePart[_:AdminCache_Overrides] = 0;
842 FetchOverrides(Handle:db, sequence)
844 decl String:query[255];
847 Format(query, sizeof(query), "SELECT type, name, flags FROM sm_overrides");
849 pk = CreateDataPack();
850 WritePackCell(pk, sequence);
851 WritePackString(pk, query);
853 SQL_TQuery(db, OnReceiveOverrides, query, pk, DBPrio_High);