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);
181 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
198 return colnames.size();
201 virtual std::string ColName(int column)
203 if (column < (int)colnames.size())
205 return colnames[column];
209 throw SQLbadColName();
214 virtual int ColNum(const std::string &column)
216 for (unsigned int i = 0; i < colnames.size(); i++)
218 if (column == colnames[i])
221 throw SQLbadColName();
225 virtual SQLfield GetValue(int row, int column)
227 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
229 return fieldlists[row][column];
232 throw SQLbadColName();
234 /* XXX: We never actually get here because of the throw */
235 return SQLfield("",true);
238 virtual SQLfieldList& GetRow()
240 if (currentrow < rows)
241 return fieldlists[currentrow++];
243 return emptyfieldlist;
246 virtual SQLfieldMap& GetRowMap()
250 if (currentrow < rows)
252 for (int i = 0; i < Cols(); i++)
254 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
262 virtual SQLfieldList* GetRowPtr()
264 SQLfieldList* fieldlist = new SQLfieldList();
266 if (currentrow < rows)
268 for (int i = 0; i < Rows(); i++)
270 fieldlist->push_back(fieldlists[currentrow][i]);
277 virtual SQLfieldMap* GetRowMapPtr()
279 fieldmap = new SQLfieldMap();
281 if (currentrow < rows)
283 for (int i = 0; i < Cols(); i++)
285 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
293 virtual void Free(SQLfieldMap* fm)
298 virtual void Free(SQLfieldList* fl)
306 void NotifyMainThread(SQLConnection* connection_with_new_result);
308 /** Represents a connection to a mysql database
310 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) : connection(NULL), 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 connection = 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 /* The length of the longest parameter */
366 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
368 if (i->size() > maxparamlen)
369 maxparamlen = i->size();
372 /* How many params are there in the query? */
373 paramcount = count(req.query.q.c_str(), '?');
375 /* This stores copy of params to be inserted with using numbered params 1;3B*/
376 ParamL paramscopy(req.query.p);
378 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
379 * sizeofquery + (maxtotalparamlength*2) + 1
381 * The +1 is for null-terminating the string for mysql_real_escape_string
384 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
387 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
388 * the parameters into it...
391 for(unsigned long i = 0; i < req.query.q.length(); i++)
393 if(req.query.q[i] == '?')
395 /* We found a place to substitute..what fun.
396 * use mysql calls to escape and write the
397 * escaped string onto the end of our query buffer,
398 * then we "just" need to make sure queryend is
399 * pointing at the right place.
402 /* Is it numbered parameter?
408 /* Numbered parameter number :|
410 unsigned int paramnum;
413 /* Let's check if it's a numbered param. And also calculate it's number.
416 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
420 paramnum = paramnum * 10 + req.query.q[i] - '0';
423 if (paramnum > paramscopy.size() - 1)
425 /* index is out of range!
432 unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
436 else if (req.query.p.size())
438 unsigned long len = mysql_real_escape_string(connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
441 req.query.p.pop_front();
448 *queryend = req.query.q[i];
455 Parent->QueueMutex->Lock();
457 Parent->QueueMutex->Unlock();
459 if (!mysql_real_query(connection, req.query.q.data(), req.query.q.length()))
461 /* Successfull query */
462 res = mysql_use_result(connection);
463 unsigned long rows = mysql_affected_rows(connection);
464 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
465 r->dbid = this->GetID();
466 r->query = req.query.q;
467 /* Put this new result onto the results queue.
468 * XXX: Remember to mutex the queue!
470 Parent->ResultsMutex->Lock();
472 Parent->ResultsMutex->Unlock();
476 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
477 * possible error numbers and error messages */
478 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
479 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
480 r->dbid = this->GetID();
481 r->query = req.query.q;
483 Parent->ResultsMutex->Lock();
485 Parent->ResultsMutex->Unlock();
488 /* Now signal the main thread that we've got a result to process.
489 * Pass them this connection id as what to examine
494 NotifyMainThread(this);
497 bool ConnectionLost()
501 return (mysql_ping(connection) != 0);
506 bool CheckConnection()
508 if (ConnectionLost())
515 std::string GetError()
517 return mysql_error(connection);
520 const std::string& GetID()
525 std::string GetHost()
530 void SetEnable(bool Enable)
542 mysql_close(connection);
545 const SQLhost& GetConfHost()
554 bool HasHost(const SQLhost &host)
556 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
558 if (host == iter->second->GetConfHost())
564 bool HostInConf(ConfigReader* conf, const SQLhost &h)
566 for(int i = 0; i < conf->Enumerate("database"); i++)
569 host.id = conf->ReadValue("database", "id", i);
570 host.host = conf->ReadValue("database", "hostname", i);
571 host.port = conf->ReadInteger("database", "port", i, true);
572 host.name = conf->ReadValue("database", "name", i);
573 host.user = conf->ReadValue("database", "username", i);
574 host.pass = conf->ReadValue("database", "password", i);
575 host.ssl = conf->ReadFlag("database", "ssl", i);
582 void ClearOldConnections(ConfigReader* conf)
584 ConnMap::iterator i,safei;
585 for (i = Connections.begin(); i != Connections.end(); i++)
587 if (!HostInConf(conf, i->second->GetConfHost()))
592 Connections.erase(safei);
597 void ClearAllConnections()
600 while ((i = Connections.begin()) != Connections.end())
602 Connections.erase(i);
607 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
609 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
611 if (i->second->IsEnabled())
614 i->second->SetEnable(true);
615 if (!i->second->Connect())
618 Parent->LoggingMutex->Lock();
619 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
620 i->second->SetEnable(false);
621 Parent->LoggingMutex->Unlock();
626 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
628 Parent->ConnMutex->Lock();
629 ClearOldConnections(conf);
630 for (int j =0; j < conf->Enumerate("database"); j++)
633 host.id = conf->ReadValue("database", "id", j);
634 host.host = conf->ReadValue("database", "hostname", j);
635 host.port = conf->ReadInteger("database", "port", j, true);
636 host.name = conf->ReadValue("database", "name", j);
637 host.user = conf->ReadValue("database", "username", j);
638 host.pass = conf->ReadValue("database", "password", j);
639 host.ssl = conf->ReadFlag("database", "ssl", j);
644 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
646 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
647 Connections[host.id] = ThisSQL;
650 ConnectDatabases(ServerInstance, Parent);
651 Parent->ConnMutex->Unlock();
654 char FindCharId(const std::string &id)
657 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
659 if (iter->first == id)
667 ConnMap::iterator GetCharId(char id)
670 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
675 return Connections.end();
678 void NotifyMainThread(SQLConnection* connection_with_new_result)
680 /* Here we write() to the socket the main thread has open
681 * and we connect()ed back to before our thread became active.
682 * The main thread is using a nonblocking socket tied into
683 * the socket engine, so they wont block and they'll receive
684 * nearly instant notification. Because we're in a seperate
685 * thread, we can just use standard connect(), and we can
686 * block if we like. We just send the connection id of the
689 * NOTE: We only send a single char down the connection, this
690 * way we know it wont get a partial read at the other end if
691 * the system is especially congested (see bug #263).
692 * The function FindCharId translates a connection name into a
693 * one character id, and GetCharId translates a character id
694 * back into an iterator.
696 char id = FindCharId(connection_with_new_result->GetID());
697 send(QueueFD, &id, 1, 0);
702 class DispatcherThread : public Thread
706 InspIRCd* ServerInstance;
708 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
709 ~DispatcherThread() { }
713 /** Used by m_mysql to notify one thread when the other has a result
715 class Notifier : public BufferedSocket
720 Notifier(ModuleSQL* P, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), Parent(P) { }
722 virtual bool OnDataReady()
725 /* NOTE: Only a single character is read so we know we
726 * cant get a partial read. (We've been told that theres
727 * data waiting, so we wont ever get EAGAIN)
728 * The function GetCharId translates a single character
729 * back into an iterator.
732 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
734 Parent->ConnMutex->Lock();
735 ConnMap::iterator iter = GetCharId(data);
736 Parent->ConnMutex->Unlock();
737 if (iter != Connections.end())
739 Parent->ResultsMutex->Lock();
740 ResultQueue::iterator n = iter->second->rq.begin();
741 Parent->ResultsMutex->Unlock();
746 Parent->ResultsMutex->Lock();
747 iter->second->rq.pop_front();
748 Parent->ResultsMutex->Unlock();
752 /* No error, but unknown id */
756 /* Erk, error on descriptor! */
761 /** Spawn sockets from a listener
763 class MySQLListener : public ListenSocketBase
766 irc::sockets::insp_sockaddr sock_us;
771 MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
773 uslen = sizeof(sock_us);
774 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
776 throw ModuleException("Could not getsockname() to find out port number for ITC port");
780 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
782 // XXX unsafe casts suck
783 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str());
786 /* Using getsockname and ntohs, we can determine which port number we were allocated */
790 return ntohs(sock_us.sin6_port);
792 return ntohs(sock_us.sin_port);
797 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
799 ServerInstance->Modules->UseInterface("SQLutils");
801 Conf = new ConfigReader(ServerInstance);
802 PublicServerInstance = ServerInstance;
805 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
807 MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
809 MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
812 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
813 ConnMutex = ServerInstance->Mutexes->CreateMutex();
815 if (MessagePipe->GetFd() == -1)
818 ServerInstance->Modules->DoneWithInterface("SQLutils");
819 throw ModuleException("m_mysql: unable to create ITC pipe");
823 LoggingMutex->Lock();
824 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
825 LoggingMutex->Unlock();
828 Dispatcher = new DispatcherThread(ServerInstance, this);
829 ServerInstance->Threads->Create(Dispatcher);
831 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
832 QueueMutex = ServerInstance->Mutexes->CreateMutex();
834 if (!ServerInstance->Modules->PublishFeature("SQL", this))
836 /* Tell worker thread to exit NOW,
837 * Automatically joins */
843 ServerInstance->Modules->DoneWithInterface("SQLutils");
844 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
847 ServerInstance->Modules->PublishInterface("SQL", this);
848 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
849 ServerInstance->Modules->Attach(eventlist, this, 2);
852 ModuleSQL::~ModuleSQL()
855 ClearAllConnections();
857 ServerInstance->Modules->UnpublishInterface("SQL", this);
858 ServerInstance->Modules->UnpublishFeature("SQL");
859 ServerInstance->Modules->DoneWithInterface("SQLutils");
866 unsigned long ModuleSQL::NewID()
873 const char* ModuleSQL::OnRequest(Request* request)
875 if(strcmp(SQLREQID, request->GetId()) == 0)
877 SQLrequest* req = (SQLrequest*)request;
882 ConnMap::iterator iter;
884 const char* returnval = NULL;
887 if((iter = Connections.find(req->dbid)) != Connections.end())
890 iter->second->queue.push(*req);
891 returnval = SQLSUCCESS;
895 req->error.Id(SQL_BAD_DBID);
899 QueueMutex->Unlock();
907 void ModuleSQL::OnRehash(User* user, const std::string ¶meter)
912 Version ModuleSQL::GetVersion()
914 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
917 void DispatcherThread::Run()
919 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
921 /* Connect back to the Notifier */
923 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
925 /* crap, we're out of sockets... */
929 irc::sockets::insp_sockaddr addr;
932 irc::sockets::insp_aton("::1", &addr.sin6_addr);
933 addr.sin6_family = AF_FAMILY;
934 addr.sin6_port = htons(MessagePipe->GetPort());
936 irc::sockets::insp_inaddr ia;
937 irc::sockets::insp_aton("127.0.0.1", &ia);
938 addr.sin_family = AF_FAMILY;
940 addr.sin_port = htons(MessagePipe->GetPort());
943 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
945 /* wtf, we cant connect to it, but we just created it! */
949 while (this->GetExitFlag() == false)
951 if (Parent->rehashing)
954 Parent->QueueMutex->Lock();
955 Parent->rehashing = false;
956 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
957 Parent->QueueMutex->Unlock();
961 SQLConnection* conn = NULL;
962 /* XXX: Lock here for safety */
963 Parent->QueueMutex->Lock();
964 Parent->ConnMutex->Lock();
965 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
967 if (i->second->queue.totalsize())
973 Parent->ConnMutex->Unlock();
974 Parent->QueueMutex->Unlock();
977 /* Theres an item! */
980 conn->DoLeadingQuery();
983 Parent->QueueMutex->Lock();
985 Parent->QueueMutex->Unlock();
994 MODULE_INIT(ModuleSQL)