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