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