1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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 /* $CompileFlags: exec("grep VERSION_NO /usr/include/tdsver.h 2>/dev/null | perl -e 'print "-D_TDSVER=".((<> =~ /freetds v(\d+\.\d+)/i) ? $1*100 : 0);'") */
25 /* $LinkerFlags: -ltds */
26 /* $ModDep: m_sqlv2.h */
34 typedef std::map<std::string, SQLConn*> ConnMap;
35 typedef std::deque<MsSQLResult*> ResultQueue;
37 unsigned long count(const char * const str, char a)
40 const char *p = reinterpret_cast<const char *>(str);
42 while ((p = strchr(p, a)) != NULL)
50 ResultNotifier* notifier = NULL;
51 MsSQLListener* listener = NULL;
59 class QueryThread : public Thread
63 InspIRCd* ServerInstance;
65 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
66 : Thread(), Parent(mod), ServerInstance(si)
73 class ResultNotifier : public BufferedSocket
78 ResultNotifier(ModuleMsSQL* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
82 virtual bool OnDataReady()
85 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
96 class MsSQLListener : public ListenSocketBase
99 irc::sockets::insp_sockaddr sock_us;
104 MsSQLListener(ModuleMsSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
106 uslen = sizeof(sock_us);
107 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
109 throw ModuleException("Could not getsockname() to find out port number for ITC port");
113 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
115 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
118 /* Using getsockname and ntohs, we can determine which port number we were allocated */
122 return ntohs(sock_us.sin6_port);
124 return ntohs(sock_us.sin_port);
130 class MsSQLResult : public SQLresult
137 std::vector<std::string> colnames;
138 std::vector<SQLfieldList> fieldlists;
139 SQLfieldList emptyfieldlist;
141 SQLfieldList* fieldlist;
142 SQLfieldMap* fieldmap;
145 MsSQLResult(Module* self, Module* to, unsigned int rid)
146 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
154 void AddRow(int colsnum, char **dat, char **colname)
158 for (int i = 0; i < colsnum; i++)
160 fieldlists.resize(fieldlists.size()+1);
161 colnames.push_back(colname[i]);
162 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
163 fieldlists[rows].push_back(sf);
168 void UpdateAffectedCount()
183 virtual std::string ColName(int column)
185 if (column < (int)colnames.size())
187 return colnames[column];
191 throw SQLbadColName();
196 virtual int ColNum(const std::string &column)
198 for (unsigned int i = 0; i < colnames.size(); i++)
200 if (column == colnames[i])
203 throw SQLbadColName();
207 virtual SQLfield GetValue(int row, int column)
209 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
211 return fieldlists[row][column];
214 throw SQLbadColName();
216 /* XXX: We never actually get here because of the throw */
217 return SQLfield("",true);
220 virtual SQLfieldList& GetRow()
222 if (currentrow < rows)
223 return fieldlists[currentrow];
225 return emptyfieldlist;
228 virtual SQLfieldMap& GetRowMap()
230 /* In an effort to reduce overhead we don't actually allocate the map
231 * until the first time it's needed...so...
239 fieldmap = new SQLfieldMap;
242 if (currentrow < rows)
244 for (int i = 0; i < Cols(); i++)
246 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
254 virtual SQLfieldList* GetRowPtr()
256 fieldlist = new SQLfieldList();
258 if (currentrow < rows)
260 for (int i = 0; i < Rows(); i++)
262 fieldlist->push_back(fieldlists[currentrow][i]);
269 virtual SQLfieldMap* GetRowMapPtr()
271 fieldmap = new SQLfieldMap();
273 if (currentrow < rows)
275 for (int i = 0; i < Cols(); i++)
277 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
285 virtual void Free(SQLfieldMap* fm)
290 virtual void Free(SQLfieldList* fl)
298 class SQLConn : public classbase
302 InspIRCd* ServerInstance;
312 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
313 : ServerInstance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
317 std::string query("USE " + host.name);
318 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
320 if (tds_process_simple_query(sock) != TDS_SUCCEED)
322 LoggingMutex->Lock();
323 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
324 LoggingMutex->Unlock();
330 LoggingMutex->Lock();
331 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
332 LoggingMutex->Unlock();
338 LoggingMutex->Lock();
339 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
340 LoggingMutex->Unlock();
350 SQLerror Query(SQLrequest &req)
353 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
355 /* Pointer to the buffer we screw around with substitution in */
358 /* Pointer to the current end of query, where we append new stuff */
361 /* Total length of the unescaped parameters */
362 unsigned long maxparamlen, paramcount;
364 /* Total length of query, used for binary-safety */
365 unsigned long querylength = 0;
367 /* The length of the longest parameter */
370 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
372 if (i->size() > maxparamlen)
373 maxparamlen = i->size();
376 /* How many params are there in the query? */
377 paramcount = count(req.query.q.c_str(), '?');
379 /* This stores copy of params to be inserted with using numbered params 1;3B*/
380 ParamL paramscopy(req.query.p);
382 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
383 * sizeofquery + (maxtotalparamlength*2) + 1
385 * The +1 is for null-terminating the string
388 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
391 for(unsigned long i = 0; i < req.query.q.length(); i++)
393 if(req.query.q[i] == '?')
395 /* We found a place to substitute..what fun.
396 * use mssql calls to escape and write the
397 * escaped string onto the end of our query buffer,
398 * then we "just" need to make sure queryend is
399 * pointing at the right place.
402 /* Is it numbered parameter?
408 /* Numbered parameter number :|
410 unsigned int paramnum;
413 /* Let's check if it's a numbered param. And also calculate it's number.
416 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
420 paramnum = paramnum * 10 + req.query.q[i] - '0';
423 if (paramnum > paramscopy.size() - 1)
425 /* index is out of range!
432 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
434 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
435 char* escend = escaped;
436 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
449 for (char* n = escaped; *n; n++)
456 else if (req.query.p.size())
458 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
460 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
461 char* escend = escaped;
462 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
475 for (char* n = escaped; *n; n++)
481 req.query.p.pop_front();
488 *queryend = req.query.q[i];
496 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
498 res->query = req.query.q;
500 char* msquery = strdup(req.query.q.data());
501 LoggingMutex->Lock();
502 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
503 LoggingMutex->Unlock();
504 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
506 std::string error("failed to execute: "+std::string(req.query.q.data()));
510 return SQLerror(SQL_QSEND_FAIL, error);
516 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
518 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
519 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
522 case TDS_ROWFMT_RESULT:
525 case TDS_DONE_RESULT:
526 if (sock->rows_affected > -1)
528 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
534 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
536 if (tds_res != TDS_ROW_RESULT)
539 if (!sock->current_results)
542 if (sock->res_info->row_count > 0)
544 int cols = sock->res_info->num_cols;
545 char** name = new char*[MAXBUF];
546 char** data = new char*[MAXBUF];
547 for (int j=0; j<cols; j++)
549 TDSCOLUMN* col = sock->current_results->columns[j];
550 name[j] = col->column_name;
556 ctype = tds_get_conversion_type(col->column_type, col->column_size);
558 src = col->column_data;
560 src = &(sock->current_results->current_row[col->column_offset]);
562 srclen = col->column_cur_size;
563 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
564 data[j] = (char*)dres.ib;
566 ResultReady(res, cols, data, name);
575 ResultsMutex->Lock();
576 results.push_back(res);
577 ResultsMutex->Unlock();
582 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
584 SQLConn* sc = (SQLConn*)pContext->parent;
585 LoggingMutex->Lock();
586 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
587 LoggingMutex->Unlock();
591 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
593 SQLConn* sc = (SQLConn*)pContext->parent;
594 LoggingMutex->Lock();
595 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
596 LoggingMutex->Unlock();
600 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
602 res->AddRow(cols, data, colnames);
605 void AffectedReady(MsSQLResult *res)
607 res->UpdateAffectedCount();
614 TDSCONNECTION* conn = NULL;
616 login = tds_alloc_login();
617 tds_set_app(login, "TSQL");
618 tds_set_library(login,"TDS-Library");
619 tds_set_host(login, "");
620 tds_set_server(login, host.host.c_str());
621 tds_set_server_addr(login, host.host.c_str());
622 tds_set_user(login, host.user.c_str());
623 tds_set_passwd(login, host.pass.c_str());
624 tds_set_port(login, host.port);
625 tds_set_packet(login, 512);
627 context = tds_alloc_context(this);
628 context->msg_handler = HandleMessage;
629 context->err_handler = HandleError;
631 sock = tds_alloc_socket(context, 512);
632 tds_set_parent(sock, NULL);
634 conn = tds_read_config_info(NULL, login, context->locale);
636 if (tds_connect(sock, conn) == TDS_SUCCEED)
638 tds_free_connection(conn);
641 tds_free_connection(conn);
649 tds_free_socket(sock);
654 tds_free_context(context);
659 tds_free_login(login);
664 SQLhost GetConfHost()
671 while (results.size())
673 MsSQLResult* res = results[0];
674 ResultsMutex->Lock();
681 /* If the client module is unloaded partway through a query then the provider will set
682 * the pointer to NULL. We cannot just cancel the query as the result will still come
683 * through at some point...and it could get messy if we play with invalid pointers...
688 ResultsMutex->Unlock();
694 while (results.size())
696 MsSQLResult* res = results[0];
706 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
708 /* crap, we're out of sockets... */
712 irc::sockets::insp_sockaddr addr;
715 irc::sockets::insp_aton("::1", &addr.sin6_addr);
716 addr.sin6_family = AF_FAMILY;
717 addr.sin6_port = htons(listener->GetPort());
719 irc::sockets::insp_inaddr ia;
720 irc::sockets::insp_aton("127.0.0.1", &ia);
721 addr.sin_family = AF_FAMILY;
723 addr.sin_port = htons(listener->GetPort());
726 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
728 /* wtf, we cant connect to it, but we just created it! */
733 send(QueueFD, &id, 1, 0);
736 void DoLeadingQuery()
738 SQLrequest& req = queue.front();
739 req.error = Query(req);
745 class ModuleMsSQL : public Module
748 unsigned long currid;
749 QueryThread* queryDispatcher;
752 ModuleMsSQL(InspIRCd* Me)
753 : Module(Me), currid(0)
755 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
756 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
757 QueueMutex = ServerInstance->Mutexes->CreateMutex();
759 ServerInstance->Modules->UseInterface("SQLutils");
761 if (!ServerInstance->Modules->PublishFeature("SQL", this))
763 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
766 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
768 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
770 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
773 if (listener->GetFd() == -1)
775 ServerInstance->Modules->DoneWithInterface("SQLutils");
776 throw ModuleException("m_mssql: unable to create ITC pipe");
780 LoggingMutex->Lock();
781 ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
782 LoggingMutex->Unlock();
787 queryDispatcher = new QueryThread(ServerInstance, this);
788 ServerInstance->Threads->Create(queryDispatcher);
790 ServerInstance->Modules->PublishInterface("SQL", this);
791 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
792 ServerInstance->Modules->Attach(eventlist, this, 2);
795 virtual ~ModuleMsSQL()
797 delete queryDispatcher;
799 ClearAllConnections();
801 ServerInstance->SE->DelFd(listener);
802 ServerInstance->BufferedSocketCull();
806 shutdown(QueueFD, 2);
812 ServerInstance->SE->DelFd(notifier);
814 ServerInstance->BufferedSocketCull();
817 ServerInstance->Modules->UnpublishInterface("SQL", this);
818 ServerInstance->Modules->UnpublishFeature("SQL");
819 ServerInstance->Modules->DoneWithInterface("SQLutils");
829 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
831 iter->second->SendResults();
837 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
839 iter->second->ClearResults();
843 bool HasHost(const SQLhost &host)
845 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
847 if (host == iter->second->GetConfHost())
853 bool HostInConf(const SQLhost &h)
855 ConfigReader conf(ServerInstance);
856 for(int i = 0; i < conf.Enumerate("database"); i++)
859 host.id = conf.ReadValue("database", "id", i);
860 host.host = conf.ReadValue("database", "hostname", i);
861 host.port = conf.ReadInteger("database", "port", "1433", i, true);
862 host.name = conf.ReadValue("database", "name", i);
863 host.user = conf.ReadValue("database", "username", i);
864 host.pass = conf.ReadValue("database", "password", i);
873 ClearOldConnections();
875 ConfigReader conf(ServerInstance);
876 for(int i = 0; i < conf.Enumerate("database"); i++)
880 host.id = conf.ReadValue("database", "id", i);
881 host.host = conf.ReadValue("database", "hostname", i);
882 host.port = conf.ReadInteger("database", "port", "1433", i, true);
883 host.name = conf.ReadValue("database", "name", i);
884 host.user = conf.ReadValue("database", "username", i);
885 host.pass = conf.ReadValue("database", "password", i);
894 void AddConn(const SQLhost& hi)
898 LoggingMutex->Lock();
899 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
900 LoggingMutex->Unlock();
906 newconn = new SQLConn(ServerInstance, this, hi);
908 connections.insert(std::make_pair(hi.id, newconn));
911 void ClearOldConnections()
913 ConnMap::iterator iter,safei;
914 for (iter = connections.begin(); iter != connections.end(); iter++)
916 if (!HostInConf(iter->second->GetConfHost()))
921 connections.erase(safei);
926 void ClearAllConnections()
929 while ((i = connections.begin()) != connections.end())
931 connections.erase(i);
936 virtual void OnRehash(User* user, const std::string ¶meter)
940 QueueMutex->Unlock();
943 virtual const char* OnRequest(Request* request)
945 if(strcmp(SQLREQID, request->GetId()) == 0)
947 SQLrequest* req = (SQLrequest*)request;
951 ConnMap::iterator iter;
953 const char* returnval = NULL;
955 if((iter = connections.find(req->dbid)) != connections.end())
958 iter->second->queue.push(*req);
959 returnval= SQLSUCCESS;
963 req->error.Id(SQL_BAD_DBID);
966 QueueMutex->Unlock();
973 unsigned long NewID()
981 virtual Version GetVersion()
983 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
988 void ResultNotifier::Dispatch()
993 void QueryThread::Run()
995 while (this->GetExitFlag() == false)
997 SQLConn* conn = NULL;
999 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
1001 if (i->second->queue.totalsize())
1007 QueueMutex->Unlock();
1010 conn->DoLeadingQuery();
1013 QueueMutex->Unlock();
1019 MODULE_INIT(ModuleMsSQL)