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