1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
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 pthreads, 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;
72 static Module* SQLModule = NULL;
73 static Notifier* MessagePipe = NULL;
77 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
78 #define mysql_field_count mysql_num_fields
81 typedef std::deque<SQLresult*> ResultQueue;
83 /* A mutex to wrap around queue accesses */
84 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
86 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
88 pthread_mutex_t logging_mutex = PTHREAD_MUTEX_INITIALIZER;
90 /** Represents a mysql result set
92 class MySQLresult : public SQLresult
95 std::vector<std::string> colnames;
96 std::vector<SQLfieldList> fieldlists;
97 SQLfieldMap* fieldmap;
98 SQLfieldMap fieldmap2;
99 SQLfieldList emptyfieldlist;
103 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL)
105 /* A number of affected rows from from mysql_affected_rows.
109 if (affected_rows >= 1)
111 rows = affected_rows;
112 fieldlists.resize(rows);
114 unsigned int field_count = 0;
119 while ((row = mysql_fetch_row(res)))
121 if (fieldlists.size() < (unsigned int)rows+1)
123 fieldlists.resize(fieldlists.size()+1);
126 MYSQL_FIELD *fields = mysql_fetch_fields(res);
127 if(mysql_num_fields(res) == 0)
129 if (fields && mysql_num_fields(res))
132 while (field_count < mysql_num_fields(res))
134 std::string a = (fields[field_count].name ? fields[field_count].name : "");
135 std::string b = (row[field_count] ? row[field_count] : "");
136 SQLfield sqlf(b, !row[field_count]);
137 colnames.push_back(a);
138 fieldlists[n].push_back(sqlf);
145 mysql_free_result(res);
149 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0)
166 return colnames.size();
169 virtual std::string ColName(int column)
171 if (column < (int)colnames.size())
173 return colnames[column];
177 throw SQLbadColName();
182 virtual int ColNum(const std::string &column)
184 for (unsigned int i = 0; i < colnames.size(); i++)
186 if (column == colnames[i])
189 throw SQLbadColName();
193 virtual SQLfield GetValue(int row, int column)
195 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
197 return fieldlists[row][column];
200 throw SQLbadColName();
202 /* XXX: We never actually get here because of the throw */
203 return SQLfield("",true);
206 virtual SQLfieldList& GetRow()
208 if (currentrow < rows)
209 return fieldlists[currentrow];
211 return emptyfieldlist;
214 virtual SQLfieldMap& GetRowMap()
218 if (currentrow < rows)
220 for (int i = 0; i < Cols(); i++)
222 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
230 virtual SQLfieldList* GetRowPtr()
232 SQLfieldList* fieldlist = new SQLfieldList();
234 if (currentrow < rows)
236 for (int i = 0; i < Rows(); i++)
238 fieldlist->push_back(fieldlists[currentrow][i]);
245 virtual SQLfieldMap* GetRowMapPtr()
247 fieldmap = new SQLfieldMap();
249 if (currentrow < rows)
251 for (int i = 0; i < Cols(); i++)
253 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
261 virtual void Free(SQLfieldMap* fm)
266 virtual void Free(SQLfieldList* fl)
274 void NotifyMainThread(SQLConnection* connection_with_new_result);
276 /** Represents a connection to a mysql database
278 class SQLConnection : public classbase
286 std::map<std::string,std::string> thisrow;
294 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
295 SQLConnection(const SQLhost &hi) : host(hi), Enabled(false)
304 // This method connects to the database using the credentials supplied to the constructor, and returns
305 // true upon success.
308 unsigned int timeout = 1;
309 mysql_init(&connection);
310 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
311 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);
314 void DoLeadingQuery()
316 if (!CheckConnection())
319 /* Parse the command string and dispatch it to mysql */
320 SQLrequest& req = queue.front();
322 /* Pointer to the buffer we screw around with substitution in */
325 /* Pointer to the current end of query, where we append new stuff */
328 /* Total length of the unescaped parameters */
329 unsigned long paramlen;
331 /* Total length of query, used for binary-safety in mysql_real_query */
332 unsigned long querylength = 0;
336 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
338 paramlen += i->size();
341 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
342 * sizeofquery + (totalparamlength*2) + 1
344 * The +1 is for null-terminating the string for mysql_real_escape_string
347 query = new char[req.query.q.length() + (paramlen*2) + 1];
350 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
351 * the parameters into it...
354 for(unsigned long i = 0; i < req.query.q.length(); i++)
356 if(req.query.q[i] == '?')
358 /* We found a place to substitute..what fun.
359 * use mysql calls to escape and write the
360 * escaped string onto the end of our query buffer,
361 * then we "just" need to make sure queryend is
362 * pointing at the right place.
364 if(req.query.p.size())
366 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
369 req.query.p.pop_front();
376 *queryend = req.query.q[i];
384 pthread_mutex_lock(&queue_mutex);
386 pthread_mutex_unlock(&queue_mutex);
388 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
390 /* Successfull query */
391 res = mysql_use_result(&connection);
392 unsigned long rows = mysql_affected_rows(&connection);
393 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
394 r->dbid = this->GetID();
395 r->query = req.query.q;
396 /* Put this new result onto the results queue.
397 * XXX: Remember to mutex the queue!
399 pthread_mutex_lock(&results_mutex);
401 pthread_mutex_unlock(&results_mutex);
405 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
406 * possible error numbers and error messages */
407 SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
408 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
409 r->dbid = this->GetID();
410 r->query = req.query.q;
412 pthread_mutex_lock(&results_mutex);
414 pthread_mutex_unlock(&results_mutex);
417 /* Now signal the main thread that we've got a result to process.
418 * Pass them this connection id as what to examine
423 NotifyMainThread(this);
426 bool ConnectionLost()
429 return (mysql_ping(&connection) != 0);
434 bool CheckConnection()
436 if (ConnectionLost()) {
442 std::string GetError()
444 return mysql_error(&connection);
447 const std::string& GetID()
452 std::string GetHost()
457 void SetEnable(bool Enable)
469 mysql_close(&connection);
472 const SQLhost& GetConfHost()
481 bool HasHost(const SQLhost &host)
483 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
485 if (host == iter->second->GetConfHost())
491 bool HostInConf(ConfigReader* conf, const SQLhost &h)
493 for(int i = 0; i < conf->Enumerate("database"); i++)
496 host.id = conf->ReadValue("database", "id", i);
497 host.host = conf->ReadValue("database", "hostname", i);
498 host.port = conf->ReadInteger("database", "port", i, true);
499 host.name = conf->ReadValue("database", "name", i);
500 host.user = conf->ReadValue("database", "username", i);
501 host.pass = conf->ReadValue("database", "password", i);
502 host.ssl = conf->ReadFlag("database", "ssl", i);
509 void ClearOldConnections(ConfigReader* conf)
511 ConnMap::iterator i,safei;
512 for (i = Connections.begin(); i != Connections.end(); i++)
514 if (!HostInConf(conf, i->second->GetConfHost()))
519 Connections.erase(safei);
524 void ClearAllConnections()
527 while ((i = Connections.begin()) != Connections.end())
529 Connections.erase(i);
534 void ConnectDatabases(InspIRCd* ServerInstance)
536 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
538 if (i->second->IsEnabled())
541 i->second->SetEnable(true);
542 if (!i->second->Connect())
545 pthread_mutex_lock(&logging_mutex);
546 ServerInstance->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
547 i->second->SetEnable(false);
548 pthread_mutex_unlock(&logging_mutex);
553 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance)
555 ClearOldConnections(conf);
556 for (int j =0; j < conf->Enumerate("database"); j++)
559 host.id = conf->ReadValue("database", "id", j);
560 host.host = conf->ReadValue("database", "hostname", j);
561 host.port = conf->ReadInteger("database", "port", j, true);
562 host.name = conf->ReadValue("database", "name", j);
563 host.user = conf->ReadValue("database", "username", j);
564 host.pass = conf->ReadValue("database", "password", j);
565 host.ssl = conf->ReadFlag("database", "ssl", j);
570 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
572 SQLConnection* ThisSQL = new SQLConnection(host);
573 Connections[host.id] = ThisSQL;
576 ConnectDatabases(ServerInstance);
579 void NotifyMainThread(SQLConnection* connection_with_new_result)
581 /* Here we write() to the socket the main thread has open
582 * and we connect()ed back to before our thread became active.
583 * The main thread is using a nonblocking socket tied into
584 * the socket engine, so they wont block and they'll receive
585 * nearly instant notification. Because we're in a seperate
586 * thread, we can just use standard connect(), and we can
587 * block if we like. We just send the connection id of the
590 send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0);
593 void* DispatcherThread(void* arg);
595 /** Used by m_mysql to notify one thread when the other has a result
597 class Notifier : public InspSocket
599 insp_sockaddr sock_us;
605 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
607 Notifier(InspIRCd* SI) : InspSocket(SI, "::1", 0, true, 3000)
609 Notifier(InspIRCd* SI) : InspSocket(SI, "127.0.0.1", 0, true, 3000)
612 uslen = sizeof(sock_us);
613 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
615 throw ModuleException("Could not create random listening port on localhost");
619 Notifier(InspIRCd* SI, int newfd, char* ip) : InspSocket(SI, newfd, ip)
623 /* Using getsockname and ntohs, we can determine which port number we were allocated */
627 return ntohs(sock_us.sin6_port);
629 return ntohs(sock_us.sin_port);
633 virtual int OnIncomingConnection(int newsock, char* ip)
635 Notifier* n = new Notifier(this->Instance, newsock, ip);
636 n = n; /* Stop bitching at me, GCC */
640 virtual bool OnDataReady()
642 char* data = this->Read();
643 ConnMap::iterator iter;
647 /* We expect to be sent a null terminated string */
648 if((iter = Connections.find(data)) != Connections.end())
650 /* Lock the mutex, send back the data */
651 pthread_mutex_lock(&results_mutex);
652 ResultQueue::iterator n = iter->second->rq.begin();
654 iter->second->rq.pop_front();
655 pthread_mutex_unlock(&results_mutex);
666 class ModuleSQL : public Module
671 InspIRCd* PublicServerInstance;
672 pthread_t Dispatcher;
676 ModuleSQL(InspIRCd* Me)
677 : Module::Module(Me), rehashing(false)
679 ServerInstance->UseInterface("SQLutils");
681 Conf = new ConfigReader(ServerInstance);
682 PublicServerInstance = ServerInstance;
686 MessagePipe = new Notifier(ServerInstance);
688 pthread_attr_t attribs;
689 pthread_attr_init(&attribs);
690 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
691 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
693 throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
696 if (!ServerInstance->PublishFeature("SQL", this))
698 /* Tell worker thread to exit NOW */
700 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
703 ServerInstance->PublishInterface("SQL", this);
709 ClearAllConnections();
711 ServerInstance->UnpublishInterface("SQL", this);
712 ServerInstance->UnpublishFeature("SQL");
713 ServerInstance->DoneWithInterface("SQLutils");
717 void Implements(char* List)
719 List[I_OnRehash] = List[I_OnRequest] = 1;
722 unsigned long NewID()
729 char* OnRequest(Request* request)
731 if(strcmp(SQLREQID, request->GetId()) == 0)
733 SQLrequest* req = (SQLrequest*)request;
736 pthread_mutex_lock(&queue_mutex);
738 ConnMap::iterator iter;
740 char* returnval = NULL;
742 if((iter = Connections.find(req->dbid)) != Connections.end())
745 iter->second->queue.push(*req);
746 returnval = SQLSUCCESS;
750 req->error.Id(BAD_DBID);
753 pthread_mutex_unlock(&queue_mutex);
762 virtual void OnRehash(userrec* user, const std::string ¶meter)
767 virtual Version GetVersion()
769 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
774 void* DispatcherThread(void* arg)
776 ModuleSQL* thismodule = (ModuleSQL*)arg;
777 LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance);
779 /* Connect back to the Notifier */
781 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
783 /* crap, we're out of sockets... */
790 insp_aton("::1", &addr.sin6_addr);
791 addr.sin6_family = AF_FAMILY;
792 addr.sin6_port = htons(MessagePipe->GetPort());
795 insp_aton("127.0.0.1", &ia);
796 addr.sin_family = AF_FAMILY;
798 addr.sin_port = htons(MessagePipe->GetPort());
801 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
803 /* wtf, we cant connect to it, but we just created it! */
809 if (thismodule->rehashing)
812 pthread_mutex_lock(&queue_mutex);
813 thismodule->rehashing = false;
814 LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance);
815 pthread_mutex_unlock(&queue_mutex);
819 SQLConnection* conn = NULL;
820 /* XXX: Lock here for safety */
821 pthread_mutex_lock(&queue_mutex);
822 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
824 if (i->second->queue.totalsize())
830 pthread_mutex_unlock(&queue_mutex);
833 /* Theres an item! */
836 conn->DoLeadingQuery();
839 pthread_mutex_lock(&queue_mutex);
841 pthread_mutex_unlock(&queue_mutex);
852 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
854 class ModuleSQLFactory : public ModuleFactory
865 virtual Module * CreateModule(InspIRCd* Me)
867 return new ModuleSQL(Me);
873 extern "C" void * init_module( void )
875 return new ModuleSQLFactory;