1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* Stop mysql wanting to use long long */
15 #define NO_CLIENT_LONG_LONG
22 #pragma comment(lib, "mysqlclient.lib")
25 /* VERSION 2 API: With nonblocking (threaded) requests */
27 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
28 /* $CompileFlags: exec("mysql_config --include") */
29 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
30 /* $ModDep: m_sqlv2.h */
32 /* THE NONBLOCKING MYSQL API!
34 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
35 * that instead, you should thread your program. This is what i've done here to allow for
36 * asyncronous SQL requests via mysql. The way this works is as follows:
38 * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
39 * using a queue with priorities. There is a mutex on either end which prevents two threads
40 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
41 * worker thread wakes up, and checks if there is a request at the head of its queue.
42 * If there is, it processes this request, blocking the worker thread but leaving the ircd
43 * thread to go about its business as usual. During this period, the ircd thread is able
44 * to insert futher pending requests into the queue.
46 * Once the processing of a request is complete, it is removed from the incoming queue to
47 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
48 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
49 * connection ID through the connection.
51 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
52 * of the queue, and sends it on its way to the original calling module.
54 * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
55 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
56 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
57 * however, if we were to call a module's OnRequest even from within a thread which was not the
58 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
59 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
60 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
61 * gauranteed threadsafe!)
63 * For a diagram of this system please see http://wiki.inspircd.org/Mysql2
68 class DispatcherThread;
70 typedef std::map<std::string, SQLConnection*> ConnMap;
71 typedef std::deque<SQLresult*> ResultQueue;
73 unsigned long count(const char * const str, char a)
76 for (const char *p = str; *p; ++p)
87 class ModuleSQL : public Module
92 InspIRCd* PublicServerInstance;
95 DispatcherThread* Dispatcher;
100 ModuleSQL(InspIRCd* Me);
102 unsigned long NewID();
103 const char* OnRequest(Request* request);
104 void OnRehash(User* user);
105 Version GetVersion();
109 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
110 #define mysql_field_count mysql_num_fields
113 /** Represents a mysql result set
115 class MySQLresult : public SQLresult
118 std::vector<std::string> colnames;
119 std::vector<SQLfieldList> fieldlists;
120 SQLfieldMap* fieldmap;
121 SQLfieldMap fieldmap2;
122 SQLfieldList emptyfieldlist;
126 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
128 /* A number of affected rows from from mysql_affected_rows.
132 if (affected_rows >= 1)
134 rows = affected_rows;
135 fieldlists.resize(rows);
137 unsigned int field_count = 0;
142 while ((row = mysql_fetch_row(res)))
144 if (fieldlists.size() < (unsigned int)rows+1)
146 fieldlists.resize(fieldlists.size()+1);
149 MYSQL_FIELD *fields = mysql_fetch_fields(res);
150 if(mysql_num_fields(res) == 0)
152 if (fields && mysql_num_fields(res))
155 while (field_count < mysql_num_fields(res))
157 std::string a = (fields[field_count].name ? fields[field_count].name : "");
158 std::string b = (row[field_count] ? row[field_count] : "");
159 SQLfield sqlf(b, !row[field_count]);
160 colnames.push_back(a);
161 fieldlists[n].push_back(sqlf);
168 mysql_free_result(res);
173 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
190 return colnames.size();
193 virtual std::string ColName(int column)
195 if (column < (int)colnames.size())
197 return colnames[column];
201 throw SQLbadColName();
206 virtual int ColNum(const std::string &column)
208 for (unsigned int i = 0; i < colnames.size(); i++)
210 if (column == colnames[i])
213 throw SQLbadColName();
217 virtual SQLfield GetValue(int row, int column)
219 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
221 return fieldlists[row][column];
224 throw SQLbadColName();
226 /* XXX: We never actually get here because of the throw */
227 return SQLfield("",true);
230 virtual SQLfieldList& GetRow()
232 if (currentrow < rows)
233 return fieldlists[currentrow++];
235 return emptyfieldlist;
238 virtual SQLfieldMap& GetRowMap()
242 if (currentrow < rows)
244 for (int i = 0; i < Cols(); i++)
246 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
254 virtual SQLfieldList* GetRowPtr()
256 SQLfieldList* fieldlist = new SQLfieldList();
258 if (currentrow < rows)
260 for (int i = 0; i < Rows(); i++)
262 fieldlist->push_back(fieldlists[currentrow][i]);
269 virtual SQLfieldMap* GetRowMapPtr()
271 fieldmap = new SQLfieldMap();
273 if (currentrow < rows)
275 for (int i = 0; i < Cols(); i++)
277 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
285 virtual void Free(SQLfieldMap* fm)
290 virtual void Free(SQLfieldList* fl)
296 /** Represents a connection to a mysql database
298 class SQLConnection : public classbase
305 std::map<std::string,std::string> thisrow;
308 std::string initquery;
315 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
316 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : connection(NULL), host(hi), Enabled(false), Parent(Creator)
325 // This method connects to the database using the credentials supplied to the constructor, and returns
326 // true upon success.
329 unsigned int timeout = 1;
330 connection = mysql_init(connection);
331 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
332 return mysql_real_connect(connection, host.host.c_str(), host.user.c_str(), host.pass.c_str(), host.name.c_str(), host.port, NULL, 0);
335 void DoLeadingQuery()
337 if (!CheckConnection())
340 if( !initquery.empty() )
341 mysql_query(connection,initquery.c_str());
343 /* Parse the command string and dispatch it to mysql */
344 SQLrequest& req = queue.front();
346 /* Pointer to the buffer we screw around with substitution in */
349 /* Pointer to the current end of query, where we append new stuff */
352 /* Total length of the unescaped parameters */
353 unsigned long maxparamlen, paramcount;
355 /* The length of the longest parameter */
358 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
360 if (i->size() > maxparamlen)
361 maxparamlen = i->size();
364 /* How many params are there in the query? */
365 paramcount = count(req.query.q.c_str(), '?');
367 /* This stores copy of params to be inserted with using numbered params 1;3B*/
368 ParamL paramscopy(req.query.p);
370 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
371 * sizeofquery + (maxtotalparamlength*2) + 1
373 * The +1 is for null-terminating the string for mysql_real_escape_string
376 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
379 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
380 * the parameters into it...
383 for(unsigned long i = 0; i < req.query.q.length(); i++)
385 if(req.query.q[i] == '?')
387 /* We found a place to substitute..what fun.
388 * use mysql calls to escape and write the
389 * escaped string onto the end of our query buffer,
390 * then we "just" need to make sure queryend is
391 * pointing at the right place.
394 /* Is it numbered parameter?
400 /* Numbered parameter number :|
402 unsigned int paramnum;
405 /* Let's check if it's a numbered param. And also calculate it's number.
408 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
412 paramnum = paramnum * 10 + req.query.q[i] - '0';
415 if (paramnum > paramscopy.size() - 1)
417 /* index is out of range!
424 unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
428 else if (req.query.p.size())
430 unsigned long len = mysql_real_escape_string(connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
433 req.query.p.pop_front();
440 *queryend = req.query.q[i];
449 if (!mysql_real_query(connection, req.query.q.data(), req.query.q.length()))
451 /* Successfull query */
452 res = mysql_use_result(connection);
453 unsigned long rows = mysql_affected_rows(connection);
454 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
455 r->dbid = this->GetID();
456 r->query = req.query.q;
457 /* Put this new result onto the results queue.
458 * XXX: Remember to mutex the queue!
460 Parent->ResultsMutex.Lock();
462 Parent->ResultsMutex.Unlock();
466 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
467 * possible error numbers and error messages */
468 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
469 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
470 r->dbid = this->GetID();
471 r->query = req.query.q;
473 Parent->ResultsMutex.Lock();
475 Parent->ResultsMutex.Unlock();
481 bool ConnectionLost()
485 return (mysql_ping(connection) != 0);
490 bool CheckConnection()
492 if (ConnectionLost())
499 std::string GetError()
501 return mysql_error(connection);
504 const std::string& GetID()
509 std::string GetHost()
514 void setInitialQuery(std::string init)
519 void SetEnable(bool Enable)
531 mysql_close(connection);
534 const SQLhost& GetConfHost()
543 bool HasHost(const SQLhost &host)
545 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
547 if (host == iter->second->GetConfHost())
553 bool HostInConf(ConfigReader* conf, const SQLhost &h)
555 for(int i = 0; i < conf->Enumerate("database"); i++)
558 host.id = conf->ReadValue("database", "id", i);
559 host.host = conf->ReadValue("database", "hostname", i);
560 host.port = conf->ReadInteger("database", "port", i, true);
561 host.name = conf->ReadValue("database", "name", i);
562 host.user = conf->ReadValue("database", "username", i);
563 host.pass = conf->ReadValue("database", "password", i);
564 host.ssl = conf->ReadFlag("database", "ssl", i);
571 void ClearOldConnections(ConfigReader* conf)
573 ConnMap::iterator i,safei;
574 for (i = Connections.begin(); i != Connections.end(); i++)
576 if (!HostInConf(conf, i->second->GetConfHost()))
581 Connections.erase(safei);
586 void ClearAllConnections()
589 while ((i = Connections.begin()) != Connections.end())
591 Connections.erase(i);
596 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
598 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
600 if (i->second->IsEnabled())
603 i->second->SetEnable(true);
604 if (!i->second->Connect())
607 Parent->LoggingMutex.Lock();
608 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
609 i->second->SetEnable(false);
610 Parent->LoggingMutex.Unlock();
615 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
617 Parent->ConnMutex.Lock();
618 ClearOldConnections(conf);
619 for (int j =0; j < conf->Enumerate("database"); j++)
622 host.id = conf->ReadValue("database", "id", j);
623 host.host = conf->ReadValue("database", "hostname", j);
624 host.port = conf->ReadInteger("database", "port", j, true);
625 host.name = conf->ReadValue("database", "name", j);
626 host.user = conf->ReadValue("database", "username", j);
627 host.pass = conf->ReadValue("database", "password", j);
628 host.ssl = conf->ReadFlag("database", "ssl", j);
629 std::string initquery = conf->ReadValue("database", "initialquery", j);
634 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
636 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
637 Connections[host.id] = ThisSQL;
639 ThisSQL->setInitialQuery(initquery);
642 ConnectDatabases(ServerInstance, Parent);
643 Parent->ConnMutex.Unlock();
646 char FindCharId(const std::string &id)
649 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
651 if (iter->first == id)
659 ConnMap::iterator GetCharId(char id)
662 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
667 return Connections.end();
672 class DispatcherThread : public SocketThread
676 InspIRCd* ServerInstance;
678 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : SocketThread(Instance), Parent(CreatorModule), ServerInstance(Instance) { }
679 ~DispatcherThread() { }
681 virtual void OnNotify();
684 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
686 ServerInstance->Modules->UseInterface("SQLutils");
688 Conf = new ConfigReader(ServerInstance);
689 PublicServerInstance = ServerInstance;
692 Dispatcher = new DispatcherThread(ServerInstance, this);
693 ServerInstance->Threads->Start(Dispatcher);
695 if (!ServerInstance->Modules->PublishFeature("SQL", this))
699 ServerInstance->Modules->DoneWithInterface("SQLutils");
700 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
703 ServerInstance->Modules->PublishInterface("SQL", this);
704 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
705 ServerInstance->Modules->Attach(eventlist, this, 2);
708 ModuleSQL::~ModuleSQL()
711 ClearAllConnections();
713 ServerInstance->Modules->UnpublishInterface("SQL", this);
714 ServerInstance->Modules->UnpublishFeature("SQL");
715 ServerInstance->Modules->DoneWithInterface("SQLutils");
718 unsigned long ModuleSQL::NewID()
725 const char* ModuleSQL::OnRequest(Request* request)
727 if(strcmp(SQLREQID, request->GetId()) == 0)
729 SQLrequest* req = (SQLrequest*)request;
731 ConnMap::iterator iter;
733 const char* returnval = NULL;
735 Dispatcher->LockQueue();
737 if((iter = Connections.find(req->dbid)) != Connections.end())
740 iter->second->queue.push(*req);
741 returnval = SQLSUCCESS;
745 req->error.Id(SQL_BAD_DBID);
749 Dispatcher->UnlockQueueWakeup();
750 /* Yes, it's possible this will generate a spurious wakeup.
751 * That's fine, it'll just get ignored.
760 void ModuleSQL::OnRehash(User* user)
762 Dispatcher->LockQueue();
764 Dispatcher->UnlockQueueWakeup();
767 Version ModuleSQL::GetVersion()
769 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
772 void DispatcherThread::Run()
774 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
776 SQLConnection* conn = NULL;
779 while (!this->GetExitFlag())
781 if (Parent->rehashing)
783 Parent->rehashing = false;
784 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
788 Parent->ConnMutex.Lock();
789 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
791 if (i->second->queue.totalsize())
797 Parent->ConnMutex.Unlock();
801 /* There's an item! */
803 conn->DoLeadingQuery();
804 this->NotifyParent();
810 /* We know the queue is empty, we can safely hang this thread until
813 this->WaitForQueue();
819 void DispatcherThread::OnNotify()
825 Parent->ConnMutex.Lock();
826 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
828 if (!iter->second->rq.empty())
834 Parent->ConnMutex.Unlock();
839 Parent->ResultsMutex.Lock();
840 ResultQueue::iterator n = conn->rq.begin();
841 Parent->ResultsMutex.Unlock();
846 Parent->ResultsMutex.Lock();
847 conn->rq.pop_front();
848 Parent->ResultsMutex.Unlock();
852 MODULE_INIT(ModuleSQL)