Fix Windows build (require stdint.h i.e. MSVC 2010+).
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "sourcemod.h"
34 #include "sm_stringutil.h"
37 #include <IThreader.h>
38 #include "logic_bridge.h"
40 #define DBPARSE_LEVEL_NONE 0
41 #define DBPARSE_LEVEL_MAIN 1
42 #define DBPARSE_LEVEL_DATABASE 2
45 static bool s_OneTimeThreaderErrorMsg = false;
47 DBManager::DBManager()
48 : m_ParseLevel(0), m_ParseState(0), m_pDefault(NULL)
52 void DBManager::OnSourceModAllInitialized()
56 handlesys->InitAccessDefaults(NULL, &sec);
57 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
58 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
60 m_DriverType = handlesys->CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
61 m_DatabaseType = handlesys->CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
63 sharesys->AddInterface(NULL, this);
65 g_SourceMod.BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
67 m_pConfigLock = g_pThreader->MakeMutex();
68 m_pThinkLock = g_pThreader->MakeMutex();
69 m_pQueueLock = g_pThreader->MakeMutex();
71 scripts->AddPluginsListener(this);
74 void DBManager::OnSourceModLevelChange(const char *mapName)
77 SMCStates states = {0, 0};
79 /* We lock and don't give up the lock until we're done.
80 * This way the thread's search won't be searching through a
81 * potentially empty/corrupt list, which would be very bad.
83 m_pConfigLock->Lock();
84 if ((err = textparsers->ParseFile_SMC(m_Filename, this, &states)) != SMCError_Okay)
86 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
87 if (err != SMCError_Custom)
89 const char *txt = textparsers->GetSMCErrorString(err);
90 g_Logger.LogError("[SM] Line %d: %s", states.line, txt);
93 m_pConfigLock->Unlock();
96 void DBManager::OnSourceModShutdown()
99 scripts->RemovePluginsListener(this);
100 m_pConfigLock->DestroyThis();
101 m_pThinkLock->DestroyThis();
102 m_pQueueLock->DestroyThis();
103 handlesys->RemoveType(m_DatabaseType, g_pCoreIdent);
104 handlesys->RemoveType(m_DriverType, g_pCoreIdent);
108 unsigned int DBManager::GetInterfaceVersion()
110 return SMINTERFACE_DBI_VERSION;
113 const char *DBManager::GetInterfaceName()
115 return SMINTERFACE_DBI_NAME;
118 void DBManager::OnHandleDestroy(HandleType_t type, void *object)
120 if (type == m_DriverType)
126 if (handlesys->TypeCheck(type, m_DatabaseType))
128 IDatabase *pdb = (IDatabase *)object;
133 void DBManager::ReadSMC_ParseStart()
137 m_ParseState = DBPARSE_LEVEL_NONE;
141 void DBManager::ClearConfigs()
143 List<ConfDbInfo *>::iterator iter;
144 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
149 ConfDbInfo s_CurInfo;
150 SMCResult DBManager::ReadSMC_NewSection(const SMCStates *states, const char *name)
155 return SMCResult_Continue;
158 if (m_ParseState == DBPARSE_LEVEL_NONE)
160 if (strcmp(name, "Databases") == 0)
162 m_ParseState = DBPARSE_LEVEL_MAIN;
166 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
167 s_CurInfo = ConfDbInfo();
168 s_CurInfo.name = name;
169 m_ParseState = DBPARSE_LEVEL_DATABASE;
170 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
174 return SMCResult_Continue;
177 SMCResult DBManager::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
181 return SMCResult_Continue;
184 if (m_ParseState == DBPARSE_LEVEL_MAIN)
186 if (strcmp(key, "driver_default") == 0)
188 m_DefDriver.assign(value);
190 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
191 if (strcmp(key, "driver") == 0)
193 if (strcmp(value, "default") != 0)
195 s_CurInfo.driver = value;
197 } else if (strcmp(key, "database") == 0) {
198 s_CurInfo.database = value;
199 } else if (strcmp(key, "host") == 0) {
200 s_CurInfo.host = value;
201 } else if (strcmp(key, "user") == 0) {
202 s_CurInfo.user = value;
203 } else if (strcmp(key, "pass") == 0) {
204 s_CurInfo.pass = value;
205 } else if (strcmp(key, "timeout") == 0) {
206 s_CurInfo.info.maxTimeout = atoi(value);
207 } else if (strcmp(key, "port") == 0) {
208 s_CurInfo.info.port = atoi(value);
212 return SMCResult_Continue;
215 SMCResult DBManager::ReadSMC_LeavingSection(const SMCStates *states)
220 return SMCResult_Continue;
223 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
225 ConfDbInfo *cdb = new ConfDbInfo();
227 cdb->name = s_CurInfo.name;
228 cdb->driver = s_CurInfo.driver;
229 cdb->host = s_CurInfo.host;
230 cdb->user = s_CurInfo.user;
231 cdb->pass = s_CurInfo.pass;
232 cdb->database = s_CurInfo.database;
233 cdb->realDriver = s_CurInfo.realDriver;
234 cdb->info.maxTimeout = s_CurInfo.info.maxTimeout;
235 cdb->info.port = s_CurInfo.info.port;
237 cdb->info.driver = cdb->driver.c_str();
238 cdb->info.database = cdb->database.c_str();
239 cdb->info.host = cdb->host.c_str();
240 cdb->info.user = cdb->user.c_str();
241 cdb->info.pass = cdb->pass.c_str();
244 m_confs.push_back(cdb);
246 /* Go up one level */
247 m_ParseState = DBPARSE_LEVEL_MAIN;
248 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
249 m_ParseState = DBPARSE_LEVEL_NONE;
250 return SMCResult_Halt;
253 return SMCResult_Continue;
256 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
260 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
262 ConfDbInfo *pInfo = GetDatabaseConf(name);
271 UTIL_Format(error, maxlength, "Configuration \"%s\" not found", name);
275 const char *dname = pInfo->info.driver;
276 if (!pInfo->realDriver)
278 /* Try to assign a real driver pointer */
279 if (pInfo->info.driver[0] == '\0')
281 if (!m_pDefault && m_DefDriver.size() > 0)
283 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
285 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
286 pInfo->realDriver = m_pDefault;
288 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
292 if (pInfo->realDriver)
296 *pdr = pInfo->realDriver;
298 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
299 return (*pdb != NULL);
308 UTIL_Format(error, maxlength, "Driver \"%s\" not found", dname);
313 void DBManager::AddDriver(IDBDriver *pDriver)
315 /* Let's kill the worker. Join the thread and let the queries flush.
316 * This is kind of stupid but we just want to unload safely.
317 * Rather than recreate the worker, we'll wait until someone throws
318 * another query through.
322 m_drivers.push_back(pDriver);
325 void DBManager::RemoveDriver(IDBDriver *pDriver)
327 /* Again, we're forced to kill the worker. How rude!
328 * Doing this flushes the queue, and thus we don't need to
329 * clean anything else.
333 for (size_t i=0; i<m_drivers.size(); i++)
335 if (m_drivers[i] == pDriver)
337 m_drivers.erase(m_drivers.iterAt(i));
342 /* Make sure NOTHING references this! */
343 List<ConfDbInfo *>::iterator iter;
344 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
346 ConfDbInfo &db = *(*iter);
347 if (db.realDriver == pDriver)
349 db.realDriver = NULL;
353 /* Now that the driver is gone, we have to test the think queue.
354 * Whatever happens therein is up to the db op!
356 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
357 Queue<IDBThreadOperation *> templist;
358 while (qiter != m_ThinkQueue.end())
360 IDBThreadOperation *op = (*qiter);
361 if (op->GetDriver() == pDriver)
364 qiter = m_ThinkQueue.erase(qiter);
370 for (qiter = templist.begin();
371 qiter != templist.end();
374 IDBThreadOperation *op = (*qiter);
375 op->CancelThinkPart();
380 IDBDriver *DBManager::GetDefaultDriver()
382 if (!m_pDefault && m_DefDriver.size() > 0)
384 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
390 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
392 HandleType_t type = 0;
394 if (dtype == DBHandle_Driver)
397 } else if (dtype == DBHandle_Database) {
398 type = m_DatabaseType;
403 return handlesys->CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
406 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
408 HandleType_t type = 0;
410 if (dtype == DBHandle_Driver)
413 } else if (dtype == DBHandle_Database) {
414 type = m_DatabaseType;
416 return HandleError_Type;
419 HandleSecurity sec(NULL, g_pCoreIdent);
421 return handlesys->ReadHandle(hndl, type, &sec, ptr);
424 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
426 HandleSecurity sec(token, g_pCoreIdent);
427 return handlesys->FreeHandle(hndl, &sec);
430 unsigned int DBManager::GetDriverCount()
432 return (unsigned int)m_drivers.size();
435 IDBDriver *DBManager::GetDriver(unsigned int index)
437 if (index >= m_drivers.size())
442 return m_drivers[index];
445 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
447 ConfDbInfo *info = GetDatabaseConf(name);
456 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
458 List<ConfDbInfo *>::iterator iter;
460 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
462 ConfDbInfo &conf = *(*iter);
463 if (conf.name == name)
472 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
474 size_t last_size = m_drivers.size();
475 for (size_t i=0; i<last_size; i++)
477 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
483 char filename[PLATFORM_MAX_PATH];
484 UTIL_Format(filename, sizeof(filename), "dbi.%s.ext", name);
486 IExtension *pExt = extsys->LoadAutoExtension(filename);
487 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
492 /* last_size is now gauranteed to be a valid index.
493 * The identifier must match the name.
495 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
497 return m_drivers[last_size];
503 void DBManager::KillWorkerThread()
507 m_pWorker->Stop(false);
508 g_pThreader->DestroyWorker(m_pWorker);
510 s_OneTimeThreaderErrorMsg = false;
514 static IdentityToken_t *s_pAddBlock = NULL;
516 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
518 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
525 m_pWorker = g_pThreader->MakeWorker(this, true);
528 if (!s_OneTimeThreaderErrorMsg)
530 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
531 s_OneTimeThreaderErrorMsg = true;
535 if (!m_pWorker->Start())
537 if (!s_OneTimeThreaderErrorMsg)
539 g_Logger.LogError("[SM] Unable to start db threader (error unknown)");
540 s_OneTimeThreaderErrorMsg = true;
542 g_pThreader->DestroyWorker(m_pWorker);
548 /* Add to the queue */
550 m_pQueueLock->Lock();
551 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
553 m_pQueueLock->Unlock();
556 /* Make the thread */
557 m_pWorker->MakeThread(this);
562 void DBManager::OnWorkerStart(IThreadWorker *pWorker)
565 for (size_t i=0; i<m_drivers.size(); i++)
567 if (m_drivers[i]->IsThreadSafe())
569 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
571 m_drSafety.push_back(false);
576 void DBManager::OnWorkerStop(IThreadWorker *pWorker)
578 for (size_t i=0; i<m_drivers.size(); i++)
582 m_drivers[i]->ShutdownThreadSafety();
588 void DBManager::RunThread(IThreadHandle *pThread)
590 IDBThreadOperation *op = NULL;
592 /* Get something from the queue */
594 m_pQueueLock->Lock();
595 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
601 m_pQueueLock->Unlock();
604 /* whoa. hi. did we get something? we should have. */
613 m_pThinkLock->Lock();
614 m_ThinkQueue.push(op);
615 m_pThinkLock->Unlock();
618 void DBManager::RunFrame()
620 /* Don't bother if we're empty */
621 if (!m_ThinkQueue.size())
626 /* Dump one thing per-frame so the server stays sane. */
627 m_pThinkLock->Lock();
628 IDBThreadOperation *op = m_ThinkQueue.first();
630 m_pThinkLock->Unlock();
635 void DBManager::OnTerminate(IThreadHandle *pThread, bool cancel)
640 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
642 s_pAddBlock = pToken;
644 /* Kill the thread so we can flush everything into the think queue... */
647 /* Run all of the think operations.
648 * Unlike the driver unloading example, we'll let these calls go through,
649 * since a plugin unloading is far more normal.
651 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
652 Queue<IDBThreadOperation *> templist;
653 while (iter != m_ThinkQueue.end())
655 IDBThreadOperation *op = (*iter);
656 if (op->GetOwner() == pToken)
659 iter = m_ThinkQueue.erase(iter);
665 for (iter = templist.begin();
666 iter != templist.end();
669 IDBThreadOperation *op = (*iter);
677 void DBManager::OnPluginUnloaded(IPlugin *plugin)
679 /* Kill the thread so we can flush everything into the think queue... */
682 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
683 plugin->SetProperty("DisallowDBThreads", NULL);
685 /* Run all of the think operations.
686 * Unlike the driver unloading example, we'll let these calls go through,
687 * since a plugin unloading is far more normal.
689 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
690 Queue<IDBThreadOperation *> templist;
691 while (iter != m_ThinkQueue.end())
693 IDBThreadOperation *op = (*iter);
694 if (op->GetOwner() == plugin->GetIdentity())
697 iter = m_ThinkQueue.erase(iter);
703 for (iter = templist.begin();
704 iter != templist.end();
707 IDBThreadOperation *op = (*iter);
713 void DBManager::LockConfig()
715 m_pConfigLock->Lock();
718 void DBManager::UnlockConfig()
720 m_pConfigLock->Unlock();
723 const char *DBManager::GetDefaultDriverName()
725 return m_DefDriver.c_str();
728 void DBManager::AddDependency(IExtension *myself, IDBDriver *driver)
730 extsys->AddRawDependency(myself, driver->GetIdentity(), driver);