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