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