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