]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Added <oper:swhois> to m_swhois, which will override <type:swhois> if specified
[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
35 /* THE NONBLOCKING MYSQL API!
36  * 
37  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
38  * that instead, you should thread your program. This is what i've done here to allow for
39  * asyncronous SQL requests via mysql. The way this works is as follows:
40  *
41  * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
42  * using a queue with priorities. There is a mutex on either end which prevents two threads
43  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
44  * worker thread wakes up, and checks if there is a request at the head of its queue.
45  * If there is, it processes this request, blocking the worker thread but leaving the ircd
46  * thread to go about its business as usual. During this period, the ircd thread is able
47  * to insert futher pending requests into the queue.
48  *
49  * Once the processing of a request is complete, it is removed from the incoming queue to
50  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
51  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
52  * connection ID through the connection.
53  *
54  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
55  * of the queue, and sends it on its way to the original calling module.
56  *
57  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
58  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
59  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
60  * however, if we were to call a module's OnRequest even from within a thread which was not the
61  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
62  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
63  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
64  * gauranteed threadsafe!)
65  *
66  * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
67  */
68
69
70 class SQLConnection;
71 class Notifier;
72
73
74 typedef std::map<std::string, SQLConnection*> ConnMap;
75 bool giveup = false;
76 static Module* SQLModule = NULL;
77 static Notifier* MessagePipe = NULL;
78 int QueueFD = -1;
79
80
81 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
82 #define mysql_field_count mysql_num_fields
83 #endif
84
85 typedef std::deque<SQLresult*> ResultQueue;
86
87 /** Represents a mysql query queue
88  */
89 class QueryQueue : public classbase
90 {
91 private:
92         typedef std::deque<SQLrequest> ReqDeque;
93
94         ReqDeque priority;      /* The priority queue */
95         ReqDeque normal;        /* The 'normal' queue */
96         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
97
98 public:
99         QueryQueue()
100         : which(NON)
101         {
102         }
103
104         void push(const SQLrequest &q)
105         {
106                 if(q.pri)
107                         priority.push_back(q);
108                 else
109                         normal.push_back(q);
110         }
111
112         void pop()
113         {
114                 if((which == PRI) && priority.size())
115                 {
116                         priority.pop_front();
117                 }
118                 else if((which == NOR) && normal.size())
119                 {
120                         normal.pop_front();
121                 }
122
123                 /* Reset this */
124                 which = NON;
125
126                 /* Silently do nothing if there was no element to pop() */
127         }
128
129         SQLrequest& front()
130         {
131                 switch(which)
132                 {
133                         case PRI:
134                                 return priority.front();
135                         case NOR:
136                                 return normal.front();
137                         default:
138                                 if(priority.size())
139                                 {
140                                         which = PRI;
141                                         return priority.front();
142                                 }
143
144                                 if(normal.size())
145                                 {
146                                         which = NOR;
147                                         return normal.front();
148                                 }
149
150                                 /* This will probably result in a segfault,
151                                  * but the caller should have checked totalsize()
152                                  * first so..meh - moron :p
153                                  */
154
155                                 return priority.front();
156                 }
157         }
158
159         std::pair<int, int> size()
160         {
161                 return std::make_pair(priority.size(), normal.size());
162         }
163
164         int totalsize()
165         {
166                 return priority.size() + normal.size();
167         }
168
169         void PurgeModule(Module* mod)
170         {
171                 DoPurgeModule(mod, priority);
172                 DoPurgeModule(mod, normal);
173         }
174
175 private:
176         void DoPurgeModule(Module* mod, ReqDeque& q)
177         {
178                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
179                 {
180                         if(iter->GetSource() == mod)
181                         {
182                                 if(iter->id == front().id)
183                                 {
184                                         /* It's the currently active query.. :x */
185                                         iter->SetSource(NULL);
186                                 }
187                                 else
188                                 {
189                                         /* It hasn't been executed yet..just remove it */
190                                         iter = q.erase(iter);
191                                 }
192                         }
193                 }
194         }
195 };
196
197 /* A mutex to wrap around queue accesses */
198 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
199
200 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
201
202 /** Represents a mysql result set
203  */
204 class MySQLresult : public SQLresult
205 {
206         int currentrow;
207         //std::vector<std::map<std::string,std::string> > results;
208         std::vector<std::string> colnames;
209         std::vector<SQLfieldList> fieldlists;
210         SQLfieldMap* fieldmap;
211         SQLfieldMap fieldmap2;
212         SQLfieldList emptyfieldlist;
213         int rows;
214  public:
215
216         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL)
217         {
218                 /* A number of affected rows from from mysql_affected_rows.
219                  */
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                                                 field_count++;
253                                         }
254                                         n++;
255                                 }
256                                 rows++;
257                         }
258                         mysql_free_result(res);
259                 }
260         }
261
262         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0)
263         {
264                 rows = 0;
265                 error = e;
266         }
267
268         ~MySQLresult()
269         {
270         }
271
272         virtual int Rows()
273         {
274                 return rows;
275         }
276
277         virtual int Cols()
278         {
279                 return colnames.size();
280         }
281
282         virtual std::string ColName(int column)
283         {
284                 if (column < (int)colnames.size())
285                 {
286                         return colnames[column];
287                 }
288                 else
289                 {
290                         throw SQLbadColName();
291                 }
292                 return "";
293         }
294
295         virtual int ColNum(const std::string &column)
296         {
297                 for (unsigned int i = 0; i < colnames.size(); i++)
298                 {
299                         if (column == colnames[i])
300                                 return i;
301                 }
302                 throw SQLbadColName();
303                 return 0;
304         }
305
306         virtual SQLfield GetValue(int row, int column)
307         {
308                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
309                 {
310                         return fieldlists[row][column];
311                 }
312
313                 throw SQLbadColName();
314
315                 /* XXX: We never actually get here because of the throw */
316                 return SQLfield("",true);
317         }
318
319         virtual SQLfieldList& GetRow()
320         {
321                 if (currentrow < rows)
322                         return fieldlists[currentrow];
323                 else
324                         return emptyfieldlist;
325         }
326
327         virtual SQLfieldMap& GetRowMap()
328         {
329                 fieldmap2.clear();
330
331                 if (currentrow < rows)
332                 {
333                         for (int i = 0; i < Cols(); i++)
334                         {
335                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
336                         }
337                         currentrow++;
338                 }
339
340                 return fieldmap2;
341         }
342
343         virtual SQLfieldList* GetRowPtr()
344         {
345                 SQLfieldList* fieldlist = new SQLfieldList();
346
347                 if (currentrow < rows)
348                 {
349                         for (int i = 0; i < Rows(); i++)
350                         {
351                                 fieldlist->push_back(fieldlists[currentrow][i]);
352                         }
353                         currentrow++;
354                 }
355                 return fieldlist;
356         }
357
358         virtual SQLfieldMap* GetRowMapPtr()
359         {
360                 fieldmap = new SQLfieldMap();
361                 
362                 if (currentrow < rows)
363                 {
364                         for (int i = 0; i < Cols(); i++)
365                         {
366                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
367                         }
368                         currentrow++;
369                 }
370
371                 return fieldmap;
372         }
373
374         virtual void Free(SQLfieldMap* fm)
375         {
376                 delete fm;
377         }
378
379         virtual void Free(SQLfieldList* fl)
380         {
381                 delete fl;
382         }
383 };
384
385 class SQLConnection;
386
387 void NotifyMainThread(SQLConnection* connection_with_new_result);
388
389 /** Represents a connection to a mysql database
390  */
391 class SQLConnection : public classbase
392 {
393  protected:
394
395         MYSQL connection;
396         MYSQL_RES *res;
397         MYSQL_ROW row;
398         std::string host;
399         std::string user;
400         std::string pass;
401         std::string db;
402         std::map<std::string,std::string> thisrow;
403         bool Enabled;
404         std::string id;
405
406  public:
407
408         QueryQueue queue;
409         ResultQueue rq;
410
411         // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
412         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)
413         {
414         }
415
416         // This method connects to the database using the credentials supplied to the constructor, and returns
417         // true upon success.
418         bool Connect()
419         {
420                 unsigned int timeout = 1;
421                 mysql_init(&connection);
422                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
423                 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
424         }
425
426         void DoLeadingQuery()
427         {
428                 if (!CheckConnection())
429                         return;
430
431                 /* Parse the command string and dispatch it to mysql */
432                 SQLrequest& req = queue.front();
433
434                 /* Pointer to the buffer we screw around with substitution in */
435                 char* query;
436
437                 /* Pointer to the current end of query, where we append new stuff */
438                 char* queryend;
439
440                 /* Total length of the unescaped parameters */
441                 unsigned long paramlen;
442
443                 /* Total length of query, used for binary-safety in mysql_real_query */
444                 unsigned long querylength = 0;
445
446                 paramlen = 0;
447
448                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
449                 {
450                         paramlen += i->size();
451                 }
452
453                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
454                  * sizeofquery + (totalparamlength*2) + 1
455                  *
456                  * The +1 is for null-terminating the string for mysql_real_escape_string
457                  */
458
459                 query = new char[req.query.q.length() + (paramlen*2)];
460                 queryend = query;
461
462                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
463                  * the parameters into it...
464                  */
465
466                 for(unsigned long i = 0; i < req.query.q.length(); i++)
467                 {
468                         if(req.query.q[i] == '?')
469                         {
470                                 /* We found a place to substitute..what fun.
471                                  * use mysql calls to escape and write the
472                                  * escaped string onto the end of our query buffer,
473                                  * then we "just" need to make sure queryend is
474                                  * pointing at the right place.
475                                  */
476                                 if(req.query.p.size())
477                                 {
478                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
479
480                                         queryend += len;
481                                         req.query.p.pop_front();
482                                 }
483                                 else
484                                         break;
485                         }
486                         else
487                         {
488                                 *queryend = req.query.q[i];
489                                 queryend++;
490                         }
491                         querylength++;
492                 }
493
494                 *queryend = 0;
495
496                 pthread_mutex_lock(&queue_mutex);
497                 req.query.q = query;
498                 pthread_mutex_unlock(&queue_mutex);
499
500                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
501                 {
502                         /* Successfull query */
503                         res = mysql_use_result(&connection);
504                         unsigned long rows = mysql_affected_rows(&connection);
505                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
506                         r->dbid = this->GetID();
507                         r->query = req.query.q;
508                         /* Put this new result onto the results queue.
509                          * XXX: Remember to mutex the queue!
510                          */
511                         pthread_mutex_lock(&results_mutex);
512                         rq.push_back(r);
513                         pthread_mutex_unlock(&results_mutex);
514                 }
515                 else
516                 {
517                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
518                          * possible error numbers and error messages */
519                         SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
520                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
521                         r->dbid = this->GetID();
522                         r->query = req.query.q;
523
524                         pthread_mutex_lock(&results_mutex);
525                         rq.push_back(r);
526                         pthread_mutex_unlock(&results_mutex);
527                 }
528
529                 /* Now signal the main thread that we've got a result to process.
530                  * Pass them this connection id as what to examine
531                  */
532
533                 delete[] query;
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                         ServerInstance->Log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
591                 }
592                 else
593                 {
594                         ServerInstance->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         ServerInstance->Log(DEFAULT,"SQL: Loading database settings");
604         Connections.clear();
605         ServerInstance->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                 ServerInstance->Log(DEBUG,"Read database settings");
614                 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
615                 {
616                         SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
617                         ServerInstance->Log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
618                         Connections[id] = ThisSQL;
619                         ServerInstance->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 /** Used by m_mysql to notify one thread when the other has a result
642  */
643 class Notifier : public InspSocket
644 {
645         insp_sockaddr sock_us;
646         socklen_t uslen;
647         
648
649  public:
650
651         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
652 #ifdef IPV6
653         Notifier(InspIRCd* SI) : InspSocket(SI, "::1", 0, true, 3000)
654 #else
655         Notifier(InspIRCd* SI) : InspSocket(SI, "127.0.0.1", 0, true, 3000)
656 #endif
657         {
658                 uslen = sizeof(sock_us);
659                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
660                 {
661                         throw ModuleException("Could not create random listening port on localhost");
662                 }
663         }
664
665         Notifier(InspIRCd* SI, int newfd, char* ip) : InspSocket(SI, newfd, ip)
666         {
667                 Instance->Log(DEBUG,"Constructor of new socket");
668         }
669
670         /* Using getsockname and ntohs, we can determine which port number we were allocated */
671         int GetPort()
672         {
673 #ifdef IPV6
674                 return ntohs(sock_us.sin6_port);
675 #else
676                 return ntohs(sock_us.sin_port);
677 #endif
678         }
679
680         virtual int OnIncomingConnection(int newsock, char* ip)
681         {
682                 Instance->Log(DEBUG,"Inbound connection on fd %d!",newsock);
683                 Notifier* n = new Notifier(this->Instance, newsock, ip);
684                 n = n; /* Stop bitching at me, GCC */
685                 return true;
686         }
687
688         virtual bool OnDataReady()
689         {
690                 Instance->Log(DEBUG,"Inbound data!");
691                 char* data = this->Read();
692                 ConnMap::iterator iter;
693
694                 if (data && *data)
695                 {
696                         Instance->Log(DEBUG,"Looking for connection %s",data);
697                         /* We expect to be sent a null terminated string */
698                         if((iter = Connections.find(data)) != Connections.end())
699                         {
700                                 Instance->Log(DEBUG,"Found it!");
701
702                                 /* Lock the mutex, send back the data */
703                                 pthread_mutex_lock(&results_mutex);
704                                 ResultQueue::iterator n = iter->second->rq.begin();
705                                 (*n)->Send();
706                                 iter->second->rq.pop_front();
707                                 pthread_mutex_unlock(&results_mutex);
708                                 return true;
709                         }
710                 }
711
712                 return false;
713         }
714 };
715
716 /** MySQL module
717  */
718 class ModuleSQL : public Module
719 {
720  public:
721         
722         ConfigReader *Conf;
723         InspIRCd* PublicServerInstance;
724         pthread_t Dispatcher;
725         int currid;
726
727         void Implements(char* List)
728         {
729                 List[I_OnRehash] = List[I_OnRequest] = 1;
730         }
731
732         unsigned long NewID()
733         {
734                 if (currid+1 == 0)
735                         currid++;
736                 return ++currid;
737         }
738
739         char* OnRequest(Request* request)
740         {
741                 if(strcmp(SQLREQID, request->GetId()) == 0)
742                 {
743                         SQLrequest* req = (SQLrequest*)request;
744
745                         /* XXX: Lock */
746                         pthread_mutex_lock(&queue_mutex);
747
748                         ConnMap::iterator iter;
749
750                         char* returnval = NULL;
751
752                         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());
753
754                         if((iter = Connections.find(req->dbid)) != Connections.end())
755                         {
756                                 req->id = NewID();
757                                 iter->second->queue.push(*req);
758                                 returnval = SQLSUCCESS;
759                         }
760                         else
761                         {
762                                 req->error.Id(BAD_DBID);
763                         }
764
765                         pthread_mutex_unlock(&queue_mutex);
766                         /* XXX: Unlock */
767
768                         return returnval;
769                 }
770
771                 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
772
773                 return NULL;
774         }
775
776         ModuleSQL(InspIRCd* Me)
777                 : Module::Module(Me)
778         {
779                 
780                 Conf = new ConfigReader(ServerInstance);
781                 PublicServerInstance = ServerInstance;
782                 currid = 0;
783                 SQLModule = this;
784
785                 MessagePipe = new Notifier(ServerInstance);
786                 ServerInstance->Log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
787                 
788                 pthread_attr_t attribs;
789                 pthread_attr_init(&attribs);
790                 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
791                 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
792                 {
793                         throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
794                 }
795                 if (!ServerInstance->PublishFeature("SQL", this))
796                 {
797                         /* Tell worker thread to exit NOW */
798                         giveup = true;
799                         throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
800                 }
801         }
802         
803         virtual ~ModuleSQL()
804         {
805                 DELETE(Conf);
806         }
807         
808         virtual void OnRehash(const std::string &parameter)
809         {
810                 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
811         }
812         
813         virtual Version GetVersion()
814         {
815                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
816         }
817         
818 };
819
820 void* DispatcherThread(void* arg)
821 {
822         ModuleSQL* thismodule = (ModuleSQL*)arg;
823         LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance);
824
825         /* Connect back to the Notifier */
826
827         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
828         {
829                 /* crap, we're out of sockets... */
830                 return NULL;
831         }
832
833         insp_sockaddr addr;
834
835 #ifdef IPV6
836         insp_aton("::1", &addr.sin6_addr);
837         addr.sin6_family = AF_FAMILY;
838         addr.sin6_port = htons(MessagePipe->GetPort());
839 #else
840         insp_inaddr ia;
841         insp_aton("127.0.0.1", &ia);
842         addr.sin_family = AF_FAMILY;
843         addr.sin_addr = ia;
844         addr.sin_port = htons(MessagePipe->GetPort());
845 #endif
846
847         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
848         {
849                 /* wtf, we cant connect to it, but we just created it! */
850                 return NULL;
851         }
852
853         while (!giveup)
854         {
855                 SQLConnection* conn = NULL;
856                 /* XXX: Lock here for safety */
857                 pthread_mutex_lock(&queue_mutex);
858                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
859                 {
860                         if (i->second->queue.totalsize())
861                         {
862                                 conn = i->second;
863                                 break;
864                         }
865                 }
866                 pthread_mutex_unlock(&queue_mutex);
867                 /* XXX: Unlock */
868
869                 /* Theres an item! */
870                 if (conn)
871                 {
872                         conn->DoLeadingQuery();
873
874                         /* XXX: Lock */
875                         pthread_mutex_lock(&queue_mutex);
876                         conn->queue.pop();
877                         pthread_mutex_unlock(&queue_mutex);
878                         /* XXX: Unlock */
879                 }
880
881                 usleep(50);
882         }
883
884         return NULL;
885 }
886
887
888 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
889
890 class ModuleSQLFactory : public ModuleFactory
891 {
892  public:
893         ModuleSQLFactory()
894         {
895         }
896         
897         ~ModuleSQLFactory()
898         {
899         }
900         
901         virtual Module * CreateModule(InspIRCd* Me)
902         {
903                 return new ModuleSQL(Me);
904         }
905         
906 };
907
908
909 extern "C" void * init_module( void )
910 {
911         return new ModuleSQLFactory;
912 }