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