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