]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
0d579a382e35618472f0815459efd039e008868b
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* Stop mysql wanting to use long long */
15 #define NO_CLIENT_LONG_LONG
16
17 #include "inspircd.h"
18 #include <mysql.h>
19 #include "users.h"
20 #include "channels.h"
21 #include "modules.h"
22 #include "m_sqlv2.h"
23
24 #ifdef WINDOWS
25 #pragma comment(lib, "mysqlclient.lib")
26 #endif
27
28 /* VERSION 2 API: With nonblocking (threaded) requests */
29
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 */
34
35 /* THE NONBLOCKING MYSQL API!
36  *
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:
40  *
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.
48  *
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.
53  *
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.
56  *
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!)
65  *
66  * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
67  */
68
69
70 class SQLConnection;
71 class MySQLListener;
72
73
74 typedef std::map<std::string, SQLConnection*> ConnMap;
75 static MySQLListener *MessagePipe = NULL;
76 int QueueFD = -1;
77
78 class DispatcherThread;
79
80 /** MySQL module
81  *  */
82 class ModuleSQL : public Module
83 {
84  public:
85
86          ConfigReader *Conf;
87          InspIRCd* PublicServerInstance;
88          int currid;
89          bool rehashing;
90          DispatcherThread* Dispatcher;
91          Mutex* QueueMutex;
92          Mutex* ResultsMutex;
93          Mutex* LoggingMutex;
94          Mutex* ConnMutex;
95
96          ModuleSQL(InspIRCd* Me);
97          ~ModuleSQL();
98          unsigned long NewID();
99          const char* OnRequest(Request* request);
100          void OnRehash(User* user, const std::string &parameter);
101          Version GetVersion();
102 };
103
104
105
106 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
107 #define mysql_field_count mysql_num_fields
108 #endif
109
110 typedef std::deque<SQLresult*> ResultQueue;
111
112 /** Represents a mysql result set
113  */
114 class MySQLresult : public SQLresult
115 {
116         int currentrow;
117         std::vector<std::string> colnames;
118         std::vector<SQLfieldList> fieldlists;
119         SQLfieldMap* fieldmap;
120         SQLfieldMap fieldmap2;
121         SQLfieldList emptyfieldlist;
122         int rows;
123  public:
124
125         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
126         {
127                 /* A number of affected rows from from mysql_affected_rows.
128                  */
129                 fieldlists.clear();
130                 rows = 0;
131                 if (affected_rows >= 1)
132                 {
133                         rows = affected_rows;
134                         fieldlists.resize(rows);
135                 }
136                 unsigned int field_count = 0;
137                 if (res)
138                 {
139                         MYSQL_ROW row;
140                         int n = 0;
141                         while ((row = mysql_fetch_row(res)))
142                         {
143                                 if (fieldlists.size() < (unsigned int)rows+1)
144                                 {
145                                         fieldlists.resize(fieldlists.size()+1);
146                                 }
147                                 field_count = 0;
148                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
149                                 if(mysql_num_fields(res) == 0)
150                                         break;
151                                 if (fields && mysql_num_fields(res))
152                                 {
153                                         colnames.clear();
154                                         while (field_count < mysql_num_fields(res))
155                                         {
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);
161                                                 field_count++;
162                                         }
163                                         n++;
164                                 }
165                                 rows++;
166                         }
167                         mysql_free_result(res);
168                 }
169         }
170
171         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
172         {
173                 rows = 0;
174                 error = e;
175         }
176
177         ~MySQLresult()
178         {
179         }
180
181         virtual int Rows()
182         {
183                 return rows;
184         }
185
186         virtual int Cols()
187         {
188                 return colnames.size();
189         }
190
191         virtual std::string ColName(int column)
192         {
193                 if (column < (int)colnames.size())
194                 {
195                         return colnames[column];
196                 }
197                 else
198                 {
199                         throw SQLbadColName();
200                 }
201                 return "";
202         }
203
204         virtual int ColNum(const std::string &column)
205         {
206                 for (unsigned int i = 0; i < colnames.size(); i++)
207                 {
208                         if (column == colnames[i])
209                                 return i;
210                 }
211                 throw SQLbadColName();
212                 return 0;
213         }
214
215         virtual SQLfield GetValue(int row, int column)
216         {
217                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
218                 {
219                         return fieldlists[row][column];
220                 }
221
222                 throw SQLbadColName();
223
224                 /* XXX: We never actually get here because of the throw */
225                 return SQLfield("",true);
226         }
227
228         virtual SQLfieldList& GetRow()
229         {
230                 if (currentrow < rows)
231                         return fieldlists[currentrow++];
232                 else
233                         return emptyfieldlist;
234         }
235
236         virtual SQLfieldMap& GetRowMap()
237         {
238                 fieldmap2.clear();
239
240                 if (currentrow < rows)
241                 {
242                         for (int i = 0; i < Cols(); i++)
243                         {
244                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
245                         }
246                         currentrow++;
247                 }
248
249                 return fieldmap2;
250         }
251
252         virtual SQLfieldList* GetRowPtr()
253         {
254                 SQLfieldList* fieldlist = new SQLfieldList();
255
256                 if (currentrow < rows)
257                 {
258                         for (int i = 0; i < Rows(); i++)
259                         {
260                                 fieldlist->push_back(fieldlists[currentrow][i]);
261                         }
262                         currentrow++;
263                 }
264                 return fieldlist;
265         }
266
267         virtual SQLfieldMap* GetRowMapPtr()
268         {
269                 fieldmap = new SQLfieldMap();
270
271                 if (currentrow < rows)
272                 {
273                         for (int i = 0; i < Cols(); i++)
274                         {
275                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
276                         }
277                         currentrow++;
278                 }
279
280                 return fieldmap;
281         }
282
283         virtual void Free(SQLfieldMap* fm)
284         {
285                 delete fm;
286         }
287
288         virtual void Free(SQLfieldList* fl)
289         {
290                 delete fl;
291         }
292 };
293
294 class SQLConnection;
295
296 void NotifyMainThread(SQLConnection* connection_with_new_result);
297
298 /** Represents a connection to a mysql database
299  */
300 class SQLConnection : public classbase
301 {
302  protected:
303
304         MYSQL connection;
305         MYSQL_RES *res;
306         MYSQL_ROW row;
307         SQLhost host;
308         std::map<std::string,std::string> thisrow;
309         bool Enabled;
310         ModuleSQL* Parent;
311
312  public:
313
314         QueryQueue queue;
315         ResultQueue rq;
316
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)
319         {
320         }
321
322         ~SQLConnection()
323         {
324                 Close();
325         }
326
327         // This method connects to the database using the credentials supplied to the constructor, and returns
328         // true upon success.
329         bool Connect()
330         {
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);
335         }
336
337         void DoLeadingQuery()
338         {
339                 if (!CheckConnection())
340                         return;
341
342                 /* Parse the command string and dispatch it to mysql */
343                 SQLrequest& req = queue.front();
344
345                 /* Pointer to the buffer we screw around with substitution in */
346                 char* query;
347
348                 /* Pointer to the current end of query, where we append new stuff */
349                 char* queryend;
350
351                 /* Total length of the unescaped parameters */
352                 unsigned long paramlen;
353
354                 /* Total length of query, used for binary-safety in mysql_real_query */
355                 unsigned long querylength = 0;
356
357                 paramlen = 0;
358
359                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
360                 {
361                         paramlen += i->size();
362                 }
363
364                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
365                  * sizeofquery + (totalparamlength*2) + 1
366                  *
367                  * The +1 is for null-terminating the string for mysql_real_escape_string
368                  */
369
370                 query = new char[req.query.q.length() + (paramlen*2) + 1];
371                 queryend = query;
372
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...
375                  */
376
377                 for(unsigned long i = 0; i < req.query.q.length(); i++)
378                 {
379                         if(req.query.q[i] == '?')
380                         {
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.
386                                  */
387                                 if(req.query.p.size())
388                                 {
389                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
390
391                                         queryend += len;
392                                         req.query.p.pop_front();
393                                 }
394                                 else
395                                         break;
396                         }
397                         else
398                         {
399                                 *queryend = req.query.q[i];
400                                 queryend++;
401                         }
402                         querylength++;
403                 }
404
405                 *queryend = 0;
406
407                 Parent->QueueMutex->Lock();
408                 req.query.q = query;
409                 Parent->QueueMutex->Unlock();
410
411                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
412                 {
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!
421                          */
422                         Parent->ResultsMutex->Lock();
423                         rq.push_back(r);
424                         Parent->ResultsMutex->Unlock();
425                 }
426                 else
427                 {
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;
434
435                         Parent->ResultsMutex->Lock();
436                         rq.push_back(r);
437                         Parent->ResultsMutex->Unlock();
438                 }
439
440                 /* Now signal the main thread that we've got a result to process.
441                  * Pass them this connection id as what to examine
442                  */
443
444                 delete[] query;
445
446                 NotifyMainThread(this);
447         }
448
449         bool ConnectionLost()
450         {
451                 if (&connection) {
452                         return (mysql_ping(&connection) != 0);
453                 }
454                 else return false;
455         }
456
457         bool CheckConnection()
458         {
459                 if (ConnectionLost()) {
460                         return Connect();
461                 }
462                 else return true;
463         }
464
465         std::string GetError()
466         {
467                 return mysql_error(&connection);
468         }
469
470         const std::string& GetID()
471         {
472                 return host.id;
473         }
474
475         std::string GetHost()
476         {
477                 return host.host;
478         }
479
480         void SetEnable(bool Enable)
481         {
482                 Enabled = Enable;
483         }
484
485         bool IsEnabled()
486         {
487                 return Enabled;
488         }
489
490         void Close()
491         {
492                 mysql_close(&connection);
493         }
494
495         const SQLhost& GetConfHost()
496         {
497                 return host;
498         }
499
500 };
501
502 ConnMap Connections;
503
504 bool HasHost(const SQLhost &host)
505 {
506         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
507         {
508                 if (host == iter->second->GetConfHost())
509                         return true;
510         }
511         return false;
512 }
513
514 bool HostInConf(ConfigReader* conf, const SQLhost &h)
515 {
516         for(int i = 0; i < conf->Enumerate("database"); i++)
517         {
518                 SQLhost host;
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);
526                 if (h == host)
527                         return true;
528         }
529         return false;
530 }
531
532 void ClearOldConnections(ConfigReader* conf)
533 {
534         ConnMap::iterator i,safei;
535         for (i = Connections.begin(); i != Connections.end(); i++)
536         {
537                 if (!HostInConf(conf, i->second->GetConfHost()))
538                 {
539                         delete i->second;
540                         safei = i;
541                         --i;
542                         Connections.erase(safei);
543                 }
544         }
545 }
546
547 void ClearAllConnections()
548 {
549         ConnMap::iterator i;
550         while ((i = Connections.begin()) != Connections.end())
551         {
552                 Connections.erase(i);
553                 delete i->second;
554         }
555 }
556
557 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
558 {
559         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
560         {
561                 if (i->second->IsEnabled())
562                         continue;
563
564                 i->second->SetEnable(true);
565                 if (!i->second->Connect())
566                 {
567                         /* XXX: MUTEX */
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();
572                 }
573         }
574 }
575
576 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
577 {
578         Parent->ConnMutex->Lock();
579         ClearOldConnections(conf);
580         for (int j =0; j < conf->Enumerate("database"); j++)
581         {
582                 SQLhost host;
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);
590
591                 if (HasHost(host))
592                         continue;
593
594                 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
595                 {
596                         SQLConnection* ThisSQL = new SQLConnection(host, Parent);
597                         Connections[host.id] = ThisSQL;
598                 }
599         }
600         ConnectDatabases(ServerInstance, Parent);
601         Parent->ConnMutex->Unlock();
602 }
603
604 char FindCharId(const std::string &id)
605 {
606         char i = 1;
607         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
608         {
609                 if (iter->first == id)
610                 {
611                         return i;
612                 }
613         }
614         return 0;
615 }
616
617 ConnMap::iterator GetCharId(char id)
618 {
619         char i = 1;
620         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
621         {
622                 if (i == id)
623                         return iter;
624         }
625         return Connections.end();
626 }
627
628 void NotifyMainThread(SQLConnection* connection_with_new_result)
629 {
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
637          * connection back.
638          *
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.
645          */
646         char id = FindCharId(connection_with_new_result->GetID());
647         send(QueueFD, &id, 1, 0);
648 }
649
650 class ModuleSQL;
651
652 class DispatcherThread : public Thread
653 {
654  private:
655         ModuleSQL* Parent;
656         InspIRCd* ServerInstance;
657  public:
658         DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
659         ~DispatcherThread() { }
660         virtual void Run();
661 };
662
663 /** Used by m_mysql to notify one thread when the other has a result
664  */
665 class Notifier : public BufferedSocket
666 {
667         ModuleSQL* Parent;
668
669  public:
670         Notifier(ModuleSQL* P, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), Parent(P) { }
671
672         virtual bool OnDataReady()
673         {
674                 char data = 0;
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.
680                  */
681
682                 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
683                 {
684                         Parent->ConnMutex->Lock();
685                         ConnMap::iterator iter = GetCharId(data);
686                         if (iter != Connections.end())
687                         {
688                                 /* Lock the mutex, send back the data */
689                                 Parent->ResultsMutex->Lock();
690                                 ResultQueue::iterator n = iter->second->rq.begin();
691                                 (*n)->Send();
692                                 delete (*n);
693                                 iter->second->rq.pop_front();
694                                 Parent->ResultsMutex->Unlock();
695                                 Parent->ConnMutex->Unlock();
696                                 return true;
697                         }
698                         /* No error, but unknown id */
699                         Parent->ConnMutex->Unlock();
700                         return true;
701                 }
702
703                 /* Erk, error on descriptor! */
704                 return false;
705         }
706 };
707
708 /** Spawn sockets from a listener
709  */
710 class MySQLListener : public ListenSocketBase
711 {
712         ModuleSQL* Parent;
713         irc::sockets::insp_sockaddr sock_us;
714         socklen_t uslen;
715         FileReader* index;
716
717  public:
718         MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
719         {
720                 uslen = sizeof(sock_us);
721                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
722                 {
723                         throw ModuleException("Could not getsockname() to find out port number for ITC port");
724                 }
725         }
726
727         virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
728         {
729                 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
730         }
731
732         /* Using getsockname and ntohs, we can determine which port number we were allocated */
733         int GetPort()
734         {
735 #ifdef IPV6
736                 return ntohs(sock_us.sin6_port);
737 #else
738                 return ntohs(sock_us.sin_port);
739 #endif
740         }
741 };
742
743 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
744 {
745         ServerInstance->Modules->UseInterface("SQLutils");
746
747         Conf = new ConfigReader(ServerInstance);
748         PublicServerInstance = ServerInstance;
749         currid = 0;
750
751         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
752 #ifdef IPV6
753         MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
754 #else
755         MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
756 #endif
757
758         LoggingMutex = ServerInstance->Mutexes->CreateMutex();
759         ConnMutex = ServerInstance->Mutexes->CreateMutex();
760
761         if (MessagePipe->GetFd() == -1)
762         {
763                 delete ConnMutex;
764                 ServerInstance->Modules->DoneWithInterface("SQLutils");
765                 throw ModuleException("m_mysql: unable to create ITC pipe");
766         }
767         else
768         {
769                 LoggingMutex->Lock();
770                 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
771                 LoggingMutex->Unlock();
772         }
773
774         Dispatcher = new DispatcherThread(ServerInstance, this);
775         ServerInstance->Threads->Create(Dispatcher);
776
777         ResultsMutex = ServerInstance->Mutexes->CreateMutex();
778         QueueMutex = ServerInstance->Mutexes->CreateMutex();
779
780         if (!ServerInstance->Modules->PublishFeature("SQL", this))
781         {
782                 /* Tell worker thread to exit NOW,
783                  * Automatically joins */
784                 delete Dispatcher;
785                 delete LoggingMutex;
786                 delete ResultsMutex;
787                 delete QueueMutex;
788                 delete ConnMutex;
789                 ServerInstance->Modules->DoneWithInterface("SQLutils");
790                 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
791         }
792
793         ServerInstance->Modules->PublishInterface("SQL", this);
794         Implementation eventlist[] = { I_OnRehash, I_OnRequest };
795         ServerInstance->Modules->Attach(eventlist, this, 2);
796 }
797
798 ModuleSQL::~ModuleSQL()
799 {
800         delete Dispatcher;
801         ClearAllConnections();
802         delete Conf;
803         ServerInstance->Modules->UnpublishInterface("SQL", this);
804         ServerInstance->Modules->UnpublishFeature("SQL");
805         ServerInstance->Modules->DoneWithInterface("SQLutils");
806         delete LoggingMutex;
807         delete ResultsMutex;
808         delete QueueMutex;
809         delete ConnMutex;
810 }
811
812 unsigned long ModuleSQL::NewID()
813 {
814         if (currid+1 == 0)
815                 currid++;
816         return ++currid;
817 }
818
819 const char* ModuleSQL::OnRequest(Request* request)
820 {
821         if(strcmp(SQLREQID, request->GetId()) == 0)
822         {
823                 SQLrequest* req = (SQLrequest*)request;
824
825                 /* XXX: Lock */
826                 QueueMutex->Lock();
827
828                 ConnMap::iterator iter;
829
830                 const char* returnval = NULL;
831
832                 ConnMutex->Lock();
833                 if((iter = Connections.find(req->dbid)) != Connections.end())
834                 {
835                         req->id = NewID();
836                         iter->second->queue.push(*req);
837                         returnval = SQLSUCCESS;
838                 }
839                 else
840                 {
841                         req->error.Id(SQL_BAD_DBID);
842                 }
843
844                 ConnMutex->Unlock();
845                 QueueMutex->Unlock();
846
847                 return returnval;
848         }
849
850         return NULL;
851 }
852
853 void ModuleSQL::OnRehash(User* user, const std::string &parameter)
854 {
855         rehashing = true;
856 }
857
858 Version ModuleSQL::GetVersion()
859 {
860         return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
861 }
862
863 void DispatcherThread::Run()
864 {
865         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
866
867         /* Connect back to the Notifier */
868
869         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
870         {
871                 /* crap, we're out of sockets... */
872                 return;
873         }
874
875         irc::sockets::insp_sockaddr addr;
876
877 #ifdef IPV6
878         irc::sockets::insp_aton("::1", &addr.sin6_addr);
879         addr.sin6_family = AF_FAMILY;
880         addr.sin6_port = htons(MessagePipe->GetPort());
881 #else
882         irc::sockets::insp_inaddr ia;
883         irc::sockets::insp_aton("127.0.0.1", &ia);
884         addr.sin_family = AF_FAMILY;
885         addr.sin_addr = ia;
886         addr.sin_port = htons(MessagePipe->GetPort());
887 #endif
888
889         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
890         {
891                 /* wtf, we cant connect to it, but we just created it! */
892                 return;
893         }
894
895         while (this->GetExitFlag() == false)
896         {
897                 if (Parent->rehashing)
898                 {
899                 /* XXX: Lock */
900                         Parent->QueueMutex->Lock();
901                         Parent->rehashing = false;
902                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
903                         Parent->QueueMutex->Unlock();
904                         /* XXX: Unlock */
905                 }
906
907                 SQLConnection* conn = NULL;
908                 /* XXX: Lock here for safety */
909                 Parent->QueueMutex->Lock();
910                 Parent->ConnMutex->Lock();
911                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
912                 {
913                         if (i->second->queue.totalsize())
914                         {
915                                 conn = i->second;
916                                 break;
917                         }
918                 }
919                 Parent->ConnMutex->Unlock();
920                 Parent->QueueMutex->Unlock();
921                 /* XXX: Unlock */
922
923                 /* Theres an item! */
924                 if (conn)
925                 {
926                         conn->DoLeadingQuery();
927
928                         /* XXX: Lock */
929                         Parent->QueueMutex->Lock();
930                         conn->queue.pop();
931                         Parent->QueueMutex->Unlock();
932                         /* XXX: Unlock */
933                 }
934
935                 usleep(1000);
936         }
937 }
938
939 MODULE_INIT(ModuleSQL)
940