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
24 /* VERSION 2 API: With nonblocking (threaded) requests */
26 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
27 /* $CompileFlags: exec("mysql_config --include") */
28 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
29 /* $ModDep: m_sqlv2.h */
31 /* THE NONBLOCKING MYSQL API!
33 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
34 * that instead, you should thread your program. This is what i've done here to allow for
35 * asyncronous SQL requests via mysql. The way this works is as follows:
37 * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
38 * using a queue with priorities. There is a mutex on either end which prevents two threads
39 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
40 * worker thread wakes up, and checks if there is a request at the head of its queue.
41 * If there is, it processes this request, blocking the worker thread but leaving the ircd
42 * thread to go about its business as usual. During this period, the ircd thread is able
43 * to insert futher pending requests into the queue.
45 * Once the processing of a request is complete, it is removed from the incoming queue to
46 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
47 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
48 * connection ID through the connection.
50 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
51 * of the queue, and sends it on its way to the original calling module.
53 * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
54 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
55 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
56 * however, if we were to call a module's OnRequest even from within a thread which was not the
57 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
58 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
59 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
60 * gauranteed threadsafe!)
62 * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
70 typedef std::map<std::string, SQLConnection*> ConnMap;
71 static Notifier* MessagePipe = NULL;
74 class DispatcherThread;
78 class ModuleSQL : public Module
83 InspIRCd* PublicServerInstance;
86 DispatcherThread* Dispatcher;
91 ModuleSQL(InspIRCd* Me);
93 unsigned long NewID();
94 const char* OnRequest(Request* request);
95 void OnRehash(User* user, const std::string ¶meter);
101 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
102 #define mysql_field_count mysql_num_fields
105 typedef std::deque<SQLresult*> ResultQueue;
107 /** Represents a mysql result set
109 class MySQLresult : public SQLresult
112 std::vector<std::string> colnames;
113 std::vector<SQLfieldList> fieldlists;
114 SQLfieldMap* fieldmap;
115 SQLfieldMap fieldmap2;
116 SQLfieldList emptyfieldlist;
120 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
122 /* A number of affected rows from from mysql_affected_rows.
126 if (affected_rows >= 1)
128 rows = affected_rows;
129 fieldlists.resize(rows);
131 unsigned int field_count = 0;
136 while ((row = mysql_fetch_row(res)))
138 if (fieldlists.size() < (unsigned int)rows+1)
140 fieldlists.resize(fieldlists.size()+1);
143 MYSQL_FIELD *fields = mysql_fetch_fields(res);
144 if(mysql_num_fields(res) == 0)
146 if (fields && mysql_num_fields(res))
149 while (field_count < mysql_num_fields(res))
151 std::string a = (fields[field_count].name ? fields[field_count].name : "");
152 std::string b = (row[field_count] ? row[field_count] : "");
153 SQLfield sqlf(b, !row[field_count]);
154 colnames.push_back(a);
155 fieldlists[n].push_back(sqlf);
162 mysql_free_result(res);
166 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
183 return colnames.size();
186 virtual std::string ColName(int column)
188 if (column < (int)colnames.size())
190 return colnames[column];
194 throw SQLbadColName();
199 virtual int ColNum(const std::string &column)
201 for (unsigned int i = 0; i < colnames.size(); i++)
203 if (column == colnames[i])
206 throw SQLbadColName();
210 virtual SQLfield GetValue(int row, int column)
212 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
214 return fieldlists[row][column];
217 throw SQLbadColName();
219 /* XXX: We never actually get here because of the throw */
220 return SQLfield("",true);
223 virtual SQLfieldList& GetRow()
225 if (currentrow < rows)
226 return fieldlists[currentrow++];
228 return emptyfieldlist;
231 virtual SQLfieldMap& GetRowMap()
235 if (currentrow < rows)
237 for (int i = 0; i < Cols(); i++)
239 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
247 virtual SQLfieldList* GetRowPtr()
249 SQLfieldList* fieldlist = new SQLfieldList();
251 if (currentrow < rows)
253 for (int i = 0; i < Rows(); i++)
255 fieldlist->push_back(fieldlists[currentrow][i]);
262 virtual SQLfieldMap* GetRowMapPtr()
264 fieldmap = new SQLfieldMap();
266 if (currentrow < rows)
268 for (int i = 0; i < Cols(); i++)
270 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
278 virtual void Free(SQLfieldMap* fm)
283 virtual void Free(SQLfieldList* fl)
291 void NotifyMainThread(SQLConnection* connection_with_new_result);
293 /** Represents a connection to a mysql database
295 class SQLConnection : public classbase
303 std::map<std::string,std::string> thisrow;
312 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
313 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : host(hi), Enabled(false), Parent(Creator)
322 // This method connects to the database using the credentials supplied to the constructor, and returns
323 // true upon success.
326 unsigned int timeout = 1;
327 mysql_init(&connection);
328 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
329 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);
332 void DoLeadingQuery()
334 if (!CheckConnection())
337 /* Parse the command string and dispatch it to mysql */
338 SQLrequest& req = queue.front();
340 /* Pointer to the buffer we screw around with substitution in */
343 /* Pointer to the current end of query, where we append new stuff */
346 /* Total length of the unescaped parameters */
347 unsigned long paramlen;
349 /* Total length of query, used for binary-safety in mysql_real_query */
350 unsigned long querylength = 0;
354 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
356 paramlen += i->size();
359 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
360 * sizeofquery + (totalparamlength*2) + 1
362 * The +1 is for null-terminating the string for mysql_real_escape_string
365 query = new char[req.query.q.length() + (paramlen*2) + 1];
368 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
369 * the parameters into it...
372 for(unsigned long i = 0; i < req.query.q.length(); i++)
374 if(req.query.q[i] == '?')
376 /* We found a place to substitute..what fun.
377 * use mysql calls to escape and write the
378 * escaped string onto the end of our query buffer,
379 * then we "just" need to make sure queryend is
380 * pointing at the right place.
382 if(req.query.p.size())
384 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
387 req.query.p.pop_front();
394 *queryend = req.query.q[i];
402 Parent->QueueMutex->Enable(true);
404 Parent->QueueMutex->Enable(false);
406 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
408 /* Successfull query */
409 res = mysql_use_result(&connection);
410 unsigned long rows = mysql_affected_rows(&connection);
411 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
412 r->dbid = this->GetID();
413 r->query = req.query.q;
414 /* Put this new result onto the results queue.
415 * XXX: Remember to mutex the queue!
417 Parent->ResultsMutex->Enable(true);
419 Parent->ResultsMutex->Enable(false);
423 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
424 * possible error numbers and error messages */
425 SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
426 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
427 r->dbid = this->GetID();
428 r->query = req.query.q;
430 Parent->ResultsMutex->Enable(true);
432 Parent->ResultsMutex->Enable(false);
435 /* Now signal the main thread that we've got a result to process.
436 * Pass them this connection id as what to examine
441 NotifyMainThread(this);
444 bool ConnectionLost()
447 return (mysql_ping(&connection) != 0);
452 bool CheckConnection()
454 if (ConnectionLost()) {
460 std::string GetError()
462 return mysql_error(&connection);
465 const std::string& GetID()
470 std::string GetHost()
475 void SetEnable(bool Enable)
487 mysql_close(&connection);
490 const SQLhost& GetConfHost()
499 bool HasHost(const SQLhost &host)
501 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
503 if (host == iter->second->GetConfHost())
509 bool HostInConf(ConfigReader* conf, const SQLhost &h)
511 for(int i = 0; i < conf->Enumerate("database"); i++)
514 host.id = conf->ReadValue("database", "id", i);
515 host.host = conf->ReadValue("database", "hostname", i);
516 host.port = conf->ReadInteger("database", "port", i, true);
517 host.name = conf->ReadValue("database", "name", i);
518 host.user = conf->ReadValue("database", "username", i);
519 host.pass = conf->ReadValue("database", "password", i);
520 host.ssl = conf->ReadFlag("database", "ssl", i);
527 void ClearOldConnections(ConfigReader* conf)
529 ConnMap::iterator i,safei;
530 for (i = Connections.begin(); i != Connections.end(); i++)
532 if (!HostInConf(conf, i->second->GetConfHost()))
537 Connections.erase(safei);
542 void ClearAllConnections()
545 while ((i = Connections.begin()) != Connections.end())
547 Connections.erase(i);
552 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
554 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
556 if (i->second->IsEnabled())
559 i->second->SetEnable(true);
560 if (!i->second->Connect())
563 Parent->LoggingMutex->Enable(true);
564 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
565 i->second->SetEnable(false);
566 Parent->LoggingMutex->Enable(false);
571 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
573 ClearOldConnections(conf);
574 for (int j =0; j < conf->Enumerate("database"); j++)
577 host.id = conf->ReadValue("database", "id", j);
578 host.host = conf->ReadValue("database", "hostname", j);
579 host.port = conf->ReadInteger("database", "port", j, true);
580 host.name = conf->ReadValue("database", "name", j);
581 host.user = conf->ReadValue("database", "username", j);
582 host.pass = conf->ReadValue("database", "password", j);
583 host.ssl = conf->ReadFlag("database", "ssl", j);
588 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
590 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
591 Connections[host.id] = ThisSQL;
594 ConnectDatabases(ServerInstance, Parent);
597 char FindCharId(const std::string &id)
600 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
602 if (iter->first == id)
610 ConnMap::iterator GetCharId(char id)
613 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
618 return Connections.end();
621 void NotifyMainThread(SQLConnection* connection_with_new_result)
623 /* Here we write() to the socket the main thread has open
624 * and we connect()ed back to before our thread became active.
625 * The main thread is using a nonblocking socket tied into
626 * the socket engine, so they wont block and they'll receive
627 * nearly instant notification. Because we're in a seperate
628 * thread, we can just use standard connect(), and we can
629 * block if we like. We just send the connection id of the
632 * NOTE: We only send a single char down the connection, this
633 * way we know it wont get a partial read at the other end if
634 * the system is especially congested (see bug #263).
635 * The function FindCharId translates a connection name into a
636 * one character id, and GetCharId translates a character id
637 * back into an iterator.
639 char id = FindCharId(connection_with_new_result->GetID());
640 send(QueueFD, &id, 1, 0);
645 class DispatcherThread : public Thread
649 InspIRCd* ServerInstance;
651 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
652 ~DispatcherThread() { }
656 /** Used by m_mysql to notify one thread when the other has a result
658 class Notifier : public BufferedSocket
660 insp_sockaddr sock_us;
666 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
668 Notifier(InspIRCd* SI, ModuleSQL* Creator) : BufferedSocket(SI, "::1", 0, true, 3000), Parent(Creator)
670 Notifier(InspIRCd* SI, ModuleSQL* Creator) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), Parent(Creator)
673 uslen = sizeof(sock_us);
674 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
676 throw ModuleException("Could not create random listening port on localhost");
680 Notifier(InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip)
684 /* Using getsockname and ntohs, we can determine which port number we were allocated */
688 return ntohs(sock_us.sin6_port);
690 return ntohs(sock_us.sin_port);
694 virtual int OnIncomingConnection(int newsock, char* ip)
696 Notifier* n = new Notifier(this->Instance, newsock, ip);
697 n = n; /* Stop bitching at me, GCC */
701 virtual bool OnDataReady()
704 /* NOTE: Only a single character is read so we know we
705 * cant get a partial read. (We've been told that theres
706 * data waiting, so we wont ever get EAGAIN)
707 * The function GetCharId translates a single character
708 * back into an iterator.
710 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
712 ConnMap::iterator iter = GetCharId(data);
713 if (iter != Connections.end())
715 /* Lock the mutex, send back the data */
716 Parent->ResultsMutex->Enable(true);
717 ResultQueue::iterator n = iter->second->rq.begin();
720 iter->second->rq.pop_front();
721 Parent->ResultsMutex->Enable(false);
724 /* No error, but unknown id */
728 /* Erk, error on descriptor! */
734 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module::Module(Me), rehashing(false)
736 ServerInstance->Modules->UseInterface("SQLutils");
738 Conf = new ConfigReader(ServerInstance);
739 PublicServerInstance = ServerInstance;
742 MessagePipe = new Notifier(ServerInstance, this);
744 Dispatcher = new DispatcherThread(ServerInstance, this);
745 ServerInstance->Threads->Create(Dispatcher);
747 if (!ServerInstance->Modules->PublishFeature("SQL", this))
749 /* Tell worker thread to exit NOW,
750 * Automatically joins */
752 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
755 ServerInstance->Modules->PublishInterface("SQL", this);
756 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
757 ServerInstance->Modules->Attach(eventlist, this, 2);
760 ModuleSQL::~ModuleSQL()
763 ClearAllConnections();
765 ServerInstance->Modules->UnpublishInterface("SQL", this);
766 ServerInstance->Modules->UnpublishFeature("SQL");
767 ServerInstance->Modules->DoneWithInterface("SQLutils");
772 unsigned long ModuleSQL::NewID()
779 const char* ModuleSQL::OnRequest(Request* request)
781 if(strcmp(SQLREQID, request->GetId()) == 0)
783 SQLrequest* req = (SQLrequest*)request;
786 QueueMutex->Enable(true);
788 ConnMap::iterator iter;
790 const char* returnval = NULL;
792 if((iter = Connections.find(req->dbid)) != Connections.end())
795 iter->second->queue.push(*req);
796 returnval = SQLSUCCESS;
800 req->error.Id(BAD_DBID);
803 QueueMutex->Enable(false);
812 void ModuleSQL::OnRehash(User* user, const std::string ¶meter)
817 Version ModuleSQL::GetVersion()
819 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
822 void DispatcherThread::Run()
824 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
826 /* Connect back to the Notifier */
828 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
830 /* crap, we're out of sockets... */
837 insp_aton("::1", &addr.sin6_addr);
838 addr.sin6_family = AF_FAMILY;
839 addr.sin6_port = htons(MessagePipe->GetPort());
842 insp_aton("127.0.0.1", &ia);
843 addr.sin_family = AF_FAMILY;
845 addr.sin_port = htons(MessagePipe->GetPort());
848 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
850 /* wtf, we cant connect to it, but we just created it! */
854 while (this->GetExitFlag() == false)
856 if (Parent->rehashing)
859 Parent->QueueMutex->Enable(true);
860 Parent->rehashing = false;
861 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
862 Parent->QueueMutex->Enable(false);
866 SQLConnection* conn = NULL;
867 /* XXX: Lock here for safety */
868 Parent->QueueMutex->Enable(true);
869 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
871 if (i->second->queue.totalsize())
877 Parent->QueueMutex->Enable(false);
880 /* Theres an item! */
883 conn->DoLeadingQuery();
886 Parent->QueueMutex->Enable(true);
888 Parent->QueueMutex->Enable(false);
896 MODULE_INIT(ModuleSQL)