1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include <tdsconvert.h>
23 /* $ModDesc: MsSQL provider */
24 /* $LinkerFlags: -ltds */
25 /* $ModDep: m_sqlv2.h */
33 typedef std::map<std::string, SQLConn*> ConnMap;
34 typedef std::deque<MsSQLResult*> ResultQueue;
36 ResultNotifier* notifier;
37 MsSQLListener* listener;
46 class QueryThread : public Thread
52 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
53 : Thread(), Parent(mod), Instance(si)
61 class ResultNotifier : public BufferedSocket
66 ResultNotifier(ModuleMsSQL* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
70 virtual bool OnDataReady()
73 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
84 class MsSQLListener : public ListenSocketBase
87 insp_sockaddr sock_us;
92 MsSQLListener(ModuleMsSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
94 uslen = sizeof(sock_us);
95 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
97 throw ModuleException("Could not getsockname() to find out port number for ITC port");
101 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
103 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
106 /* Using getsockname and ntohs, we can determine which port number we were allocated */
110 return ntohs(sock_us.sin6_port);
112 return ntohs(sock_us.sin_port);
118 class MsSQLResult : public SQLresult
125 std::vector<std::string> colnames;
126 std::vector<SQLfieldList> fieldlists;
127 SQLfieldList emptyfieldlist;
129 SQLfieldList* fieldlist;
130 SQLfieldMap* fieldmap;
133 MsSQLResult(Module* self, Module* to, unsigned int rid)
134 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
142 void AddRow(int colsnum, char **dat, char **colname)
146 for (int i = 0; i < colsnum; i++)
148 fieldlists.resize(fieldlists.size()+1);
149 colnames.push_back(colname[i]);
150 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
151 fieldlists[rows].push_back(sf);
156 void UpdateAffectedCount()
171 virtual std::string ColName(int column)
173 if (column < (int)colnames.size())
175 return colnames[column];
179 throw SQLbadColName();
184 virtual int ColNum(const std::string &column)
186 for (unsigned int i = 0; i < colnames.size(); i++)
188 if (column == colnames[i])
191 throw SQLbadColName();
195 virtual SQLfield GetValue(int row, int column)
197 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
199 return fieldlists[row][column];
202 throw SQLbadColName();
204 /* XXX: We never actually get here because of the throw */
205 return SQLfield("",true);
208 virtual SQLfieldList& GetRow()
210 if (currentrow < rows)
211 return fieldlists[currentrow];
213 return emptyfieldlist;
216 virtual SQLfieldMap& GetRowMap()
218 /* In an effort to reduce overhead we don't actually allocate the map
219 * until the first time it's needed...so...
227 fieldmap = new SQLfieldMap;
230 if (currentrow < rows)
232 for (int i = 0; i < Cols(); i++)
234 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
242 virtual SQLfieldList* GetRowPtr()
244 fieldlist = new SQLfieldList();
246 if (currentrow < rows)
248 for (int i = 0; i < Rows(); i++)
250 fieldlist->push_back(fieldlists[currentrow][i]);
257 virtual SQLfieldMap* GetRowMapPtr()
259 fieldmap = new SQLfieldMap();
261 if (currentrow < rows)
263 for (int i = 0; i < Cols(); i++)
265 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
273 virtual void Free(SQLfieldMap* fm)
278 virtual void Free(SQLfieldList* fl)
286 class SQLConn : public classbase
300 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
301 : Instance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
305 std::string query("USE " + host.name);
306 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
308 if (tds_process_simple_query(sock) != TDS_SUCCEED)
310 LoggingMutex->Lock();
311 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
312 LoggingMutex->Unlock();
318 LoggingMutex->Lock();
319 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
320 LoggingMutex->Unlock();
326 LoggingMutex->Lock();
327 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
328 LoggingMutex->Unlock();
338 SQLerror Query(SQLrequest &req)
341 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
343 /* Pointer to the buffer we screw around with substitution in */
346 /* Pointer to the current end of query, where we append new stuff */
349 /* Total length of the unescaped parameters */
350 unsigned long paramlen;
352 /* Total length of query, used for binary-safety in mysql_real_query */
353 unsigned long querylength = 0;
356 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
358 paramlen += i->size();
361 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
362 * sizeofquery + (totalparamlength*2) + 1
364 * The +1 is for null-terminating the string
366 query = new char[req.query.q.length() + (paramlen*2) + 1];
369 for(unsigned long i = 0; i < req.query.q.length(); i++)
371 if(req.query.q[i] == '?')
373 if(req.query.p.size())
375 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
377 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
378 char* escend = escaped;
379 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
392 for (char* n = escaped; *n; n++)
398 req.query.p.pop_front();
405 *queryend = req.query.q[i];
413 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
415 res->query = req.query.q;
417 char* msquery = strdup(req.query.q.data());
418 LoggingMutex->Lock();
419 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
420 LoggingMutex->Unlock();
421 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
423 std::string error("failed to execute: "+std::string(req.query.q.data()));
427 return SQLerror(SQL_QSEND_FAIL, error);
433 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
435 //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
436 //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
439 case TDS_ROWFMT_RESULT:
442 case TDS_DONE_RESULT:
443 if (sock->rows_affected > -1)
445 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
451 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
453 if (tds_res != TDS_ROW_RESULT)
456 if (!sock->current_results)
459 if (sock->res_info->row_count > 0)
461 int cols = sock->res_info->num_cols;
462 char** name = new char*[MAXBUF];
463 char** data = new char*[MAXBUF];
464 for (int j=0; j<cols; j++)
466 TDSCOLUMN* col = sock->current_results->columns[j];
467 name[j] = col->column_name;
473 ctype = tds_get_conversion_type(col->column_type, col->column_size);
474 src = &(sock->current_results->current_row[col->column_offset]);
475 srclen = col->column_cur_size;
476 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
477 data[j] = (char*)dres.ib;
479 ResultReady(res, cols, data, name);
488 ResultsMutex->Lock();
489 results.push_back(res);
490 ResultsMutex->Unlock();
495 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
497 SQLConn* sc = (SQLConn*)pContext->parent;
498 LoggingMutex->Lock();
499 sc->Instance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
500 LoggingMutex->Unlock();
504 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
506 SQLConn* sc = (SQLConn*)pContext->parent;
507 LoggingMutex->Lock();
508 sc->Instance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
509 LoggingMutex->Unlock();
513 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
515 res->AddRow(cols, data, colnames);
518 void AffectedReady(MsSQLResult *res)
520 res->UpdateAffectedCount();
527 TDSCONNECTION* conn = NULL;
529 login = tds_alloc_login();
530 tds_set_app(login, "TSQL");
531 tds_set_library(login,"TDS-Library");
532 tds_set_host(login, "");
533 tds_set_server(login, host.host.c_str());
534 tds_set_server_addr(login, host.host.c_str());
535 tds_set_user(login, host.user.c_str());
536 tds_set_passwd(login, host.pass.c_str());
537 tds_set_port(login, host.port);
538 tds_set_packet(login, 512);
540 context = tds_alloc_context(this);
541 context->msg_handler = HandleMessage;
542 context->err_handler = HandleError;
544 sock = tds_alloc_socket(context, 512);
545 tds_set_parent(sock, NULL);
547 conn = tds_read_config_info(NULL, login, context->locale);
549 if (tds_connect(sock, conn) == TDS_SUCCEED)
551 tds_free_connection(conn);
554 tds_free_connection(conn);
562 tds_free_socket(sock);
567 tds_free_context(context);
572 tds_free_login(login);
577 SQLhost GetConfHost()
584 while (results.size())
586 MsSQLResult* res = results[0];
587 ResultsMutex->Lock();
594 /* If the client module is unloaded partway through a query then the provider will set
595 * the pointer to NULL. We cannot just cancel the query as the result will still come
596 * through at some point...and it could get messy if we play with invalid pointers...
601 ResultsMutex->Unlock();
607 while (results.size())
609 MsSQLResult* res = results[0];
619 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
621 /* crap, we're out of sockets... */
628 insp_aton("::1", &addr.sin6_addr);
629 addr.sin6_family = AF_FAMILY;
630 addr.sin6_port = htons(listener->GetPort());
633 insp_aton("127.0.0.1", &ia);
634 addr.sin_family = AF_FAMILY;
636 addr.sin_port = htons(listener->GetPort());
639 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
641 /* wtf, we cant connect to it, but we just created it! */
646 send(QueueFD, &id, 1, 0);
649 void DoLeadingQuery()
651 SQLrequest& req = queue.front();
652 req.error = Query(req);
658 class ModuleMsSQL : public Module
661 unsigned long currid;
662 QueryThread* queryDispatcher;
665 ModuleMsSQL(InspIRCd* Me)
666 : Module(Me), currid(0)
668 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
669 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
670 QueueMutex = ServerInstance->Mutexes->CreateMutex();
672 ServerInstance->Modules->UseInterface("SQLutils");
674 if (!ServerInstance->Modules->PublishFeature("SQL", this))
676 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
679 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
681 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
683 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
686 if (listener->GetFd() == -1)
688 ServerInstance->Modules->DoneWithInterface("SQLutils");
689 throw ModuleException("m_mysql: unable to create ITC pipe");
693 LoggingMutex->Lock();
694 ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
695 LoggingMutex->Unlock();
700 queryDispatcher = new QueryThread(ServerInstance, this);
701 ServerInstance->Threads->Create(queryDispatcher);
703 ServerInstance->Modules->PublishInterface("SQL", this);
704 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
705 ServerInstance->Modules->Attach(eventlist, this, 2);
708 virtual ~ModuleMsSQL()
710 delete queryDispatcher;
712 ClearAllConnections();
714 ServerInstance->SE->DelFd(listener);
716 ServerInstance->BufferedSocketCull();
720 shutdown(QueueFD, 2);
726 ServerInstance->SE->DelFd(notifier);
728 ServerInstance->BufferedSocketCull();
731 ServerInstance->Modules->UnpublishInterface("SQL", this);
732 ServerInstance->Modules->UnpublishFeature("SQL");
733 ServerInstance->Modules->DoneWithInterface("SQLutils");
743 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
745 iter->second->SendResults();
751 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
753 iter->second->ClearResults();
757 bool HasHost(const SQLhost &host)
759 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
761 if (host == iter->second->GetConfHost())
767 bool HostInConf(const SQLhost &h)
769 ConfigReader conf(ServerInstance);
770 for(int i = 0; i < conf.Enumerate("database"); i++)
773 host.id = conf.ReadValue("database", "id", i);
774 host.host = conf.ReadValue("database", "hostname", i);
775 host.port = conf.ReadInteger("database", "port", "1433", i, true);
776 host.name = conf.ReadValue("database", "name", i);
777 host.user = conf.ReadValue("database", "username", i);
778 host.pass = conf.ReadValue("database", "password", i);
787 ClearOldConnections();
789 ConfigReader conf(ServerInstance);
790 for(int i = 0; i < conf.Enumerate("database"); i++)
794 host.id = conf.ReadValue("database", "id", i);
795 host.host = conf.ReadValue("database", "hostname", i);
796 host.port = conf.ReadInteger("database", "port", "1433", i, true);
797 host.name = conf.ReadValue("database", "name", i);
798 host.user = conf.ReadValue("database", "username", i);
799 host.pass = conf.ReadValue("database", "password", i);
808 void AddConn(const SQLhost& hi)
812 LoggingMutex->Lock();
813 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
814 LoggingMutex->Unlock();
820 newconn = new SQLConn(ServerInstance, this, hi);
822 connections.insert(std::make_pair(hi.id, newconn));
825 void ClearOldConnections()
827 ConnMap::iterator iter,safei;
828 for (iter = connections.begin(); iter != connections.end(); iter++)
830 if (!HostInConf(iter->second->GetConfHost()))
835 connections.erase(safei);
840 void ClearAllConnections()
843 while ((i = connections.begin()) != connections.end())
845 connections.erase(i);
850 virtual void OnRehash(User* user, const std::string ¶meter)
854 QueueMutex->Unlock();
857 virtual const char* OnRequest(Request* request)
859 if(strcmp(SQLREQID, request->GetId()) == 0)
861 SQLrequest* req = (SQLrequest*)request;
865 ConnMap::iterator iter;
867 const char* returnval = NULL;
869 if((iter = connections.find(req->dbid)) != connections.end())
872 iter->second->queue.push(*req);
873 returnval= SQLSUCCESS;
877 req->error.Id(SQL_BAD_DBID);
880 QueueMutex->Unlock();
887 unsigned long NewID()
895 virtual Version GetVersion()
897 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
902 void ResultNotifier::Dispatch()
907 void QueryThread::Run()
909 while (this->GetExitFlag() == false)
911 SQLConn* conn = NULL;
913 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
915 if (i->second->queue.totalsize())
921 QueueMutex->Unlock();
924 conn->DoLeadingQuery();
927 QueueMutex->Unlock();
933 MODULE_INIT(ModuleMsSQL)