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
94 DispatcherThread* Dispatcher;
101 unsigned long NewID();
102 void OnRequest(Request& request);
103 void OnRehash(User* user);
104 Version GetVersion();
108 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
109 #define mysql_field_count mysql_num_fields
112 /** Represents a mysql result set
114 class MySQLresult : public SQLresult
117 std::vector<std::string> colnames;
118 std::vector<SQLfieldList> fieldlists;
119 SQLfieldMap* fieldmap;
120 SQLfieldMap fieldmap2;
121 SQLfieldList emptyfieldlist;
125 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
127 /* A number of affected rows from from mysql_affected_rows.
131 if (affected_rows >= 1)
133 rows = affected_rows;
134 fieldlists.resize(rows);
136 unsigned int field_count = 0;
141 while ((row = mysql_fetch_row(res)))
143 if (fieldlists.size() < (unsigned int)rows+1)
145 fieldlists.resize(fieldlists.size()+1);
148 MYSQL_FIELD *fields = mysql_fetch_fields(res);
149 if(mysql_num_fields(res) == 0)
151 if (fields && mysql_num_fields(res))
154 while (field_count < mysql_num_fields(res))
156 std::string a = (fields[field_count].name ? fields[field_count].name : "");
157 std::string b = (row[field_count] ? row[field_count] : "");
158 SQLfield sqlf(b, !row[field_count]);
159 colnames.push_back(a);
160 fieldlists[n].push_back(sqlf);
167 mysql_free_result(res);
172 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
189 return colnames.size();
192 virtual std::string ColName(int column)
194 if (column < (int)colnames.size())
196 return colnames[column];
200 throw SQLbadColName();
205 virtual int ColNum(const std::string &column)
207 for (unsigned int i = 0; i < colnames.size(); i++)
209 if (column == colnames[i])
212 throw SQLbadColName();
216 virtual SQLfield GetValue(int row, int column)
218 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
220 return fieldlists[row][column];
223 throw SQLbadColName();
225 /* XXX: We never actually get here because of the throw */
226 return SQLfield("",true);
229 virtual SQLfieldList& GetRow()
231 if (currentrow < rows)
232 return fieldlists[currentrow++];
234 return emptyfieldlist;
237 virtual SQLfieldMap& GetRowMap()
241 if (currentrow < rows)
243 for (int i = 0; i < Cols(); i++)
245 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
253 virtual SQLfieldList* GetRowPtr()
255 SQLfieldList* fieldlist = new SQLfieldList();
257 if (currentrow < rows)
259 for (int i = 0; i < Rows(); i++)
261 fieldlist->push_back(fieldlists[currentrow][i]);
268 virtual SQLfieldMap* GetRowMapPtr()
270 fieldmap = new SQLfieldMap();
272 if (currentrow < rows)
274 for (int i = 0; i < Cols(); i++)
276 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
284 virtual void Free(SQLfieldMap* fm)
289 virtual void Free(SQLfieldList* fl)
295 /** Represents a connection to a mysql database
297 class SQLConnection : public classbase
304 std::map<std::string,std::string> thisrow;
307 std::string initquery;
314 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
315 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : connection(NULL), host(hi), Enabled(false), Parent(Creator)
324 // This method connects to the database using the credentials supplied to the constructor, and returns
325 // true upon success.
328 unsigned int timeout = 1;
329 connection = mysql_init(connection);
330 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
331 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);
334 void DoLeadingQuery()
336 if (!CheckConnection())
339 if( !initquery.empty() )
340 mysql_query(connection,initquery.c_str());
342 /* Parse the command string and dispatch it to mysql */
343 SQLrequest* req = queue.front();
345 /* Pointer to the buffer we screw around with substitution in */
348 /* Pointer to the current end of query, where we append new stuff */
351 /* Total length of the unescaped parameters */
352 unsigned long maxparamlen, paramcount;
354 /* The length of the longest parameter */
357 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
359 if (i->size() > maxparamlen)
360 maxparamlen = i->size();
363 /* How many params are there in the query? */
364 paramcount = count(req->query.q.c_str(), '?');
366 /* This stores copy of params to be inserted with using numbered params 1;3B*/
367 ParamL paramscopy(req->query.p);
369 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
370 * sizeofquery + (maxtotalparamlength*2) + 1
372 * The +1 is for null-terminating the string for mysql_real_escape_string
375 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
378 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
379 * the parameters into it...
382 for(unsigned long i = 0; i < req->query.q.length(); i++)
384 if(req->query.q[i] == '?')
386 /* We found a place to substitute..what fun.
387 * use mysql calls to escape and write the
388 * escaped string onto the end of our query buffer,
389 * then we "just" need to make sure queryend is
390 * pointing at the right place.
393 /* Is it numbered parameter?
399 /* Numbered parameter number :|
401 unsigned int paramnum;
404 /* Let's check if it's a numbered param. And also calculate it's number.
407 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
411 paramnum = paramnum * 10 + req->query.q[i] - '0';
414 if (paramnum > paramscopy.size() - 1)
416 /* index is out of range!
423 unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
427 else if (req->query.p.size())
429 unsigned long len = mysql_real_escape_string(connection, queryend, req->query.p.front().c_str(), req->query.p.front().length());
432 req->query.p.pop_front();
439 *queryend = req->query.q[i];
446 req->query.q = query;
448 if (!mysql_real_query(connection, req->query.q.data(), req->query.q.length()))
450 /* Successfull query */
451 res = mysql_use_result(connection);
452 unsigned long rows = mysql_affected_rows(connection);
453 MySQLresult* r = new MySQLresult(Parent, req->source, res, rows, req->id);
454 r->dbid = this->GetID();
455 r->query = req->query.q;
456 /* Put this new result onto the results queue.
457 * XXX: Remember to mutex the queue!
459 Parent->ResultsMutex.Lock();
461 Parent->ResultsMutex.Unlock();
465 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
466 * possible error numbers and error messages */
467 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
468 MySQLresult* r = new MySQLresult(Parent, req->source, e, req->id);
469 r->dbid = this->GetID();
470 r->query = req->query.q;
472 Parent->ResultsMutex.Lock();
474 Parent->ResultsMutex.Unlock();
480 bool ConnectionLost()
484 return (mysql_ping(connection) != 0);
489 bool CheckConnection()
491 if (ConnectionLost())
498 std::string GetError()
500 return mysql_error(connection);
503 const std::string& GetID()
508 std::string GetHost()
513 void setInitialQuery(std::string init)
518 void SetEnable(bool Enable)
530 mysql_close(connection);
533 const SQLhost& GetConfHost()
542 bool HasHost(const SQLhost &host)
544 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
546 if (host == iter->second->GetConfHost())
552 bool HostInConf(ConfigReader* conf, const SQLhost &h)
554 for(int i = 0; i < conf->Enumerate("database"); i++)
557 host.id = conf->ReadValue("database", "id", i);
558 host.host = conf->ReadValue("database", "hostname", i);
559 host.port = conf->ReadInteger("database", "port", i, true);
560 host.name = conf->ReadValue("database", "name", i);
561 host.user = conf->ReadValue("database", "username", i);
562 host.pass = conf->ReadValue("database", "password", i);
563 host.ssl = conf->ReadFlag("database", "ssl", i);
570 void ClearOldConnections(ConfigReader* conf)
572 ConnMap::iterator i,safei;
573 for (i = Connections.begin(); i != Connections.end(); i++)
575 if (!HostInConf(conf, i->second->GetConfHost()))
580 Connections.erase(safei);
585 void ClearAllConnections()
588 while ((i = Connections.begin()) != Connections.end())
590 Connections.erase(i);
595 void ConnectDatabases(ModuleSQL* Parent)
597 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
599 if (i->second->IsEnabled())
602 i->second->SetEnable(true);
603 if (!i->second->Connect())
606 Parent->LoggingMutex.Lock();
607 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
608 i->second->SetEnable(false);
609 Parent->LoggingMutex.Unlock();
614 void LoadDatabases(ConfigReader* conf, ModuleSQL* Parent)
616 Parent->ConnMutex.Lock();
617 ClearOldConnections(conf);
618 for (int j =0; j < conf->Enumerate("database"); j++)
621 host.id = conf->ReadValue("database", "id", j);
622 host.host = conf->ReadValue("database", "hostname", j);
623 host.port = conf->ReadInteger("database", "port", j, true);
624 host.name = conf->ReadValue("database", "name", j);
625 host.user = conf->ReadValue("database", "username", j);
626 host.pass = conf->ReadValue("database", "password", j);
627 host.ssl = conf->ReadFlag("database", "ssl", j);
628 std::string initquery = conf->ReadValue("database", "initialquery", j);
633 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
635 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
636 Connections[host.id] = ThisSQL;
638 ThisSQL->setInitialQuery(initquery);
641 ConnectDatabases(Parent);
642 Parent->ConnMutex.Unlock();
645 char FindCharId(const std::string &id)
648 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
650 if (iter->first == id)
658 ConnMap::iterator GetCharId(char id)
661 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
666 return Connections.end();
671 class DispatcherThread : public SocketThread
674 ModuleSQL* const Parent;
676 DispatcherThread(ModuleSQL* CreatorModule) : Parent(CreatorModule) { }
677 ~DispatcherThread() { }
679 virtual void OnNotify();
682 ModuleSQL::ModuleSQL() : rehashing(false)
684 ServerInstance->Modules->UseInterface("SQLutils");
686 Conf = new ConfigReader;
689 Dispatcher = new DispatcherThread(this);
690 ServerInstance->Threads->Start(Dispatcher);
692 if (!ServerInstance->Modules->PublishFeature("SQL", this))
696 ServerInstance->Modules->DoneWithInterface("SQLutils");
697 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
700 ServerInstance->Modules->PublishInterface("SQL", this);
701 Implementation eventlist[] = { I_OnRehash };
702 ServerInstance->Modules->Attach(eventlist, this, 1);
705 ModuleSQL::~ModuleSQL()
708 ClearAllConnections();
710 ServerInstance->Modules->UnpublishInterface("SQL", this);
711 ServerInstance->Modules->UnpublishFeature("SQL");
712 ServerInstance->Modules->DoneWithInterface("SQLutils");
715 unsigned long ModuleSQL::NewID()
722 void ModuleSQL::OnRequest(Request& request)
724 if(strcmp(SQLREQID, request.id) == 0)
726 SQLrequest* req = (SQLrequest*)&request;
728 ConnMap::iterator iter;
730 Dispatcher->LockQueue();
732 if((iter = Connections.find(req->dbid)) != Connections.end())
735 iter->second->queue.push(new SQLrequest(*req));
739 req->error.Id(SQL_BAD_DBID);
743 Dispatcher->UnlockQueueWakeup();
744 /* Yes, it's possible this will generate a spurious wakeup.
745 * That's fine, it'll just get ignored.
750 void ModuleSQL::OnRehash(User* user)
752 Dispatcher->LockQueue();
754 Dispatcher->UnlockQueueWakeup();
757 Version ModuleSQL::GetVersion()
759 return Version("SQL Service Provider module for all other m_sql* modules", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
762 void DispatcherThread::Run()
764 LoadDatabases(Parent->Conf, Parent);
766 SQLConnection* conn = NULL;
769 while (!this->GetExitFlag())
771 if (Parent->rehashing)
773 Parent->rehashing = false;
774 LoadDatabases(Parent->Conf, Parent);
778 Parent->ConnMutex.Lock();
779 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
781 if (i->second->queue.totalsize())
787 Parent->ConnMutex.Unlock();
791 /* There's an item! */
793 conn->DoLeadingQuery();
794 this->NotifyParent();
800 /* We know the queue is empty, we can safely hang this thread until
803 this->WaitForQueue();
809 void DispatcherThread::OnNotify()
815 Parent->ConnMutex.Lock();
816 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
818 if (!iter->second->rq.empty())
824 Parent->ConnMutex.Unlock();
829 Parent->ResultsMutex.Lock();
830 ResultQueue::iterator n = conn->rq.begin();
831 Parent->ResultsMutex.Unlock();
836 Parent->ResultsMutex.Lock();
837 conn->rq.pop_front();
838 Parent->ResultsMutex.Unlock();
842 MODULE_INIT(ModuleSQL)