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 for (const char *p = reinterpret_cast<const char *>(str); *p; ++p)
48 ResultNotifier* notifier = NULL;
49 MsSQLListener* listener = NULL;
57 class QueryThread : public Thread
61 InspIRCd* ServerInstance;
63 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
64 : Thread(), Parent(mod), ServerInstance(si)
71 class ResultNotifier : public BufferedSocket
76 ResultNotifier(ModuleMsSQL* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
80 virtual bool OnDataReady()
83 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
94 class MsSQLListener : public ListenSocketBase
97 irc::sockets::insp_sockaddr sock_us;
102 MsSQLListener(ModuleMsSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
104 uslen = sizeof(sock_us);
105 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
107 throw ModuleException("Could not getsockname() to find out port number for ITC port");
111 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
113 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
116 /* Using getsockname and ntohs, we can determine which port number we were allocated */
120 return ntohs(sock_us.sin6_port);
122 return ntohs(sock_us.sin_port);
128 class MsSQLResult : public SQLresult
135 std::vector<std::string> colnames;
136 std::vector<SQLfieldList> fieldlists;
137 SQLfieldList emptyfieldlist;
139 SQLfieldList* fieldlist;
140 SQLfieldMap* fieldmap;
143 MsSQLResult(Module* self, Module* to, unsigned int rid)
144 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
152 void AddRow(int colsnum, char **dat, char **colname)
156 for (int i = 0; i < colsnum; i++)
158 fieldlists.resize(fieldlists.size()+1);
159 colnames.push_back(colname[i]);
160 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
161 fieldlists[rows].push_back(sf);
166 void UpdateAffectedCount()
181 virtual std::string ColName(int column)
183 if (column < (int)colnames.size())
185 return colnames[column];
189 throw SQLbadColName();
194 virtual int ColNum(const std::string &column)
196 for (unsigned int i = 0; i < colnames.size(); i++)
198 if (column == colnames[i])
201 throw SQLbadColName();
205 virtual SQLfield GetValue(int row, int column)
207 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
209 return fieldlists[row][column];
212 throw SQLbadColName();
214 /* XXX: We never actually get here because of the throw */
215 return SQLfield("",true);
218 virtual SQLfieldList& GetRow()
220 if (currentrow < rows)
221 return fieldlists[currentrow];
223 return emptyfieldlist;
226 virtual SQLfieldMap& GetRowMap()
228 /* In an effort to reduce overhead we don't actually allocate the map
229 * until the first time it's needed...so...
237 fieldmap = new SQLfieldMap;
240 if (currentrow < rows)
242 for (int i = 0; i < Cols(); i++)
244 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
252 virtual SQLfieldList* GetRowPtr()
254 fieldlist = new SQLfieldList();
256 if (currentrow < rows)
258 for (int i = 0; i < Rows(); i++)
260 fieldlist->push_back(fieldlists[currentrow][i]);
267 virtual SQLfieldMap* GetRowMapPtr()
269 fieldmap = new SQLfieldMap();
271 if (currentrow < rows)
273 for (int i = 0; i < Cols(); i++)
275 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
283 virtual void Free(SQLfieldMap* fm)
288 virtual void Free(SQLfieldList* fl)
296 class SQLConn : public classbase
300 InspIRCd* ServerInstance;
310 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
311 : ServerInstance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
315 std::string query("USE " + host.name);
316 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
318 if (tds_process_simple_query(sock) != TDS_SUCCEED)
320 LoggingMutex->Lock();
321 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
322 LoggingMutex->Unlock();
328 LoggingMutex->Lock();
329 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
330 LoggingMutex->Unlock();
336 LoggingMutex->Lock();
337 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
338 LoggingMutex->Unlock();
348 SQLerror Query(SQLrequest &req)
351 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
353 /* Pointer to the buffer we screw around with substitution in */
356 /* Pointer to the current end of query, where we append new stuff */
359 /* Total length of the unescaped parameters */
360 unsigned long maxparamlen, paramcount;
362 /* Total length of query, used for binary-safety */
363 unsigned long querylength = 0;
365 /* The length of the longest parameter */
368 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
370 if (i->size() > maxparamlen)
371 maxparamlen = i->size();
374 /* How many params are there in the query? */
375 paramcount = count(req.query.q.c_str(), '?');
377 /* This stores copy of params to be inserted with using numbered params 1;3B*/
378 ParamL paramscopy(req.query.p);
380 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
381 * sizeofquery + (maxtotalparamlength*2) + 1
383 * The +1 is for null-terminating the string
386 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
389 for(unsigned long i = 0; i < req.query.q.length(); i++)
391 if(req.query.q[i] == '?')
393 /* We found a place to substitute..what fun.
394 * use mssql calls to escape and write the
395 * escaped string onto the end of our query buffer,
396 * then we "just" need to make sure queryend is
397 * pointing at the right place.
400 /* Is it numbered parameter?
406 /* Numbered parameter number :|
408 unsigned int paramnum;
411 /* Let's check if it's a numbered param. And also calculate it's number.
414 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
418 paramnum = paramnum * 10 + req.query.q[i] - '0';
421 if (paramnum > paramscopy.size() - 1)
423 /* index is out of range!
430 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
432 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
433 char* escend = escaped;
434 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
447 for (char* n = escaped; *n; n++)
454 else if (req.query.p.size())
456 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
458 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
459 char* escend = escaped;
460 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
473 for (char* n = escaped; *n; n++)
479 req.query.p.pop_front();
486 *queryend = req.query.q[i];
494 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
496 res->query = req.query.q;
498 char* msquery = strdup(req.query.q.data());
499 LoggingMutex->Lock();
500 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
501 LoggingMutex->Unlock();
502 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
504 std::string error("failed to execute: "+std::string(req.query.q.data()));
508 return SQLerror(SQL_QSEND_FAIL, error);
514 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
516 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
517 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
520 case TDS_ROWFMT_RESULT:
523 case TDS_DONE_RESULT:
524 if (sock->rows_affected > -1)
526 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
532 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
534 if (tds_res != TDS_ROW_RESULT)
537 if (!sock->current_results)
540 if (sock->res_info->row_count > 0)
542 int cols = sock->res_info->num_cols;
543 char** name = new char*[MAXBUF];
544 char** data = new char*[MAXBUF];
545 for (int j=0; j<cols; j++)
547 TDSCOLUMN* col = sock->current_results->columns[j];
548 name[j] = col->column_name;
554 ctype = tds_get_conversion_type(col->column_type, col->column_size);
556 src = col->column_data;
558 src = &(sock->current_results->current_row[col->column_offset]);
560 srclen = col->column_cur_size;
561 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
562 data[j] = (char*)dres.ib;
564 ResultReady(res, cols, data, name);
573 ResultsMutex->Lock();
574 results.push_back(res);
575 ResultsMutex->Unlock();
580 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
582 SQLConn* sc = (SQLConn*)pContext->parent;
583 LoggingMutex->Lock();
584 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
585 LoggingMutex->Unlock();
589 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
591 SQLConn* sc = (SQLConn*)pContext->parent;
592 LoggingMutex->Lock();
593 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
594 LoggingMutex->Unlock();
598 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
600 res->AddRow(cols, data, colnames);
603 void AffectedReady(MsSQLResult *res)
605 res->UpdateAffectedCount();
612 TDSCONNECTION* conn = NULL;
614 login = tds_alloc_login();
615 tds_set_app(login, "TSQL");
616 tds_set_library(login,"TDS-Library");
617 tds_set_host(login, "");
618 tds_set_server(login, host.host.c_str());
619 tds_set_server_addr(login, host.host.c_str());
620 tds_set_user(login, host.user.c_str());
621 tds_set_passwd(login, host.pass.c_str());
622 tds_set_port(login, host.port);
623 tds_set_packet(login, 512);
625 context = tds_alloc_context(this);
626 context->msg_handler = HandleMessage;
627 context->err_handler = HandleError;
629 sock = tds_alloc_socket(context, 512);
630 tds_set_parent(sock, NULL);
632 conn = tds_read_config_info(NULL, login, context->locale);
634 if (tds_connect(sock, conn) == TDS_SUCCEED)
636 tds_free_connection(conn);
639 tds_free_connection(conn);
647 tds_free_socket(sock);
652 tds_free_context(context);
657 tds_free_login(login);
662 SQLhost GetConfHost()
669 while (results.size())
671 MsSQLResult* res = results[0];
672 ResultsMutex->Lock();
679 /* If the client module is unloaded partway through a query then the provider will set
680 * the pointer to NULL. We cannot just cancel the query as the result will still come
681 * through at some point...and it could get messy if we play with invalid pointers...
686 ResultsMutex->Unlock();
692 while (results.size())
694 MsSQLResult* res = results[0];
704 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
706 /* crap, we're out of sockets... */
710 irc::sockets::insp_sockaddr addr;
713 irc::sockets::insp_aton("::1", &addr.sin6_addr);
714 addr.sin6_family = AF_FAMILY;
715 addr.sin6_port = htons(listener->GetPort());
717 irc::sockets::insp_inaddr ia;
718 irc::sockets::insp_aton("127.0.0.1", &ia);
719 addr.sin_family = AF_FAMILY;
721 addr.sin_port = htons(listener->GetPort());
724 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
726 /* wtf, we cant connect to it, but we just created it! */
731 send(QueueFD, &id, 1, 0);
734 void DoLeadingQuery()
736 SQLrequest& req = queue.front();
737 req.error = Query(req);
743 class ModuleMsSQL : public Module
746 unsigned long currid;
747 QueryThread* queryDispatcher;
750 ModuleMsSQL(InspIRCd* Me)
751 : Module(Me), currid(0)
753 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
754 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
755 QueueMutex = ServerInstance->Mutexes->CreateMutex();
757 ServerInstance->Modules->UseInterface("SQLutils");
759 if (!ServerInstance->Modules->PublishFeature("SQL", this))
761 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
764 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
766 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
768 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
771 if (listener->GetFd() == -1)
773 ServerInstance->Modules->DoneWithInterface("SQLutils");
774 throw ModuleException("m_mssql: unable to create ITC pipe");
778 LoggingMutex->Lock();
779 ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
780 LoggingMutex->Unlock();
785 queryDispatcher = new QueryThread(ServerInstance, this);
786 ServerInstance->Threads->Create(queryDispatcher);
788 ServerInstance->Modules->PublishInterface("SQL", this);
789 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
790 ServerInstance->Modules->Attach(eventlist, this, 2);
793 virtual ~ModuleMsSQL()
795 delete queryDispatcher;
797 ClearAllConnections();
799 ServerInstance->SE->DelFd(listener);
800 ServerInstance->BufferedSocketCull();
804 shutdown(QueueFD, 2);
810 ServerInstance->SE->DelFd(notifier);
812 ServerInstance->BufferedSocketCull();
815 ServerInstance->Modules->UnpublishInterface("SQL", this);
816 ServerInstance->Modules->UnpublishFeature("SQL");
817 ServerInstance->Modules->DoneWithInterface("SQLutils");
827 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
829 iter->second->SendResults();
835 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
837 iter->second->ClearResults();
841 bool HasHost(const SQLhost &host)
843 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
845 if (host == iter->second->GetConfHost())
851 bool HostInConf(const SQLhost &h)
853 ConfigReader conf(ServerInstance);
854 for(int i = 0; i < conf.Enumerate("database"); i++)
857 host.id = conf.ReadValue("database", "id", i);
858 host.host = conf.ReadValue("database", "hostname", i);
859 host.port = conf.ReadInteger("database", "port", "1433", i, true);
860 host.name = conf.ReadValue("database", "name", i);
861 host.user = conf.ReadValue("database", "username", i);
862 host.pass = conf.ReadValue("database", "password", i);
871 ClearOldConnections();
873 ConfigReader conf(ServerInstance);
874 for(int i = 0; i < conf.Enumerate("database"); i++)
878 host.id = conf.ReadValue("database", "id", i);
879 host.host = conf.ReadValue("database", "hostname", i);
880 host.port = conf.ReadInteger("database", "port", "1433", i, true);
881 host.name = conf.ReadValue("database", "name", i);
882 host.user = conf.ReadValue("database", "username", i);
883 host.pass = conf.ReadValue("database", "password", i);
892 void AddConn(const SQLhost& hi)
896 LoggingMutex->Lock();
897 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
898 LoggingMutex->Unlock();
904 newconn = new SQLConn(ServerInstance, this, hi);
906 connections.insert(std::make_pair(hi.id, newconn));
909 void ClearOldConnections()
911 ConnMap::iterator iter,safei;
912 for (iter = connections.begin(); iter != connections.end(); iter++)
914 if (!HostInConf(iter->second->GetConfHost()))
919 connections.erase(safei);
924 void ClearAllConnections()
927 while ((i = connections.begin()) != connections.end())
929 connections.erase(i);
934 virtual void OnRehash(User* user, const std::string ¶meter)
938 QueueMutex->Unlock();
941 virtual const char* OnRequest(Request* request)
943 if(strcmp(SQLREQID, request->GetId()) == 0)
945 SQLrequest* req = (SQLrequest*)request;
949 ConnMap::iterator iter;
951 const char* returnval = NULL;
953 if((iter = connections.find(req->dbid)) != connections.end())
956 iter->second->queue.push(*req);
957 returnval= SQLSUCCESS;
961 req->error.Id(SQL_BAD_DBID);
964 QueueMutex->Unlock();
971 unsigned long NewID()
979 virtual Version GetVersion()
981 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
986 void ResultNotifier::Dispatch()
991 void QueryThread::Run()
993 while (this->GetExitFlag() == false)
995 SQLConn* conn = NULL;
997 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
999 if (i->second->queue.totalsize())
1005 QueueMutex->Unlock();
1008 conn->DoLeadingQuery();
1011 QueueMutex->Unlock();
1017 MODULE_INIT(ModuleMsSQL)