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 /* 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 pthreads, 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;
73 bool threadfinished = false;
74 static Module* SQLModule = NULL;
75 static Notifier* MessagePipe = NULL;
79 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
80 #define mysql_field_count mysql_num_fields
83 typedef std::deque<SQLresult*> ResultQueue;
85 /* A mutex to wrap around queue accesses */
86 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
88 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
90 pthread_mutex_t logging_mutex = PTHREAD_MUTEX_INITIALIZER;
92 /** Represents a mysql result set
94 class MySQLresult : public SQLresult
97 std::vector<std::string> colnames;
98 std::vector<SQLfieldList> fieldlists;
99 SQLfieldMap* fieldmap;
100 SQLfieldMap fieldmap2;
101 SQLfieldList emptyfieldlist;
105 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
107 /* A number of affected rows from from mysql_affected_rows.
111 if (affected_rows >= 1)
113 rows = affected_rows;
114 fieldlists.resize(rows);
116 unsigned int field_count = 0;
121 while ((row = mysql_fetch_row(res)))
123 if (fieldlists.size() < (unsigned int)rows+1)
125 fieldlists.resize(fieldlists.size()+1);
128 MYSQL_FIELD *fields = mysql_fetch_fields(res);
129 if(mysql_num_fields(res) == 0)
131 if (fields && mysql_num_fields(res))
134 while (field_count < mysql_num_fields(res))
136 std::string a = (fields[field_count].name ? fields[field_count].name : "");
137 std::string b = (row[field_count] ? row[field_count] : "");
138 SQLfield sqlf(b, !row[field_count]);
139 colnames.push_back(a);
140 fieldlists[n].push_back(sqlf);
147 mysql_free_result(res);
151 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
168 return colnames.size();
171 virtual std::string ColName(int column)
173 if (column < (int)colnames.size())
175 return colnames[column];
179 throw SQLbadColName();
184 virtual int ColNum(const std::string &column)
186 for (unsigned int i = 0; i < colnames.size(); i++)
188 if (column == colnames[i])
191 throw SQLbadColName();
195 virtual SQLfield GetValue(int row, int column)
197 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
199 return fieldlists[row][column];
202 throw SQLbadColName();
204 /* XXX: We never actually get here because of the throw */
205 return SQLfield("",true);
208 virtual SQLfieldList& GetRow()
210 if (currentrow < rows)
211 return fieldlists[currentrow++];
213 return emptyfieldlist;
216 virtual SQLfieldMap& GetRowMap()
220 if (currentrow < rows)
222 for (int i = 0; i < Cols(); i++)
224 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
232 virtual SQLfieldList* GetRowPtr()
234 SQLfieldList* fieldlist = new SQLfieldList();
236 if (currentrow < rows)
238 for (int i = 0; i < Rows(); i++)
240 fieldlist->push_back(fieldlists[currentrow][i]);
247 virtual SQLfieldMap* GetRowMapPtr()
249 fieldmap = new SQLfieldMap();
251 if (currentrow < rows)
253 for (int i = 0; i < Cols(); i++)
255 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
263 virtual void Free(SQLfieldMap* fm)
268 virtual void Free(SQLfieldList* fl)
276 void NotifyMainThread(SQLConnection* connection_with_new_result);
278 /** Represents a connection to a mysql database
280 class SQLConnection : public classbase
288 std::map<std::string,std::string> thisrow;
296 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
297 SQLConnection(const SQLhost &hi) : host(hi), Enabled(false)
306 // This method connects to the database using the credentials supplied to the constructor, and returns
307 // true upon success.
310 unsigned int timeout = 1;
311 mysql_init(&connection);
312 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
313 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);
316 void DoLeadingQuery()
318 if (!CheckConnection())
321 /* Parse the command string and dispatch it to mysql */
322 SQLrequest& req = queue.front();
324 /* Pointer to the buffer we screw around with substitution in */
327 /* Pointer to the current end of query, where we append new stuff */
330 /* Total length of the unescaped parameters */
331 unsigned long paramlen;
333 /* Total length of query, used for binary-safety in mysql_real_query */
334 unsigned long querylength = 0;
338 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
340 paramlen += i->size();
343 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
344 * sizeofquery + (totalparamlength*2) + 1
346 * The +1 is for null-terminating the string for mysql_real_escape_string
349 query = new char[req.query.q.length() + (paramlen*2) + 1];
352 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
353 * the parameters into it...
356 for(unsigned long i = 0; i < req.query.q.length(); i++)
358 if(req.query.q[i] == '?')
360 /* We found a place to substitute..what fun.
361 * use mysql calls to escape and write the
362 * escaped string onto the end of our query buffer,
363 * then we "just" need to make sure queryend is
364 * pointing at the right place.
366 if(req.query.p.size())
368 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
371 req.query.p.pop_front();
378 *queryend = req.query.q[i];
386 pthread_mutex_lock(&queue_mutex);
388 pthread_mutex_unlock(&queue_mutex);
390 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
392 /* Successfull query */
393 res = mysql_use_result(&connection);
394 unsigned long rows = mysql_affected_rows(&connection);
395 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
396 r->dbid = this->GetID();
397 r->query = req.query.q;
398 /* Put this new result onto the results queue.
399 * XXX: Remember to mutex the queue!
401 pthread_mutex_lock(&results_mutex);
403 pthread_mutex_unlock(&results_mutex);
407 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
408 * possible error numbers and error messages */
409 SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
410 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
411 r->dbid = this->GetID();
412 r->query = req.query.q;
414 pthread_mutex_lock(&results_mutex);
416 pthread_mutex_unlock(&results_mutex);
419 /* Now signal the main thread that we've got a result to process.
420 * Pass them this connection id as what to examine
425 NotifyMainThread(this);
428 bool ConnectionLost()
431 return (mysql_ping(&connection) != 0);
436 bool CheckConnection()
438 if (ConnectionLost()) {
444 std::string GetError()
446 return mysql_error(&connection);
449 const std::string& GetID()
454 std::string GetHost()
459 void SetEnable(bool Enable)
471 mysql_close(&connection);
474 const SQLhost& GetConfHost()
483 bool HasHost(const SQLhost &host)
485 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
487 if (host == iter->second->GetConfHost())
493 bool HostInConf(ConfigReader* conf, const SQLhost &h)
495 for(int i = 0; i < conf->Enumerate("database"); i++)
498 host.id = conf->ReadValue("database", "id", i);
499 host.host = conf->ReadValue("database", "hostname", i);
500 host.port = conf->ReadInteger("database", "port", i, true);
501 host.name = conf->ReadValue("database", "name", i);
502 host.user = conf->ReadValue("database", "username", i);
503 host.pass = conf->ReadValue("database", "password", i);
504 host.ssl = conf->ReadFlag("database", "ssl", i);
511 void ClearOldConnections(ConfigReader* conf)
513 ConnMap::iterator i,safei;
514 for (i = Connections.begin(); i != Connections.end(); i++)
516 if (!HostInConf(conf, i->second->GetConfHost()))
521 Connections.erase(safei);
526 void ClearAllConnections()
529 while ((i = Connections.begin()) != Connections.end())
531 Connections.erase(i);
536 void ConnectDatabases(InspIRCd* ServerInstance)
538 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
540 if (i->second->IsEnabled())
543 i->second->SetEnable(true);
544 if (!i->second->Connect())
547 pthread_mutex_lock(&logging_mutex);
548 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
549 i->second->SetEnable(false);
550 pthread_mutex_unlock(&logging_mutex);
555 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance)
557 ClearOldConnections(conf);
558 for (int j =0; j < conf->Enumerate("database"); j++)
561 host.id = conf->ReadValue("database", "id", j);
562 host.host = conf->ReadValue("database", "hostname", j);
563 host.port = conf->ReadInteger("database", "port", j, true);
564 host.name = conf->ReadValue("database", "name", j);
565 host.user = conf->ReadValue("database", "username", j);
566 host.pass = conf->ReadValue("database", "password", j);
567 host.ssl = conf->ReadFlag("database", "ssl", j);
572 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
574 SQLConnection* ThisSQL = new SQLConnection(host);
575 Connections[host.id] = ThisSQL;
578 ConnectDatabases(ServerInstance);
581 char FindCharId(const std::string &id)
584 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
586 if (iter->first == id)
594 ConnMap::iterator GetCharId(char id)
597 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
602 return Connections.end();
605 void NotifyMainThread(SQLConnection* connection_with_new_result)
607 /* Here we write() to the socket the main thread has open
608 * and we connect()ed back to before our thread became active.
609 * The main thread is using a nonblocking socket tied into
610 * the socket engine, so they wont block and they'll receive
611 * nearly instant notification. Because we're in a seperate
612 * thread, we can just use standard connect(), and we can
613 * block if we like. We just send the connection id of the
616 * NOTE: We only send a single char down the connection, this
617 * way we know it wont get a partial read at the other end if
618 * the system is especially congested (see bug #263).
619 * The function FindCharId translates a connection name into a
620 * one character id, and GetCharId translates a character id
621 * back into an iterator.
623 char id = FindCharId(connection_with_new_result->GetID());
624 send(QueueFD, &id, 1, 0);
627 void* DispatcherThread(void* arg);
629 /** Used by m_mysql to notify one thread when the other has a result
631 class Notifier : public BufferedSocket
633 insp_sockaddr sock_us;
639 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
641 Notifier(InspIRCd* SI) : BufferedSocket(SI, "::1", 0, true, 3000)
643 Notifier(InspIRCd* SI) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000)
646 uslen = sizeof(sock_us);
647 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
649 throw ModuleException("Could not create random listening port on localhost");
653 Notifier(InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip)
657 /* Using getsockname and ntohs, we can determine which port number we were allocated */
661 return ntohs(sock_us.sin6_port);
663 return ntohs(sock_us.sin_port);
667 virtual int OnIncomingConnection(int newsock, char* ip)
669 Notifier* n = new Notifier(this->Instance, newsock, ip);
670 n = n; /* Stop bitching at me, GCC */
674 virtual bool OnDataReady()
677 /* NOTE: Only a single character is read so we know we
678 * cant get a partial read. (We've been told that theres
679 * data waiting, so we wont ever get EAGAIN)
680 * The function GetCharId translates a single character
681 * back into an iterator.
683 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
685 ConnMap::iterator iter = GetCharId(data);
686 if (iter != Connections.end())
688 /* Lock the mutex, send back the data */
689 pthread_mutex_lock(&results_mutex);
690 ResultQueue::iterator n = iter->second->rq.begin();
693 iter->second->rq.pop_front();
694 pthread_mutex_unlock(&results_mutex);
697 /* No error, but unknown id */
701 /* Erk, error on descriptor! */
708 class ModuleSQL : public Module
713 InspIRCd* PublicServerInstance;
714 pthread_t Dispatcher;
718 ModuleSQL(InspIRCd* Me)
719 : Module::Module(Me), rehashing(false)
721 ServerInstance->Modules->UseInterface("SQLutils");
723 Conf = new ConfigReader(ServerInstance);
724 PublicServerInstance = ServerInstance;
728 MessagePipe = new Notifier(ServerInstance);
730 pthread_attr_t attribs;
731 pthread_attr_init(&attribs);
732 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_JOINABLE);
733 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
735 throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
737 pthread_attr_destroy(&attribs);
739 if (!ServerInstance->Modules->PublishFeature("SQL", this))
741 /* Tell worker thread to exit NOW */
745 rc = pthread_join(Dispatcher, &status);
748 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Error code from pthread_join() is %d", rc);
750 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
753 ServerInstance->Modules->PublishInterface("SQL", this);
754 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
755 ServerInstance->Modules->Attach(eventlist, this, 2);
763 rc = pthread_join(Dispatcher, &status);
766 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Error code from pthread_join() is %d", rc);
768 ClearAllConnections();
770 ServerInstance->Modules->UnpublishInterface("SQL", this);
771 ServerInstance->Modules->UnpublishFeature("SQL");
772 ServerInstance->Modules->DoneWithInterface("SQLutils");
777 unsigned long NewID()
784 virtual const char* OnRequest(Request* request)
786 if(strcmp(SQLREQID, request->GetId()) == 0)
788 SQLrequest* req = (SQLrequest*)request;
791 pthread_mutex_lock(&queue_mutex);
793 ConnMap::iterator iter;
795 const char* returnval = NULL;
797 if((iter = Connections.find(req->dbid)) != Connections.end())
800 iter->second->queue.push(*req);
801 returnval = SQLSUCCESS;
805 req->error.Id(BAD_DBID);
808 pthread_mutex_unlock(&queue_mutex);
817 virtual void OnRehash(User* user, const std::string ¶meter)
822 virtual Version GetVersion()
824 return Version(1,2,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
829 void* DispatcherThread(void* arg)
831 ModuleSQL* thismodule = (ModuleSQL*)arg;
832 LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance);
834 /* Connect back to the Notifier */
836 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
838 /* crap, we're out of sockets... */
845 insp_aton("::1", &addr.sin6_addr);
846 addr.sin6_family = AF_FAMILY;
847 addr.sin6_port = htons(MessagePipe->GetPort());
850 insp_aton("127.0.0.1", &ia);
851 addr.sin_family = AF_FAMILY;
853 addr.sin_port = htons(MessagePipe->GetPort());
856 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
858 /* wtf, we cant connect to it, but we just created it! */
864 if (thismodule->rehashing)
867 pthread_mutex_lock(&queue_mutex);
868 thismodule->rehashing = false;
869 LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance);
870 pthread_mutex_unlock(&queue_mutex);
874 SQLConnection* conn = NULL;
875 /* XXX: Lock here for safety */
876 pthread_mutex_lock(&queue_mutex);
877 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
879 if (i->second->queue.totalsize())
885 pthread_mutex_unlock(&queue_mutex);
888 /* Theres an item! */
891 conn->DoLeadingQuery();
894 pthread_mutex_lock(&queue_mutex);
896 pthread_mutex_unlock(&queue_mutex);
903 pthread_exit((void *) 0);
906 MODULE_INIT(ModuleSQL)