]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Ah pasting, also remove this var from here
[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                         res = NULL;
178                 }
179         }
180
181         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
182         {
183                 rows = 0;
184                 error = e;
185         }
186
187         ~MySQLresult()
188         {
189         }
190
191         virtual int Rows()
192         {
193                 return rows;
194         }
195
196         virtual int Cols()
197         {
198                 return colnames.size();
199         }
200
201         virtual std::string ColName(int column)
202         {
203                 if (column < (int)colnames.size())
204                 {
205                         return colnames[column];
206                 }
207                 else
208                 {
209                         throw SQLbadColName();
210                 }
211                 return "";
212         }
213
214         virtual int ColNum(const std::string &column)
215         {
216                 for (unsigned int i = 0; i < colnames.size(); i++)
217                 {
218                         if (column == colnames[i])
219                                 return i;
220                 }
221                 throw SQLbadColName();
222                 return 0;
223         }
224
225         virtual SQLfield GetValue(int row, int column)
226         {
227                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
228                 {
229                         return fieldlists[row][column];
230                 }
231
232                 throw SQLbadColName();
233
234                 /* XXX: We never actually get here because of the throw */
235                 return SQLfield("",true);
236         }
237
238         virtual SQLfieldList& GetRow()
239         {
240                 if (currentrow < rows)
241                         return fieldlists[currentrow++];
242                 else
243                         return emptyfieldlist;
244         }
245
246         virtual SQLfieldMap& GetRowMap()
247         {
248                 fieldmap2.clear();
249
250                 if (currentrow < rows)
251                 {
252                         for (int i = 0; i < Cols(); i++)
253                         {
254                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
255                         }
256                         currentrow++;
257                 }
258
259                 return fieldmap2;
260         }
261
262         virtual SQLfieldList* GetRowPtr()
263         {
264                 SQLfieldList* fieldlist = new SQLfieldList();
265
266                 if (currentrow < rows)
267                 {
268                         for (int i = 0; i < Rows(); i++)
269                         {
270                                 fieldlist->push_back(fieldlists[currentrow][i]);
271                         }
272                         currentrow++;
273                 }
274                 return fieldlist;
275         }
276
277         virtual SQLfieldMap* GetRowMapPtr()
278         {
279                 fieldmap = new SQLfieldMap();
280
281                 if (currentrow < rows)
282                 {
283                         for (int i = 0; i < Cols(); i++)
284                         {
285                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
286                         }
287                         currentrow++;
288                 }
289
290                 return fieldmap;
291         }
292
293         virtual void Free(SQLfieldMap* fm)
294         {
295                 delete fm;
296         }
297
298         virtual void Free(SQLfieldList* fl)
299         {
300                 delete fl;
301         }
302 };
303
304 class SQLConnection;
305
306 void NotifyMainThread(SQLConnection* connection_with_new_result);
307
308 /** Represents a connection to a mysql database
309  */
310 class SQLConnection : public classbase
311 {
312  protected:
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) : connection(NULL), 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                 connection = 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                         Parent->ConnMutex->Unlock();
741                         if (iter != Connections.end())
742                         {
743                                 Parent->ResultsMutex->Lock();
744                                 ResultQueue::iterator n = iter->second->rq.begin();
745                                 Parent->ResultsMutex->Unlock();
746
747                                 (*n)->Send();
748                                 delete (*n);
749
750                                 Parent->ResultsMutex->Lock();
751                                 iter->second->rq.pop_front();
752                                 Parent->ResultsMutex->Unlock();
753
754                                 return true;
755                         }
756                         /* No error, but unknown id */
757                         return true;
758                 }
759
760                 /* Erk, error on descriptor! */
761                 return false;
762         }
763 };
764
765 /** Spawn sockets from a listener
766  */
767 class MySQLListener : public ListenSocketBase
768 {
769         ModuleSQL* Parent;
770         irc::sockets::insp_sockaddr sock_us;
771         socklen_t uslen;
772         FileReader* index;
773
774  public:
775         MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
776         {
777                 uslen = sizeof(sock_us);
778                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
779                 {
780                         throw ModuleException("Could not getsockname() to find out port number for ITC port");
781                 }
782         }
783
784         virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
785         {
786                 // XXX unsafe casts suck
787                 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str());
788         }
789
790         /* Using getsockname and ntohs, we can determine which port number we were allocated */
791         int GetPort()
792         {
793 #ifdef IPV6
794                 return ntohs(sock_us.sin6_port);
795 #else
796                 return ntohs(sock_us.sin_port);
797 #endif
798         }
799 };
800
801 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
802 {
803         ServerInstance->Modules->UseInterface("SQLutils");
804
805         Conf = new ConfigReader(ServerInstance);
806         PublicServerInstance = ServerInstance;
807         currid = 0;
808
809         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
810 #ifdef IPV6
811         MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
812 #else
813         MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
814 #endif
815
816         LoggingMutex = ServerInstance->Mutexes->CreateMutex();
817         ConnMutex = ServerInstance->Mutexes->CreateMutex();
818
819         if (MessagePipe->GetFd() == -1)
820         {
821                 delete ConnMutex;
822                 ServerInstance->Modules->DoneWithInterface("SQLutils");
823                 throw ModuleException("m_mysql: unable to create ITC pipe");
824         }
825         else
826         {
827                 LoggingMutex->Lock();
828                 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
829                 LoggingMutex->Unlock();
830         }
831
832         Dispatcher = new DispatcherThread(ServerInstance, this);
833         ServerInstance->Threads->Create(Dispatcher);
834
835         ResultsMutex = ServerInstance->Mutexes->CreateMutex();
836         QueueMutex = ServerInstance->Mutexes->CreateMutex();
837
838         if (!ServerInstance->Modules->PublishFeature("SQL", this))
839         {
840                 /* Tell worker thread to exit NOW,
841                  * Automatically joins */
842                 delete Dispatcher;
843                 delete LoggingMutex;
844                 delete ResultsMutex;
845                 delete QueueMutex;
846                 delete ConnMutex;
847                 ServerInstance->Modules->DoneWithInterface("SQLutils");
848                 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
849         }
850
851         ServerInstance->Modules->PublishInterface("SQL", this);
852         Implementation eventlist[] = { I_OnRehash, I_OnRequest };
853         ServerInstance->Modules->Attach(eventlist, this, 2);
854 }
855
856 ModuleSQL::~ModuleSQL()
857 {
858         delete Dispatcher;
859         ClearAllConnections();
860         delete Conf;
861         ServerInstance->Modules->UnpublishInterface("SQL", this);
862         ServerInstance->Modules->UnpublishFeature("SQL");
863         ServerInstance->Modules->DoneWithInterface("SQLutils");
864         delete LoggingMutex;
865         delete ResultsMutex;
866         delete QueueMutex;
867         delete ConnMutex;
868 }
869
870 unsigned long ModuleSQL::NewID()
871 {
872         if (currid+1 == 0)
873                 currid++;
874         return ++currid;
875 }
876
877 const char* ModuleSQL::OnRequest(Request* request)
878 {
879         if(strcmp(SQLREQID, request->GetId()) == 0)
880         {
881                 SQLrequest* req = (SQLrequest*)request;
882
883                 /* XXX: Lock */
884                 QueueMutex->Lock();
885
886                 ConnMap::iterator iter;
887
888                 const char* returnval = NULL;
889
890                 ConnMutex->Lock();
891                 if((iter = Connections.find(req->dbid)) != Connections.end())
892                 {
893                         req->id = NewID();
894                         iter->second->queue.push(*req);
895                         returnval = SQLSUCCESS;
896                 }
897                 else
898                 {
899                         req->error.Id(SQL_BAD_DBID);
900                 }
901
902                 ConnMutex->Unlock();
903                 QueueMutex->Unlock();
904
905                 return returnval;
906         }
907
908         return NULL;
909 }
910
911 void ModuleSQL::OnRehash(User* user, const std::string &parameter)
912 {
913         rehashing = true;
914 }
915
916 Version ModuleSQL::GetVersion()
917 {
918         return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
919 }
920
921 void DispatcherThread::Run()
922 {
923         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
924
925         /* Connect back to the Notifier */
926
927         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
928         {
929                 /* crap, we're out of sockets... */
930                 return;
931         }
932
933         irc::sockets::insp_sockaddr addr;
934
935 #ifdef IPV6
936         irc::sockets::insp_aton("::1", &addr.sin6_addr);
937         addr.sin6_family = AF_FAMILY;
938         addr.sin6_port = htons(MessagePipe->GetPort());
939 #else
940         irc::sockets::insp_inaddr ia;
941         irc::sockets::insp_aton("127.0.0.1", &ia);
942         addr.sin_family = AF_FAMILY;
943         addr.sin_addr = ia;
944         addr.sin_port = htons(MessagePipe->GetPort());
945 #endif
946
947         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
948         {
949                 /* wtf, we cant connect to it, but we just created it! */
950                 return;
951         }
952
953         while (this->GetExitFlag() == false)
954         {
955                 if (Parent->rehashing)
956                 {
957                 /* XXX: Lock */
958                         Parent->QueueMutex->Lock();
959                         Parent->rehashing = false;
960                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
961                         Parent->QueueMutex->Unlock();
962                         /* XXX: Unlock */
963                 }
964
965                 SQLConnection* conn = NULL;
966                 /* XXX: Lock here for safety */
967                 Parent->QueueMutex->Lock();
968                 Parent->ConnMutex->Lock();
969                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
970                 {
971                         if (i->second->queue.totalsize())
972                         {
973                                 conn = i->second;
974                                 break;
975                         }
976                 }
977                 Parent->ConnMutex->Unlock();
978                 Parent->QueueMutex->Unlock();
979                 /* XXX: Unlock */
980
981                 /* Theres an item! */
982                 if (conn)
983                 {
984                         conn->DoLeadingQuery();
985
986                         /* XXX: Lock */
987                         Parent->QueueMutex->Lock();
988                         conn->queue.pop();
989                         Parent->QueueMutex->Unlock();
990                         /* XXX: Unlock */
991                 }
992
993                 usleep(1000);
994         }
995 }
996
997
998 MODULE_INIT(ModuleSQL)