]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Thread is now a Thread derived class, now need to convert the mutexes. With the new...
[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 <pthread.h>
20 #include "users.h"
21 #include "channels.h"
22 #include "modules.h"
23 #include "m_sqlv2.h"
24
25 /* VERSION 2 API: With nonblocking (threaded) requests */
26
27 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
28 /* $CompileFlags: exec("mysql_config --include") */
29 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
30 /* $ModDep: m_sqlv2.h */
31
32 /* THE NONBLOCKING MYSQL API!
33  *
34  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
35  * that instead, you should thread your program. This is what i've done here to allow for
36  * asyncronous SQL requests via mysql. The way this works is as follows:
37  *
38  * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
39  * using a queue with priorities. There is a mutex on either end which prevents two threads
40  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
41  * worker thread wakes up, and checks if there is a request at the head of its queue.
42  * If there is, it processes this request, blocking the worker thread but leaving the ircd
43  * thread to go about its business as usual. During this period, the ircd thread is able
44  * to insert futher pending requests into the queue.
45  *
46  * Once the processing of a request is complete, it is removed from the incoming queue to
47  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
48  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
49  * connection ID through the connection.
50  *
51  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
52  * of the queue, and sends it on its way to the original calling module.
53  *
54  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
55  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
56  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
57  * however, if we were to call a module's OnRequest even from within a thread which was not the
58  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
59  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
60  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
61  * gauranteed threadsafe!)
62  *
63  * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
64  */
65
66
67 class SQLConnection;
68 class Notifier;
69
70
71 typedef std::map<std::string, SQLConnection*> ConnMap;
72 bool giveup = false;
73 bool threadfinished = false;
74 static Module* SQLModule = NULL;
75 static Notifier* MessagePipe = NULL;
76 int QueueFD = -1;
77
78
79 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
80 #define mysql_field_count mysql_num_fields
81 #endif
82
83 typedef std::deque<SQLresult*> ResultQueue;
84
85 /* A mutex to wrap around queue accesses */
86 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
87
88 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
89
90 pthread_mutex_t logging_mutex = PTHREAD_MUTEX_INITIALIZER;
91
92 /** Represents a mysql result set
93  */
94 class MySQLresult : public SQLresult
95 {
96         int currentrow;
97         std::vector<std::string> colnames;
98         std::vector<SQLfieldList> fieldlists;
99         SQLfieldMap* fieldmap;
100         SQLfieldMap fieldmap2;
101         SQLfieldList emptyfieldlist;
102         int rows;
103  public:
104
105         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
106         {
107                 /* A number of affected rows from from mysql_affected_rows.
108                  */
109                 fieldlists.clear();
110                 rows = 0;
111                 if (affected_rows >= 1)
112                 {
113                         rows = affected_rows;
114                         fieldlists.resize(rows);
115                 }
116                 unsigned int field_count = 0;
117                 if (res)
118                 {
119                         MYSQL_ROW row;
120                         int n = 0;
121                         while ((row = mysql_fetch_row(res)))
122                         {
123                                 if (fieldlists.size() < (unsigned int)rows+1)
124                                 {
125                                         fieldlists.resize(fieldlists.size()+1);
126                                 }
127                                 field_count = 0;
128                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
129                                 if(mysql_num_fields(res) == 0)
130                                         break;
131                                 if (fields && mysql_num_fields(res))
132                                 {
133                                         colnames.clear();
134                                         while (field_count < mysql_num_fields(res))
135                                         {
136                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
137                                                 std::string b = (row[field_count] ? row[field_count] : "");
138                                                 SQLfield sqlf(b, !row[field_count]);
139                                                 colnames.push_back(a);
140                                                 fieldlists[n].push_back(sqlf);
141                                                 field_count++;
142                                         }
143                                         n++;
144                                 }
145                                 rows++;
146                         }
147                         mysql_free_result(res);
148                 }
149         }
150
151         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
152         {
153                 rows = 0;
154                 error = e;
155         }
156
157         ~MySQLresult()
158         {
159         }
160
161         virtual int Rows()
162         {
163                 return rows;
164         }
165
166         virtual int Cols()
167         {
168                 return colnames.size();
169         }
170
171         virtual std::string ColName(int column)
172         {
173                 if (column < (int)colnames.size())
174                 {
175                         return colnames[column];
176                 }
177                 else
178                 {
179                         throw SQLbadColName();
180                 }
181                 return "";
182         }
183
184         virtual int ColNum(const std::string &column)
185         {
186                 for (unsigned int i = 0; i < colnames.size(); i++)
187                 {
188                         if (column == colnames[i])
189                                 return i;
190                 }
191                 throw SQLbadColName();
192                 return 0;
193         }
194
195         virtual SQLfield GetValue(int row, int column)
196         {
197                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
198                 {
199                         return fieldlists[row][column];
200                 }
201
202                 throw SQLbadColName();
203
204                 /* XXX: We never actually get here because of the throw */
205                 return SQLfield("",true);
206         }
207
208         virtual SQLfieldList& GetRow()
209         {
210                 if (currentrow < rows)
211                         return fieldlists[currentrow++];
212                 else
213                         return emptyfieldlist;
214         }
215
216         virtual SQLfieldMap& GetRowMap()
217         {
218                 fieldmap2.clear();
219
220                 if (currentrow < rows)
221                 {
222                         for (int i = 0; i < Cols(); i++)
223                         {
224                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
225                         }
226                         currentrow++;
227                 }
228
229                 return fieldmap2;
230         }
231
232         virtual SQLfieldList* GetRowPtr()
233         {
234                 SQLfieldList* fieldlist = new SQLfieldList();
235
236                 if (currentrow < rows)
237                 {
238                         for (int i = 0; i < Rows(); i++)
239                         {
240                                 fieldlist->push_back(fieldlists[currentrow][i]);
241                         }
242                         currentrow++;
243                 }
244                 return fieldlist;
245         }
246
247         virtual SQLfieldMap* GetRowMapPtr()
248         {
249                 fieldmap = new SQLfieldMap();
250
251                 if (currentrow < rows)
252                 {
253                         for (int i = 0; i < Cols(); i++)
254                         {
255                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
256                         }
257                         currentrow++;
258                 }
259
260                 return fieldmap;
261         }
262
263         virtual void Free(SQLfieldMap* fm)
264         {
265                 delete fm;
266         }
267
268         virtual void Free(SQLfieldList* fl)
269         {
270                 delete fl;
271         }
272 };
273
274 class SQLConnection;
275
276 void NotifyMainThread(SQLConnection* connection_with_new_result);
277
278 /** Represents a connection to a mysql database
279  */
280 class SQLConnection : public classbase
281 {
282  protected:
283
284         MYSQL connection;
285         MYSQL_RES *res;
286         MYSQL_ROW row;
287         SQLhost host;
288         std::map<std::string,std::string> thisrow;
289         bool Enabled;
290
291  public:
292
293         QueryQueue queue;
294         ResultQueue rq;
295
296         // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
297         SQLConnection(const SQLhost &hi) : host(hi), Enabled(false)
298         {
299         }
300
301         ~SQLConnection()
302         {
303                 Close();
304         }
305
306         // This method connects to the database using the credentials supplied to the constructor, and returns
307         // true upon success.
308         bool Connect()
309         {
310                 unsigned int timeout = 1;
311                 mysql_init(&connection);
312                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
313                 return mysql_real_connect(&connection, host.host.c_str(), host.user.c_str(), host.pass.c_str(), host.name.c_str(), host.port, NULL, 0);
314         }
315
316         void DoLeadingQuery()
317         {
318                 if (!CheckConnection())
319                         return;
320
321                 /* Parse the command string and dispatch it to mysql */
322                 SQLrequest& req = queue.front();
323
324                 /* Pointer to the buffer we screw around with substitution in */
325                 char* query;
326
327                 /* Pointer to the current end of query, where we append new stuff */
328                 char* queryend;
329
330                 /* Total length of the unescaped parameters */
331                 unsigned long paramlen;
332
333                 /* Total length of query, used for binary-safety in mysql_real_query */
334                 unsigned long querylength = 0;
335
336                 paramlen = 0;
337
338                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
339                 {
340                         paramlen += i->size();
341                 }
342
343                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
344                  * sizeofquery + (totalparamlength*2) + 1
345                  *
346                  * The +1 is for null-terminating the string for mysql_real_escape_string
347                  */
348
349                 query = new char[req.query.q.length() + (paramlen*2) + 1];
350                 queryend = query;
351
352                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
353                  * the parameters into it...
354                  */
355
356                 for(unsigned long i = 0; i < req.query.q.length(); i++)
357                 {
358                         if(req.query.q[i] == '?')
359                         {
360                                 /* We found a place to substitute..what fun.
361                                  * use mysql calls to escape and write the
362                                  * escaped string onto the end of our query buffer,
363                                  * then we "just" need to make sure queryend is
364                                  * pointing at the right place.
365                                  */
366                                 if(req.query.p.size())
367                                 {
368                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
369
370                                         queryend += len;
371                                         req.query.p.pop_front();
372                                 }
373                                 else
374                                         break;
375                         }
376                         else
377                         {
378                                 *queryend = req.query.q[i];
379                                 queryend++;
380                         }
381                         querylength++;
382                 }
383
384                 *queryend = 0;
385
386                 pthread_mutex_lock(&queue_mutex);
387                 req.query.q = query;
388                 pthread_mutex_unlock(&queue_mutex);
389
390                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
391                 {
392                         /* Successfull query */
393                         res = mysql_use_result(&connection);
394                         unsigned long rows = mysql_affected_rows(&connection);
395                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
396                         r->dbid = this->GetID();
397                         r->query = req.query.q;
398                         /* Put this new result onto the results queue.
399                          * XXX: Remember to mutex the queue!
400                          */
401                         pthread_mutex_lock(&results_mutex);
402                         rq.push_back(r);
403                         pthread_mutex_unlock(&results_mutex);
404                 }
405                 else
406                 {
407                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
408                          * possible error numbers and error messages */
409                         SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
410                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
411                         r->dbid = this->GetID();
412                         r->query = req.query.q;
413
414                         pthread_mutex_lock(&results_mutex);
415                         rq.push_back(r);
416                         pthread_mutex_unlock(&results_mutex);
417                 }
418
419                 /* Now signal the main thread that we've got a result to process.
420                  * Pass them this connection id as what to examine
421                  */
422
423                 delete[] query;
424
425                 NotifyMainThread(this);
426         }
427
428         bool ConnectionLost()
429         {
430                 if (&connection) {
431                         return (mysql_ping(&connection) != 0);
432                 }
433                 else return false;
434         }
435
436         bool CheckConnection()
437         {
438                 if (ConnectionLost()) {
439                         return Connect();
440                 }
441                 else return true;
442         }
443
444         std::string GetError()
445         {
446                 return mysql_error(&connection);
447         }
448
449         const std::string& GetID()
450         {
451                 return host.id;
452         }
453
454         std::string GetHost()
455         {
456                 return host.host;
457         }
458
459         void SetEnable(bool Enable)
460         {
461                 Enabled = Enable;
462         }
463
464         bool IsEnabled()
465         {
466                 return Enabled;
467         }
468
469         void Close()
470         {
471                 mysql_close(&connection);
472         }
473
474         const SQLhost& GetConfHost()
475         {
476                 return host;
477         }
478
479 };
480
481 ConnMap Connections;
482
483 bool HasHost(const SQLhost &host)
484 {
485         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
486         {
487                 if (host == iter->second->GetConfHost())
488                         return true;
489         }
490         return false;
491 }
492
493 bool HostInConf(ConfigReader* conf, const SQLhost &h)
494 {
495         for(int i = 0; i < conf->Enumerate("database"); i++)
496         {
497                 SQLhost host;
498                 host.id         = conf->ReadValue("database", "id", i);
499                 host.host       = conf->ReadValue("database", "hostname", i);
500                 host.port       = conf->ReadInteger("database", "port", i, true);
501                 host.name       = conf->ReadValue("database", "name", i);
502                 host.user       = conf->ReadValue("database", "username", i);
503                 host.pass       = conf->ReadValue("database", "password", i);
504                 host.ssl        = conf->ReadFlag("database", "ssl", i);
505                 if (h == host)
506                         return true;
507         }
508         return false;
509 }
510
511 void ClearOldConnections(ConfigReader* conf)
512 {
513         ConnMap::iterator i,safei;
514         for (i = Connections.begin(); i != Connections.end(); i++)
515         {
516                 if (!HostInConf(conf, i->second->GetConfHost()))
517                 {
518                         delete i->second;
519                         safei = i;
520                         --i;
521                         Connections.erase(safei);
522                 }
523         }
524 }
525
526 void ClearAllConnections()
527 {
528         ConnMap::iterator i;
529         while ((i = Connections.begin()) != Connections.end())
530         {
531                 Connections.erase(i);
532                 delete i->second;
533         }
534 }
535
536 void ConnectDatabases(InspIRCd* ServerInstance)
537 {
538         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
539         {
540                 if (i->second->IsEnabled())
541                         continue;
542
543                 i->second->SetEnable(true);
544                 if (!i->second->Connect())
545                 {
546                         /* XXX: MUTEX */
547                         pthread_mutex_lock(&logging_mutex);
548                         ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
549                         i->second->SetEnable(false);
550                         pthread_mutex_unlock(&logging_mutex);
551                 }
552         }
553 }
554
555 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance)
556 {
557         ClearOldConnections(conf);
558         for (int j =0; j < conf->Enumerate("database"); j++)
559         {
560                 SQLhost host;
561                 host.id         = conf->ReadValue("database", "id", j);
562                 host.host       = conf->ReadValue("database", "hostname", j);
563                 host.port       = conf->ReadInteger("database", "port", j, true);
564                 host.name       = conf->ReadValue("database", "name", j);
565                 host.user       = conf->ReadValue("database", "username", j);
566                 host.pass       = conf->ReadValue("database", "password", j);
567                 host.ssl        = conf->ReadFlag("database", "ssl", j);
568
569                 if (HasHost(host))
570                         continue;
571
572                 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
573                 {
574                         SQLConnection* ThisSQL = new SQLConnection(host);
575                         Connections[host.id] = ThisSQL;
576                 }
577         }
578         ConnectDatabases(ServerInstance);
579 }
580
581 char FindCharId(const std::string &id)
582 {
583         char i = 1;
584         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
585         {
586                 if (iter->first == id)
587                 {
588                         return i;
589                 }
590         }
591         return 0;
592 }
593
594 ConnMap::iterator GetCharId(char id)
595 {
596         char i = 1;
597         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
598         {
599                 if (i == id)
600                         return iter;
601         }
602         return Connections.end();
603 }
604
605 void NotifyMainThread(SQLConnection* connection_with_new_result)
606 {
607         /* Here we write() to the socket the main thread has open
608          * and we connect()ed back to before our thread became active.
609          * The main thread is using a nonblocking socket tied into
610          * the socket engine, so they wont block and they'll receive
611          * nearly instant notification. Because we're in a seperate
612          * thread, we can just use standard connect(), and we can
613          * block if we like. We just send the connection id of the
614          * connection back.
615          *
616          * NOTE: We only send a single char down the connection, this
617          * way we know it wont get a partial read at the other end if
618          * the system is especially congested (see bug #263).
619          * The function FindCharId translates a connection name into a
620          * one character id, and GetCharId translates a character id
621          * back into an iterator.
622          */
623         char id = FindCharId(connection_with_new_result->GetID());
624         send(QueueFD, &id, 1, 0);
625 }
626
627 class ModuleSQL;
628
629 class DispatcherThread : public Thread
630 {
631  private:
632         ModuleSQL* Parent;
633         InspIRCd* ServerInstance;
634  public:
635         DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
636         ~DispatcherThread() { }
637         virtual void Run();
638 };
639
640 /** Used by m_mysql to notify one thread when the other has a result
641  */
642 class Notifier : public BufferedSocket
643 {
644         insp_sockaddr sock_us;
645         socklen_t uslen;
646
647
648  public:
649
650         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
651 #ifdef IPV6
652         Notifier(InspIRCd* SI) : BufferedSocket(SI, "::1", 0, true, 3000)
653 #else
654         Notifier(InspIRCd* SI) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000)
655 #endif
656         {
657                 uslen = sizeof(sock_us);
658                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
659                 {
660                         throw ModuleException("Could not create random listening port on localhost");
661                 }
662         }
663
664         Notifier(InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip)
665         {
666         }
667
668         /* Using getsockname and ntohs, we can determine which port number we were allocated */
669         int GetPort()
670         {
671 #ifdef IPV6
672                 return ntohs(sock_us.sin6_port);
673 #else
674                 return ntohs(sock_us.sin_port);
675 #endif
676         }
677
678         virtual int OnIncomingConnection(int newsock, char* ip)
679         {
680                 Notifier* n = new Notifier(this->Instance, newsock, ip);
681                 n = n; /* Stop bitching at me, GCC */
682                 return true;
683         }
684
685         virtual bool OnDataReady()
686         {
687                 char data = 0;
688                 /* NOTE: Only a single character is read so we know we
689                  * cant get a partial read. (We've been told that theres
690                  * data waiting, so we wont ever get EAGAIN)
691                  * The function GetCharId translates a single character
692                  * back into an iterator.
693                  */
694                 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
695                 {
696                         ConnMap::iterator iter = GetCharId(data);
697                         if (iter != Connections.end())
698                         {
699                                 /* Lock the mutex, send back the data */
700                                 pthread_mutex_lock(&results_mutex);
701                                 ResultQueue::iterator n = iter->second->rq.begin();
702                                 (*n)->Send();
703                                 delete (*n);
704                                 iter->second->rq.pop_front();
705                                 pthread_mutex_unlock(&results_mutex);
706                                 return true;
707                         }
708                         /* No error, but unknown id */
709                         return true;
710                 }
711
712                 /* Erk, error on descriptor! */
713                 return false;
714         }
715 };
716
717 /** MySQL module
718  */
719 class ModuleSQL : public Module
720 {
721  public:
722
723         ConfigReader *Conf;
724         InspIRCd* PublicServerInstance;
725         int currid;
726         bool rehashing;
727         DispatcherThread* Dispatcher;
728
729         ModuleSQL(InspIRCd* Me)
730         : Module::Module(Me), rehashing(false)
731         {
732                 ServerInstance->Modules->UseInterface("SQLutils");
733
734                 Conf = new ConfigReader(ServerInstance);
735                 PublicServerInstance = ServerInstance;
736                 currid = 0;
737                 SQLModule = this;
738
739                 MessagePipe = new Notifier(ServerInstance);
740
741                 Dispatcher = new DispatcherThread(ServerInstance, this);
742                 ServerInstance->Threads->Create(Dispatcher);
743
744                 if (!ServerInstance->Modules->PublishFeature("SQL", this))
745                 {
746                         /* Tell worker thread to exit NOW,
747                          * Automatically joins */
748                         delete Dispatcher;
749
750                         throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
751                 }
752
753                 ServerInstance->Modules->PublishInterface("SQL", this);
754                 Implementation eventlist[] = { I_OnRehash, I_OnRequest };
755                 ServerInstance->Modules->Attach(eventlist, this, 2);
756         }
757
758         virtual ~ModuleSQL()
759         {
760                 delete Dispatcher;
761                 ClearAllConnections();
762                 delete Conf;
763                 ServerInstance->Modules->UnpublishInterface("SQL", this);
764                 ServerInstance->Modules->UnpublishFeature("SQL");
765                 ServerInstance->Modules->DoneWithInterface("SQLutils");
766         }
767
768
769
770         unsigned long NewID()
771         {
772                 if (currid+1 == 0)
773                         currid++;
774                 return ++currid;
775         }
776
777         virtual const char* OnRequest(Request* request)
778         {
779                 if(strcmp(SQLREQID, request->GetId()) == 0)
780                 {
781                         SQLrequest* req = (SQLrequest*)request;
782
783                         /* XXX: Lock */
784                         pthread_mutex_lock(&queue_mutex);
785
786                         ConnMap::iterator iter;
787
788                         const char* returnval = NULL;
789
790                         if((iter = Connections.find(req->dbid)) != Connections.end())
791                         {
792                                 req->id = NewID();
793                                 iter->second->queue.push(*req);
794                                 returnval = SQLSUCCESS;
795                         }
796                         else
797                         {
798                                 req->error.Id(BAD_DBID);
799                         }
800
801                         pthread_mutex_unlock(&queue_mutex);
802                         /* XXX: Unlock */
803
804                         return returnval;
805                 }
806
807                 return NULL;
808         }
809
810         virtual void OnRehash(User* user, const std::string &parameter)
811         {
812                 rehashing = true;
813         }
814
815         virtual Version GetVersion()
816         {
817                 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
818         }
819
820 };
821
822 void DispatcherThread::Run(void)
823 {
824         LoadDatabases(Parent->Conf, Parent->PublicServerInstance);
825
826         /* Connect back to the Notifier */
827
828         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
829         {
830                 /* crap, we're out of sockets... */
831                 return;
832         }
833
834         insp_sockaddr addr;
835
836 #ifdef IPV6
837         insp_aton("::1", &addr.sin6_addr);
838         addr.sin6_family = AF_FAMILY;
839         addr.sin6_port = htons(MessagePipe->GetPort());
840 #else
841         insp_inaddr ia;
842         insp_aton("127.0.0.1", &ia);
843         addr.sin_family = AF_FAMILY;
844         addr.sin_addr = ia;
845         addr.sin_port = htons(MessagePipe->GetPort());
846 #endif
847
848         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
849         {
850                 /* wtf, we cant connect to it, but we just created it! */
851                 return;
852         }
853
854         while (this->GetExitFlag() == false)
855         {
856                 if (Parent->rehashing)
857                 {
858                 /* XXX: Lock */
859                         pthread_mutex_lock(&queue_mutex);
860                         Parent->rehashing = false;
861                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance);
862                         pthread_mutex_unlock(&queue_mutex);
863                         /* XXX: Unlock */
864                 }
865
866                 SQLConnection* conn = NULL;
867                 /* XXX: Lock here for safety */
868                 pthread_mutex_lock(&queue_mutex);
869                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
870                 {
871                         if (i->second->queue.totalsize())
872                         {
873                                 conn = i->second;
874                                 break;
875                         }
876                 }
877                 pthread_mutex_unlock(&queue_mutex);
878                 /* XXX: Unlock */
879
880                 /* Theres an item! */
881                 if (conn)
882                 {
883                         conn->DoLeadingQuery();
884
885                         /* XXX: Lock */
886                         pthread_mutex_lock(&queue_mutex);
887                         conn->queue.pop();
888                         pthread_mutex_unlock(&queue_mutex);
889                         /* XXX: Unlock */
890                 }
891
892                 usleep(1000);
893         }
894 }
895
896 MODULE_INIT(ModuleSQL)
897