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