1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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
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://www.inspircd.org/wiki/Mysql2
71 typedef std::map<std::string, SQLConnection*> ConnMap;
72 static MySQLListener *MessagePipe = NULL;
75 class DispatcherThread;
77 unsigned long count(const char * const str, char a)
80 for (const char *p = reinterpret_cast<const char *>(str); *p; ++p)
91 class ModuleSQL : public Module
96 InspIRCd* PublicServerInstance;
99 DispatcherThread* Dispatcher;
105 ModuleSQL(InspIRCd* Me);
107 unsigned long NewID();
108 const char* OnRequest(Request* request);
109 void OnRehash(User* user, const std::string ¶meter);
110 Version GetVersion();
115 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
116 #define mysql_field_count mysql_num_fields
119 typedef std::deque<SQLresult*> ResultQueue;
121 /** Represents a mysql result set
123 class MySQLresult : public SQLresult
126 std::vector<std::string> colnames;
127 std::vector<SQLfieldList> fieldlists;
128 SQLfieldMap* fieldmap;
129 SQLfieldMap fieldmap2;
130 SQLfieldList emptyfieldlist;
134 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
136 /* A number of affected rows from from mysql_affected_rows.
140 if (affected_rows >= 1)
142 rows = affected_rows;
143 fieldlists.resize(rows);
145 unsigned int field_count = 0;
150 while ((row = mysql_fetch_row(res)))
152 if (fieldlists.size() < (unsigned int)rows+1)
154 fieldlists.resize(fieldlists.size()+1);
157 MYSQL_FIELD *fields = mysql_fetch_fields(res);
158 if(mysql_num_fields(res) == 0)
160 if (fields && mysql_num_fields(res))
163 while (field_count < mysql_num_fields(res))
165 std::string a = (fields[field_count].name ? fields[field_count].name : "");
166 std::string b = (row[field_count] ? row[field_count] : "");
167 SQLfield sqlf(b, !row[field_count]);
168 colnames.push_back(a);
169 fieldlists[n].push_back(sqlf);
176 mysql_free_result(res);
180 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
197 return colnames.size();
200 virtual std::string ColName(int column)
202 if (column < (int)colnames.size())
204 return colnames[column];
208 throw SQLbadColName();
213 virtual int ColNum(const std::string &column)
215 for (unsigned int i = 0; i < colnames.size(); i++)
217 if (column == colnames[i])
220 throw SQLbadColName();
224 virtual SQLfield GetValue(int row, int column)
226 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
228 return fieldlists[row][column];
231 throw SQLbadColName();
233 /* XXX: We never actually get here because of the throw */
234 return SQLfield("",true);
237 virtual SQLfieldList& GetRow()
239 if (currentrow < rows)
240 return fieldlists[currentrow++];
242 return emptyfieldlist;
245 virtual SQLfieldMap& GetRowMap()
249 if (currentrow < rows)
251 for (int i = 0; i < Cols(); i++)
253 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
261 virtual SQLfieldList* GetRowPtr()
263 SQLfieldList* fieldlist = new SQLfieldList();
265 if (currentrow < rows)
267 for (int i = 0; i < Rows(); i++)
269 fieldlist->push_back(fieldlists[currentrow][i]);
276 virtual SQLfieldMap* GetRowMapPtr()
278 fieldmap = new SQLfieldMap();
280 if (currentrow < rows)
282 for (int i = 0; i < Cols(); i++)
284 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
292 virtual void Free(SQLfieldMap* fm)
297 virtual void Free(SQLfieldList* fl)
305 void NotifyMainThread(SQLConnection* connection_with_new_result);
307 /** Represents a connection to a mysql database
309 class SQLConnection : public classbase
317 std::map<std::string,std::string> thisrow;
326 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
327 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : host(hi), Enabled(false), Parent(Creator)
336 // This method connects to the database using the credentials supplied to the constructor, and returns
337 // true upon success.
340 unsigned int timeout = 1;
341 mysql_init(&connection);
342 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
343 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);
346 void DoLeadingQuery()
348 if (!CheckConnection())
351 /* Parse the command string and dispatch it to mysql */
352 SQLrequest& req = queue.front();
354 /* Pointer to the buffer we screw around with substitution in */
357 /* Pointer to the current end of query, where we append new stuff */
360 /* Total length of the unescaped parameters */
361 unsigned long maxparamlen, paramcount;
363 /* Total length of query, used for binary-safety in mysql_real_query */
364 unsigned long querylength = 0;
366 /* The length of the longest parameter */
369 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
371 if (i->size() > maxparamlen)
372 maxparamlen = i->size();
375 /* How many params are there in the query? */
376 paramcount = count(req.query.q.c_str(), '?');
378 /* This stores copy of params to be inserted with using numbered params 1;3B*/
379 ParamL paramscopy(req.query.p);
381 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
382 * sizeofquery + (maxtotalparamlength*2) + 1
384 * The +1 is for null-terminating the string for mysql_real_escape_string
387 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
390 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
391 * the parameters into it...
394 for(unsigned long i = 0; i < req.query.q.length(); i++)
396 if(req.query.q[i] == '?')
398 /* We found a place to substitute..what fun.
399 * use mysql calls to escape and write the
400 * escaped string onto the end of our query buffer,
401 * then we "just" need to make sure queryend is
402 * pointing at the right place.
405 /* Is it numbered parameter?
411 /* Numbered parameter number :|
413 unsigned int paramnum;
416 /* Let's check if it's a numbered param. And also calculate it's number.
419 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
423 paramnum = paramnum * 10 + req.query.q[i] - '0';
426 if (paramnum > paramscopy.size() - 1)
428 /* index is out of range!
435 unsigned long len = mysql_real_escape_string(&connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
439 else if (req.query.p.size())
441 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
444 req.query.p.pop_front();
451 *queryend = req.query.q[i];
459 Parent->QueueMutex->Lock();
461 Parent->QueueMutex->Unlock();
463 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
465 /* Successfull query */
466 res = mysql_use_result(&connection);
467 unsigned long rows = mysql_affected_rows(&connection);
468 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
469 r->dbid = this->GetID();
470 r->query = req.query.q;
471 /* Put this new result onto the results queue.
472 * XXX: Remember to mutex the queue!
474 Parent->ResultsMutex->Lock();
476 Parent->ResultsMutex->Unlock();
480 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
481 * possible error numbers and error messages */
482 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
483 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
484 r->dbid = this->GetID();
485 r->query = req.query.q;
487 Parent->ResultsMutex->Lock();
489 Parent->ResultsMutex->Unlock();
492 /* Now signal the main thread that we've got a result to process.
493 * Pass them this connection id as what to examine
498 NotifyMainThread(this);
501 bool ConnectionLost()
505 return (mysql_ping(&connection) != 0);
510 bool CheckConnection()
512 if (ConnectionLost())
519 std::string GetError()
521 return mysql_error(&connection);
524 const std::string& GetID()
529 std::string GetHost()
534 void SetEnable(bool Enable)
546 mysql_close(&connection);
549 const SQLhost& GetConfHost()
558 bool HasHost(const SQLhost &host)
560 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
562 if (host == iter->second->GetConfHost())
568 bool HostInConf(ConfigReader* conf, const SQLhost &h)
570 for(int i = 0; i < conf->Enumerate("database"); i++)
573 host.id = conf->ReadValue("database", "id", i);
574 host.host = conf->ReadValue("database", "hostname", i);
575 host.port = conf->ReadInteger("database", "port", i, true);
576 host.name = conf->ReadValue("database", "name", i);
577 host.user = conf->ReadValue("database", "username", i);
578 host.pass = conf->ReadValue("database", "password", i);
579 host.ssl = conf->ReadFlag("database", "ssl", i);
586 void ClearOldConnections(ConfigReader* conf)
588 ConnMap::iterator i,safei;
589 for (i = Connections.begin(); i != Connections.end(); i++)
591 if (!HostInConf(conf, i->second->GetConfHost()))
596 Connections.erase(safei);
601 void ClearAllConnections()
604 while ((i = Connections.begin()) != Connections.end())
606 Connections.erase(i);
611 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
613 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
615 if (i->second->IsEnabled())
618 i->second->SetEnable(true);
619 if (!i->second->Connect())
622 Parent->LoggingMutex->Lock();
623 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
624 i->second->SetEnable(false);
625 Parent->LoggingMutex->Unlock();
630 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
632 Parent->ConnMutex->Lock();
633 ClearOldConnections(conf);
634 for (int j =0; j < conf->Enumerate("database"); j++)
637 host.id = conf->ReadValue("database", "id", j);
638 host.host = conf->ReadValue("database", "hostname", j);
639 host.port = conf->ReadInteger("database", "port", j, true);
640 host.name = conf->ReadValue("database", "name", j);
641 host.user = conf->ReadValue("database", "username", j);
642 host.pass = conf->ReadValue("database", "password", j);
643 host.ssl = conf->ReadFlag("database", "ssl", j);
648 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
650 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
651 Connections[host.id] = ThisSQL;
654 ConnectDatabases(ServerInstance, Parent);
655 Parent->ConnMutex->Unlock();
658 char FindCharId(const std::string &id)
661 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
663 if (iter->first == id)
671 ConnMap::iterator GetCharId(char id)
674 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
679 return Connections.end();
682 void NotifyMainThread(SQLConnection* connection_with_new_result)
684 /* Here we write() to the socket the main thread has open
685 * and we connect()ed back to before our thread became active.
686 * The main thread is using a nonblocking socket tied into
687 * the socket engine, so they wont block and they'll receive
688 * nearly instant notification. Because we're in a seperate
689 * thread, we can just use standard connect(), and we can
690 * block if we like. We just send the connection id of the
693 * NOTE: We only send a single char down the connection, this
694 * way we know it wont get a partial read at the other end if
695 * the system is especially congested (see bug #263).
696 * The function FindCharId translates a connection name into a
697 * one character id, and GetCharId translates a character id
698 * back into an iterator.
700 char id = FindCharId(connection_with_new_result->GetID());
701 send(QueueFD, &id, 1, 0);
706 class DispatcherThread : public Thread
710 InspIRCd* ServerInstance;
712 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
713 ~DispatcherThread() { }
717 /** Used by m_mysql to notify one thread when the other has a result
719 class Notifier : public BufferedSocket
724 Notifier(ModuleSQL* P, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), Parent(P) { }
726 virtual bool OnDataReady()
729 /* NOTE: Only a single character is read so we know we
730 * cant get a partial read. (We've been told that theres
731 * data waiting, so we wont ever get EAGAIN)
732 * The function GetCharId translates a single character
733 * back into an iterator.
736 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
738 Parent->ConnMutex->Lock();
739 ConnMap::iterator iter = GetCharId(data);
740 if (iter != Connections.end())
742 /* Lock the mutex, send back the data */
743 Parent->ResultsMutex->Lock();
744 ResultQueue::iterator n = iter->second->rq.begin();
747 iter->second->rq.pop_front();
748 Parent->ResultsMutex->Unlock();
749 Parent->ConnMutex->Unlock();
752 /* No error, but unknown id */
753 Parent->ConnMutex->Unlock();
757 /* Erk, error on descriptor! */
762 /** Spawn sockets from a listener
764 class MySQLListener : public ListenSocketBase
767 irc::sockets::insp_sockaddr sock_us;
772 MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
774 uslen = sizeof(sock_us);
775 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
777 throw ModuleException("Could not getsockname() to find out port number for ITC port");
781 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
783 // XXX unsafe casts suck
784 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str());
787 /* Using getsockname and ntohs, we can determine which port number we were allocated */
791 return ntohs(sock_us.sin6_port);
793 return ntohs(sock_us.sin_port);
798 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
800 ServerInstance->Modules->UseInterface("SQLutils");
802 Conf = new ConfigReader(ServerInstance);
803 PublicServerInstance = ServerInstance;
806 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
808 MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
810 MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
813 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
814 ConnMutex = ServerInstance->Mutexes->CreateMutex();
816 if (MessagePipe->GetFd() == -1)
819 ServerInstance->Modules->DoneWithInterface("SQLutils");
820 throw ModuleException("m_mysql: unable to create ITC pipe");
824 LoggingMutex->Lock();
825 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
826 LoggingMutex->Unlock();
829 Dispatcher = new DispatcherThread(ServerInstance, this);
830 ServerInstance->Threads->Create(Dispatcher);
832 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
833 QueueMutex = ServerInstance->Mutexes->CreateMutex();
835 if (!ServerInstance->Modules->PublishFeature("SQL", this))
837 /* Tell worker thread to exit NOW,
838 * Automatically joins */
844 ServerInstance->Modules->DoneWithInterface("SQLutils");
845 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
848 ServerInstance->Modules->PublishInterface("SQL", this);
849 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
850 ServerInstance->Modules->Attach(eventlist, this, 2);
853 ModuleSQL::~ModuleSQL()
856 ClearAllConnections();
858 ServerInstance->Modules->UnpublishInterface("SQL", this);
859 ServerInstance->Modules->UnpublishFeature("SQL");
860 ServerInstance->Modules->DoneWithInterface("SQLutils");
867 unsigned long ModuleSQL::NewID()
874 const char* ModuleSQL::OnRequest(Request* request)
876 if(strcmp(SQLREQID, request->GetId()) == 0)
878 SQLrequest* req = (SQLrequest*)request;
883 ConnMap::iterator iter;
885 const char* returnval = NULL;
888 if((iter = Connections.find(req->dbid)) != Connections.end())
891 iter->second->queue.push(*req);
892 returnval = SQLSUCCESS;
896 req->error.Id(SQL_BAD_DBID);
900 QueueMutex->Unlock();
908 void ModuleSQL::OnRehash(User* user, const std::string ¶meter)
913 Version ModuleSQL::GetVersion()
915 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
918 void DispatcherThread::Run()
920 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
922 /* Connect back to the Notifier */
924 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
926 /* crap, we're out of sockets... */
930 irc::sockets::insp_sockaddr addr;
933 irc::sockets::insp_aton("::1", &addr.sin6_addr);
934 addr.sin6_family = AF_FAMILY;
935 addr.sin6_port = htons(MessagePipe->GetPort());
937 irc::sockets::insp_inaddr ia;
938 irc::sockets::insp_aton("127.0.0.1", &ia);
939 addr.sin_family = AF_FAMILY;
941 addr.sin_port = htons(MessagePipe->GetPort());
944 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
946 /* wtf, we cant connect to it, but we just created it! */
950 while (this->GetExitFlag() == false)
952 if (Parent->rehashing)
955 Parent->QueueMutex->Lock();
956 Parent->rehashing = false;
957 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
958 Parent->QueueMutex->Unlock();
962 SQLConnection* conn = NULL;
963 /* XXX: Lock here for safety */
964 Parent->QueueMutex->Lock();
965 Parent->ConnMutex->Lock();
966 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
968 if (i->second->queue.totalsize())
974 Parent->ConnMutex->Unlock();
975 Parent->QueueMutex->Unlock();
978 /* Theres an item! */
981 conn->DoLeadingQuery();
984 Parent->QueueMutex->Lock();
986 Parent->QueueMutex->Unlock();
995 MODULE_INIT(ModuleSQL)