]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mssql.cpp
Ah pasting, also remove this var from here
[user/henk/code/inspircd.git] / src / modules / extra / m_mssql.cpp
1 /*               +------------------------------------+
2  *               | Inspire Internet Relay Chat Daemon |
3  *               +------------------------------------+
4  *
5  *      InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *                        the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <tds.h>
16 #include <tdsconvert.h>
17 #include "users.h"
18 #include "channels.h"
19 #include "modules.h"
20
21 #include "m_sqlv2.h"
22
23 /* $ModDesc: MsSQL provider */
24 /* $CompileFlags: exec("grep VERSION_NO /usr/include/tdsver.h 2>/dev/null | perl -e 'print "-D_TDSVER=".((<> =~ /freetds v(\d+\.\d+)/i) ? $1*100 : 0);'") */
25 /* $LinkerFlags: -ltds */
26 /* $ModDep: m_sqlv2.h */
27
28 class SQLConn;
29 class MsSQLResult;
30 class ResultNotifier;
31 class MsSQLListener;
32 class ModuleMsSQL;
33
34 typedef std::map<std::string, SQLConn*> ConnMap;
35 typedef std::deque<MsSQLResult*> ResultQueue;
36
37 unsigned long count(const char * const str, char a)
38 {
39         unsigned long n = 0;
40         for (const char *p = reinterpret_cast<const char *>(str); *p; ++p)
41         {
42                 if (*p == '?')
43                         ++n;
44         }
45         return n;
46 }
47
48 ResultNotifier* notifier = NULL;
49 MsSQLListener* listener = NULL;
50 int QueueFD = -1;
51
52 ConnMap connections;
53 Mutex* QueueMutex;
54 Mutex* ResultsMutex;
55 Mutex* LoggingMutex;
56
57 class QueryThread : public Thread
58 {
59   private:
60         ModuleMsSQL* Parent;
61         InspIRCd* ServerInstance;
62   public:
63         QueryThread(InspIRCd* si, ModuleMsSQL* mod)
64         : Thread(), Parent(mod), ServerInstance(si)
65         {
66         }
67         ~QueryThread() { }
68         virtual void Run();
69 };
70
71 class ResultNotifier : public BufferedSocket
72 {
73         ModuleMsSQL* mod;
74
75  public:
76         ResultNotifier(ModuleMsSQL* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
77         {
78         }
79
80         virtual bool OnDataReady()
81         {
82                 char data = 0;
83                 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
84                 {
85                         Dispatch();
86                         return true;
87                 }
88                 return false;
89         }
90
91         void Dispatch();
92 };
93
94 class MsSQLListener : public ListenSocketBase
95 {
96         ModuleMsSQL* Parent;
97         irc::sockets::insp_sockaddr sock_us;
98         socklen_t uslen;
99         FileReader* index;
100
101  public:
102         MsSQLListener(ModuleMsSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
103         {
104                 uslen = sizeof(sock_us);
105                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
106                 {
107                         throw ModuleException("Could not getsockname() to find out port number for ITC port");
108                 }
109         }
110
111         virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
112         {
113                 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
114         }
115
116         /* Using getsockname and ntohs, we can determine which port number we were allocated */
117         int GetPort()
118         {
119 #ifdef IPV6
120                 return ntohs(sock_us.sin6_port);
121 #else
122                 return ntohs(sock_us.sin_port);
123 #endif
124         }
125 };
126
127
128 class MsSQLResult : public SQLresult
129 {
130  private:
131         int currentrow;
132         int rows;
133         int cols;
134
135         std::vector<std::string> colnames;
136         std::vector<SQLfieldList> fieldlists;
137         SQLfieldList emptyfieldlist;
138
139         SQLfieldList* fieldlist;
140         SQLfieldMap* fieldmap;
141
142  public:
143         MsSQLResult(Module* self, Module* to, unsigned int rid)
144         : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
145         {
146         }
147
148         ~MsSQLResult()
149         {
150         }
151
152         void AddRow(int colsnum, char **dat, char **colname)
153         {
154                 colnames.clear();
155                 cols = colsnum;
156                 for (int i = 0; i < colsnum; i++)
157                 {
158                         fieldlists.resize(fieldlists.size()+1);
159                         colnames.push_back(colname[i]);
160                         SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
161                         fieldlists[rows].push_back(sf);
162                 }
163                 rows++;
164         }
165
166         void UpdateAffectedCount()
167         {
168                 rows++;
169         }
170
171         virtual int Rows()
172         {
173                 return rows;
174         }
175
176         virtual int Cols()
177         {
178                 return cols;
179         }
180
181         virtual std::string ColName(int column)
182         {
183                 if (column < (int)colnames.size())
184                 {
185                         return colnames[column];
186                 }
187                 else
188                 {
189                         throw SQLbadColName();
190                 }
191                 return "";
192         }
193
194         virtual int ColNum(const std::string &column)
195         {
196                 for (unsigned int i = 0; i < colnames.size(); i++)
197                 {
198                         if (column == colnames[i])
199                                 return i;
200                 }
201                 throw SQLbadColName();
202                 return 0;
203         }
204
205         virtual SQLfield GetValue(int row, int column)
206         {
207                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
208                 {
209                         return fieldlists[row][column];
210                 }
211
212                 throw SQLbadColName();
213
214                 /* XXX: We never actually get here because of the throw */
215                 return SQLfield("",true);
216         }
217
218         virtual SQLfieldList& GetRow()
219         {
220                 if (currentrow < rows)
221                         return fieldlists[currentrow];
222                 else
223                         return emptyfieldlist;
224         }
225
226         virtual SQLfieldMap& GetRowMap()
227         {
228                 /* In an effort to reduce overhead we don't actually allocate the map
229                  * until the first time it's needed...so...
230                  */
231                 if(fieldmap)
232                 {
233                         fieldmap->clear();
234                 }
235                 else
236                 {
237                         fieldmap = new SQLfieldMap;
238                 }
239
240                 if (currentrow < rows)
241                 {
242                         for (int i = 0; i < Cols(); i++)
243                         {
244                                 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
245                         }
246                         currentrow++;
247                 }
248
249                 return *fieldmap;
250         }
251
252         virtual SQLfieldList* GetRowPtr()
253         {
254                 fieldlist = new SQLfieldList();
255
256                 if (currentrow < rows)
257                 {
258                         for (int i = 0; i < Rows(); i++)
259                         {
260                                 fieldlist->push_back(fieldlists[currentrow][i]);
261                         }
262                         currentrow++;
263                 }
264                 return fieldlist;
265         }
266
267         virtual SQLfieldMap* GetRowMapPtr()
268         {
269                 fieldmap = new SQLfieldMap();
270
271                 if (currentrow < rows)
272                 {
273                         for (int i = 0; i < Cols(); i++)
274                         {
275                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
276                         }
277                         currentrow++;
278                 }
279
280                 return fieldmap;
281         }
282
283         virtual void Free(SQLfieldMap* fm)
284         {
285                 delete fm;
286         }
287
288         virtual void Free(SQLfieldList* fl)
289         {
290                 delete fl;
291         }
292
293
294 };
295
296 class SQLConn : public classbase
297 {
298  private:
299         ResultQueue results;
300         InspIRCd* ServerInstance;
301         Module* mod;
302         SQLhost host;
303         TDSLOGIN* login;
304         TDSSOCKET* sock;
305         TDSCONTEXT* context;
306
307  public:
308         QueryQueue queue;
309
310         SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
311         : ServerInstance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
312         {
313                 if (OpenDB())
314                 {
315                         std::string query("USE " + host.name);
316                         if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
317                         {
318                                 if (tds_process_simple_query(sock) != TDS_SUCCEED)
319                                 {
320                                         LoggingMutex->Lock();
321                                         ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
322                                         LoggingMutex->Unlock();
323                                         CloseDB();
324                                 }
325                         }
326                         else
327                         {
328                                 LoggingMutex->Lock();
329                                 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
330                                 LoggingMutex->Unlock();
331                                 CloseDB();
332                         }
333                 }
334                 else
335                 {
336                         LoggingMutex->Lock();
337                         ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
338                         LoggingMutex->Unlock();
339                         CloseDB();
340                 }
341         }
342
343         ~SQLConn()
344         {
345                 CloseDB();
346         }
347
348         SQLerror Query(SQLrequest &req)
349         {
350                 if (!sock)
351                         return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
352
353                 /* Pointer to the buffer we screw around with substitution in */
354                 char* query;
355
356                 /* Pointer to the current end of query, where we append new stuff */
357                 char* queryend;
358
359                 /* Total length of the unescaped parameters */
360                 unsigned long maxparamlen, paramcount;
361
362                 /* Total length of query, used for binary-safety */
363                 unsigned long querylength = 0;
364
365                 /* The length of the longest parameter */
366                 maxparamlen = 0;
367
368                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
369                 {
370                         if (i->size() > maxparamlen)
371                                 maxparamlen = i->size();
372                 }
373
374                 /* How many params are there in the query? */
375                 paramcount = count(req.query.q.c_str(), '?');
376
377                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
378                 ParamL paramscopy(req.query.p);
379
380                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
381                  * sizeofquery + (maxtotalparamlength*2) + 1
382                  *
383                  * The +1 is for null-terminating the string
384                  */
385
386                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
387                 queryend = query;
388
389                 for(unsigned long i = 0; i < req.query.q.length(); i++)
390                 {
391                         if(req.query.q[i] == '?')
392                         {
393                                 /* We found a place to substitute..what fun.
394                                  * use mssql calls to escape and write the
395                                  * escaped string onto the end of our query buffer,
396                                  * then we "just" need to make sure queryend is
397                                  * pointing at the right place.
398                                  */
399
400                                 /* Is it numbered parameter?
401                                  */
402
403                                 bool numbered;
404                                 numbered = false;
405
406                                 /* Numbered parameter number :|
407                                  */
408                                 unsigned int paramnum;
409                                 paramnum = 0;
410
411                                 /* Let's check if it's a numbered param. And also calculate it's number.
412                                  */
413
414                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
415                                 {
416                                         numbered = true;
417                                         ++i;
418                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
419                                 }
420
421                                 if (paramnum > paramscopy.size() - 1)
422                                 {
423                                         /* index is out of range!
424                                          */
425                                         numbered = false;
426                                 }
427
428                                 if (numbered)
429                                 {
430                                         /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
431                                          */
432                                         char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
433                                         char* escend = escaped;
434                                         for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
435                                         {
436                                                 if (*p == '\'')
437                                                 {
438                                                         *escend = *p;
439                                                         escend++;
440                                                         *escend = *p;
441                                                 }
442                                                 *escend = *p;
443                                                 escend++;
444                                         }
445                                         *escend = 0;
446
447                                         for (char* n = escaped; *n; n++)
448                                         {
449                                                 *queryend = *n;
450                                                 queryend++;
451                                         }
452                                         delete[] escaped;
453                                 }
454                                 else if (req.query.p.size())
455                                 {
456                                         /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
457                                          */
458                                         char* escaped = new char[(req.query.p.front().length() * 2) + 1];
459                                         char* escend = escaped;
460                                         for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
461                                         {
462                                                 if (*p == '\'')
463                                                 {
464                                                         *escend = *p;
465                                                         escend++;
466                                                         *escend = *p;
467                                                 }
468                                                 *escend = *p;
469                                                 escend++;
470                                         }
471                                         *escend = 0;
472
473                                         for (char* n = escaped; *n; n++)
474                                         {
475                                                 *queryend = *n;
476                                                 queryend++;
477                                         }
478                                         delete[] escaped;
479                                         req.query.p.pop_front();
480                                 }
481                                 else
482                                         break;
483                         }
484                         else
485                         {
486                                 *queryend = req.query.q[i];
487                                 queryend++;
488                         }
489                         querylength++;
490                 }
491                 *queryend = 0;
492                 req.query.q = query;
493
494                 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
495                 res->dbid = host.id;
496                 res->query = req.query.q;
497
498                 char* msquery = strdup(req.query.q.data());
499                 LoggingMutex->Lock();
500                 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
501                 LoggingMutex->Unlock();
502                 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
503                 {
504                         std::string error("failed to execute: "+std::string(req.query.q.data()));
505                         delete[] query;
506                         delete res;
507                         free(msquery);
508                         return SQLerror(SQL_QSEND_FAIL, error);
509                 }
510                 delete[] query;
511                 free(msquery);
512
513                 int tds_res;
514                 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
515                 {
516                         //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
517                         //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
518                         switch (tds_res)
519                         {
520                                 case TDS_ROWFMT_RESULT:
521                                         break;
522
523                                 case TDS_DONE_RESULT:
524                                         if (sock->rows_affected > -1)
525                                         {
526                                                 for (int c = 0; c < sock->rows_affected; c++)  res->UpdateAffectedCount();
527                                                 continue;
528                                         }
529                                         break;
530
531                                 case TDS_ROW_RESULT:
532                                         while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
533                                         {
534                                                 if (tds_res != TDS_ROW_RESULT)
535                                                         break;
536
537                                                 if (!sock->current_results)
538                                                         continue;
539
540                                                 if (sock->res_info->row_count > 0)
541                                                 {
542                                                         int cols = sock->res_info->num_cols;
543                                                         char** name = new char*[MAXBUF];
544                                                         char** data = new char*[MAXBUF];
545                                                         for (int j=0; j<cols; j++)
546                                                         {
547                                                                 TDSCOLUMN* col = sock->current_results->columns[j];
548                                                                 name[j] = col->column_name;
549
550                                                                 int ctype;
551                                                                 int srclen;
552                                                                 unsigned char* src;
553                                                                 CONV_RESULT dres;
554                                                                 ctype = tds_get_conversion_type(col->column_type, col->column_size);
555 #if _TDSVER >= 82
556                                                                         src = col->column_data;
557 #else
558                                                                         src = &(sock->current_results->current_row[col->column_offset]);
559 #endif
560                                                                 srclen = col->column_cur_size;
561                                                                 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
562                                                                 data[j] = (char*)dres.ib;
563                                                         }
564                                                         ResultReady(res, cols, data, name);
565                                                 }
566                                         }
567                                         break;
568
569                                 default:
570                                         break;
571                         }
572                 }
573                 ResultsMutex->Lock();
574                 results.push_back(res);
575                 ResultsMutex->Unlock();
576                 SendNotify();
577                 return SQLerror();
578         }
579
580         static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
581         {
582                 SQLConn* sc = (SQLConn*)pContext->parent;
583                 LoggingMutex->Lock();
584                 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
585                 LoggingMutex->Unlock();
586                 return 0;
587         }
588
589         static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
590         {
591                 SQLConn* sc = (SQLConn*)pContext->parent;
592                 LoggingMutex->Lock();
593                 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
594                 LoggingMutex->Unlock();
595                 return 0;
596         }
597
598         void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
599         {
600                 res->AddRow(cols, data, colnames);
601         }
602
603         void AffectedReady(MsSQLResult *res)
604         {
605                 res->UpdateAffectedCount();
606         }
607
608         bool OpenDB()
609         {
610                 CloseDB();
611
612                 TDSCONNECTION* conn = NULL;
613
614                 login = tds_alloc_login();
615                 tds_set_app(login, "TSQL");
616                 tds_set_library(login,"TDS-Library");
617                 tds_set_host(login, "");
618                 tds_set_server(login, host.host.c_str());
619                 tds_set_server_addr(login, host.host.c_str());
620                 tds_set_user(login, host.user.c_str());
621                 tds_set_passwd(login, host.pass.c_str());
622                 tds_set_port(login, host.port);
623                 tds_set_packet(login, 512);
624
625                 context = tds_alloc_context(this);
626                 context->msg_handler = HandleMessage;
627                 context->err_handler = HandleError;
628
629                 sock = tds_alloc_socket(context, 512);
630                 tds_set_parent(sock, NULL);
631
632                 conn = tds_read_config_info(NULL, login, context->locale);
633
634                 if (tds_connect(sock, conn) == TDS_SUCCEED)
635                 {
636                         tds_free_connection(conn);
637                         return 1;
638                 }
639                 tds_free_connection(conn);
640                 return 0;
641         }
642
643         void CloseDB()
644         {
645                 if (sock)
646                 {
647                         tds_free_socket(sock);
648                         sock = NULL;
649                 }
650                 if (context)
651                 {
652                         tds_free_context(context);
653                         context = NULL;
654                 }
655                 if (login)
656                 {
657                         tds_free_login(login);
658                         login = NULL;
659                 }
660         }
661
662         SQLhost GetConfHost()
663         {
664                 return host;
665         }
666
667         void SendResults()
668         {
669                 while (results.size())
670                 {
671                         MsSQLResult* res = results[0];
672                         ResultsMutex->Lock();
673                         if (res->GetDest())
674                         {
675                                 res->Send();
676                         }
677                         else
678                         {
679                                 /* If the client module is unloaded partway through a query then the provider will set
680                                  * the pointer to NULL. We cannot just cancel the query as the result will still come
681                                  * through at some point...and it could get messy if we play with invalid pointers...
682                                  */
683                                 delete res;
684                         }
685                         results.pop_front();
686                         ResultsMutex->Unlock();
687                 }
688         }
689
690         void ClearResults()
691         {
692                 while (results.size())
693                 {
694                         MsSQLResult* res = results[0];
695                         delete res;
696                         results.pop_front();
697                 }
698         }
699
700         void SendNotify()
701         {
702                 if (QueueFD < 0)
703                 {
704                         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
705                         {
706                                 /* crap, we're out of sockets... */
707                                 return;
708                         }
709
710                         irc::sockets::insp_sockaddr addr;
711
712 #ifdef IPV6
713                         irc::sockets::insp_aton("::1", &addr.sin6_addr);
714                         addr.sin6_family = AF_FAMILY;
715                         addr.sin6_port = htons(listener->GetPort());
716 #else
717                         irc::sockets::insp_inaddr ia;
718                         irc::sockets::insp_aton("127.0.0.1", &ia);
719                         addr.sin_family = AF_FAMILY;
720                         addr.sin_addr = ia;
721                         addr.sin_port = htons(listener->GetPort());
722 #endif
723
724                         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
725                         {
726                                 /* wtf, we cant connect to it, but we just created it! */
727                                 return;
728                         }
729                 }
730                 char id = 0;
731                 send(QueueFD, &id, 1, 0);
732         }
733
734         void DoLeadingQuery()
735         {
736                 SQLrequest& req = queue.front();
737                 req.error = Query(req);
738         }
739
740 };
741
742
743 class ModuleMsSQL : public Module
744 {
745  private:
746         unsigned long currid;
747         QueryThread* queryDispatcher;
748
749  public:
750         ModuleMsSQL(InspIRCd* Me)
751         : Module(Me), currid(0)
752         {
753                 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
754                 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
755                 QueueMutex = ServerInstance->Mutexes->CreateMutex();
756
757                 ServerInstance->Modules->UseInterface("SQLutils");
758
759                 if (!ServerInstance->Modules->PublishFeature("SQL", this))
760                 {
761                         throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
762                 }
763
764                 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
765 #ifdef IPV6
766                 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
767 #else
768                 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
769 #endif
770
771                 if (listener->GetFd() == -1)
772                 {
773                         ServerInstance->Modules->DoneWithInterface("SQLutils");
774                         throw ModuleException("m_mssql: unable to create ITC pipe");
775                 }
776                 else
777                 {
778                         LoggingMutex->Lock();
779                         ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
780                         LoggingMutex->Unlock();
781                 }
782
783                 ReadConf();
784
785                 queryDispatcher = new QueryThread(ServerInstance, this);
786                 ServerInstance->Threads->Create(queryDispatcher);
787
788                 ServerInstance->Modules->PublishInterface("SQL", this);
789                 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
790                 ServerInstance->Modules->Attach(eventlist, this, 2);
791         }
792
793         virtual ~ModuleMsSQL()
794         {
795                 delete queryDispatcher;
796                 ClearQueue();
797                 ClearAllConnections();
798
799                 ServerInstance->SE->DelFd(listener);
800                 ServerInstance->BufferedSocketCull();
801
802                 if (QueueFD >= 0)
803                 {
804                         shutdown(QueueFD, 2);
805                         close(QueueFD);
806                 }
807
808                 if (notifier)
809                 {
810                         ServerInstance->SE->DelFd(notifier);
811                         notifier->Close();
812                         ServerInstance->BufferedSocketCull();
813                 }
814
815                 ServerInstance->Modules->UnpublishInterface("SQL", this);
816                 ServerInstance->Modules->UnpublishFeature("SQL");
817                 ServerInstance->Modules->DoneWithInterface("SQLutils");
818
819                 delete LoggingMutex;
820                 delete ResultsMutex;
821                 delete QueueMutex;
822         }
823
824
825         void SendQueue()
826         {
827                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
828                 {
829                         iter->second->SendResults();
830                 }
831         }
832
833         void ClearQueue()
834         {
835                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
836                 {
837                         iter->second->ClearResults();
838                 }
839         }
840
841         bool HasHost(const SQLhost &host)
842         {
843                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
844                 {
845                         if (host == iter->second->GetConfHost())
846                                 return true;
847                 }
848                 return false;
849         }
850
851         bool HostInConf(const SQLhost &h)
852         {
853                 ConfigReader conf(ServerInstance);
854                 for(int i = 0; i < conf.Enumerate("database"); i++)
855                 {
856                         SQLhost host;
857                         host.id         = conf.ReadValue("database", "id", i);
858                         host.host       = conf.ReadValue("database", "hostname", i);
859                         host.port       = conf.ReadInteger("database", "port", "1433", i, true);
860                         host.name       = conf.ReadValue("database", "name", i);
861                         host.user       = conf.ReadValue("database", "username", i);
862                         host.pass       = conf.ReadValue("database", "password", i);
863                         if (h == host)
864                                 return true;
865                 }
866                 return false;
867         }
868
869         void ReadConf()
870         {
871                 ClearOldConnections();
872
873                 ConfigReader conf(ServerInstance);
874                 for(int i = 0; i < conf.Enumerate("database"); i++)
875                 {
876                         SQLhost host;
877
878                         host.id         = conf.ReadValue("database", "id", i);
879                         host.host       = conf.ReadValue("database", "hostname", i);
880                         host.port       = conf.ReadInteger("database", "port", "1433", i, true);
881                         host.name       = conf.ReadValue("database", "name", i);
882                         host.user       = conf.ReadValue("database", "username", i);
883                         host.pass       = conf.ReadValue("database", "password", i);
884
885                         if (HasHost(host))
886                                 continue;
887
888                         this->AddConn(host);
889                 }
890         }
891
892         void AddConn(const SQLhost& hi)
893         {
894                 if (HasHost(hi))
895                 {
896                         LoggingMutex->Lock();
897                         ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
898                         LoggingMutex->Unlock();
899                         return;
900                 }
901
902                 SQLConn* newconn;
903
904                 newconn = new SQLConn(ServerInstance, this, hi);
905
906                 connections.insert(std::make_pair(hi.id, newconn));
907         }
908
909         void ClearOldConnections()
910         {
911                 ConnMap::iterator iter,safei;
912                 for (iter = connections.begin(); iter != connections.end(); iter++)
913                 {
914                         if (!HostInConf(iter->second->GetConfHost()))
915                         {
916                                 delete iter->second;
917                                 safei = iter;
918                                 --iter;
919                                 connections.erase(safei);
920                         }
921                 }
922         }
923
924         void ClearAllConnections()
925         {
926                 ConnMap::iterator i;
927                 while ((i = connections.begin()) != connections.end())
928                 {
929                         connections.erase(i);
930                         delete i->second;
931                 }
932         }
933
934         virtual void OnRehash(User* user, const std::string &parameter)
935         {
936                 QueueMutex->Lock();
937                 ReadConf();
938                 QueueMutex->Unlock();
939         }
940
941         virtual const char* OnRequest(Request* request)
942         {
943                 if(strcmp(SQLREQID, request->GetId()) == 0)
944                 {
945                         SQLrequest* req = (SQLrequest*)request;
946
947                         QueueMutex->Lock();
948
949                         ConnMap::iterator iter;
950
951                         const char* returnval = NULL;
952
953                         if((iter = connections.find(req->dbid)) != connections.end())
954                         {
955                                 req->id = NewID();
956                                 iter->second->queue.push(*req);
957                                 returnval= SQLSUCCESS;
958                         }
959                         else
960                         {
961                                 req->error.Id(SQL_BAD_DBID);
962                         }
963
964                         QueueMutex->Unlock();
965
966                         return returnval;
967                 }
968                 return NULL;
969         }
970
971         unsigned long NewID()
972         {
973                 if (currid+1 == 0)
974                         currid++;
975
976                 return ++currid;
977         }
978
979         virtual Version GetVersion()
980         {
981                 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
982         }
983
984 };
985
986 void ResultNotifier::Dispatch()
987 {
988         mod->SendQueue();
989 }
990
991 void QueryThread::Run()
992 {
993         while (this->GetExitFlag() == false)
994         {
995                 SQLConn* conn = NULL;
996                 QueueMutex->Lock();
997                 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
998                 {
999                         if (i->second->queue.totalsize())
1000                         {
1001                                 conn = i->second;
1002                                 break;
1003                         }
1004                 }
1005                 QueueMutex->Unlock();
1006                 if (conn)
1007                 {
1008                         conn->DoLeadingQuery();
1009                         QueueMutex->Lock();
1010                         conn->queue.pop();
1011                         QueueMutex->Unlock();
1012                 }
1013                 usleep(1000);
1014         }
1015 }
1016
1017 MODULE_INIT(ModuleMsSQL)