1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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
25 #pragma comment(lib, "mysqlclient.lib")
28 /* VERSION 2 API: With nonblocking (threaded) requests */
30 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
31 /* $CompileFlags: exec("mysql_config --include") */
32 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
33 /* $ModDep: m_sqlv2.h */
35 /* THE NONBLOCKING MYSQL API!
37 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
38 * that instead, you should thread your program. This is what i've done here to allow for
39 * asyncronous SQL requests via mysql. The way this works is as follows:
41 * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
42 * using a queue with priorities. There is a mutex on either end which prevents two threads
43 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
44 * worker thread wakes up, and checks if there is a request at the head of its queue.
45 * If there is, it processes this request, blocking the worker thread but leaving the ircd
46 * thread to go about its business as usual. During this period, the ircd thread is able
47 * to insert futher pending requests into the queue.
49 * Once the processing of a request is complete, it is removed from the incoming queue to
50 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
51 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
52 * connection ID through the connection.
54 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
55 * of the queue, and sends it on its way to the original calling module.
57 * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
58 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
59 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
60 * however, if we were to call a module's OnRequest even from within a thread which was not the
61 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
62 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
63 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
64 * gauranteed threadsafe!)
66 * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
73 typedef std::map<std::string, SQLConnection*> ConnMap;
74 static MySQLListener *MessagePipe = NULL;
77 class DispatcherThread;
81 class ModuleSQL : public Module
86 InspIRCd* PublicServerInstance;
89 DispatcherThread* Dispatcher;
94 ModuleSQL(InspIRCd* Me);
96 unsigned long NewID();
97 const char* OnRequest(Request* request);
98 void OnRehash(User* user, const std::string ¶meter);
104 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
105 #define mysql_field_count mysql_num_fields
108 typedef std::deque<SQLresult*> ResultQueue;
110 /** Represents a mysql result set
112 class MySQLresult : public SQLresult
115 std::vector<std::string> colnames;
116 std::vector<SQLfieldList> fieldlists;
117 SQLfieldMap* fieldmap;
118 SQLfieldMap fieldmap2;
119 SQLfieldList emptyfieldlist;
123 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
125 /* A number of affected rows from from mysql_affected_rows.
129 if (affected_rows >= 1)
131 rows = affected_rows;
132 fieldlists.resize(rows);
134 unsigned int field_count = 0;
139 while ((row = mysql_fetch_row(res)))
141 if (fieldlists.size() < (unsigned int)rows+1)
143 fieldlists.resize(fieldlists.size()+1);
146 MYSQL_FIELD *fields = mysql_fetch_fields(res);
147 if(mysql_num_fields(res) == 0)
149 if (fields && mysql_num_fields(res))
152 while (field_count < mysql_num_fields(res))
154 std::string a = (fields[field_count].name ? fields[field_count].name : "");
155 std::string b = (row[field_count] ? row[field_count] : "");
156 SQLfield sqlf(b, !row[field_count]);
157 colnames.push_back(a);
158 fieldlists[n].push_back(sqlf);
165 mysql_free_result(res);
169 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
186 return colnames.size();
189 virtual std::string ColName(int column)
191 if (column < (int)colnames.size())
193 return colnames[column];
197 throw SQLbadColName();
202 virtual int ColNum(const std::string &column)
204 for (unsigned int i = 0; i < colnames.size(); i++)
206 if (column == colnames[i])
209 throw SQLbadColName();
213 virtual SQLfield GetValue(int row, int column)
215 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
217 return fieldlists[row][column];
220 throw SQLbadColName();
222 /* XXX: We never actually get here because of the throw */
223 return SQLfield("",true);
226 virtual SQLfieldList& GetRow()
228 if (currentrow < rows)
229 return fieldlists[currentrow++];
231 return emptyfieldlist;
234 virtual SQLfieldMap& GetRowMap()
238 if (currentrow < rows)
240 for (int i = 0; i < Cols(); i++)
242 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
250 virtual SQLfieldList* GetRowPtr()
252 SQLfieldList* fieldlist = new SQLfieldList();
254 if (currentrow < rows)
256 for (int i = 0; i < Rows(); i++)
258 fieldlist->push_back(fieldlists[currentrow][i]);
265 virtual SQLfieldMap* GetRowMapPtr()
267 fieldmap = new SQLfieldMap();
269 if (currentrow < rows)
271 for (int i = 0; i < Cols(); i++)
273 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
281 virtual void Free(SQLfieldMap* fm)
286 virtual void Free(SQLfieldList* fl)
294 void NotifyMainThread(SQLConnection* connection_with_new_result);
296 /** Represents a connection to a mysql database
298 class SQLConnection : public classbase
306 std::map<std::string,std::string> thisrow;
315 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
316 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : 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 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 /* Parse the command string and dispatch it to mysql */
341 SQLrequest& req = queue.front();
343 /* Pointer to the buffer we screw around with substitution in */
346 /* Pointer to the current end of query, where we append new stuff */
349 /* Total length of the unescaped parameters */
350 unsigned long paramlen;
352 /* Total length of query, used for binary-safety in mysql_real_query */
353 unsigned long querylength = 0;
357 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
359 paramlen += i->size();
362 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
363 * sizeofquery + (totalparamlength*2) + 1
365 * The +1 is for null-terminating the string for mysql_real_escape_string
368 query = new char[req.query.q.length() + (paramlen*2) + 1];
371 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
372 * the parameters into it...
375 for(unsigned long i = 0; i < req.query.q.length(); i++)
377 if(req.query.q[i] == '?')
379 /* We found a place to substitute..what fun.
380 * use mysql calls to escape and write the
381 * escaped string onto the end of our query buffer,
382 * then we "just" need to make sure queryend is
383 * pointing at the right place.
385 if(req.query.p.size())
387 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
390 req.query.p.pop_front();
397 *queryend = req.query.q[i];
405 Parent->QueueMutex->Lock();
407 Parent->QueueMutex->Unlock();
409 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
411 /* Successfull query */
412 res = mysql_use_result(&connection);
413 unsigned long rows = mysql_affected_rows(&connection);
414 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
415 r->dbid = this->GetID();
416 r->query = req.query.q;
417 /* Put this new result onto the results queue.
418 * XXX: Remember to mutex the queue!
420 Parent->ResultsMutex->Lock();
422 Parent->ResultsMutex->Unlock();
426 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
427 * possible error numbers and error messages */
428 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
429 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
430 r->dbid = this->GetID();
431 r->query = req.query.q;
433 Parent->ResultsMutex->Lock();
435 Parent->ResultsMutex->Unlock();
438 /* Now signal the main thread that we've got a result to process.
439 * Pass them this connection id as what to examine
444 NotifyMainThread(this);
447 bool ConnectionLost()
450 return (mysql_ping(&connection) != 0);
455 bool CheckConnection()
457 if (ConnectionLost()) {
463 std::string GetError()
465 return mysql_error(&connection);
468 const std::string& GetID()
473 std::string GetHost()
478 void SetEnable(bool Enable)
490 mysql_close(&connection);
493 const SQLhost& GetConfHost()
502 bool HasHost(const SQLhost &host)
504 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
506 if (host == iter->second->GetConfHost())
512 bool HostInConf(ConfigReader* conf, const SQLhost &h)
514 for(int i = 0; i < conf->Enumerate("database"); i++)
517 host.id = conf->ReadValue("database", "id", i);
518 host.host = conf->ReadValue("database", "hostname", i);
519 host.port = conf->ReadInteger("database", "port", i, true);
520 host.name = conf->ReadValue("database", "name", i);
521 host.user = conf->ReadValue("database", "username", i);
522 host.pass = conf->ReadValue("database", "password", i);
523 host.ssl = conf->ReadFlag("database", "ssl", i);
530 void ClearOldConnections(ConfigReader* conf)
532 ConnMap::iterator i,safei;
533 for (i = Connections.begin(); i != Connections.end(); i++)
535 if (!HostInConf(conf, i->second->GetConfHost()))
540 Connections.erase(safei);
545 void ClearAllConnections()
548 while ((i = Connections.begin()) != Connections.end())
550 Connections.erase(i);
555 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
557 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
559 if (i->second->IsEnabled())
562 i->second->SetEnable(true);
563 if (!i->second->Connect())
566 Parent->LoggingMutex->Lock();
567 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
568 i->second->SetEnable(false);
569 Parent->LoggingMutex->Unlock();
574 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
576 ClearOldConnections(conf);
577 for (int j =0; j < conf->Enumerate("database"); j++)
580 host.id = conf->ReadValue("database", "id", j);
581 host.host = conf->ReadValue("database", "hostname", j);
582 host.port = conf->ReadInteger("database", "port", j, true);
583 host.name = conf->ReadValue("database", "name", j);
584 host.user = conf->ReadValue("database", "username", j);
585 host.pass = conf->ReadValue("database", "password", j);
586 host.ssl = conf->ReadFlag("database", "ssl", j);
591 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
593 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
594 Connections[host.id] = ThisSQL;
597 ConnectDatabases(ServerInstance, Parent);
600 char FindCharId(const std::string &id)
603 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
605 if (iter->first == id)
613 ConnMap::iterator GetCharId(char id)
616 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
621 return Connections.end();
624 void NotifyMainThread(SQLConnection* connection_with_new_result)
626 /* Here we write() to the socket the main thread has open
627 * and we connect()ed back to before our thread became active.
628 * The main thread is using a nonblocking socket tied into
629 * the socket engine, so they wont block and they'll receive
630 * nearly instant notification. Because we're in a seperate
631 * thread, we can just use standard connect(), and we can
632 * block if we like. We just send the connection id of the
635 * NOTE: We only send a single char down the connection, this
636 * way we know it wont get a partial read at the other end if
637 * the system is especially congested (see bug #263).
638 * The function FindCharId translates a connection name into a
639 * one character id, and GetCharId translates a character id
640 * back into an iterator.
642 char id = FindCharId(connection_with_new_result->GetID());
643 send(QueueFD, &id, 1, 0);
648 class DispatcherThread : public Thread
652 InspIRCd* ServerInstance;
654 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
655 ~DispatcherThread() { }
659 /** Used by m_mysql to notify one thread when the other has a result
661 class Notifier : public BufferedSocket
666 Notifier(ModuleSQL* P, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), Parent(P) { }
668 virtual bool OnDataReady()
671 /* NOTE: Only a single character is read so we know we
672 * cant get a partial read. (We've been told that theres
673 * data waiting, so we wont ever get EAGAIN)
674 * The function GetCharId translates a single character
675 * back into an iterator.
677 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
679 ConnMap::iterator iter = GetCharId(data);
680 if (iter != Connections.end())
682 /* Lock the mutex, send back the data */
683 Parent->ResultsMutex->Lock();
684 ResultQueue::iterator n = iter->second->rq.begin();
687 iter->second->rq.pop_front();
688 Parent->ResultsMutex->Unlock();
691 /* No error, but unknown id */
695 /* Erk, error on descriptor! */
700 /** Spawn sockets from a listener
702 class MySQLListener : public ListenSocketBase
705 insp_sockaddr sock_us;
710 MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
712 uslen = sizeof(sock_us);
713 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
715 throw ModuleException("Could not getsockname() to find out port number for ITC port");
719 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
721 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
724 /* Using getsockname and ntohs, we can determine which port number we were allocated */
728 return ntohs(sock_us.sin6_port);
730 return ntohs(sock_us.sin_port);
735 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
737 ServerInstance->Modules->UseInterface("SQLutils");
739 Conf = new ConfigReader(ServerInstance);
740 PublicServerInstance = ServerInstance;
743 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
745 MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
747 MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
750 if (MessagePipe->GetFd() == -1)
751 throw ModuleException("m_mysql: unable to create ITC pipe");
753 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
755 Dispatcher = new DispatcherThread(ServerInstance, this);
756 ServerInstance->Threads->Create(Dispatcher);
758 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
759 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
760 QueueMutex = ServerInstance->Mutexes->CreateMutex();
762 if (!ServerInstance->Modules->PublishFeature("SQL", this))
764 /* Tell worker thread to exit NOW,
765 * Automatically joins */
767 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
770 ServerInstance->Modules->PublishInterface("SQL", this);
771 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
772 ServerInstance->Modules->Attach(eventlist, this, 2);
775 ModuleSQL::~ModuleSQL()
778 ClearAllConnections();
780 ServerInstance->Modules->UnpublishInterface("SQL", this);
781 ServerInstance->Modules->UnpublishFeature("SQL");
782 ServerInstance->Modules->DoneWithInterface("SQLutils");
788 unsigned long ModuleSQL::NewID()
795 const char* ModuleSQL::OnRequest(Request* request)
797 if(strcmp(SQLREQID, request->GetId()) == 0)
799 SQLrequest* req = (SQLrequest*)request;
804 ConnMap::iterator iter;
806 const char* returnval = NULL;
808 if((iter = Connections.find(req->dbid)) != Connections.end())
811 iter->second->queue.push(*req);
812 returnval = SQLSUCCESS;
816 req->error.Id(SQL_BAD_DBID);
819 QueueMutex->Unlock();
828 void ModuleSQL::OnRehash(User* user, const std::string ¶meter)
833 Version ModuleSQL::GetVersion()
835 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
838 void DispatcherThread::Run()
840 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
842 /* Connect back to the Notifier */
844 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
846 /* crap, we're out of sockets... */
853 insp_aton("::1", &addr.sin6_addr);
854 addr.sin6_family = AF_FAMILY;
855 addr.sin6_port = htons(MessagePipe->GetPort());
858 insp_aton("127.0.0.1", &ia);
859 addr.sin_family = AF_FAMILY;
861 addr.sin_port = htons(MessagePipe->GetPort());
864 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
866 /* wtf, we cant connect to it, but we just created it! */
870 while (this->GetExitFlag() == false)
872 if (Parent->rehashing)
875 Parent->QueueMutex->Lock();
876 Parent->rehashing = false;
877 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
878 Parent->QueueMutex->Unlock();
882 SQLConnection* conn = NULL;
883 /* XXX: Lock here for safety */
884 Parent->QueueMutex->Lock();
885 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
887 if (i->second->queue.totalsize())
893 Parent->QueueMutex->Unlock();
896 /* Theres an item! */
899 conn->DoLeadingQuery();
902 Parent->QueueMutex->Lock();
904 Parent->QueueMutex->Unlock();
912 MODULE_INIT(ModuleSQL)