]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
eefeea74dd1bb5e639cba3320a6253fcbfa14785
[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://wiki.inspircd.org/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://wiki.inspircd.org/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                 /* The length of the longest parameter */
364                 maxparamlen = 0;
365
366                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
367                 {
368                         if (i->size() > maxparamlen)
369                                 maxparamlen = i->size();
370                 }
371
372                 /* How many params are there in the query? */
373                 paramcount = count(req.query.q.c_str(), '?');
374
375                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
376                 ParamL paramscopy(req.query.p);
377
378                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
379                  * sizeofquery + (maxtotalparamlength*2) + 1
380                  *
381                  * The +1 is for null-terminating the string for mysql_real_escape_string
382                  */
383
384                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
385                 queryend = query;
386
387                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
388                  * the parameters into it...
389                  */
390
391                 for(unsigned long i = 0; i < req.query.q.length(); i++)
392                 {
393                         if(req.query.q[i] == '?')
394                         {
395                                 /* We found a place to substitute..what fun.
396                                  * use mysql calls to escape and write the
397                                  * escaped string onto the end of our query buffer,
398                                  * then we "just" need to make sure queryend is
399                                  * pointing at the right place.
400                                  */
401
402                                 /* Is it numbered parameter?
403                                  */
404
405                                 bool numbered;
406                                 numbered = false;
407
408                                 /* Numbered parameter number :|
409                                  */
410                                 unsigned int paramnum;
411                                 paramnum = 0;
412
413                                 /* Let's check if it's a numbered param. And also calculate it's number.
414                                  */
415
416                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
417                                 {
418                                         numbered = true;
419                                         ++i;
420                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
421                                 }
422
423                                 if (paramnum > paramscopy.size() - 1)
424                                 {
425                                         /* index is out of range!
426                                          */
427                                         numbered = false;
428                                 }
429
430                                 if (numbered)
431                                 {
432                                         unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
433
434                                         queryend += len;
435                                 }
436                                 else if (req.query.p.size())
437                                 {
438                                         unsigned long len = mysql_real_escape_string(connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
439
440                                         queryend += len;
441                                         req.query.p.pop_front();
442                                 }
443                                 else
444                                         break;
445                         }
446                         else
447                         {
448                                 *queryend = req.query.q[i];
449                                 queryend++;
450                         }
451                 }
452
453                 *queryend = 0;
454
455                 Parent->QueueMutex.Lock();
456                 req.query.q = query;
457                 Parent->QueueMutex.Unlock();
458
459                 if (!mysql_real_query(connection, req.query.q.data(), req.query.q.length()))
460                 {
461                         /* Successfull query */
462                         res = mysql_use_result(connection);
463                         unsigned long rows = mysql_affected_rows(connection);
464                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
465                         r->dbid = this->GetID();
466                         r->query = req.query.q;
467                         /* Put this new result onto the results queue.
468                          * XXX: Remember to mutex the queue!
469                          */
470                         Parent->ResultsMutex.Lock();
471                         rq.push_back(r);
472                         Parent->ResultsMutex.Unlock();
473                 }
474                 else
475                 {
476                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
477                          * possible error numbers and error messages */
478                         SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
479                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
480                         r->dbid = this->GetID();
481                         r->query = req.query.q;
482
483                         Parent->ResultsMutex.Lock();
484                         rq.push_back(r);
485                         Parent->ResultsMutex.Unlock();
486                 }
487
488                 /* Now signal the main thread that we've got a result to process.
489                  * Pass them this connection id as what to examine
490                  */
491
492                 delete[] query;
493
494                 NotifyMainThread(this);
495         }
496
497         bool ConnectionLost()
498         {
499                 if (&connection)
500                 {
501                         return (mysql_ping(connection) != 0);
502                 }
503                 else return false;
504         }
505
506         bool CheckConnection()
507         {
508                 if (ConnectionLost())
509                 {
510                         return Connect();
511                 }
512                 else return true;
513         }
514
515         std::string GetError()
516         {
517                 return mysql_error(connection);
518         }
519
520         const std::string& GetID()
521         {
522                 return host.id;
523         }
524
525         std::string GetHost()
526         {
527                 return host.host;
528         }
529
530         void SetEnable(bool Enable)
531         {
532                 Enabled = Enable;
533         }
534
535         bool IsEnabled()
536         {
537                 return Enabled;
538         }
539
540         void Close()
541         {
542                 mysql_close(connection);
543         }
544
545         const SQLhost& GetConfHost()
546         {
547                 return host;
548         }
549
550 };
551
552 ConnMap Connections;
553
554 bool HasHost(const SQLhost &host)
555 {
556         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
557         {
558                 if (host == iter->second->GetConfHost())
559                         return true;
560         }
561         return false;
562 }
563
564 bool HostInConf(ConfigReader* conf, const SQLhost &h)
565 {
566         for(int i = 0; i < conf->Enumerate("database"); i++)
567         {
568                 SQLhost host;
569                 host.id         = conf->ReadValue("database", "id", i);
570                 host.host       = conf->ReadValue("database", "hostname", i);
571                 host.port       = conf->ReadInteger("database", "port", i, true);
572                 host.name       = conf->ReadValue("database", "name", i);
573                 host.user       = conf->ReadValue("database", "username", i);
574                 host.pass       = conf->ReadValue("database", "password", i);
575                 host.ssl        = conf->ReadFlag("database", "ssl", i);
576                 if (h == host)
577                         return true;
578         }
579         return false;
580 }
581
582 void ClearOldConnections(ConfigReader* conf)
583 {
584         ConnMap::iterator i,safei;
585         for (i = Connections.begin(); i != Connections.end(); i++)
586         {
587                 if (!HostInConf(conf, i->second->GetConfHost()))
588                 {
589                         delete i->second;
590                         safei = i;
591                         --i;
592                         Connections.erase(safei);
593                 }
594         }
595 }
596
597 void ClearAllConnections()
598 {
599         ConnMap::iterator i;
600         while ((i = Connections.begin()) != Connections.end())
601         {
602                 Connections.erase(i);
603                 delete i->second;
604         }
605 }
606
607 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
608 {
609         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
610         {
611                 if (i->second->IsEnabled())
612                         continue;
613
614                 i->second->SetEnable(true);
615                 if (!i->second->Connect())
616                 {
617                         /* XXX: MUTEX */
618                         Parent->LoggingMutex.Lock();
619                         ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
620                         i->second->SetEnable(false);
621                         Parent->LoggingMutex.Unlock();
622                 }
623         }
624 }
625
626 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
627 {
628         Parent->ConnMutex.Lock();
629         ClearOldConnections(conf);
630         for (int j =0; j < conf->Enumerate("database"); j++)
631         {
632                 SQLhost host;
633                 host.id         = conf->ReadValue("database", "id", j);
634                 host.host       = conf->ReadValue("database", "hostname", j);
635                 host.port       = conf->ReadInteger("database", "port", j, true);
636                 host.name       = conf->ReadValue("database", "name", j);
637                 host.user       = conf->ReadValue("database", "username", j);
638                 host.pass       = conf->ReadValue("database", "password", j);
639                 host.ssl        = conf->ReadFlag("database", "ssl", j);
640
641                 if (HasHost(host))
642                         continue;
643
644                 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
645                 {
646                         SQLConnection* ThisSQL = new SQLConnection(host, Parent);
647                         Connections[host.id] = ThisSQL;
648                 }
649         }
650         ConnectDatabases(ServerInstance, Parent);
651         Parent->ConnMutex.Unlock();
652 }
653
654 char FindCharId(const std::string &id)
655 {
656         char i = 1;
657         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
658         {
659                 if (iter->first == id)
660                 {
661                         return i;
662                 }
663         }
664         return 0;
665 }
666
667 ConnMap::iterator GetCharId(char id)
668 {
669         char i = 1;
670         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
671         {
672                 if (i == id)
673                         return iter;
674         }
675         return Connections.end();
676 }
677
678 void NotifyMainThread(SQLConnection* connection_with_new_result)
679 {
680         /* Here we write() to the socket the main thread has open
681          * and we connect()ed back to before our thread became active.
682          * The main thread is using a nonblocking socket tied into
683          * the socket engine, so they wont block and they'll receive
684          * nearly instant notification. Because we're in a seperate
685          * thread, we can just use standard connect(), and we can
686          * block if we like. We just send the connection id of the
687          * connection back.
688          *
689          * NOTE: We only send a single char down the connection, this
690          * way we know it wont get a partial read at the other end if
691          * the system is especially congested (see bug #263).
692          * The function FindCharId translates a connection name into a
693          * one character id, and GetCharId translates a character id
694          * back into an iterator.
695          */
696         char id = FindCharId(connection_with_new_result->GetID());
697         send(QueueFD, &id, 1, 0);
698 }
699
700 class ModuleSQL;
701
702 class DispatcherThread : public Thread
703 {
704  private:
705         ModuleSQL* Parent;
706         InspIRCd* ServerInstance;
707  public:
708         DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : Thread(), Parent(CreatorModule), ServerInstance(Instance) { }
709         ~DispatcherThread() { }
710         virtual void Run();
711 };
712
713 /** Used by m_mysql to notify one thread when the other has a result
714  */
715 class Notifier : public BufferedSocket
716 {
717         ModuleSQL* Parent;
718
719  public:
720         Notifier(ModuleSQL* P, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), Parent(P) { }
721
722         virtual bool OnDataReady()
723         {
724                 char data = 0;
725                 /* NOTE: Only a single character is read so we know we
726                  * cant get a partial read. (We've been told that theres
727                  * data waiting, so we wont ever get EAGAIN)
728                  * The function GetCharId translates a single character
729                  * back into an iterator.
730                  */
731
732                 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
733                 {
734                         Parent->ConnMutex.Lock();
735                         ConnMap::iterator iter = GetCharId(data);
736                         Parent->ConnMutex.Unlock();
737                         if (iter != Connections.end())
738                         {
739                                 Parent->ResultsMutex.Lock();
740                                 ResultQueue::iterator n = iter->second->rq.begin();
741                                 Parent->ResultsMutex.Unlock();
742
743                                 (*n)->Send();
744                                 delete (*n);
745
746                                 Parent->ResultsMutex.Lock();
747                                 iter->second->rq.pop_front();
748                                 Parent->ResultsMutex.Unlock();
749
750                                 return true;
751                         }
752                         /* No error, but unknown id */
753                         return true;
754                 }
755
756                 /* Erk, error on descriptor! */
757                 return false;
758         }
759 };
760
761 /** Spawn sockets from a listener
762  */
763 class MySQLListener : public ListenSocketBase
764 {
765         ModuleSQL* Parent;
766         irc::sockets::insp_sockaddr sock_us;
767         socklen_t uslen;
768         FileReader* index;
769
770  public:
771         MySQLListener(ModuleSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
772         {
773                 uslen = sizeof(sock_us);
774                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
775                 {
776                         throw ModuleException("Could not getsockname() to find out port number for ITC port");
777                 }
778         }
779
780         virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
781         {
782                 // XXX unsafe casts suck
783                 new Notifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str());
784         }
785
786         /* Using getsockname and ntohs, we can determine which port number we were allocated */
787         int GetPort()
788         {
789 #ifdef IPV6
790                 return ntohs(sock_us.sin6_port);
791 #else
792                 return ntohs(sock_us.sin_port);
793 #endif
794         }
795 };
796
797 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
798 {
799         ServerInstance->Modules->UseInterface("SQLutils");
800
801         Conf = new ConfigReader(ServerInstance);
802         PublicServerInstance = ServerInstance;
803         currid = 0;
804
805         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
806 #ifdef IPV6
807         MessagePipe = new MySQLListener(this, ServerInstance, 0, "::1");
808 #else
809         MessagePipe = new MySQLListener(this, ServerInstance, 0, "127.0.0.1");
810 #endif
811
812         if (MessagePipe->GetFd() == -1)
813         {
814                 ServerInstance->Modules->DoneWithInterface("SQLutils");
815                 throw ModuleException("m_mysql: unable to create ITC pipe");
816         }
817         else
818         {
819                 LoggingMutex.Lock();
820                 ServerInstance->Logs->Log("m_mysql", DEBUG, "MySQL: Interthread comms port is %d", MessagePipe->GetPort());
821                 LoggingMutex.Unlock();
822         }
823
824         Dispatcher = new DispatcherThread(ServerInstance, this);
825         ServerInstance->Threads->Start(Dispatcher);
826
827         if (!ServerInstance->Modules->PublishFeature("SQL", this))
828         {
829                 /* Tell worker thread to exit NOW,
830                  * Automatically joins */
831                 delete Dispatcher;
832                 ServerInstance->Modules->DoneWithInterface("SQLutils");
833                 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
834         }
835
836         ServerInstance->Modules->PublishInterface("SQL", this);
837         Implementation eventlist[] = { I_OnRehash, I_OnRequest };
838         ServerInstance->Modules->Attach(eventlist, this, 2);
839 }
840
841 ModuleSQL::~ModuleSQL()
842 {
843         delete Dispatcher;
844         ClearAllConnections();
845         delete Conf;
846         ServerInstance->Modules->UnpublishInterface("SQL", this);
847         ServerInstance->Modules->UnpublishFeature("SQL");
848         ServerInstance->Modules->DoneWithInterface("SQLutils");
849 }
850
851 unsigned long ModuleSQL::NewID()
852 {
853         if (currid+1 == 0)
854                 currid++;
855         return ++currid;
856 }
857
858 const char* ModuleSQL::OnRequest(Request* request)
859 {
860         if(strcmp(SQLREQID, request->GetId()) == 0)
861         {
862                 SQLrequest* req = (SQLrequest*)request;
863
864                 /* XXX: Lock */
865                 QueueMutex.Lock();
866
867                 ConnMap::iterator iter;
868
869                 const char* returnval = NULL;
870
871                 ConnMutex.Lock();
872                 if((iter = Connections.find(req->dbid)) != Connections.end())
873                 {
874                         req->id = NewID();
875                         iter->second->queue.push(*req);
876                         returnval = SQLSUCCESS;
877                 }
878                 else
879                 {
880                         req->error.Id(SQL_BAD_DBID);
881                 }
882
883                 ConnMutex.Unlock();
884                 QueueMutex.Unlock();
885
886                 return returnval;
887         }
888
889         return NULL;
890 }
891
892 void ModuleSQL::OnRehash(User* user, const std::string &parameter)
893 {
894         rehashing = true;
895 }
896
897 Version ModuleSQL::GetVersion()
898 {
899         return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
900 }
901
902 void DispatcherThread::Run()
903 {
904         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
905
906         /* Connect back to the Notifier */
907
908         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
909         {
910                 /* crap, we're out of sockets... */
911                 return;
912         }
913
914         irc::sockets::insp_sockaddr addr;
915
916 #ifdef IPV6
917         irc::sockets::insp_aton("::1", &addr.sin6_addr);
918         addr.sin6_family = AF_FAMILY;
919         addr.sin6_port = htons(MessagePipe->GetPort());
920 #else
921         irc::sockets::insp_inaddr ia;
922         irc::sockets::insp_aton("127.0.0.1", &ia);
923         addr.sin_family = AF_FAMILY;
924         addr.sin_addr = ia;
925         addr.sin_port = htons(MessagePipe->GetPort());
926 #endif
927
928         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
929         {
930                 /* wtf, we cant connect to it, but we just created it! */
931                 return;
932         }
933
934         while (this->GetExitFlag() == false)
935         {
936                 if (Parent->rehashing)
937                 {
938                 /* XXX: Lock */
939                         Parent->QueueMutex.Lock();
940                         Parent->rehashing = false;
941                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
942                         Parent->QueueMutex.Unlock();
943                         /* XXX: Unlock */
944                 }
945
946                 SQLConnection* conn = NULL;
947                 /* XXX: Lock here for safety */
948                 Parent->QueueMutex.Lock();
949                 Parent->ConnMutex.Lock();
950                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
951                 {
952                         if (i->second->queue.totalsize())
953                         {
954                                 conn = i->second;
955                                 break;
956                         }
957                 }
958                 Parent->ConnMutex.Unlock();
959                 Parent->QueueMutex.Unlock();
960                 /* XXX: Unlock */
961
962                 /* Theres an item! */
963                 if (conn)
964                 {
965                         conn->DoLeadingQuery();
966
967                         /* XXX: Lock */
968                         Parent->QueueMutex.Lock();
969                         conn->queue.pop();
970                         Parent->QueueMutex.Unlock();
971                         /* XXX: Unlock */
972                 }
973
974                 usleep(1000);
975         }
976 }
977
978
979 MODULE_INIT(ModuleSQL)