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