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