]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
The IPV6 stuff compiles now, with compile-correct ipv6 code. I dont know if this...
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 using namespace std;
18
19 #include <stdio.h>
20 #include <string>
21 #include <mysql.h>
22 #include <pthread.h>
23 #include "users.h"
24 #include "channels.h"
25 #include "modules.h"
26 #include "helperfuncs.h"
27 #include "m_sqlv2.h"
28
29 /* VERSION 2 API: With nonblocking (threaded) requests */
30
31 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
32 /* $CompileFlags: `mysql_config --include` */
33 /* $LinkerFlags: `mysql_config --libs_r` `perl extra/mysql_rpath.pl` */
34
35 /* THE NONBLOCKING MYSQL API!
36  * 
37  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
38  * that instead, you should thread your program. This is what i've done here to allow for
39  * asyncronous SQL requests via mysql. The way this works is as follows:
40  *
41  * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
42  * using a queue with priorities. There is a mutex on either end which prevents two threads
43  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
44  * worker thread wakes up, and checks if there is a request at the head of its queue.
45  * If there is, it processes this request, blocking the worker thread but leaving the ircd
46  * thread to go about its business as usual. During this period, the ircd thread is able
47  * to insert futher pending requests into the queue.
48  *
49  * Once the processing of a request is complete, it is removed from the incoming queue to
50  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
51  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
52  * connection ID through the connection.
53  *
54  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
55  * of the queue, and sends it on its way to the original calling module.
56  *
57  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
58  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
59  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
60  * however, if we were to call a module's OnRequest even from within a thread which was not the
61  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
62  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
63  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
64  * gauranteed threadsafe!)
65  *
66  * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
67  */
68
69
70 class SQLConnection;
71 class Notifier;
72
73 extern InspIRCd* ServerInstance;
74 typedef std::map<std::string, SQLConnection*> ConnMap;
75 bool giveup = false;
76 static Module* SQLModule = NULL;
77 static Notifier* MessagePipe = NULL;
78 int QueueFD = -1;
79
80
81 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
82 #define mysql_field_count mysql_num_fields
83 #endif
84
85 typedef std::deque<SQLresult*> ResultQueue;
86
87 class QueryQueue : public classbase
88 {
89 private:
90         typedef std::deque<SQLrequest> ReqDeque;
91
92         ReqDeque priority;      /* The priority queue */
93         ReqDeque normal;        /* The 'normal' queue */
94         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
95
96 public:
97         QueryQueue()
98         : which(NON)
99         {
100         }
101
102         void push(const SQLrequest &q)
103         {
104                 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
105
106                 if(q.pri)
107                         priority.push_back(q);
108                 else
109                         normal.push_back(q);
110         }
111
112         void pop()
113         {
114                 if((which == PRI) && priority.size())
115                 {
116                         priority.pop_front();
117                 }
118                 else if((which == NOR) && normal.size())
119                 {
120                         normal.pop_front();
121                 }
122
123                 /* Reset this */
124                 which = NON;
125
126                 /* Silently do nothing if there was no element to pop() */
127         }
128
129         SQLrequest& front()
130         {
131                 switch(which)
132                 {
133                         case PRI:
134                                 return priority.front();
135                         case NOR:
136                                 return normal.front();
137                         default:
138                                 if(priority.size())
139                                 {
140                                         which = PRI;
141                                         return priority.front();
142                                 }
143
144                                 if(normal.size())
145                                 {
146                                         which = NOR;
147                                         return normal.front();
148                                 }
149
150                                 /* This will probably result in a segfault,
151                                  * but the caller should have checked totalsize()
152                                  * first so..meh - moron :p
153                                  */
154
155                                 return priority.front();
156                 }
157         }
158
159         std::pair<int, int> size()
160         {
161                 return std::make_pair(priority.size(), normal.size());
162         }
163
164         int totalsize()
165         {
166                 return priority.size() + normal.size();
167         }
168
169         void PurgeModule(Module* mod)
170         {
171                 DoPurgeModule(mod, priority);
172                 DoPurgeModule(mod, normal);
173         }
174
175 private:
176         void DoPurgeModule(Module* mod, ReqDeque& q)
177         {
178                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
179                 {
180                         if(iter->GetSource() == mod)
181                         {
182                                 if(iter->id == front().id)
183                                 {
184                                         /* It's the currently active query.. :x */
185                                         iter->SetSource(NULL);
186                                 }
187                                 else
188                                 {
189                                         /* It hasn't been executed yet..just remove it */
190                                         iter = q.erase(iter);
191                                 }
192                         }
193                 }
194         }
195 };
196
197 /* A mutex to wrap around queue accesses */
198 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
199
200 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
201
202 class MySQLresult : public SQLresult
203 {
204         int currentrow;
205         //std::vector<std::map<std::string,std::string> > results;
206         std::vector<std::string> colnames;
207         std::vector<SQLfieldList> fieldlists;
208         SQLfieldMap* fieldmap;
209         SQLfieldMap fieldmap2;
210         SQLfieldList emptyfieldlist;
211         int rows;
212  public:
213
214         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL)
215         {
216                 /* A number of affected rows from from mysql_affected_rows.
217                  */
218                 log(DEBUG,"Created new MySQLresult of non-error type");
219                 fieldlists.clear();
220                 rows = 0;
221                 if (affected_rows >= 1)
222                 {
223                         rows = affected_rows;
224                         fieldlists.resize(rows);
225                 }
226                 unsigned int field_count = 0;
227                 if (res)
228                 {
229                         MYSQL_ROW row;
230                         int n = 0;
231                         while ((row = mysql_fetch_row(res)))
232                         {
233                                 if (fieldlists.size() < (unsigned int)rows+1)
234                                 {
235                                         fieldlists.resize(fieldlists.size()+1);
236                                 }
237                                 field_count = 0;
238                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
239                                 if(mysql_num_fields(res) == 0)
240                                         break;
241                                 if (fields && mysql_num_fields(res))
242                                 {
243                                         colnames.clear();
244                                         while (field_count < mysql_num_fields(res))
245                                         {
246                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
247                                                 std::string b = (row[field_count] ? row[field_count] : "");
248                                                 SQLfield sqlf(b, !row[field_count]);
249                                                 colnames.push_back(a);
250                                                 fieldlists[n].push_back(sqlf); 
251                                                 log(DEBUG,"Inc field count to %d",field_count+1);
252                                                 field_count++;
253                                         }
254                                         n++;
255                                 }
256                                 rows++;
257                         }
258                         mysql_free_result(res);
259                 }
260                 log(DEBUG, "Created new MySQL result; %d rows, %d columns", rows, colnames.size());
261         }
262
263         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0)
264         {
265                 rows = 0;
266                 error = e;
267                 log(DEBUG,"Created new MySQLresult of error type");
268         }
269
270         ~MySQLresult()
271         {
272         }
273
274         virtual int Rows()
275         {
276                 return rows;
277         }
278
279         virtual int Cols()
280         {
281                 return colnames.size();
282         }
283
284         virtual std::string ColName(int column)
285         {
286                 if (column < (int)colnames.size())
287                 {
288                         return colnames[column];
289                 }
290                 else
291                 {
292                         throw SQLbadColName();
293                 }
294                 return "";
295         }
296
297         virtual int ColNum(const std::string &column)
298         {
299                 for (unsigned int i = 0; i < colnames.size(); i++)
300                 {
301                         if (column == colnames[i])
302                                 return i;
303                 }
304                 throw SQLbadColName();
305                 return 0;
306         }
307
308         virtual SQLfield GetValue(int row, int column)
309         {
310                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
311                 {
312                         return fieldlists[row][column];
313                 }
314
315                 log(DEBUG,"Danger will robinson, we don't have row %d, column %d!", row, column);
316                 throw SQLbadColName();
317
318                 /* XXX: We never actually get here because of the throw */
319                 return SQLfield("",true);
320         }
321
322         virtual SQLfieldList& GetRow()
323         {
324                 if (currentrow < rows)
325                         return fieldlists[currentrow];
326                 else
327                         return emptyfieldlist;
328         }
329
330         virtual SQLfieldMap& GetRowMap()
331         {
332                 fieldmap2.clear();
333
334                 if (currentrow < rows)
335                 {
336                         for (int i = 0; i < Cols(); i++)
337                         {
338                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
339                         }
340                         currentrow++;
341                 }
342
343                 return fieldmap2;
344         }
345
346         virtual SQLfieldList* GetRowPtr()
347         {
348                 SQLfieldList* fieldlist = new SQLfieldList();
349
350                 if (currentrow < rows)
351                 {
352                         for (int i = 0; i < Rows(); i++)
353                         {
354                                 fieldlist->push_back(fieldlists[currentrow][i]);
355                         }
356                         currentrow++;
357                 }
358                 return fieldlist;
359         }
360
361         virtual SQLfieldMap* GetRowMapPtr()
362         {
363                 fieldmap = new SQLfieldMap();
364                 
365                 if (currentrow < rows)
366                 {
367                         for (int i = 0; i < Cols(); i++)
368                         {
369                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
370                         }
371                         currentrow++;
372                 }
373
374                 return fieldmap;
375         }
376
377         virtual void Free(SQLfieldMap* fm)
378         {
379                 delete fm;
380         }
381
382         virtual void Free(SQLfieldList* fl)
383         {
384                 delete fl;
385         }
386 };
387
388 class SQLConnection;
389
390 void NotifyMainThread(SQLConnection* connection_with_new_result);
391
392 class SQLConnection : public classbase
393 {
394  protected:
395
396         MYSQL connection;
397         MYSQL_RES *res;
398         MYSQL_ROW row;
399         std::string host;
400         std::string user;
401         std::string pass;
402         std::string db;
403         std::map<std::string,std::string> thisrow;
404         bool Enabled;
405         std::string id;
406
407  public:
408
409         QueryQueue queue;
410         ResultQueue rq;
411
412         // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
413         // MYSQL struct, but does not connect yet.
414         SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, const std::string &myid)
415         {
416                 this->Enabled = true;
417                 this->host = thishost;
418                 this->user = thisuser;
419                 this->pass = thispass;
420                 this->db = thisdb;
421                 this->id = myid;
422         }
423
424         // This method connects to the database using the credentials supplied to the constructor, and returns
425         // true upon success.
426         bool Connect()
427         {
428                 unsigned int timeout = 1;
429                 mysql_init(&connection);
430                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
431                 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
432         }
433
434         void DoLeadingQuery()
435         {
436                 if (!CheckConnection())
437                         return;
438
439                 /* Parse the command string and dispatch it to mysql */
440                 SQLrequest& req = queue.front();
441                 log(DEBUG,"DO QUERY: %s",req.query.q.c_str());
442
443                 /* Pointer to the buffer we screw around with substitution in */
444                 char* query;
445
446                 /* Pointer to the current end of query, where we append new stuff */
447                 char* queryend;
448
449                 /* Total length of the unescaped parameters */
450                 unsigned long paramlen;
451
452                 /* Total length of query, used for binary-safety in mysql_real_query */
453                 unsigned long querylength = 0;
454
455                 paramlen = 0;
456
457                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
458                 {
459                         paramlen += i->size();
460                 }
461
462                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
463                  * sizeofquery + (totalparamlength*2) + 1
464                  *
465                  * The +1 is for null-terminating the string for mysql_real_escape_string
466                  */
467
468                 query = new char[req.query.q.length() + (paramlen*2)];
469                 queryend = query;
470
471                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
472                  * the parameters into it...
473                  */
474
475                 for(unsigned long i = 0; i < req.query.q.length(); i++)
476                 {
477                         if(req.query.q[i] == '?')
478                         {
479                                 /* We found a place to substitute..what fun.
480                                  * use mysql calls to escape and write the
481                                  * escaped string onto the end of our query buffer,
482                                  * then we "just" need to make sure queryend is
483                                  * pointing at the right place.
484                                  */
485                                 if(req.query.p.size())
486                                 {
487                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
488
489                                         queryend += len;
490                                         req.query.p.pop_front();
491                                 }
492                                 else
493                                 {
494                                         log(DEBUG, "Found a substitution location but no parameter to substitute :|");
495                                         break;
496                                 }
497                         }
498                         else
499                         {
500                                 *queryend = req.query.q[i];
501                                 queryend++;
502                         }
503                         querylength++;
504                 }
505
506                 *queryend = 0;
507
508                 log(DEBUG, "Attempting to dispatch query: %s", query);
509
510                 pthread_mutex_lock(&queue_mutex);
511                 req.query.q = query;
512                 pthread_mutex_unlock(&queue_mutex);
513
514                 log(DEBUG,"REQUEST ID: %d",req.id);
515
516                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
517                 {
518                         /* Successfull query */
519                         res = mysql_use_result(&connection);
520                         unsigned long rows = mysql_affected_rows(&connection);
521                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
522                         r->dbid = this->GetID();
523                         r->query = req.query.q;
524                         /* Put this new result onto the results queue.
525                          * XXX: Remember to mutex the queue!
526                          */
527                         pthread_mutex_lock(&results_mutex);
528                         rq.push_back(r);
529                         pthread_mutex_unlock(&results_mutex);
530                 }
531                 else
532                 {
533                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
534                          * possible error numbers and error messages */
535                         log(DEBUG,"SQL ERROR: %s",mysql_error(&connection));
536                         SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
537                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
538                         r->dbid = this->GetID();
539                         r->query = req.query.q;
540
541                         pthread_mutex_lock(&results_mutex);
542                         rq.push_back(r);
543                         pthread_mutex_unlock(&results_mutex);
544                 }
545
546                 /* Now signal the main thread that we've got a result to process.
547                  * Pass them this connection id as what to examine
548                  */
549
550                 NotifyMainThread(this);
551         }
552
553         bool ConnectionLost()
554         {
555                 if (&connection) {
556                         return (mysql_ping(&connection) != 0);
557                 }
558                 else return false;
559         }
560
561         bool CheckConnection()
562         {
563                 if (ConnectionLost()) {
564                         return Connect();
565                 }
566                 else return true;
567         }
568
569         std::string GetError()
570         {
571                 return mysql_error(&connection);
572         }
573
574         const std::string& GetID()
575         {
576                 return id;
577         }
578
579         std::string GetHost()
580         {
581                 return host;
582         }
583
584         void SetEnable(bool Enable)
585         {
586                 Enabled = Enable;
587         }
588
589         bool IsEnabled()
590         {
591                 return Enabled;
592         }
593
594 };
595
596 ConnMap Connections;
597
598 void ConnectDatabases(Server* Srv)
599 {
600         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
601         {
602                 i->second->SetEnable(true);
603                 if (i->second->Connect())
604                 {
605                         Srv->Log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
606                 }
607                 else
608                 {
609                         Srv->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
610                         i->second->SetEnable(false);
611                 }
612         }
613 }
614
615
616 void LoadDatabases(ConfigReader* ThisConf, Server* Srv)
617 {
618         Srv->Log(DEFAULT,"SQL: Loading database settings");
619         Connections.clear();
620         Srv->Log(DEBUG,"Cleared connections");
621         for (int j =0; j < ThisConf->Enumerate("database"); j++)
622         {
623                 std::string db = ThisConf->ReadValue("database","name",j);
624                 std::string user = ThisConf->ReadValue("database","username",j);
625                 std::string pass = ThisConf->ReadValue("database","password",j);
626                 std::string host = ThisConf->ReadValue("database","hostname",j);
627                 std::string id = ThisConf->ReadValue("database","id",j);
628                 Srv->Log(DEBUG,"Read database settings");
629                 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
630                 {
631                         SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
632                         Srv->Log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
633                         Connections[id] = ThisSQL;
634                         Srv->Log(DEBUG,"Pushed back connection");
635                 }
636         }
637         ConnectDatabases(Srv);
638 }
639
640 void NotifyMainThread(SQLConnection* connection_with_new_result)
641 {
642         /* Here we write() to the socket the main thread has open
643          * and we connect()ed back to before our thread became active.
644          * The main thread is using a nonblocking socket tied into
645          * the socket engine, so they wont block and they'll receive
646          * nearly instant notification. Because we're in a seperate
647          * thread, we can just use standard connect(), and we can
648          * block if we like. We just send the connection id of the
649          * connection back.
650          */
651         log(DEBUG,"Notify of result on connection: %s",connection_with_new_result->GetID().c_str());
652         if (send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0) < 1) // add one for null terminator
653         {
654                 log(DEBUG,"Error writing to QueueFD: %s",strerror(errno));
655         }
656         log(DEBUG,"Sent it on its way via fd=%d",QueueFD);
657 }
658
659 void* DispatcherThread(void* arg);
660
661 class Notifier : public InspSocket
662 {
663         insp_sockaddr sock_us;
664         socklen_t uslen;
665         Server* Srv;
666
667  public:
668
669         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
670 #ifdef IPV6
671         Notifier(Server* S) : InspSocket("::1", 0, true, 3000), Srv(S)
672 #else
673         Notifier(Server* S) : InspSocket("127.0.0.1", 0, true, 3000), Srv(S)
674 #endif
675         {
676                 uslen = sizeof(sock_us);
677                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
678                 {
679                         throw ModuleException("Could not create random listening port on localhost");
680                 }
681         }
682
683         Notifier(int newfd, char* ip, Server* S) : InspSocket(newfd, ip), Srv(S)
684         {
685                 log(DEBUG,"Constructor of new socket");
686         }
687
688         /* Using getsockname and ntohs, we can determine which port number we were allocated */
689         int GetPort()
690         {
691 #ifdef IPV6
692                 return ntohs(sock_us.sin6_port);
693 #else
694                 return ntohs(sock_us.sin_port);
695 #endif
696         }
697
698         virtual int OnIncomingConnection(int newsock, char* ip)
699         {
700                 log(DEBUG,"Inbound connection on fd %d!",newsock);
701                 Notifier* n = new Notifier(newsock, ip, Srv);
702                 Srv->AddSocket(n);
703                 return true;
704         }
705
706         virtual bool OnDataReady()
707         {
708                 log(DEBUG,"Inbound data!");
709                 char* data = this->Read();
710                 ConnMap::iterator iter;
711
712                 if (data && *data)
713                 {
714                         log(DEBUG,"Looking for connection %s",data);
715                         /* We expect to be sent a null terminated string */
716                         if((iter = Connections.find(data)) != Connections.end())
717                         {
718                                 log(DEBUG,"Found it!");
719
720                                 /* Lock the mutex, send back the data */
721                                 pthread_mutex_lock(&results_mutex);
722                                 ResultQueue::iterator n = iter->second->rq.begin();
723                                 (*n)->Send();
724                                 iter->second->rq.pop_front();
725                                 pthread_mutex_unlock(&results_mutex);
726                                 return true;
727                         }
728                 }
729
730                 return false;
731         }
732 };
733
734 class ModuleSQL : public Module
735 {
736  public:
737         Server *Srv;
738         ConfigReader *Conf;
739         pthread_t Dispatcher;
740         int currid;
741
742         void Implements(char* List)
743         {
744                 List[I_OnRehash] = List[I_OnRequest] = 1;
745         }
746
747         unsigned long NewID()
748         {
749                 if (currid+1 == 0)
750                         currid++;
751                 return ++currid;
752         }
753
754         char* OnRequest(Request* request)
755         {
756                 if(strcmp(SQLREQID, request->GetId()) == 0)
757                 {
758                         SQLrequest* req = (SQLrequest*)request;
759
760                         /* XXX: Lock */
761                         pthread_mutex_lock(&queue_mutex);
762
763                         ConnMap::iterator iter;
764
765                         char* returnval = NULL;
766
767                         log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
768
769                         if((iter = Connections.find(req->dbid)) != Connections.end())
770                         {
771                                 req->id = NewID();
772                                 iter->second->queue.push(*req);
773                                 returnval = SQLSUCCESS;
774                         }
775                         else
776                         {
777                                 req->error.Id(BAD_DBID);
778                         }
779
780                         pthread_mutex_unlock(&queue_mutex);
781                         /* XXX: Unlock */
782
783                         return returnval;
784                 }
785
786                 log(DEBUG, "Got unsupported API version string: %s", request->GetId());
787
788                 return NULL;
789         }
790
791         ModuleSQL(Server* Me)
792                 : Module::Module(Me)
793         {
794                 Srv = Me;
795                 Conf = new ConfigReader();
796                 currid = 0;
797                 SQLModule = this;
798
799                 MessagePipe = new Notifier(Srv);
800                 Srv->AddSocket(MessagePipe);
801                 log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
802                 
803                 pthread_attr_t attribs;
804                 pthread_attr_init(&attribs);
805                 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
806                 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
807                 {
808                         throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
809                 }
810                 if (!Srv->PublishFeature("SQL", this))
811                 {
812                         /* Tell worker thread to exit NOW */
813                         giveup = true;
814                         throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
815                 }
816         }
817         
818         virtual ~ModuleSQL()
819         {
820                 DELETE(Conf);
821         }
822         
823         virtual void OnRehash(const std::string &parameter)
824         {
825                 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
826         }
827         
828         virtual Version GetVersion()
829         {
830                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
831         }
832         
833 };
834
835 void* DispatcherThread(void* arg)
836 {
837         log(DEBUG,"Starting Dispatcher thread, mysql version %d",mysql_get_client_version());
838         ModuleSQL* thismodule = (ModuleSQL*)arg;
839         LoadDatabases(thismodule->Conf, thismodule->Srv);
840
841         /* Connect back to the Notifier */
842
843         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
844         {
845                 /* crap, we're out of sockets... */
846                 log(DEBUG,"QueueFD cant be created");
847                 return NULL;
848         }
849
850         log(DEBUG,"Initialize QueueFD to %d",QueueFD);
851
852         insp_sockaddr addr;
853
854 #ifdef IPV6
855         insp_aton("::1", &addr.sin6_addr);
856         addr.sin6_family = AF_FAMILY;
857         addr.sin6_port = htons(MessagePipe->GetPort());
858 #else
859         insp_inaddr ia;
860         insp_aton("127.0.0.1", &ia);
861         addr.sin_family = AF_FAMILY;
862         addr.sin_addr = ia;
863         addr.sin_port = htons(MessagePipe->GetPort());
864 #endif
865
866         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
867         {
868                 /* wtf, we cant connect to it, but we just created it! */
869                 log(DEBUG,"QueueFD cant connect!");
870                 return NULL;
871         }
872
873         log(DEBUG,"Connect QUEUE FD");
874
875         while (!giveup)
876         {
877                 SQLConnection* conn = NULL;
878                 /* XXX: Lock here for safety */
879                 pthread_mutex_lock(&queue_mutex);
880                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
881                 {
882                         if (i->second->queue.totalsize())
883                         {
884                                 conn = i->second;
885                                 break;
886                         }
887                 }
888                 pthread_mutex_unlock(&queue_mutex);
889                 /* XXX: Unlock */
890
891                 /* Theres an item! */
892                 if (conn)
893                 {
894                         log(DEBUG,"Process Leading query");
895                         conn->DoLeadingQuery();
896
897                         /* XXX: Lock */
898                         pthread_mutex_lock(&queue_mutex);
899                         conn->queue.pop();
900                         pthread_mutex_unlock(&queue_mutex);
901                         /* XXX: Unlock */
902                 }
903
904                 usleep(50);
905         }
906
907         return NULL;
908 }
909
910
911 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
912
913 class ModuleSQLFactory : public ModuleFactory
914 {
915  public:
916         ModuleSQLFactory()
917         {
918         }
919         
920         ~ModuleSQLFactory()
921         {
922         }
923         
924         virtual Module * CreateModule(Server* Me)
925         {
926                 return new ModuleSQL(Me);
927         }
928         
929 };
930
931
932 extern "C" void * init_module( void )
933 {
934         return new ModuleSQLFactory;
935 }