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