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 Notifier* MessagePipe = NULL;
78 class DispatcherThread;
82 class ModuleSQL : public Module
87 InspIRCd* PublicServerInstance;
90 DispatcherThread* Dispatcher;
95 ModuleSQL(InspIRCd* Me);
97 unsigned long NewID();
98 const char* OnRequest(Request* request);
99 void OnRehash(User* user, const std::string ¶meter);
100 Version GetVersion();
105 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
106 #define mysql_field_count mysql_num_fields
109 typedef std::deque<SQLresult*> ResultQueue;
111 /** Represents a mysql result set
113 class MySQLresult : public SQLresult
116 std::vector<std::string> colnames;
117 std::vector<SQLfieldList> fieldlists;
118 SQLfieldMap* fieldmap;
119 SQLfieldMap fieldmap2;
120 SQLfieldList emptyfieldlist;
124 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
126 /* A number of affected rows from from mysql_affected_rows.
130 if (affected_rows >= 1)
132 rows = affected_rows;
133 fieldlists.resize(rows);
135 unsigned int field_count = 0;
140 while ((row = mysql_fetch_row(res)))
142 if (fieldlists.size() < (unsigned int)rows+1)
144 fieldlists.resize(fieldlists.size()+1);
147 MYSQL_FIELD *fields = mysql_fetch_fields(res);
148 if(mysql_num_fields(res) == 0)
150 if (fields && mysql_num_fields(res))
153 while (field_count < mysql_num_fields(res))
155 std::string a = (fields[field_count].name ? fields[field_count].name : "");
156 std::string b = (row[field_count] ? row[field_count] : "");
157 SQLfield sqlf(b, !row[field_count]);
158 colnames.push_back(a);
159 fieldlists[n].push_back(sqlf);
166 mysql_free_result(res);
170 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
187 return colnames.size();
190 virtual std::string ColName(int column)
192 if (column < (int)colnames.size())
194 return colnames[column];
198 throw SQLbadColName();
203 virtual int ColNum(const std::string &column)
205 for (unsigned int i = 0; i < colnames.size(); i++)
207 if (column == colnames[i])
210 throw SQLbadColName();
214 virtual SQLfield GetValue(int row, int column)
216 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
218 return fieldlists[row][column];
221 throw SQLbadColName();
223 /* XXX: We never actually get here because of the throw */
224 return SQLfield("",true);
227 virtual SQLfieldList& GetRow()
229 if (currentrow < rows)
230 return fieldlists[currentrow++];
232 return emptyfieldlist;
235 virtual SQLfieldMap& GetRowMap()
239 if (currentrow < rows)
241 for (int i = 0; i < Cols(); i++)
243 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
251 virtual SQLfieldList* GetRowPtr()
253 SQLfieldList* fieldlist = new SQLfieldList();
255 if (currentrow < rows)
257 for (int i = 0; i < Rows(); i++)
259 fieldlist->push_back(fieldlists[currentrow][i]);
266 virtual SQLfieldMap* GetRowMapPtr()
268 fieldmap = new SQLfieldMap();
270 if (currentrow < rows)
272 for (int i = 0; i < Cols(); i++)
274 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
282 virtual void Free(SQLfieldMap* fm)
287 virtual void Free(SQLfieldList* fl)
295 void NotifyMainThread(SQLConnection* connection_with_new_result);
297 /** Represents a connection to a mysql database
299 class SQLConnection : public classbase
307 std::map<std::string,std::string> thisrow;
316 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
317 SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : host(hi), Enabled(false), Parent(Creator)
326 // This method connects to the database using the credentials supplied to the constructor, and returns
327 // true upon success.
330 unsigned int timeout = 1;
331 mysql_init(&connection);
332 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
333 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);
336 void DoLeadingQuery()
338 if (!CheckConnection())
341 /* Parse the command string and dispatch it to mysql */
342 SQLrequest& req = queue.front();
344 /* Pointer to the buffer we screw around with substitution in */
347 /* Pointer to the current end of query, where we append new stuff */
350 /* Total length of the unescaped parameters */
351 unsigned long paramlen;
353 /* Total length of query, used for binary-safety in mysql_real_query */
354 unsigned long querylength = 0;
358 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
360 paramlen += i->size();
363 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
364 * sizeofquery + (totalparamlength*2) + 1
366 * The +1 is for null-terminating the string for mysql_real_escape_string
369 query = new char[req.query.q.length() + (paramlen*2) + 1];
372 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
373 * the parameters into it...
376 for(unsigned long i = 0; i < req.query.q.length(); i++)
378 if(req.query.q[i] == '?')
380 /* We found a place to substitute..what fun.
381 * use mysql calls to escape and write the
382 * escaped string onto the end of our query buffer,
383 * then we "just" need to make sure queryend is
384 * pointing at the right place.
386 if(req.query.p.size())
388 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
391 req.query.p.pop_front();
398 *queryend = req.query.q[i];
406 Parent->QueueMutex->Lock();
408 Parent->QueueMutex->Unlock();
410 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
412 /* Successfull query */
413 res = mysql_use_result(&connection);
414 unsigned long rows = mysql_affected_rows(&connection);
415 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
416 r->dbid = this->GetID();
417 r->query = req.query.q;
418 /* Put this new result onto the results queue.
419 * XXX: Remember to mutex the queue!
421 Parent->ResultsMutex->Lock();
423 Parent->ResultsMutex->Unlock();
427 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
428 * possible error numbers and error messages */
429 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
430 MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
431 r->dbid = this->GetID();
432 r->query = req.query.q;
434 Parent->ResultsMutex->Lock();
436 Parent->ResultsMutex->Unlock();
439 /* Now signal the main thread that we've got a result to process.
440 * Pass them this connection id as what to examine
445 NotifyMainThread(this);
448 bool ConnectionLost()
451 return (mysql_ping(&connection) != 0);
456 bool CheckConnection()
458 if (ConnectionLost()) {
464 std::string GetError()
466 return mysql_error(&connection);
469 const std::string& GetID()
474 std::string GetHost()
479 void SetEnable(bool Enable)
491 mysql_close(&connection);
494 const SQLhost& GetConfHost()
503 bool HasHost(const SQLhost &host)
505 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
507 if (host == iter->second->GetConfHost())
513 bool HostInConf(ConfigReader* conf, const SQLhost &h)
515 for(int i = 0; i < conf->Enumerate("database"); i++)
518 host.id = conf->ReadValue("database", "id", i);
519 host.host = conf->ReadValue("database", "hostname", i);
520 host.port = conf->ReadInteger("database", "port", i, true);
521 host.name = conf->ReadValue("database", "name", i);
522 host.user = conf->ReadValue("database", "username", i);
523 host.pass = conf->ReadValue("database", "password", i);
524 host.ssl = conf->ReadFlag("database", "ssl", i);
531 void ClearOldConnections(ConfigReader* conf)
533 ConnMap::iterator i,safei;
534 for (i = Connections.begin(); i != Connections.end(); i++)
536 if (!HostInConf(conf, i->second->GetConfHost()))
541 Connections.erase(safei);
546 void ClearAllConnections()
549 while ((i = Connections.begin()) != Connections.end())
551 Connections.erase(i);
556 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
558 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
560 if (i->second->IsEnabled())
563 i->second->SetEnable(true);
564 if (!i->second->Connect())
567 Parent->LoggingMutex->Lock();
568 ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
569 i->second->SetEnable(false);
570 Parent->LoggingMutex->Unlock();
575 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
577 ClearOldConnections(conf);
578 for (int j =0; j < conf->Enumerate("database"); j++)
581 host.id = conf->ReadValue("database", "id", j);
582 host.host = conf->ReadValue("database", "hostname", j);
583 host.port = conf->ReadInteger("database", "port", j, true);
584 host.name = conf->ReadValue("database", "name", j);
585 host.user = conf->ReadValue("database", "username", j);
586 host.pass = conf->ReadValue("database", "password", j);
587 host.ssl = conf->ReadFlag("database", "ssl", j);
592 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
594 SQLConnection* ThisSQL = new SQLConnection(host, Parent);
595 Connections[host.id] = ThisSQL;
598 ConnectDatabases(ServerInstance, Parent);
601 char FindCharId(const std::string &id)
604 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
606 if (iter->first == id)
614 ConnMap::iterator GetCharId(char id)
617 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
622 return Connections.end();
625 void NotifyMainThread(SQLConnection* connection_with_new_result)
627 /* Here we write() to the socket the main thread has open
628 * and we connect()ed back to before our thread became active.
629 * The main thread is using a nonblocking socket tied into
630 * the socket engine, so they wont block and they'll receive
631 * nearly instant notification. Because we're in a seperate
632 * thread, we can just use standard connect(), and we can
633 * block if we like. We just send the connection id of the
636 * NOTE: We only send a single char down the connection, this
637 * way we know it wont get a partial read at the other end if
638 * the system is especially congested (see bug #263).
639 * The function FindCharId translates a connection name into a
640 * one character id, and GetCharId translates a character id
641 * back into an iterator.
643 char id = FindCharId(connection_with_new_result->GetID());
644 send(QueueFD, &id, 1, 0);
649 class DispatcherThread : public Thread
653 InspIRCd* ServerInstance;
655 DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
656 ~DispatcherThread() { }
660 /** Used by m_mysql to notify one thread when the other has a result
662 class Notifier : public BufferedSocket
664 insp_sockaddr sock_us;
670 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
672 Notifier(InspIRCd* SI, ModuleSQL* Creator) : BufferedSocket(SI, "::1", 0, true, 3000), Parent(Creator)
674 Notifier(InspIRCd* SI, ModuleSQL* Creator) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), Parent(Creator)
677 uslen = sizeof(sock_us);
678 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
680 throw ModuleException("Could not create random listening port on localhost");
684 Notifier(InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip)
688 /* Using getsockname and ntohs, we can determine which port number we were allocated */
692 return ntohs(sock_us.sin6_port);
694 return ntohs(sock_us.sin_port);
698 virtual int OnIncomingConnection(int newsock, char* ip)
700 Notifier* n = new Notifier(this->Instance, newsock, ip);
701 n = n; /* Stop bitching at me, GCC */
705 virtual bool OnDataReady()
708 /* NOTE: Only a single character is read so we know we
709 * cant get a partial read. (We've been told that theres
710 * data waiting, so we wont ever get EAGAIN)
711 * The function GetCharId translates a single character
712 * back into an iterator.
714 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
716 ConnMap::iterator iter = GetCharId(data);
717 if (iter != Connections.end())
719 /* Lock the mutex, send back the data */
720 Parent->ResultsMutex->Lock();
721 ResultQueue::iterator n = iter->second->rq.begin();
724 iter->second->rq.pop_front();
725 Parent->ResultsMutex->Unlock();
728 /* No error, but unknown id */
732 /* Erk, error on descriptor! */
738 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
740 ServerInstance->Modules->UseInterface("SQLutils");
742 Conf = new ConfigReader(ServerInstance);
743 PublicServerInstance = ServerInstance;
746 MessagePipe = new Notifier(ServerInstance, this);
748 Dispatcher = new DispatcherThread(ServerInstance, this);
749 ServerInstance->Threads->Create(Dispatcher);
751 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
752 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
753 QueueMutex = ServerInstance->Mutexes->CreateMutex();
755 if (!ServerInstance->Modules->PublishFeature("SQL", this))
757 /* Tell worker thread to exit NOW,
758 * Automatically joins */
760 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
763 ServerInstance->Modules->PublishInterface("SQL", this);
764 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
765 ServerInstance->Modules->Attach(eventlist, this, 2);
768 ModuleSQL::~ModuleSQL()
771 ClearAllConnections();
773 ServerInstance->Modules->UnpublishInterface("SQL", this);
774 ServerInstance->Modules->UnpublishFeature("SQL");
775 ServerInstance->Modules->DoneWithInterface("SQLutils");
781 unsigned long ModuleSQL::NewID()
788 const char* ModuleSQL::OnRequest(Request* request)
790 if(strcmp(SQLREQID, request->GetId()) == 0)
792 SQLrequest* req = (SQLrequest*)request;
797 ConnMap::iterator iter;
799 const char* returnval = NULL;
801 if((iter = Connections.find(req->dbid)) != Connections.end())
804 iter->second->queue.push(*req);
805 returnval = SQLSUCCESS;
809 req->error.Id(SQL_BAD_DBID);
812 QueueMutex->Unlock();
821 void ModuleSQL::OnRehash(User* user, const std::string ¶meter)
826 Version ModuleSQL::GetVersion()
828 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
831 void DispatcherThread::Run()
833 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
835 /* Connect back to the Notifier */
837 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
839 /* crap, we're out of sockets... */
846 insp_aton("::1", &addr.sin6_addr);
847 addr.sin6_family = AF_FAMILY;
848 addr.sin6_port = htons(MessagePipe->GetPort());
851 insp_aton("127.0.0.1", &ia);
852 addr.sin_family = AF_FAMILY;
854 addr.sin_port = htons(MessagePipe->GetPort());
857 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
859 /* wtf, we cant connect to it, but we just created it! */
863 while (this->GetExitFlag() == false)
865 if (Parent->rehashing)
868 Parent->QueueMutex->Lock();
869 Parent->rehashing = false;
870 LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
871 Parent->QueueMutex->Unlock();
875 SQLConnection* conn = NULL;
876 /* XXX: Lock here for safety */
877 Parent->QueueMutex->Lock();
878 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
880 if (i->second->queue.totalsize())
886 Parent->QueueMutex->Unlock();
889 /* Theres an item! */
892 conn->DoLeadingQuery();
895 Parent->QueueMutex->Lock();
897 Parent->QueueMutex->Unlock();
905 MODULE_INIT(ModuleSQL)