]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mssql.cpp
OK that should fix it for fail too. And make it compile again.
[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                 /* Pointer to the buffer we screw around with substitution in */
298                 char* query;
299
300                 /* Pointer to the current end of query, where we append new stuff */
301                 char* queryend;
302
303                 /* Total length of the unescaped parameters */
304                 unsigned long paramlen;
305
306                 /* Total length of query, used for binary-safety in mysql_real_query */
307                 unsigned long querylength = 0;
308
309                 paramlen = 0;
310                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
311                 {
312                         paramlen += i->size();
313                 }
314
315                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
316                  * sizeofquery + (totalparamlength*2) + 1
317                  *
318                  * The +1 is for null-terminating the string
319                  */
320                 query = new char[req.query.q.length() + (paramlen*2) + 1];
321                 queryend = query;
322
323                 for(unsigned long i = 0; i < req.query.q.length(); i++)
324                 {
325                         if(req.query.q[i] == '?')
326                         {
327                                 if(req.query.p.size())
328                                 {
329                                         /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
330                                          */
331                                         char* escaped = new char[(req.query.p.front().length() * 2) + 1];
332                                         char* escend = escaped;
333                                         for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
334                                         {
335                                                 if (*p == '\'')
336                                                 {
337                                                         *escend = *p;
338                                                         escend++;
339                                                         *escend = *p;
340                                                 }
341                                                 *escend = *p;
342                                                 escend++;
343                                         }
344                                         *escend = 0;
345                                         
346                                         for (char* n = escaped; *n; n++)
347                                         {
348                                                 *queryend = *n;
349                                                 queryend++;
350                                         }
351                                         delete[] escaped;
352                                         req.query.p.pop_front();
353                                 }
354                                 else
355                                         break;
356                         }
357                         else
358                         {
359                                 *queryend = req.query.q[i];
360                                 queryend++;
361                         }
362                         querylength++;
363                 }
364                 *queryend = 0;
365                 req.query.q = query;
366
367                 MsSQLResult* res = new MsSQLResult(mod, req.GetSource(), req.id);
368                 res->dbid = host.id;
369                 res->query = req.query.q;
370
371                 char* msquery = strdup(req.query.q.data());
372                 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
373                 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
374                 {
375                         std::string error("failed to execute: "+std::string(req.query.q.data()));
376                         delete[] query;
377                         delete res;
378                         free(msquery);
379                         return SQLerror(QSEND_FAIL, error);
380                 }
381                 delete[] query;
382                 free(msquery);
383                 
384                 int tds_res;
385                 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
386                 {
387                         //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
388                         //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
389                         switch (tds_res)
390                         {
391                                 case TDS_ROWFMT_RESULT:
392                                         break;
393
394                                 case TDS_DONE_RESULT:
395                                         if (sock->rows_affected > -1)
396                                         {
397                                                 for (int c = 0; c < sock->rows_affected; c++)  res->UpdateAffectedCount();
398                                                 continue;
399                                         }
400                                         break;
401
402                                 case TDS_ROW_RESULT:
403                                         while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
404                                         {
405                                                 if (tds_res != TDS_ROW_RESULT)
406                                                         break;
407
408                                                 if (!sock->current_results)
409                                                         continue;
410
411                                                 if (sock->res_info->row_count > 0)
412                                                 {
413                                                         int cols = sock->res_info->num_cols;
414                                                         char** name = new char*[MAXBUF];
415                                                         char** data = new char*[MAXBUF];
416                                                         for (int j=0; j<cols; j++)
417                                                         {
418                                                                 TDSCOLUMN* col = sock->current_results->columns[j];
419                                                                 name[j] = col->column_name;
420
421                                                                 int ctype;
422                                                                 int srclen;
423                                                                 unsigned char* src;
424                                                                 CONV_RESULT dres;
425                                                                 ctype = tds_get_conversion_type(col->column_type, col->column_size);
426                                                                 src = &(sock->current_results->current_row[col->column_offset]);
427                                                                 srclen = col->column_cur_size;
428                                                                 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
429                                                                 data[j] = (char*)dres.ib;
430                                                         }
431                                                         ResultReady(res, cols, data, name);
432                                                 }
433                                         }
434                                         break;
435
436                                 default:
437                                         break;
438                         }       
439                 }
440                 results.push_back(res);
441                 SendNotify();
442                 return SQLerror();
443         }
444
445         static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
446         {
447                 /* TODO: FIXME */
448                 //Instance->Logs->Log("m_mssql",DEBUG,pMessage->message);
449                 //printf("Message: %s\n", pMessage->message);
450                 return 0;
451         }
452
453         static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
454         {
455                 /* TODO: FIXME */
456                 //Instance->Logs->Log("m_mssql",DEBUG,pMessage->message);
457                 //printf("Error: %s\n", pMessage->message);
458                 return 0;
459         }
460
461         void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
462         {
463                 res->AddRow(cols, data, colnames);
464         }
465
466         void AffectedReady(MsSQLResult *res)
467         {
468                 res->UpdateAffectedCount();
469         }
470
471         int OpenDB()
472         {
473                 CloseDB();
474
475                 TDSCONTEXT* cont;
476                 cont = tds_alloc_context(NULL);
477                 cont->msg_handler = HandleMessage;
478                 cont->err_handler = HandleError;
479
480                 login = tds_alloc_login();
481                 tds_set_library(login,"TDS-Library");
482                 tds_set_host(login, "");
483                 tds_set_server(login, host.host.c_str());
484                 tds_set_server_addr(login, host.host.c_str());
485                 tds_set_user(login, host.user.c_str());
486                 tds_set_passwd(login, host.pass.c_str());
487                 tds_set_port(login, host.port);
488                 tds_set_packet(login, 512);
489
490                 sock = tds_alloc_socket(cont, 512);
491                 conn = tds_read_config_info(NULL, login, cont->locale);
492                 return tds_connect(sock, conn);
493         }
494
495         void CloseDB()
496         {
497                 if (login)
498                         tds_free_login(login);
499                 if (sock)
500                         tds_free_socket(sock);
501                 if (conn)
502                         tds_free_connection(conn);
503         }
504
505         SQLhost GetConfHost()
506         {
507                 return host;
508         }
509
510         void SendResults()
511         {
512                 while (results.size())
513                 {
514                         MsSQLResult* res = results[0];
515                         if (res->GetDest())
516                         {
517                                 res->Send();
518                         }
519                         else
520                         {
521                                 /* If the client module is unloaded partway through a query then the provider will set
522                                  * the pointer to NULL. We cannot just cancel the query as the result will still come
523                                  * through at some point...and it could get messy if we play with invalid pointers...
524                                  */
525                                 delete res;
526                         }
527                         results.pop_front();
528                 }
529         }
530
531         void ClearResults()
532         {
533                 while (results.size())
534                 {
535                         MsSQLResult* res = results[0];
536                         delete res;
537                         results.pop_front();
538                 }
539         }
540
541         void SendNotify()
542         {
543                 int QueueFD;
544                 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
545                 {
546                         /* crap, we're out of sockets... */
547                         return;
548                 }
549
550                 insp_sockaddr addr;
551
552 #ifdef IPV6
553                 insp_aton("::1", &addr.sin6_addr);
554                 addr.sin6_family = AF_FAMILY;
555                 addr.sin6_port = htons(resultnotify->GetPort());
556 #else
557                 insp_inaddr ia;
558                 insp_aton("127.0.0.1", &ia);
559                 addr.sin_family = AF_FAMILY;
560                 addr.sin_addr = ia;
561                 addr.sin_port = htons(resultnotify->GetPort());
562 #endif
563
564                 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
565                 {
566                         /* wtf, we cant connect to it, but we just created it! */
567                         return;
568                 }
569         }
570
571 };
572
573
574 class ModuleMsSQL : public Module
575 {
576   private:
577         ConnMap connections;
578         unsigned long currid;
579
580   public:
581         ModuleMsSQL(InspIRCd* Me)
582         : Module::Module(Me), currid(0)
583         {
584                 ServerInstance->Modules->UseInterface("SQLutils");
585
586                 if (!ServerInstance->Modules->PublishFeature("SQL", this))
587                 {
588                         throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
589                 }
590
591                 resultnotify = new ResultNotifier(ServerInstance, this);
592
593                 ReadConf();
594
595                 ServerInstance->Modules->PublishInterface("SQL", this);
596                 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
597                 ServerInstance->Modules->Attach(eventlist, this, 2);
598         }
599
600         virtual ~ModuleMsSQL()
601         {
602                 ClearQueue();
603                 ClearAllConnections();
604                 resultnotify->SetFd(-1);
605                 resultnotify->state = I_ERROR;
606                 resultnotify->OnError(I_ERR_SOCKET);
607                 resultnotify->ClosePending = true;
608                 delete resultnotify;
609                 ServerInstance->Modules->UnpublishInterface("SQL", this);
610                 ServerInstance->Modules->UnpublishFeature("SQL");
611                 ServerInstance->Modules->DoneWithInterface("SQLutils");
612         }
613
614
615         void SendQueue()
616         {
617                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
618                 {
619                         iter->second->SendResults();
620                 }
621         }
622
623         void ClearQueue()
624         {
625                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
626                 {
627                         iter->second->ClearResults();
628                 }
629         }
630
631         bool HasHost(const SQLhost &host)
632         {
633                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
634                 {
635                         if (host == iter->second->GetConfHost())
636                                 return true;
637                 }
638                 return false;
639         }
640
641         bool HostInConf(const SQLhost &h)
642         {
643                 ConfigReader conf(ServerInstance);
644                 for(int i = 0; i < conf.Enumerate("database"); i++)
645                 {
646                         SQLhost host;
647                         host.id         = conf.ReadValue("database", "id", i);
648                         host.host       = conf.ReadValue("database", "hostname", i);
649                         host.port       = conf.ReadInteger("database", "port", "1433", i, true);
650                         host.name       = conf.ReadValue("database", "name", i);
651                         host.user       = conf.ReadValue("database", "username", i);
652                         host.pass       = conf.ReadValue("database", "password", i);
653                         host.ssl        = conf.ReadFlag("database", "ssl", "0", i);
654                         if (h == host)
655                                 return true;
656                 }
657                 return false;
658         }
659     
660         void ReadConf()
661         {
662                 ClearOldConnections();
663
664                 ConfigReader conf(ServerInstance);
665                 for(int i = 0; i < conf.Enumerate("database"); i++)
666                 {
667                         SQLhost host;
668
669                         host.id         = conf.ReadValue("database", "id", i);
670                         host.host       = conf.ReadValue("database", "hostname", i);
671                         host.port       = conf.ReadInteger("database", "port", "1433", i, true);
672                         host.name       = conf.ReadValue("database", "name", i);
673                         host.user       = conf.ReadValue("database", "username", i);
674                         host.pass       = conf.ReadValue("database", "password", i);
675                         host.ssl        = conf.ReadFlag("database", "ssl", "0", i);
676
677                         if (HasHost(host))
678                                 continue;
679
680                         this->AddConn(host);
681                 }
682         }
683
684         void AddConn(const SQLhost& hi)
685         {
686                 if (HasHost(hi))
687                 {
688                         ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
689                         return;
690                 }
691
692                 SQLConn* newconn;
693
694                 newconn = new SQLConn(ServerInstance, this, hi);
695
696                 connections.insert(std::make_pair(hi.id, newconn));
697         }
698
699         void ClearOldConnections()
700         {
701                 ConnMap::iterator iter,safei;
702                 for (iter = connections.begin(); iter != connections.end(); iter++)
703                 {
704                         if (!HostInConf(iter->second->GetConfHost()))
705                         {
706                                 delete iter->second;
707                                 safei = iter;
708                                 --iter;
709                                 connections.erase(safei);
710                         }
711                 }
712         }
713
714         void ClearAllConnections()
715         {
716                 ConnMap::iterator i;
717                 while ((i = connections.begin()) != connections.end())
718                 {
719                         connections.erase(i);
720                         delete i->second;
721                 }
722         }
723
724         virtual void OnRehash(User* user, const std::string &parameter)
725         {
726                 ReadConf();
727         }
728
729         virtual const char* OnRequest(Request* request)
730         {
731                 if(strcmp(SQLREQID, request->GetId()) == 0)
732                 {
733                         SQLrequest* req = (SQLrequest*)request;
734                         ConnMap::iterator iter;
735                         if((iter = connections.find(req->dbid)) != connections.end())
736                         {
737                                 req->id = NewID();
738                                 req->error = iter->second->Query(*req);
739                                 return SQLSUCCESS;
740                         }
741                         else
742                         {
743                                 req->error.Id(BAD_DBID);
744                                 return NULL;
745                         }
746                 }
747                 return NULL;
748         }
749
750         unsigned long NewID()
751         {
752                 if (currid+1 == 0)
753                         currid++;
754
755                 return ++currid;
756         }
757
758         virtual Version GetVersion()
759         {
760                 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
761         }
762
763 };
764
765 void ResultNotifier::Dispatch()
766 {
767         ((ModuleMsSQL*)mod)->SendQueue();
768 }
769
770 MODULE_INIT(ModuleMsSQL)