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