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