]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
daf59a5d911d48a71b6a6ec5db0e2aa01d21166e
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 using namespace std;
18
19 #include <stdio.h>
20 #include <string>
21 #include <mysql.h>
22 #include <pthread.h>
23 #include "users.h"
24 #include "channels.h"
25 #include "modules.h"
26 #include "helperfuncs.h"
27 #include "m_sqlv2.h"
28
29 /* VERSION 2 API: With nonblocking (threaded) requests */
30
31 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
32 /* $CompileFlags: `mysql_config --include` */
33 /* $LinkerFlags: `mysql_config --libs_r` `perl ../mysql_rpath.pl` */
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 pthreads, 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 Notifier;
72
73 extern InspIRCd* ServerInstance;
74 typedef std::map<std::string, SQLConnection*> ConnMap;
75 bool giveup = false;
76 static Module* SQLModule = NULL;
77 static Notifier* MessagePipe = NULL;
78 int QueueFD = -1;
79
80
81 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
82 #define mysql_field_count mysql_num_fields
83 #endif
84
85 typedef std::deque<SQLresult*> ResultQueue;
86
87 class QueryQueue : public classbase
88 {
89 private:
90         typedef std::deque<SQLrequest> ReqDeque;
91
92         ReqDeque priority;      /* The priority queue */
93         ReqDeque normal;        /* The 'normal' queue */
94         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
95
96 public:
97         QueryQueue()
98         : which(NON)
99         {
100         }
101
102         void push(const SQLrequest &q)
103         {
104                 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
105
106                 if(q.pri)
107                         priority.push_back(q);
108                 else
109                         normal.push_back(q);
110         }
111
112         void pop()
113         {
114                 if((which == PRI) && priority.size())
115                 {
116                         priority.pop_front();
117                 }
118                 else if((which == NOR) && normal.size())
119                 {
120                         normal.pop_front();
121                 }
122
123                 /* Reset this */
124                 which = NON;
125
126                 /* Silently do nothing if there was no element to pop() */
127         }
128
129         SQLrequest& front()
130         {
131                 switch(which)
132                 {
133                         case PRI:
134                                 return priority.front();
135                         case NOR:
136                                 return normal.front();
137                         default:
138                                 if(priority.size())
139                                 {
140                                         which = PRI;
141                                         return priority.front();
142                                 }
143
144                                 if(normal.size())
145                                 {
146                                         which = NOR;
147                                         return normal.front();
148                                 }
149
150                                 /* This will probably result in a segfault,
151                                  * but the caller should have checked totalsize()
152                                  * first so..meh - moron :p
153                                  */
154
155                                 return priority.front();
156                 }
157         }
158
159         std::pair<int, int> size()
160         {
161                 return std::make_pair(priority.size(), normal.size());
162         }
163
164         int totalsize()
165         {
166                 return priority.size() + normal.size();
167         }
168
169         void PurgeModule(Module* mod)
170         {
171                 DoPurgeModule(mod, priority);
172                 DoPurgeModule(mod, normal);
173         }
174
175 private:
176         void DoPurgeModule(Module* mod, ReqDeque& q)
177         {
178                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
179                 {
180                         if(iter->GetSource() == mod)
181                         {
182                                 if(iter->id == front().id)
183                                 {
184                                         /* It's the currently active query.. :x */
185                                         iter->SetSource(NULL);
186                                 }
187                                 else
188                                 {
189                                         /* It hasn't been executed yet..just remove it */
190                                         iter = q.erase(iter);
191                                 }
192                         }
193                 }
194         }
195 };
196
197 /* A mutex to wrap around queue accesses */
198 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
199
200 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
201
202 class MySQLresult : public SQLresult
203 {
204         int currentrow;
205         //std::vector<std::map<std::string,std::string> > results;
206         std::vector<std::string> colnames;
207         std::vector<SQLfieldList> fieldlists;
208         SQLfieldMap* fieldmap;
209         int rows;
210         int cols;
211  public:
212
213         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL)
214         {
215                 /* A number of affected rows from from mysql_affected_rows.
216                  */
217                 log(DEBUG,"Created new MySQLresult of non-error type");
218                 fieldlists.clear();
219                 rows = 0;
220                 if (affected_rows >= 1)
221                 {
222                         rows = affected_rows;
223                         fieldlists.resize(rows);
224                 }
225                 unsigned int field_count = 0;
226                 if (res)
227                 {
228                         MYSQL_ROW row;
229                         int n = 0;
230                         while ((row = mysql_fetch_row(res)))
231                         {
232                                 if (fieldlists.size() < (unsigned int)rows+1)
233                                 {
234                                         fieldlists.resize(fieldlists.size()+1);
235                                 }
236                                 field_count = 0;
237                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
238                                 if(mysql_num_fields(res) == 0)
239                                         break;
240                                 if (fields && mysql_num_fields(res))
241                                 {
242                                         colnames.clear();
243                                         while (field_count < mysql_num_fields(res))
244                                         {
245                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
246                                                 std::string b = (row[field_count] ? row[field_count] : "");
247                                                 SQLfield sqlf(b, !row[field_count]);
248                                                 colnames.push_back(a);
249                                                 fieldlists[n].push_back(sqlf); 
250                                                 log(DEBUG,"Inc field count to %d",field_count+1);
251                                                 field_count++;
252                                         }
253                                         n++;
254                                 }
255                                 rows++;
256                         }
257                         mysql_free_result(res);
258                 }
259                 log(DEBUG, "Created new MySQL result; %d rows, %d columns", rows, colnames.size());
260         }
261
262         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0)
263         {
264                 rows = 0;
265                 error = e;
266                 log(DEBUG,"Created new MySQLresult of error type");
267         }
268
269         ~MySQLresult()
270         {
271         }
272
273         virtual int Rows()
274         {
275                 return rows;
276         }
277
278         virtual int Cols()
279         {
280                 return colnames.size();
281         }
282
283         virtual std::string ColName(int column)
284         {
285                 if (column < (int)colnames.size())
286                 {
287                         return colnames[column];
288                 }
289                 else
290                 {
291                         throw SQLbadColName();
292                 }
293                 return "";
294         }
295
296         virtual int ColNum(const std::string &column)
297         {
298                 for (unsigned int i = 0; i < colnames.size(); i++)
299                 {
300                         if (column == colnames[i])
301                                 return i;
302                 }
303                 throw SQLbadColName();
304                 return 0;
305         }
306
307         virtual SQLfield GetValue(int row, int column)
308         {
309                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
310                 {
311                         return fieldlists[row][column];
312                 }
313
314                 log(DEBUG,"Danger will robinson, we don't have row %d, column %d!", row, column);
315                 throw SQLbadColName();
316
317                 /* XXX: We never actually get here because of the throw */
318                 return SQLfield("",true);
319         }
320
321         virtual SQLfieldList& GetRow()
322         {
323                 return fieldlists[currentrow];
324         }
325
326         virtual SQLfieldMap& GetRowMap()
327         {
328                 fieldmap = new SQLfieldMap();
329                 
330                 for (int i = 0; i < cols; i++)
331                 {
332                         fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
333                 }
334                 currentrow++;
335
336                 return *fieldmap;
337         }
338
339         virtual SQLfieldList* GetRowPtr()
340         {
341                 return &fieldlists[currentrow++];
342         }
343
344         virtual SQLfieldMap* GetRowMapPtr()
345         {
346                 fieldmap = new SQLfieldMap();
347
348                 for (int i = 0; i < cols; i++)
349                 {
350                         fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
351                 }
352                 currentrow++;
353
354                 return fieldmap;
355         }
356
357         virtual void Free(SQLfieldMap* fm)
358         {
359                 delete fm;
360         }
361
362         virtual void Free(SQLfieldList* fl)
363         {
364                 /* XXX: Yes, this is SUPPOSED to do nothing, we
365                  * dont want to free our fieldlist until we
366                  * destruct the object. Unlike the pgsql module,
367                  * we only have the one.
368                  */
369         }
370 };
371
372 class SQLConnection;
373
374 void NotifyMainThread(SQLConnection* connection_with_new_result);
375
376 class SQLConnection : public classbase
377 {
378  protected:
379
380         MYSQL connection;
381         MYSQL_RES *res;
382         MYSQL_ROW row;
383         std::string host;
384         std::string user;
385         std::string pass;
386         std::string db;
387         std::map<std::string,std::string> thisrow;
388         bool Enabled;
389         std::string id;
390
391  public:
392
393         QueryQueue queue;
394         ResultQueue rq;
395
396         // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
397         // MYSQL struct, but does not connect yet.
398         SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, const std::string &myid)
399         {
400                 this->Enabled = true;
401                 this->host = thishost;
402                 this->user = thisuser;
403                 this->pass = thispass;
404                 this->db = thisdb;
405                 this->id = myid;
406         }
407
408         // This method connects to the database using the credentials supplied to the constructor, and returns
409         // true upon success.
410         bool Connect()
411         {
412                 unsigned int timeout = 1;
413                 mysql_init(&connection);
414                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
415                 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
416         }
417
418         void DoLeadingQuery()
419         {
420                 if (!CheckConnection())
421                         return;
422
423                 /* Parse the command string and dispatch it to mysql */
424                 SQLrequest& req = queue.front();
425                 log(DEBUG,"DO QUERY: %s",req.query.q.c_str());
426
427                 /* Pointer to the buffer we screw around with substitution in */
428                 char* query;
429
430                 /* Pointer to the current end of query, where we append new stuff */
431                 char* queryend;
432
433                 /* Total length of the unescaped parameters */
434                 unsigned long paramlen;
435
436                 /* Total length of query, used for binary-safety in mysql_real_query */
437                 unsigned long querylength = 0;
438
439                 paramlen = 0;
440
441                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
442                 {
443                         paramlen += i->size();
444                 }
445
446                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
447                  * sizeofquery + (totalparamlength*2) + 1
448                  *
449                  * The +1 is for null-terminating the string for mysql_real_escape_string
450                  */
451
452                 query = new char[req.query.q.length() + (paramlen*2)];
453                 queryend = query;
454
455                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
456                  * the parameters into it...
457                  */
458
459                 for(unsigned long i = 0; i < req.query.q.length(); i++)
460                 {
461                         if(req.query.q[i] == '?')
462                         {
463                                 /* We found a place to substitute..what fun.
464                                  * use mysql calls to escape and write the
465                                  * escaped string onto the end of our query buffer,
466                                  * then we "just" need to make sure queryend is
467                                  * pointing at the right place.
468                                  */
469                                 if(req.query.p.size())
470                                 {
471                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
472
473                                         queryend += len;
474                                         req.query.p.pop_front();
475                                 }
476                                 else
477                                 {
478                                         log(DEBUG, "Found a substitution location but no parameter to substitute :|");
479                                         break;
480                                 }
481                         }
482                         else
483                         {
484                                 *queryend = req.query.q[i];
485                                 queryend++;
486                         }
487                         querylength++;
488                 }
489
490                 *queryend = 0;
491
492                 log(DEBUG, "Attempting to dispatch query: %s", query);
493
494                 pthread_mutex_lock(&queue_mutex);
495                 req.query.q = query;
496                 pthread_mutex_unlock(&queue_mutex);
497
498                 log(DEBUG,"REQUEST ID: %d",req.id);
499
500                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
501                 {
502                         /* Successfull query */
503                         res = mysql_use_result(&connection);
504                         unsigned long rows = mysql_affected_rows(&connection);
505                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
506                         r->dbid = this->GetID();
507                         r->query = req.query.q;
508                         /* Put this new result onto the results queue.
509                          * XXX: Remember to mutex the queue!
510                          */
511                         pthread_mutex_lock(&results_mutex);
512                         rq.push_back(r);
513                         pthread_mutex_unlock(&results_mutex);
514                 }
515                 else
516                 {
517                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
518                          * possible error numbers and error messages */
519                         log(DEBUG,"SQL ERROR: %s",mysql_error(&connection));
520                         SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
521                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
522                         r->dbid = this->GetID();
523                         r->query = req.query.q;
524
525                         pthread_mutex_lock(&results_mutex);
526                         rq.push_back(r);
527                         pthread_mutex_unlock(&results_mutex);
528                 }
529
530                 /* Now signal the main thread that we've got a result to process.
531                  * Pass them this connection id as what to examine
532                  */
533
534                 NotifyMainThread(this);
535         }
536
537         bool ConnectionLost()
538         {
539                 if (&connection) {
540                         return (mysql_ping(&connection) != 0);
541                 }
542                 else return false;
543         }
544
545         bool CheckConnection()
546         {
547                 if (ConnectionLost()) {
548                         return Connect();
549                 }
550                 else return true;
551         }
552
553         std::string GetError()
554         {
555                 return mysql_error(&connection);
556         }
557
558         const std::string& GetID()
559         {
560                 return id;
561         }
562
563         std::string GetHost()
564         {
565                 return host;
566         }
567
568         void SetEnable(bool Enable)
569         {
570                 Enabled = Enable;
571         }
572
573         bool IsEnabled()
574         {
575                 return Enabled;
576         }
577
578 };
579
580 ConnMap Connections;
581
582 void ConnectDatabases(Server* Srv)
583 {
584         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
585         {
586                 i->second->SetEnable(true);
587                 if (i->second->Connect())
588                 {
589                         Srv->Log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
590                 }
591                 else
592                 {
593                         Srv->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
594                         i->second->SetEnable(false);
595                 }
596         }
597 }
598
599
600 void LoadDatabases(ConfigReader* ThisConf, Server* Srv)
601 {
602         Srv->Log(DEFAULT,"SQL: Loading database settings");
603         Connections.clear();
604         Srv->Log(DEBUG,"Cleared connections");
605         for (int j =0; j < ThisConf->Enumerate("database"); j++)
606         {
607                 std::string db = ThisConf->ReadValue("database","name",j);
608                 std::string user = ThisConf->ReadValue("database","username",j);
609                 std::string pass = ThisConf->ReadValue("database","password",j);
610                 std::string host = ThisConf->ReadValue("database","hostname",j);
611                 std::string id = ThisConf->ReadValue("database","id",j);
612                 Srv->Log(DEBUG,"Read database settings");
613                 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
614                 {
615                         SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
616                         Srv->Log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
617                         Connections[id] = ThisSQL;
618                         Srv->Log(DEBUG,"Pushed back connection");
619                 }
620         }
621         ConnectDatabases(Srv);
622 }
623
624 void NotifyMainThread(SQLConnection* connection_with_new_result)
625 {
626         /* Here we write() to the socket the main thread has open
627          * and we connect()ed back to before our thread became active.
628          * The main thread is using a nonblocking socket tied into
629          * the socket engine, so they wont block and they'll receive
630          * nearly instant notification. Because we're in a seperate
631          * thread, we can just use standard connect(), and we can
632          * block if we like. We just send the connection id of the
633          * connection back.
634          */
635         log(DEBUG,"Notify of result on connection: %s",connection_with_new_result->GetID().c_str());
636         if (send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0) < 1) // add one for null terminator
637         {
638                 log(DEBUG,"Error writing to QueueFD: %s",strerror(errno));
639         }
640         log(DEBUG,"Sent it on its way via fd=%d",QueueFD);
641 }
642
643 void* DispatcherThread(void* arg);
644
645 class Notifier : public InspSocket
646 {
647         sockaddr_in sock_us;
648         socklen_t uslen;
649         Server* Srv;
650
651  public:
652
653         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
654         Notifier(Server* S) : InspSocket("127.0.0.1", 0, true, 3000), Srv(S)
655         {
656                 uslen = sizeof(sock_us);
657                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
658                 {
659                         throw ModuleException("Could not create random listening port on localhost");
660                 }
661         }
662
663         Notifier(int newfd, char* ip, Server* S) : InspSocket(newfd, ip), Srv(S)
664         {
665                 log(DEBUG,"Constructor of new socket");
666         }
667
668         /* Using getsockname and ntohs, we can determine which port number we were allocated */
669         int GetPort()
670         {
671                 return ntohs(sock_us.sin_port);
672         }
673
674         virtual int OnIncomingConnection(int newsock, char* ip)
675         {
676                 log(DEBUG,"Inbound connection on fd %d!",newsock);
677                 Notifier* n = new Notifier(newsock, ip, Srv);
678                 Srv->AddSocket(n);
679                 return true;
680         }
681
682         virtual bool OnDataReady()
683         {
684                 log(DEBUG,"Inbound data!");
685                 char* data = this->Read();
686                 ConnMap::iterator iter;
687
688                 if (data && *data)
689                 {
690                         log(DEBUG,"Looking for connection %s",data);
691                         /* We expect to be sent a null terminated string */
692                         if((iter = Connections.find(data)) != Connections.end())
693                         {
694                                 log(DEBUG,"Found it!");
695
696                                 /* Lock the mutex, send back the data */
697                                 pthread_mutex_lock(&results_mutex);
698                                 ResultQueue::iterator n = iter->second->rq.begin();
699                                 (*n)->Send();
700                                 iter->second->rq.pop_front();
701                                 pthread_mutex_unlock(&results_mutex);
702                                 return true;
703                         }
704                 }
705
706                 return false;
707         }
708 };
709
710 class ModuleSQL : public Module
711 {
712  public:
713         Server *Srv;
714         ConfigReader *Conf;
715         pthread_t Dispatcher;
716         int currid;
717
718         void Implements(char* List)
719         {
720                 List[I_OnRehash] = List[I_OnRequest] = 1;
721         }
722
723         unsigned long NewID()
724         {
725                 if (currid+1 == 0)
726                         currid++;
727                 return ++currid;
728         }
729
730         char* OnRequest(Request* request)
731         {
732                 if(strcmp(SQLREQID, request->GetData()) == 0)
733                 {
734                         SQLrequest* req = (SQLrequest*)request;
735
736                         /* XXX: Lock */
737                         pthread_mutex_lock(&queue_mutex);
738
739                         ConnMap::iterator iter;
740
741                         char* returnval = NULL;
742
743                         log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
744
745                         if((iter = Connections.find(req->dbid)) != Connections.end())
746                         {
747                                 req->id = NewID();
748                                 iter->second->queue.push(*req);
749                                 returnval = SQLSUCCESS;
750                         }
751                         else
752                         {
753                                 req->error.Id(BAD_DBID);
754                         }
755
756                         pthread_mutex_unlock(&queue_mutex);
757                         /* XXX: Unlock */
758
759                         return returnval;
760                 }
761
762                 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
763
764                 return NULL;
765         }
766
767         ModuleSQL(Server* Me)
768                 : Module::Module(Me)
769         {
770                 Srv = Me;
771                 Conf = new ConfigReader();
772                 currid = 0;
773                 SQLModule = this;
774
775                 MessagePipe = new Notifier(Srv);
776                 Srv->AddSocket(MessagePipe);
777                 log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
778                 
779                 pthread_attr_t attribs;
780                 pthread_attr_init(&attribs);
781                 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
782                 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
783                 {
784                         throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
785                 }
786                 if (!Srv->PublishFeature("SQL", this))
787                 {
788                         /* Tell worker thread to exit NOW */
789                         giveup = true;
790                         throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
791                 }
792         }
793         
794         virtual ~ModuleSQL()
795         {
796                 DELETE(Conf);
797         }
798         
799         virtual void OnRehash(const std::string &parameter)
800         {
801                 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
802         }
803         
804         virtual Version GetVersion()
805         {
806                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
807         }
808         
809 };
810
811 void* DispatcherThread(void* arg)
812 {
813         log(DEBUG,"Starting Dispatcher thread, mysql version %d",mysql_get_client_version());
814         ModuleSQL* thismodule = (ModuleSQL*)arg;
815         LoadDatabases(thismodule->Conf, thismodule->Srv);
816
817         /* Connect back to the Notifier */
818
819         if ((QueueFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
820         {
821                 /* crap, we're out of sockets... */
822                 log(DEBUG,"QueueFD cant be created");
823                 return NULL;
824         }
825
826         log(DEBUG,"Initialize QueueFD to %d",QueueFD);
827
828         sockaddr_in addr;
829         in_addr ia;
830         inet_aton("127.0.0.1", &ia);
831         addr.sin_family = AF_INET;
832         addr.sin_addr = ia;
833         addr.sin_port = htons(MessagePipe->GetPort());
834
835         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
836         {
837                 /* wtf, we cant connect to it, but we just created it! */
838                 log(DEBUG,"QueueFD cant connect!");
839                 return NULL;
840         }
841
842         log(DEBUG,"Connect QUEUE FD");
843
844         while (!giveup)
845         {
846                 SQLConnection* conn = NULL;
847                 /* XXX: Lock here for safety */
848                 pthread_mutex_lock(&queue_mutex);
849                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
850                 {
851                         if (i->second->queue.totalsize())
852                         {
853                                 conn = i->second;
854                                 break;
855                         }
856                 }
857                 pthread_mutex_unlock(&queue_mutex);
858                 /* XXX: Unlock */
859
860                 /* Theres an item! */
861                 if (conn)
862                 {
863                         log(DEBUG,"Process Leading query");
864                         conn->DoLeadingQuery();
865
866                         /* XXX: Lock */
867                         pthread_mutex_lock(&queue_mutex);
868                         conn->queue.pop();
869                         pthread_mutex_unlock(&queue_mutex);
870                         /* XXX: Unlock */
871                 }
872
873                 usleep(50);
874         }
875
876         return NULL;
877 }
878
879
880 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
881
882 class ModuleSQLFactory : public ModuleFactory
883 {
884  public:
885         ModuleSQLFactory()
886         {
887         }
888         
889         ~ModuleSQLFactory()
890         {
891         }
892         
893         virtual Module * CreateModule(Server* Me)
894         {
895                 return new ModuleSQL(Me);
896         }
897         
898 };
899
900
901 extern "C" void * init_module( void )
902 {
903         return new ModuleSQLFactory;
904 }
905