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