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