]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mssql.cpp
[Taros] Add m_sakick.so
[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                 /* The length of the longest parameter */
363                 maxparamlen = 0;
364
365                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
366                 {
367                         if (i->size() > maxparamlen)
368                                 maxparamlen = i->size();
369                 }
370
371                 /* How many params are there in the query? */
372                 paramcount = count(req.query.q.c_str(), '?');
373
374                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
375                 ParamL paramscopy(req.query.p);
376
377                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
378                  * sizeofquery + (maxtotalparamlength*2) + 1
379                  *
380                  * The +1 is for null-terminating the string
381                  */
382
383                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
384                 queryend = query;
385
386                 for(unsigned long i = 0; i < req.query.q.length(); i++)
387                 {
388                         if(req.query.q[i] == '?')
389                         {
390                                 /* We found a place to substitute..what fun.
391                                  * use mssql calls to escape and write the
392                                  * escaped string onto the end of our query buffer,
393                                  * then we "just" need to make sure queryend is
394                                  * pointing at the right place.
395                                  */
396
397                                 /* Is it numbered parameter?
398                                  */
399
400                                 bool numbered;
401                                 numbered = false;
402
403                                 /* Numbered parameter number :|
404                                  */
405                                 unsigned int paramnum;
406                                 paramnum = 0;
407
408                                 /* Let's check if it's a numbered param. And also calculate it's number.
409                                  */
410
411                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
412                                 {
413                                         numbered = true;
414                                         ++i;
415                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
416                                 }
417
418                                 if (paramnum > paramscopy.size() - 1)
419                                 {
420                                         /* index is out of range!
421                                          */
422                                         numbered = false;
423                                 }
424
425                                 if (numbered)
426                                 {
427                                         /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
428                                          */
429                                         char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
430                                         char* escend = escaped;
431                                         for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
432                                         {
433                                                 if (*p == '\'')
434                                                 {
435                                                         *escend = *p;
436                                                         escend++;
437                                                         *escend = *p;
438                                                 }
439                                                 *escend = *p;
440                                                 escend++;
441                                         }
442                                         *escend = 0;
443
444                                         for (char* n = escaped; *n; n++)
445                                         {
446                                                 *queryend = *n;
447                                                 queryend++;
448                                         }
449                                         delete[] escaped;
450                                 }
451                                 else if (req.query.p.size())
452                                 {
453                                         /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
454                                          */
455                                         char* escaped = new char[(req.query.p.front().length() * 2) + 1];
456                                         char* escend = escaped;
457                                         for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
458                                         {
459                                                 if (*p == '\'')
460                                                 {
461                                                         *escend = *p;
462                                                         escend++;
463                                                         *escend = *p;
464                                                 }
465                                                 *escend = *p;
466                                                 escend++;
467                                         }
468                                         *escend = 0;
469
470                                         for (char* n = escaped; *n; n++)
471                                         {
472                                                 *queryend = *n;
473                                                 queryend++;
474                                         }
475                                         delete[] escaped;
476                                         req.query.p.pop_front();
477                                 }
478                                 else
479                                         break;
480                         }
481                         else
482                         {
483                                 *queryend = req.query.q[i];
484                                 queryend++;
485                         }
486                 }
487                 *queryend = 0;
488                 req.query.q = query;
489
490                 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
491                 res->dbid = host.id;
492                 res->query = req.query.q;
493
494                 char* msquery = strdup(req.query.q.data());
495                 LoggingMutex->Lock();
496                 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
497                 LoggingMutex->Unlock();
498                 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
499                 {
500                         std::string error("failed to execute: "+std::string(req.query.q.data()));
501                         delete[] query;
502                         delete res;
503                         free(msquery);
504                         return SQLerror(SQL_QSEND_FAIL, error);
505                 }
506                 delete[] query;
507                 free(msquery);
508
509                 int tds_res;
510                 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
511                 {
512                         //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
513                         //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
514                         switch (tds_res)
515                         {
516                                 case TDS_ROWFMT_RESULT:
517                                         break;
518
519                                 case TDS_DONE_RESULT:
520                                         if (sock->rows_affected > -1)
521                                         {
522                                                 for (int c = 0; c < sock->rows_affected; c++)  res->UpdateAffectedCount();
523                                                 continue;
524                                         }
525                                         break;
526
527                                 case TDS_ROW_RESULT:
528                                         while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
529                                         {
530                                                 if (tds_res != TDS_ROW_RESULT)
531                                                         break;
532
533                                                 if (!sock->current_results)
534                                                         continue;
535
536                                                 if (sock->res_info->row_count > 0)
537                                                 {
538                                                         int cols = sock->res_info->num_cols;
539                                                         char** name = new char*[MAXBUF];
540                                                         char** data = new char*[MAXBUF];
541                                                         for (int j=0; j<cols; j++)
542                                                         {
543                                                                 TDSCOLUMN* col = sock->current_results->columns[j];
544                                                                 name[j] = col->column_name;
545
546                                                                 int ctype;
547                                                                 int srclen;
548                                                                 unsigned char* src;
549                                                                 CONV_RESULT dres;
550                                                                 ctype = tds_get_conversion_type(col->column_type, col->column_size);
551 #if _TDSVER >= 82
552                                                                         src = col->column_data;
553 #else
554                                                                         src = &(sock->current_results->current_row[col->column_offset]);
555 #endif
556                                                                 srclen = col->column_cur_size;
557                                                                 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
558                                                                 data[j] = (char*)dres.ib;
559                                                         }
560                                                         ResultReady(res, cols, data, name);
561                                                 }
562                                         }
563                                         break;
564
565                                 default:
566                                         break;
567                         }
568                 }
569                 ResultsMutex->Lock();
570                 results.push_back(res);
571                 ResultsMutex->Unlock();
572                 SendNotify();
573                 return SQLerror();
574         }
575
576         static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
577         {
578                 SQLConn* sc = (SQLConn*)pContext->parent;
579                 LoggingMutex->Lock();
580                 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
581                 LoggingMutex->Unlock();
582                 return 0;
583         }
584
585         static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
586         {
587                 SQLConn* sc = (SQLConn*)pContext->parent;
588                 LoggingMutex->Lock();
589                 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
590                 LoggingMutex->Unlock();
591                 return 0;
592         }
593
594         void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
595         {
596                 res->AddRow(cols, data, colnames);
597         }
598
599         void AffectedReady(MsSQLResult *res)
600         {
601                 res->UpdateAffectedCount();
602         }
603
604         bool OpenDB()
605         {
606                 CloseDB();
607
608                 TDSCONNECTION* conn = NULL;
609
610                 login = tds_alloc_login();
611                 tds_set_app(login, "TSQL");
612                 tds_set_library(login,"TDS-Library");
613                 tds_set_host(login, "");
614                 tds_set_server(login, host.host.c_str());
615                 tds_set_server_addr(login, host.host.c_str());
616                 tds_set_user(login, host.user.c_str());
617                 tds_set_passwd(login, host.pass.c_str());
618                 tds_set_port(login, host.port);
619                 tds_set_packet(login, 512);
620
621                 context = tds_alloc_context(this);
622                 context->msg_handler = HandleMessage;
623                 context->err_handler = HandleError;
624
625                 sock = tds_alloc_socket(context, 512);
626                 tds_set_parent(sock, NULL);
627
628                 conn = tds_read_config_info(NULL, login, context->locale);
629
630                 if (tds_connect(sock, conn) == TDS_SUCCEED)
631                 {
632                         tds_free_connection(conn);
633                         return 1;
634                 }
635                 tds_free_connection(conn);
636                 return 0;
637         }
638
639         void CloseDB()
640         {
641                 if (sock)
642                 {
643                         tds_free_socket(sock);
644                         sock = NULL;
645                 }
646                 if (context)
647                 {
648                         tds_free_context(context);
649                         context = NULL;
650                 }
651                 if (login)
652                 {
653                         tds_free_login(login);
654                         login = NULL;
655                 }
656         }
657
658         SQLhost GetConfHost()
659         {
660                 return host;
661         }
662
663         void SendResults()
664         {
665                 while (results.size())
666                 {
667                         MsSQLResult* res = results[0];
668                         ResultsMutex->Lock();
669                         if (res->GetDest())
670                         {
671                                 res->Send();
672                         }
673                         else
674                         {
675                                 /* If the client module is unloaded partway through a query then the provider will set
676                                  * the pointer to NULL. We cannot just cancel the query as the result will still come
677                                  * through at some point...and it could get messy if we play with invalid pointers...
678                                  */
679                                 delete res;
680                         }
681                         results.pop_front();
682                         ResultsMutex->Unlock();
683                 }
684         }
685
686         void ClearResults()
687         {
688                 while (results.size())
689                 {
690                         MsSQLResult* res = results[0];
691                         delete res;
692                         results.pop_front();
693                 }
694         }
695
696         void SendNotify()
697         {
698                 if (QueueFD < 0)
699                 {
700                         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
701                         {
702                                 /* crap, we're out of sockets... */
703                                 return;
704                         }
705
706                         irc::sockets::insp_sockaddr addr;
707
708 #ifdef IPV6
709                         irc::sockets::insp_aton("::1", &addr.sin6_addr);
710                         addr.sin6_family = AF_FAMILY;
711                         addr.sin6_port = htons(listener->GetPort());
712 #else
713                         irc::sockets::insp_inaddr ia;
714                         irc::sockets::insp_aton("127.0.0.1", &ia);
715                         addr.sin_family = AF_FAMILY;
716                         addr.sin_addr = ia;
717                         addr.sin_port = htons(listener->GetPort());
718 #endif
719
720                         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
721                         {
722                                 /* wtf, we cant connect to it, but we just created it! */
723                                 return;
724                         }
725                 }
726                 char id = 0;
727                 send(QueueFD, &id, 1, 0);
728         }
729
730         void DoLeadingQuery()
731         {
732                 SQLrequest& req = queue.front();
733                 req.error = Query(req);
734         }
735
736 };
737
738
739 class ModuleMsSQL : public Module
740 {
741  private:
742         unsigned long currid;
743         QueryThread* queryDispatcher;
744
745  public:
746         ModuleMsSQL(InspIRCd* Me)
747         : Module(Me), currid(0)
748         {
749                 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
750                 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
751                 QueueMutex = ServerInstance->Mutexes->CreateMutex();
752
753                 ServerInstance->Modules->UseInterface("SQLutils");
754
755                 if (!ServerInstance->Modules->PublishFeature("SQL", this))
756                 {
757                         throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
758                 }
759
760                 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
761 #ifdef IPV6
762                 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
763 #else
764                 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
765 #endif
766
767                 if (listener->GetFd() == -1)
768                 {
769                         ServerInstance->Modules->DoneWithInterface("SQLutils");
770                         throw ModuleException("m_mssql: unable to create ITC pipe");
771                 }
772                 else
773                 {
774                         LoggingMutex->Lock();
775                         ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
776                         LoggingMutex->Unlock();
777                 }
778
779                 ReadConf();
780
781                 queryDispatcher = new QueryThread(ServerInstance, this);
782                 ServerInstance->Threads->Create(queryDispatcher);
783
784                 ServerInstance->Modules->PublishInterface("SQL", this);
785                 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
786                 ServerInstance->Modules->Attach(eventlist, this, 2);
787         }
788
789         virtual ~ModuleMsSQL()
790         {
791                 delete queryDispatcher;
792                 ClearQueue();
793                 ClearAllConnections();
794
795                 ServerInstance->SE->DelFd(listener);
796                 ServerInstance->BufferedSocketCull();
797
798                 if (QueueFD >= 0)
799                 {
800                         shutdown(QueueFD, 2);
801                         close(QueueFD);
802                 }
803
804                 if (notifier)
805                 {
806                         ServerInstance->SE->DelFd(notifier);
807                         notifier->Close();
808                         ServerInstance->BufferedSocketCull();
809                 }
810
811                 ServerInstance->Modules->UnpublishInterface("SQL", this);
812                 ServerInstance->Modules->UnpublishFeature("SQL");
813                 ServerInstance->Modules->DoneWithInterface("SQLutils");
814
815                 delete LoggingMutex;
816                 delete ResultsMutex;
817                 delete QueueMutex;
818         }
819
820
821         void SendQueue()
822         {
823                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
824                 {
825                         iter->second->SendResults();
826                 }
827         }
828
829         void ClearQueue()
830         {
831                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
832                 {
833                         iter->second->ClearResults();
834                 }
835         }
836
837         bool HasHost(const SQLhost &host)
838         {
839                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
840                 {
841                         if (host == iter->second->GetConfHost())
842                                 return true;
843                 }
844                 return false;
845         }
846
847         bool HostInConf(const SQLhost &h)
848         {
849                 ConfigReader conf(ServerInstance);
850                 for(int i = 0; i < conf.Enumerate("database"); i++)
851                 {
852                         SQLhost host;
853                         host.id         = conf.ReadValue("database", "id", i);
854                         host.host       = conf.ReadValue("database", "hostname", i);
855                         host.port       = conf.ReadInteger("database", "port", "1433", i, true);
856                         host.name       = conf.ReadValue("database", "name", i);
857                         host.user       = conf.ReadValue("database", "username", i);
858                         host.pass       = conf.ReadValue("database", "password", i);
859                         if (h == host)
860                                 return true;
861                 }
862                 return false;
863         }
864
865         void ReadConf()
866         {
867                 ClearOldConnections();
868
869                 ConfigReader conf(ServerInstance);
870                 for(int i = 0; i < conf.Enumerate("database"); i++)
871                 {
872                         SQLhost host;
873
874                         host.id         = conf.ReadValue("database", "id", i);
875                         host.host       = conf.ReadValue("database", "hostname", i);
876                         host.port       = conf.ReadInteger("database", "port", "1433", i, true);
877                         host.name       = conf.ReadValue("database", "name", i);
878                         host.user       = conf.ReadValue("database", "username", i);
879                         host.pass       = conf.ReadValue("database", "password", i);
880
881                         if (HasHost(host))
882                                 continue;
883
884                         this->AddConn(host);
885                 }
886         }
887
888         void AddConn(const SQLhost& hi)
889         {
890                 if (HasHost(hi))
891                 {
892                         LoggingMutex->Lock();
893                         ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
894                         LoggingMutex->Unlock();
895                         return;
896                 }
897
898                 SQLConn* newconn;
899
900                 newconn = new SQLConn(ServerInstance, this, hi);
901
902                 connections.insert(std::make_pair(hi.id, newconn));
903         }
904
905         void ClearOldConnections()
906         {
907                 ConnMap::iterator iter,safei;
908                 for (iter = connections.begin(); iter != connections.end(); iter++)
909                 {
910                         if (!HostInConf(iter->second->GetConfHost()))
911                         {
912                                 delete iter->second;
913                                 safei = iter;
914                                 --iter;
915                                 connections.erase(safei);
916                         }
917                 }
918         }
919
920         void ClearAllConnections()
921         {
922                 ConnMap::iterator i;
923                 while ((i = connections.begin()) != connections.end())
924                 {
925                         connections.erase(i);
926                         delete i->second;
927                 }
928         }
929
930         virtual void OnRehash(User* user, const std::string &parameter)
931         {
932                 QueueMutex->Lock();
933                 ReadConf();
934                 QueueMutex->Unlock();
935         }
936
937         virtual const char* OnRequest(Request* request)
938         {
939                 if(strcmp(SQLREQID, request->GetId()) == 0)
940                 {
941                         SQLrequest* req = (SQLrequest*)request;
942
943                         QueueMutex->Lock();
944
945                         ConnMap::iterator iter;
946
947                         const char* returnval = NULL;
948
949                         if((iter = connections.find(req->dbid)) != connections.end())
950                         {
951                                 req->id = NewID();
952                                 iter->second->queue.push(*req);
953                                 returnval= SQLSUCCESS;
954                         }
955                         else
956                         {
957                                 req->error.Id(SQL_BAD_DBID);
958                         }
959
960                         QueueMutex->Unlock();
961
962                         return returnval;
963                 }
964                 return NULL;
965         }
966
967         unsigned long NewID()
968         {
969                 if (currid+1 == 0)
970                         currid++;
971
972                 return ++currid;
973         }
974
975         virtual Version GetVersion()
976         {
977                 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
978         }
979
980 };
981
982 void ResultNotifier::Dispatch()
983 {
984         mod->SendQueue();
985 }
986
987 void QueryThread::Run()
988 {
989         while (this->GetExitFlag() == false)
990         {
991                 SQLConn* conn = NULL;
992                 QueueMutex->Lock();
993                 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
994                 {
995                         if (i->second->queue.totalsize())
996                         {
997                                 conn = i->second;
998                                 break;
999                         }
1000                 }
1001                 QueueMutex->Unlock();
1002                 if (conn)
1003                 {
1004                         conn->DoLeadingQuery();
1005                         QueueMutex->Lock();
1006                         conn->queue.pop();
1007                         QueueMutex->Unlock();
1008                 }
1009                 usleep(1000);
1010         }
1011 }
1012
1013 MODULE_INIT(ModuleMsSQL)