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
74 typedef std::map<std::string, SQLConnection*> ConnMap;
75 static MySQLListener *MessagePipe = NULL;
78 class DispatcherThread;
82 class ModuleSQL : public Module
87 InspIRCd* PublicServerInstance;
90 DispatcherThread* Dispatcher;
96 ModuleSQL(InspIRCd* Me);
98 unsigned long NewID();
99 const char* OnRequest(Request* request);
100 void OnRehash(User* user, const std::string ¶meter);
101 Version GetVersion();
106 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
107 #define mysql_field_count mysql_num_fields
110 typedef std::deque<SQLresult*> ResultQueue;
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);
171 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
188 return colnames.size();
191 virtual std::string ColName(int column)
193 if (column < (int)colnames.size())
195 return colnames[column];
199 throw SQLbadColName();
204 virtual int ColNum(const std::string &column)
206 for (unsigned int i = 0; i < colnames.size(); i++)
208 if (column == colnames[i])
211 throw SQLbadColName();
215 virtual SQLfield GetValue(int row, int column)
217 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
219 return fieldlists[row][column];
222 throw SQLbadColName();
224 /* XXX: We never actually get here because of the throw */
225 return SQLfield("",true);
228 virtual SQLfieldList& GetRow()
230 if (currentrow < rows)
231 return fieldlists[currentrow++];
233 return emptyfieldlist;
236 virtual SQLfieldMap& GetRowMap()
240 if (currentrow < rows)
242 for (int i = 0; i < Cols(); i++)
244 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
252 virtual SQLfieldList* GetRowPtr()
254 SQLfieldList* fieldlist = new SQLfieldList();
256 if (currentrow < rows)
258 for (int i = 0; i < Rows(); i++)
260 fieldlist->push_back(fieldlists[currentrow][i]);
267 virtual SQLfieldMap* GetRowMapPtr()
269 fieldmap = new SQLfieldMap();
271 if (currentrow < rows)
273 for (int i = 0; i < Cols(); i++)
275 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
283 virtual void Free(SQLfieldMap* fm)
288 virtual void Free(SQLfieldList* fl)
296 void NotifyMainThread(SQLConnection* connection_with_new_result);
298 /** Represents a connection to a mysql database
300 class SQLConnection : public classbase
308 std::map<std::string,std::string> thisrow;
317 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
318 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : host(hi), Enabled(false), Parent(Creator)
327 // This method connects to the database using the credentials supplied to the constructor, and returns
328 // true upon success.
331 unsigned int timeout = 1;
332 mysql_init(&connection);
333 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
334 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);
337 void DoLeadingQuery()
339 if (!CheckConnection())
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 paramlen;
354 /* Total length of query, used for binary-safety in mysql_real_query */
355 unsigned long querylength = 0;
359 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
361 paramlen += i->size();
364 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
365 * sizeofquery + (totalparamlength*2) + 1
367 * The +1 is for null-terminating the string for mysql_real_escape_string
370 query = new char[req.query.q.length() + (paramlen*2) + 1];
373 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
374 * the parameters into it...
377 for(unsigned long i = 0; i < req.query.q.length(); i++)
379 if(req.query.q[i] == '?')
381 /* We found a place to substitute..what fun.
382 * use mysql calls to escape and write the
383 * escaped string onto the end of our query buffer,
384 * then we "just" need to make sure queryend is
385 * pointing at the right place.
387 if(req.query.p.size())
389 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
392 req.query.p.pop_front();
399 *queryend = req.query.q[i];
407 Parent->QueueMutex->Lock();
409 Parent->QueueMutex->Unlock();
411 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
413 /* Successfull query */
414 res = mysql_use_result(&connection);
415 unsigned long rows = mysql_affected_rows(&connection);
416 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
417 r->dbid = this->GetID();
418 r->query = req.query.q;
419 /* Put this new result onto the results queue.
420 * XXX: Remember to mutex the queue!
422 Parent->ResultsMutex->Lock();
424 Parent->ResultsMutex->Unlock();
428 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
429 * possible error numbers and error messages */
430 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
431 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
432 r->dbid = this->GetID();
433 r->query = req.query.q;
435 Parent->ResultsMutex->Lock();
437 Parent->ResultsMutex->Unlock();
440 /* Now signal the main thread that we've got a result to process.
441 * Pass them this connection id as what to examine
446 NotifyMainThread(this);
449 bool ConnectionLost()
452 return (mysql_ping(&connection) != 0);
457 bool CheckConnection()
459 if (ConnectionLost()) {
465 std::string GetError()
467 return mysql_error(&connection);
470 const std::string& GetID()
475 std::string GetHost()
480 void SetEnable(bool Enable)
492 mysql_close(&connection);
495 const SQLhost& GetConfHost()
504 bool HasHost(const SQLhost &host)
506 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
508 if (host == iter->second->GetConfHost())
514 bool HostInConf(ConfigReader* conf, const SQLhost &h)
516 for(int i = 0; i < conf->Enumerate("database"); i++)
519 host.id = conf->ReadValue("database", "id", i);
520 host.host = conf->ReadValue("database", "hostname", i);
521 host.port = conf->ReadInteger("database", "port", i, true);
522 host.name = conf->ReadValue("database", "name", i);
523 host.user = conf->ReadValue("database", "username", i);
524 host.pass = conf->ReadValue("database", "password", i);
525 host.ssl = conf->ReadFlag("database", "ssl", i);
532 void ClearOldConnections(ConfigReader* conf)
534 ConnMap::iterator i,safei;
535 for (i = Connections.begin(); i != Connections.end(); i++)
537 if (!HostInConf(conf, i->second->GetConfHost()))
542 Connections.erase(safei);
547 void ClearAllConnections()
550 while ((i = Connections.begin()) != Connections.end())
552 Connections.erase(i);
557 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
559 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
561 if (i->second->IsEnabled())
564 i->second->SetEnable(true);
565 if (!i->second->Connect())
568 Parent->LoggingMutex->Lock();
569 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
570 i->second->SetEnable(false);
571 Parent->LoggingMutex->Unlock();
576 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
578 Parent->ConnMutex->Lock();
579 ClearOldConnections(conf);
580 for (int j =0; j < conf->Enumerate("database"); j++)
583 host.id = conf->ReadValue("database", "id", j);
584 host.host = conf->ReadValue("database", "hostname", j);
585 host.port = conf->ReadInteger("database", "port", j, true);
586 host.name = conf->ReadValue("database", "name", j);
587 host.user = conf->ReadValue("database", "username", j);
588 host.pass = conf->ReadValue("database", "password", j);
589 host.ssl = conf->ReadFlag("database", "ssl", j);
594 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
596 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
597 Connections[host.id] = ThisSQL;
600 ConnectDatabases(ServerInstance, Parent);
601 Parent->ConnMutex->Unlock();
604 char FindCharId(const std::string &id)
607 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
609 if (iter->first == id)
617 ConnMap::iterator GetCharId(char id)
620 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
625 return Connections.end();
628 void NotifyMainThread(SQLConnection* connection_with_new_result)
630 /* Here we write() to the socket the main thread has open
631 * and we connect()ed back to before our thread became active.
632 * The main thread is using a nonblocking socket tied into
633 * the socket engine, so they wont block and they'll receive
634 * nearly instant notification. Because we're in a seperate
635 * thread, we can just use standard connect(), and we can
636 * block if we like. We just send the connection id of the
639 * NOTE: We only send a single char down the connection, this
640 * way we know it wont get a partial read at the other end if
641 * the system is especially congested (see bug #263).
642 * The function FindCharId translates a connection name into a
643 * one character id, and GetCharId translates a character id
644 * back into an iterator.
646 char id = FindCharId(connection_with_new_result->GetID());
647 send(QueueFD, &id, 1, 0);
652 class DispatcherThread : public Thread
656 InspIRCd* ServerInstance;
658 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
659 ~DispatcherThread() { }
663 /** Used by m_mysql to notify one thread when the other has a result
665 class Notifier : public BufferedSocket
670 Notifier(ModuleSQL* P, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), Parent(P) { }
672 virtual bool OnDataReady()
675 /* NOTE: Only a single character is read so we know we
676 * cant get a partial read. (We've been told that theres
677 * data waiting, so we wont ever get EAGAIN)
678 * The function GetCharId translates a single character
679 * back into an iterator.
682 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
684 Parent->ConnMutex->Lock();
685 ConnMap::iterator iter = GetCharId(data);
686 if (iter != Connections.end())
688 /* Lock the mutex, send back the data */
689 Parent->ResultsMutex->Lock();
690 ResultQueue::iterator n = iter->second->rq.begin();
693 iter->second->rq.pop_front();
694 Parent->ResultsMutex->Unlock();
695 Parent->ConnMutex->Unlock();
698 /* No error, but unknown id */
699 Parent->ConnMutex->Unlock();
703 /* Erk, error on descriptor! */
708 /** Spawn sockets from a listener
710 class MySQLListener : public ListenSocketBase
713 insp_sockaddr sock_us;
718 MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
720 uslen = sizeof(sock_us);
721 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
723 throw ModuleException("Could not getsockname() to find out port number for ITC port");
727 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
729 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
732 /* Using getsockname and ntohs, we can determine which port number we were allocated */
736 return ntohs(sock_us.sin6_port);
738 return ntohs(sock_us.sin_port);
743 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
745 ServerInstance->Modules->UseInterface("SQLutils");
747 Conf = new ConfigReader(ServerInstance);
748 PublicServerInstance = ServerInstance;
751 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
753 MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
755 MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
758 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
759 ConnMutex = ServerInstance->Mutexes->CreateMutex();
761 if (MessagePipe->GetFd() == -1)
764 throw ModuleException("m_mysql: unable to create ITC pipe");
768 LoggingMutex->Lock();
769 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
770 LoggingMutex->Unlock();
773 Dispatcher = new DispatcherThread(ServerInstance, this);
774 ServerInstance->Threads->Create(Dispatcher);
776 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
777 QueueMutex = ServerInstance->Mutexes->CreateMutex();
779 if (!ServerInstance->Modules->PublishFeature("SQL", this))
781 /* Tell worker thread to exit NOW,
782 * Automatically joins */
784 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
787 ServerInstance->Modules->PublishInterface("SQL", this);
788 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
789 ServerInstance->Modules->Attach(eventlist, this, 2);
792 ModuleSQL::~ModuleSQL()
795 ClearAllConnections();
797 ServerInstance->Modules->UnpublishInterface("SQL", this);
798 ServerInstance->Modules->UnpublishFeature("SQL");
799 ServerInstance->Modules->DoneWithInterface("SQLutils");
806 unsigned long ModuleSQL::NewID()
813 const char* ModuleSQL::OnRequest(Request* request)
815 if(strcmp(SQLREQID, request->GetId()) == 0)
817 SQLrequest* req = (SQLrequest*)request;
822 ConnMap::iterator iter;
824 const char* returnval = NULL;
827 if((iter = Connections.find(req->dbid)) != Connections.end())
830 iter->second->queue.push(*req);
831 returnval = SQLSUCCESS;
835 req->error.Id(SQL_BAD_DBID);
839 QueueMutex->Unlock();
847 void ModuleSQL::OnRehash(User* user, const std::string ¶meter)
852 Version ModuleSQL::GetVersion()
854 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
857 void DispatcherThread::Run()
859 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
861 /* Connect back to the Notifier */
863 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
865 /* crap, we're out of sockets... */
872 insp_aton("::1", &addr.sin6_addr);
873 addr.sin6_family = AF_FAMILY;
874 addr.sin6_port = htons(MessagePipe->GetPort());
877 insp_aton("127.0.0.1", &ia);
878 addr.sin_family = AF_FAMILY;
880 addr.sin_port = htons(MessagePipe->GetPort());
883 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
885 /* wtf, we cant connect to it, but we just created it! */
889 while (this->GetExitFlag() == false)
891 if (Parent->rehashing)
894 Parent->QueueMutex->Lock();
895 Parent->rehashing = false;
896 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
897 Parent->QueueMutex->Unlock();
901 SQLConnection* conn = NULL;
902 /* XXX: Lock here for safety */
903 Parent->QueueMutex->Lock();
904 Parent->ConnMutex->Lock();
905 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
907 if (i->second->queue.totalsize())
913 Parent->ConnMutex->Unlock();
914 Parent->QueueMutex->Unlock();
917 /* Theres an item! */
920 conn->DoLeadingQuery();
923 Parent->QueueMutex->Lock();
925 Parent->QueueMutex->Unlock();
933 MODULE_INIT(ModuleSQL)