]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Mass-tidyup of module global vars, theyre no longer global vars.
[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 "inspircd.h"
28 #include "m_sqlv2.h"
29
30 /* VERSION 2 API: With nonblocking (threaded) requests */
31
32 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
33 /* $CompileFlags: `mysql_config --include` */
34 /* $LinkerFlags: `mysql_config --libs_r` `perl extra/mysql_rpath.pl` */
35
36 /* THE NONBLOCKING MYSQL API!
37  * 
38  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
39  * that instead, you should thread your program. This is what i've done here to allow for
40  * asyncronous SQL requests via mysql. The way this works is as follows:
41  *
42  * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
43  * using a queue with priorities. There is a mutex on either end which prevents two threads
44  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
45  * worker thread wakes up, and checks if there is a request at the head of its queue.
46  * If there is, it processes this request, blocking the worker thread but leaving the ircd
47  * thread to go about its business as usual. During this period, the ircd thread is able
48  * to insert futher pending requests into the queue.
49  *
50  * Once the processing of a request is complete, it is removed from the incoming queue to
51  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
52  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
53  * connection ID through the connection.
54  *
55  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
56  * of the queue, and sends it on its way to the original calling module.
57  *
58  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
59  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
60  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
61  * however, if we were to call a module's OnRequest even from within a thread which was not the
62  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
63  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
64  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
65  * gauranteed threadsafe!)
66  *
67  * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
68  */
69
70
71 class SQLConnection;
72 class Notifier;
73
74 extern InspIRCd* ServerInstance;
75 typedef std::map<std::string, SQLConnection*> ConnMap;
76 bool giveup = false;
77 static Module* SQLModule = NULL;
78 static Notifier* MessagePipe = NULL;
79 int QueueFD = -1;
80
81
82 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
83 #define mysql_field_count mysql_num_fields
84 #endif
85
86 typedef std::deque<SQLresult*> ResultQueue;
87
88 class QueryQueue : public classbase
89 {
90 private:
91         typedef std::deque<SQLrequest> ReqDeque;
92
93         ReqDeque priority;      /* The priority queue */
94         ReqDeque normal;        /* The 'normal' queue */
95         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
96
97 public:
98         QueryQueue()
99         : which(NON)
100         {
101         }
102
103         void push(const SQLrequest &q)
104         {
105                 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
106
107                 if(q.pri)
108                         priority.push_back(q);
109                 else
110                         normal.push_back(q);
111         }
112
113         void pop()
114         {
115                 if((which == PRI) && priority.size())
116                 {
117                         priority.pop_front();
118                 }
119                 else if((which == NOR) && normal.size())
120                 {
121                         normal.pop_front();
122                 }
123
124                 /* Reset this */
125                 which = NON;
126
127                 /* Silently do nothing if there was no element to pop() */
128         }
129
130         SQLrequest& front()
131         {
132                 switch(which)
133                 {
134                         case PRI:
135                                 return priority.front();
136                         case NOR:
137                                 return normal.front();
138                         default:
139                                 if(priority.size())
140                                 {
141                                         which = PRI;
142                                         return priority.front();
143                                 }
144
145                                 if(normal.size())
146                                 {
147                                         which = NOR;
148                                         return normal.front();
149                                 }
150
151                                 /* This will probably result in a segfault,
152                                  * but the caller should have checked totalsize()
153                                  * first so..meh - moron :p
154                                  */
155
156                                 return priority.front();
157                 }
158         }
159
160         std::pair<int, int> size()
161         {
162                 return std::make_pair(priority.size(), normal.size());
163         }
164
165         int totalsize()
166         {
167                 return priority.size() + normal.size();
168         }
169
170         void PurgeModule(Module* mod)
171         {
172                 DoPurgeModule(mod, priority);
173                 DoPurgeModule(mod, normal);
174         }
175
176 private:
177         void DoPurgeModule(Module* mod, ReqDeque& q)
178         {
179                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
180                 {
181                         if(iter->GetSource() == mod)
182                         {
183                                 if(iter->id == front().id)
184                                 {
185                                         /* It's the currently active query.. :x */
186                                         iter->SetSource(NULL);
187                                 }
188                                 else
189                                 {
190                                         /* It hasn't been executed yet..just remove it */
191                                         iter = q.erase(iter);
192                                 }
193                         }
194                 }
195         }
196 };
197
198 /* A mutex to wrap around queue accesses */
199 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
200
201 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
202
203 class MySQLresult : public SQLresult
204 {
205         int currentrow;
206         //std::vector<std::map<std::string,std::string> > results;
207         std::vector<std::string> colnames;
208         std::vector<SQLfieldList> fieldlists;
209         SQLfieldMap* fieldmap;
210         SQLfieldMap fieldmap2;
211         SQLfieldList emptyfieldlist;
212         int rows;
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[i],GetValue(currentrow, i)));
340                         }
341                         currentrow++;
342                 }
343
344                 return fieldmap2;
345         }
346
347         virtual SQLfieldList* GetRowPtr()
348         {
349                 SQLfieldList* fieldlist = new SQLfieldList();
350
351                 if (currentrow < rows)
352                 {
353                         for (int i = 0; i < Rows(); i++)
354                         {
355                                 fieldlist->push_back(fieldlists[currentrow][i]);
356                         }
357                         currentrow++;
358                 }
359                 return fieldlist;
360         }
361
362         virtual SQLfieldMap* GetRowMapPtr()
363         {
364                 fieldmap = new SQLfieldMap();
365                 
366                 if (currentrow < rows)
367                 {
368                         for (int i = 0; i < Cols(); i++)
369                         {
370                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
371                         }
372                         currentrow++;
373                 }
374
375                 return fieldmap;
376         }
377
378         virtual void Free(SQLfieldMap* fm)
379         {
380                 delete fm;
381         }
382
383         virtual void Free(SQLfieldList* fl)
384         {
385                 delete fl;
386         }
387 };
388
389 class SQLConnection;
390
391 void NotifyMainThread(SQLConnection* connection_with_new_result);
392
393 class SQLConnection : public classbase
394 {
395  protected:
396
397         MYSQL connection;
398         MYSQL_RES *res;
399         MYSQL_ROW row;
400         std::string host;
401         std::string user;
402         std::string pass;
403         std::string db;
404         std::map<std::string,std::string> thisrow;
405         bool Enabled;
406         std::string id;
407
408  public:
409
410         QueryQueue queue;
411         ResultQueue rq;
412
413         // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
414         // MYSQL struct, but does not connect yet.
415         SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, const std::string &myid)
416         {
417                 this->Enabled = true;
418                 this->host = thishost;
419                 this->user = thisuser;
420                 this->pass = thispass;
421                 this->db = thisdb;
422                 this->id = myid;
423         }
424
425         // This method connects to the database using the credentials supplied to the constructor, and returns
426         // true upon success.
427         bool Connect()
428         {
429                 unsigned int timeout = 1;
430                 mysql_init(&connection);
431                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
432                 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
433         }
434
435         void DoLeadingQuery()
436         {
437                 if (!CheckConnection())
438                         return;
439
440                 /* Parse the command string and dispatch it to mysql */
441                 SQLrequest& req = queue.front();
442                 log(DEBUG,"DO QUERY: %s",req.query.q.c_str());
443
444                 /* Pointer to the buffer we screw around with substitution in */
445                 char* query;
446
447                 /* Pointer to the current end of query, where we append new stuff */
448                 char* queryend;
449
450                 /* Total length of the unescaped parameters */
451                 unsigned long paramlen;
452
453                 /* Total length of query, used for binary-safety in mysql_real_query */
454                 unsigned long querylength = 0;
455
456                 paramlen = 0;
457
458                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
459                 {
460                         paramlen += i->size();
461                 }
462
463                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
464                  * sizeofquery + (totalparamlength*2) + 1
465                  *
466                  * The +1 is for null-terminating the string for mysql_real_escape_string
467                  */
468
469                 query = new char[req.query.q.length() + (paramlen*2)];
470                 queryend = query;
471
472                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
473                  * the parameters into it...
474                  */
475
476                 for(unsigned long i = 0; i < req.query.q.length(); i++)
477                 {
478                         if(req.query.q[i] == '?')
479                         {
480                                 /* We found a place to substitute..what fun.
481                                  * use mysql calls to escape and write the
482                                  * escaped string onto the end of our query buffer,
483                                  * then we "just" need to make sure queryend is
484                                  * pointing at the right place.
485                                  */
486                                 if(req.query.p.size())
487                                 {
488                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
489
490                                         queryend += len;
491                                         req.query.p.pop_front();
492                                 }
493                                 else
494                                 {
495                                         log(DEBUG, "Found a substitution location but no parameter to substitute :|");
496                                         break;
497                                 }
498                         }
499                         else
500                         {
501                                 *queryend = req.query.q[i];
502                                 queryend++;
503                         }
504                         querylength++;
505                 }
506
507                 *queryend = 0;
508
509                 log(DEBUG, "Attempting to dispatch query: %s", query);
510
511                 pthread_mutex_lock(&queue_mutex);
512                 req.query.q = query;
513                 pthread_mutex_unlock(&queue_mutex);
514
515                 log(DEBUG,"REQUEST ID: %d",req.id);
516
517                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
518                 {
519                         /* Successfull query */
520                         res = mysql_use_result(&connection);
521                         unsigned long rows = mysql_affected_rows(&connection);
522                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
523                         r->dbid = this->GetID();
524                         r->query = req.query.q;
525                         /* Put this new result onto the results queue.
526                          * XXX: Remember to mutex the queue!
527                          */
528                         pthread_mutex_lock(&results_mutex);
529                         rq.push_back(r);
530                         pthread_mutex_unlock(&results_mutex);
531                 }
532                 else
533                 {
534                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
535                          * possible error numbers and error messages */
536                         log(DEBUG,"SQL ERROR: %s",mysql_error(&connection));
537                         SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
538                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
539                         r->dbid = this->GetID();
540                         r->query = req.query.q;
541
542                         pthread_mutex_lock(&results_mutex);
543                         rq.push_back(r);
544                         pthread_mutex_unlock(&results_mutex);
545                 }
546
547                 /* Now signal the main thread that we've got a result to process.
548                  * Pass them this connection id as what to examine
549                  */
550
551                 NotifyMainThread(this);
552         }
553
554         bool ConnectionLost()
555         {
556                 if (&connection) {
557                         return (mysql_ping(&connection) != 0);
558                 }
559                 else return false;
560         }
561
562         bool CheckConnection()
563         {
564                 if (ConnectionLost()) {
565                         return Connect();
566                 }
567                 else return true;
568         }
569
570         std::string GetError()
571         {
572                 return mysql_error(&connection);
573         }
574
575         const std::string& GetID()
576         {
577                 return id;
578         }
579
580         std::string GetHost()
581         {
582                 return host;
583         }
584
585         void SetEnable(bool Enable)
586         {
587                 Enabled = Enable;
588         }
589
590         bool IsEnabled()
591         {
592                 return Enabled;
593         }
594
595 };
596
597 ConnMap Connections;
598
599 void ConnectDatabases(Server* Srv)
600 {
601         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
602         {
603                 i->second->SetEnable(true);
604                 if (i->second->Connect())
605                 {
606                         log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
607                 }
608                 else
609                 {
610                         log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
611                         i->second->SetEnable(false);
612                 }
613         }
614 }
615
616
617 void LoadDatabases(ConfigReader* ThisConf, Server* Srv)
618 {
619         log(DEFAULT,"SQL: Loading database settings");
620         Connections.clear();
621         log(DEBUG,"Cleared connections");
622         for (int j =0; j < ThisConf->Enumerate("database"); j++)
623         {
624                 std::string db = ThisConf->ReadValue("database","name",j);
625                 std::string user = ThisConf->ReadValue("database","username",j);
626                 std::string pass = ThisConf->ReadValue("database","password",j);
627                 std::string host = ThisConf->ReadValue("database","hostname",j);
628                 std::string id = ThisConf->ReadValue("database","id",j);
629                 log(DEBUG,"Read database settings");
630                 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
631                 {
632                         SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
633                         log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
634                         Connections[id] = ThisSQL;
635                         log(DEBUG,"Pushed back connection");
636                 }
637         }
638         ConnectDatabases(Srv);
639 }
640
641 void NotifyMainThread(SQLConnection* connection_with_new_result)
642 {
643         /* Here we write() to the socket the main thread has open
644          * and we connect()ed back to before our thread became active.
645          * The main thread is using a nonblocking socket tied into
646          * the socket engine, so they wont block and they'll receive
647          * nearly instant notification. Because we're in a seperate
648          * thread, we can just use standard connect(), and we can
649          * block if we like. We just send the connection id of the
650          * connection back.
651          */
652         log(DEBUG,"Notify of result on connection: %s",connection_with_new_result->GetID().c_str());
653         if (send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0) < 1) // add one for null terminator
654         {
655                 log(DEBUG,"Error writing to QueueFD: %s",strerror(errno));
656         }
657         log(DEBUG,"Sent it on its way via fd=%d",QueueFD);
658 }
659
660 void* DispatcherThread(void* arg);
661
662 class Notifier : public InspSocket
663 {
664         insp_sockaddr sock_us;
665         socklen_t uslen;
666         Server* Srv;
667
668  public:
669
670         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
671 #ifdef IPV6
672         Notifier(InspIRCd* SI, Server* S) : InspSocket(SI, "::1", 0, true, 3000), Srv(S)
673 #else
674         Notifier(InspIRCd* SI, Server* S) : InspSocket(SI, "127.0.0.1", 0, true, 3000), Srv(S)
675 #endif
676         {
677                 uslen = sizeof(sock_us);
678                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
679                 {
680                         throw ModuleException("Could not create random listening port on localhost");
681                 }
682         }
683
684         Notifier(InspIRCd* SI, int newfd, char* ip, Server* S) : InspSocket(SI, newfd, ip), Srv(S)
685         {
686                 log(DEBUG,"Constructor of new socket");
687         }
688
689         /* Using getsockname and ntohs, we can determine which port number we were allocated */
690         int GetPort()
691         {
692 #ifdef IPV6
693                 return ntohs(sock_us.sin6_port);
694 #else
695                 return ntohs(sock_us.sin_port);
696 #endif
697         }
698
699         virtual int OnIncomingConnection(int newsock, char* ip)
700         {
701                 log(DEBUG,"Inbound connection on fd %d!",newsock);
702                 Notifier* n = new Notifier(this->Instance, newsock, ip, Srv);
703                 Srv->AddSocket(n);
704                 return true;
705         }
706
707         virtual bool OnDataReady()
708         {
709                 log(DEBUG,"Inbound data!");
710                 char* data = this->Read();
711                 ConnMap::iterator iter;
712
713                 if (data && *data)
714                 {
715                         log(DEBUG,"Looking for connection %s",data);
716                         /* We expect to be sent a null terminated string */
717                         if((iter = Connections.find(data)) != Connections.end())
718                         {
719                                 log(DEBUG,"Found it!");
720
721                                 /* Lock the mutex, send back the data */
722                                 pthread_mutex_lock(&results_mutex);
723                                 ResultQueue::iterator n = iter->second->rq.begin();
724                                 (*n)->Send();
725                                 iter->second->rq.pop_front();
726                                 pthread_mutex_unlock(&results_mutex);
727                                 return true;
728                         }
729                 }
730
731                 return false;
732         }
733 };
734
735 class ModuleSQL : public Module
736 {
737  public:
738         Server *Srv;
739         ConfigReader *Conf;
740         pthread_t Dispatcher;
741         int currid;
742
743         void Implements(char* List)
744         {
745                 List[I_OnRehash] = List[I_OnRequest] = 1;
746         }
747
748         unsigned long NewID()
749         {
750                 if (currid+1 == 0)
751                         currid++;
752                 return ++currid;
753         }
754
755         char* OnRequest(Request* request)
756         {
757                 if(strcmp(SQLREQID, request->GetId()) == 0)
758                 {
759                         SQLrequest* req = (SQLrequest*)request;
760
761                         /* XXX: Lock */
762                         pthread_mutex_lock(&queue_mutex);
763
764                         ConnMap::iterator iter;
765
766                         char* returnval = NULL;
767
768                         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());
769
770                         if((iter = Connections.find(req->dbid)) != Connections.end())
771                         {
772                                 req->id = NewID();
773                                 iter->second->queue.push(*req);
774                                 returnval = SQLSUCCESS;
775                         }
776                         else
777                         {
778                                 req->error.Id(BAD_DBID);
779                         }
780
781                         pthread_mutex_unlock(&queue_mutex);
782                         /* XXX: Unlock */
783
784                         return returnval;
785                 }
786
787                 log(DEBUG, "Got unsupported API version string: %s", request->GetId());
788
789                 return NULL;
790         }
791
792         ModuleSQL(Server* Me)
793                 : Module::Module(Me)
794         {
795                 Srv = Me;
796                 Conf = new ConfigReader();
797                 currid = 0;
798                 SQLModule = this;
799
800                 MessagePipe = new Notifier(ServerInstance, Srv);
801                 Srv->AddSocket(MessagePipe);
802                 log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
803                 
804                 pthread_attr_t attribs;
805                 pthread_attr_init(&attribs);
806                 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
807                 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
808                 {
809                         throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
810                 }
811                 if (!ServerInstance->PublishFeature("SQL", this))
812                 {
813                         /* Tell worker thread to exit NOW */
814                         giveup = true;
815                         throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
816                 }
817         }
818         
819         virtual ~ModuleSQL()
820         {
821                 DELETE(Conf);
822         }
823         
824         virtual void OnRehash(const std::string &parameter)
825         {
826                 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
827         }
828         
829         virtual Version GetVersion()
830         {
831                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
832         }
833         
834 };
835
836 void* DispatcherThread(void* arg)
837 {
838         log(DEBUG,"Starting Dispatcher thread, mysql version %d",mysql_get_client_version());
839         ModuleSQL* thismodule = (ModuleSQL*)arg;
840         LoadDatabases(thismodule->Conf, thismodule->Srv);
841
842         /* Connect back to the Notifier */
843
844         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
845         {
846                 /* crap, we're out of sockets... */
847                 log(DEBUG,"QueueFD cant be created");
848                 return NULL;
849         }
850
851         log(DEBUG,"Initialize QueueFD to %d",QueueFD);
852
853         insp_sockaddr addr;
854
855 #ifdef IPV6
856         insp_aton("::1", &addr.sin6_addr);
857         addr.sin6_family = AF_FAMILY;
858         addr.sin6_port = htons(MessagePipe->GetPort());
859 #else
860         insp_inaddr ia;
861         insp_aton("127.0.0.1", &ia);
862         addr.sin_family = AF_FAMILY;
863         addr.sin_addr = ia;
864         addr.sin_port = htons(MessagePipe->GetPort());
865 #endif
866
867         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
868         {
869                 /* wtf, we cant connect to it, but we just created it! */
870                 log(DEBUG,"QueueFD cant connect!");
871                 return NULL;
872         }
873
874         log(DEBUG,"Connect QUEUE FD");
875
876         while (!giveup)
877         {
878                 SQLConnection* conn = NULL;
879                 /* XXX: Lock here for safety */
880                 pthread_mutex_lock(&queue_mutex);
881                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
882                 {
883                         if (i->second->queue.totalsize())
884                         {
885                                 conn = i->second;
886                                 break;
887                         }
888                 }
889                 pthread_mutex_unlock(&queue_mutex);
890                 /* XXX: Unlock */
891
892                 /* Theres an item! */
893                 if (conn)
894                 {
895                         log(DEBUG,"Process Leading query");
896                         conn->DoLeadingQuery();
897
898                         /* XXX: Lock */
899                         pthread_mutex_lock(&queue_mutex);
900                         conn->queue.pop();
901                         pthread_mutex_unlock(&queue_mutex);
902                         /* XXX: Unlock */
903                 }
904
905                 usleep(50);
906         }
907
908         return NULL;
909 }
910
911
912 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
913
914 class ModuleSQLFactory : public ModuleFactory
915 {
916  public:
917         ModuleSQLFactory()
918         {
919         }
920         
921         ~ModuleSQLFactory()
922         {
923         }
924         
925         virtual Module * CreateModule(Server* Me)
926         {
927                 return new ModuleSQL(Me);
928         }
929         
930 };
931
932
933 extern "C" void * init_module( void )
934 {
935         return new ModuleSQLFactory;
936 }