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 ResultNotifier* notifier = NULL;
38 MsSQLListener* listener = NULL;
46 class QueryThread : public Thread
50 InspIRCd* ServerInstance;
52 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
53 : Thread(), Parent(mod), ServerInstance(si)
60 class ResultNotifier : public BufferedSocket
65 ResultNotifier(ModuleMsSQL* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
69 virtual bool OnDataReady()
72 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
83 class MsSQLListener : public ListenSocketBase
86 irc::sockets::insp_sockaddr sock_us;
91 MsSQLListener(ModuleMsSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
93 uslen = sizeof(sock_us);
94 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
96 throw ModuleException("Could not getsockname() to find out port number for ITC port");
100 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
102 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
105 /* Using getsockname and ntohs, we can determine which port number we were allocated */
109 return ntohs(sock_us.sin6_port);
111 return ntohs(sock_us.sin_port);
117 class MsSQLResult : public SQLresult
124 std::vector<std::string> colnames;
125 std::vector<SQLfieldList> fieldlists;
126 SQLfieldList emptyfieldlist;
128 SQLfieldList* fieldlist;
129 SQLfieldMap* fieldmap;
132 MsSQLResult(Module* self, Module* to, unsigned int rid)
133 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
141 void AddRow(int colsnum, char **dat, char **colname)
145 for (int i = 0; i < colsnum; i++)
147 fieldlists.resize(fieldlists.size()+1);
148 colnames.push_back(colname[i]);
149 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
150 fieldlists[rows].push_back(sf);
155 void UpdateAffectedCount()
170 virtual std::string ColName(int column)
172 if (column < (int)colnames.size())
174 return colnames[column];
178 throw SQLbadColName();
183 virtual int ColNum(const std::string &column)
185 for (unsigned int i = 0; i < colnames.size(); i++)
187 if (column == colnames[i])
190 throw SQLbadColName();
194 virtual SQLfield GetValue(int row, int column)
196 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
198 return fieldlists[row][column];
201 throw SQLbadColName();
203 /* XXX: We never actually get here because of the throw */
204 return SQLfield("",true);
207 virtual SQLfieldList& GetRow()
209 if (currentrow < rows)
210 return fieldlists[currentrow];
212 return emptyfieldlist;
215 virtual SQLfieldMap& GetRowMap()
217 /* In an effort to reduce overhead we don't actually allocate the map
218 * until the first time it's needed...so...
226 fieldmap = new SQLfieldMap;
229 if (currentrow < rows)
231 for (int i = 0; i < Cols(); i++)
233 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
241 virtual SQLfieldList* GetRowPtr()
243 fieldlist = new SQLfieldList();
245 if (currentrow < rows)
247 for (int i = 0; i < Rows(); i++)
249 fieldlist->push_back(fieldlists[currentrow][i]);
256 virtual SQLfieldMap* GetRowMapPtr()
258 fieldmap = new SQLfieldMap();
260 if (currentrow < rows)
262 for (int i = 0; i < Cols(); i++)
264 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
272 virtual void Free(SQLfieldMap* fm)
277 virtual void Free(SQLfieldList* fl)
285 class SQLConn : public classbase
289 InspIRCd* ServerInstance;
299 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
300 : ServerInstance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
304 std::string query("USE " + host.name);
305 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
307 if (tds_process_simple_query(sock) != TDS_SUCCEED)
309 LoggingMutex->Lock();
310 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
311 LoggingMutex->Unlock();
317 LoggingMutex->Lock();
318 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
319 LoggingMutex->Unlock();
325 LoggingMutex->Lock();
326 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
327 LoggingMutex->Unlock();
337 SQLerror Query(SQLrequest &req)
340 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
342 /* Pointer to the buffer we screw around with substitution in */
345 /* Pointer to the current end of query, where we append new stuff */
348 /* Total length of the unescaped parameters */
349 unsigned long paramlen;
351 /* Total length of query, used for binary-safety */
352 unsigned long querylength = 0;
355 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
357 paramlen += i->size();
360 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
361 * sizeofquery + (totalparamlength*2) + 1
363 * The +1 is for null-terminating the string
365 query = new char[req.query.q.length() + (paramlen*2) + 1];
368 for(unsigned long i = 0; i < req.query.q.length(); i++)
370 if(req.query.q[i] == '?')
372 if(req.query.p.size())
374 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
376 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
377 char* escend = escaped;
378 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
391 for (char* n = escaped; *n; n++)
397 req.query.p.pop_front();
404 *queryend = req.query.q[i];
412 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
414 res->query = req.query.q;
416 char* msquery = strdup(req.query.q.data());
417 LoggingMutex->Lock();
418 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
419 LoggingMutex->Unlock();
420 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
422 std::string error("failed to execute: "+std::string(req.query.q.data()));
426 return SQLerror(SQL_QSEND_FAIL, error);
432 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
434 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
435 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
438 case TDS_ROWFMT_RESULT:
441 case TDS_DONE_RESULT:
442 if (sock->rows_affected > -1)
444 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
450 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
452 if (tds_res != TDS_ROW_RESULT)
455 if (!sock->current_results)
458 if (sock->res_info->row_count > 0)
460 int cols = sock->res_info->num_cols;
461 char** name = new char*[MAXBUF];
462 char** data = new char*[MAXBUF];
463 for (int j=0; j<cols; j++)
465 TDSCOLUMN* col = sock->current_results->columns[j];
466 name[j] = col->column_name;
472 ctype = tds_get_conversion_type(col->column_type, col->column_size);
474 src = col->column_data;
476 src = &(sock->current_results->current_row[col->column_offset]);
478 srclen = col->column_cur_size;
479 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
480 data[j] = (char*)dres.ib;
482 ResultReady(res, cols, data, name);
491 ResultsMutex->Lock();
492 results.push_back(res);
493 ResultsMutex->Unlock();
498 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
500 SQLConn* sc = (SQLConn*)pContext->parent;
501 LoggingMutex->Lock();
502 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
503 LoggingMutex->Unlock();
507 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
509 SQLConn* sc = (SQLConn*)pContext->parent;
510 LoggingMutex->Lock();
511 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
512 LoggingMutex->Unlock();
516 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
518 res->AddRow(cols, data, colnames);
521 void AffectedReady(MsSQLResult *res)
523 res->UpdateAffectedCount();
530 TDSCONNECTION* conn = NULL;
532 login = tds_alloc_login();
533 tds_set_app(login, "TSQL");
534 tds_set_library(login,"TDS-Library");
535 tds_set_host(login, "");
536 tds_set_server(login, host.host.c_str());
537 tds_set_server_addr(login, host.host.c_str());
538 tds_set_user(login, host.user.c_str());
539 tds_set_passwd(login, host.pass.c_str());
540 tds_set_port(login, host.port);
541 tds_set_packet(login, 512);
543 context = tds_alloc_context(this);
544 context->msg_handler = HandleMessage;
545 context->err_handler = HandleError;
547 sock = tds_alloc_socket(context, 512);
548 tds_set_parent(sock, NULL);
550 conn = tds_read_config_info(NULL, login, context->locale);
552 if (tds_connect(sock, conn) == TDS_SUCCEED)
554 tds_free_connection(conn);
557 tds_free_connection(conn);
565 tds_free_socket(sock);
570 tds_free_context(context);
575 tds_free_login(login);
580 SQLhost GetConfHost()
587 while (results.size())
589 MsSQLResult* res = results[0];
590 ResultsMutex->Lock();
597 /* If the client module is unloaded partway through a query then the provider will set
598 * the pointer to NULL. We cannot just cancel the query as the result will still come
599 * through at some point...and it could get messy if we play with invalid pointers...
604 ResultsMutex->Unlock();
610 while (results.size())
612 MsSQLResult* res = results[0];
622 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
624 /* crap, we're out of sockets... */
628 irc::sockets::insp_sockaddr addr;
631 irc::sockets::insp_aton("::1", &addr.sin6_addr);
632 addr.sin6_family = AF_FAMILY;
633 addr.sin6_port = htons(listener->GetPort());
635 irc::sockets::insp_inaddr ia;
636 irc::sockets::insp_aton("127.0.0.1", &ia);
637 addr.sin_family = AF_FAMILY;
639 addr.sin_port = htons(listener->GetPort());
642 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
644 /* wtf, we cant connect to it, but we just created it! */
649 send(QueueFD, &id, 1, 0);
652 void DoLeadingQuery()
654 SQLrequest& req = queue.front();
655 req.error = Query(req);
661 class ModuleMsSQL : public Module
664 unsigned long currid;
665 QueryThread* queryDispatcher;
668 ModuleMsSQL(InspIRCd* Me)
669 : Module(Me), currid(0)
671 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
672 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
673 QueueMutex = ServerInstance->Mutexes->CreateMutex();
675 ServerInstance->Modules->UseInterface("SQLutils");
677 if (!ServerInstance->Modules->PublishFeature("SQL", this))
679 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
682 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
684 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
686 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
689 if (listener->GetFd() == -1)
691 ServerInstance->Modules->DoneWithInterface("SQLutils");
692 throw ModuleException("m_mssql: unable to create ITC pipe");
696 LoggingMutex->Lock();
697 ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
698 LoggingMutex->Unlock();
703 queryDispatcher = new QueryThread(ServerInstance, this);
704 ServerInstance->Threads->Create(queryDispatcher);
706 ServerInstance->Modules->PublishInterface("SQL", this);
707 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
708 ServerInstance->Modules->Attach(eventlist, this, 2);
711 virtual ~ModuleMsSQL()
713 delete queryDispatcher;
715 ClearAllConnections();
717 ServerInstance->SE->DelFd(listener);
718 ServerInstance->BufferedSocketCull();
722 shutdown(QueueFD, 2);
728 ServerInstance->SE->DelFd(notifier);
730 ServerInstance->BufferedSocketCull();
733 ServerInstance->Modules->UnpublishInterface("SQL", this);
734 ServerInstance->Modules->UnpublishFeature("SQL");
735 ServerInstance->Modules->DoneWithInterface("SQLutils");
745 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
747 iter->second->SendResults();
753 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
755 iter->second->ClearResults();
759 bool HasHost(const SQLhost &host)
761 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
763 if (host == iter->second->GetConfHost())
769 bool HostInConf(const SQLhost &h)
771 ConfigReader conf(ServerInstance);
772 for(int i = 0; i < conf.Enumerate("database"); i++)
775 host.id = conf.ReadValue("database", "id", i);
776 host.host = conf.ReadValue("database", "hostname", i);
777 host.port = conf.ReadInteger("database", "port", "1433", i, true);
778 host.name = conf.ReadValue("database", "name", i);
779 host.user = conf.ReadValue("database", "username", i);
780 host.pass = conf.ReadValue("database", "password", i);
789 ClearOldConnections();
791 ConfigReader conf(ServerInstance);
792 for(int i = 0; i < conf.Enumerate("database"); i++)
796 host.id = conf.ReadValue("database", "id", i);
797 host.host = conf.ReadValue("database", "hostname", i);
798 host.port = conf.ReadInteger("database", "port", "1433", i, true);
799 host.name = conf.ReadValue("database", "name", i);
800 host.user = conf.ReadValue("database", "username", i);
801 host.pass = conf.ReadValue("database", "password", i);
810 void AddConn(const SQLhost& hi)
814 LoggingMutex->Lock();
815 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
816 LoggingMutex->Unlock();
822 newconn = new SQLConn(ServerInstance, this, hi);
824 connections.insert(std::make_pair(hi.id, newconn));
827 void ClearOldConnections()
829 ConnMap::iterator iter,safei;
830 for (iter = connections.begin(); iter != connections.end(); iter++)
832 if (!HostInConf(iter->second->GetConfHost()))
837 connections.erase(safei);
842 void ClearAllConnections()
845 while ((i = connections.begin()) != connections.end())
847 connections.erase(i);
852 virtual void OnRehash(User* user, const std::string ¶meter)
856 QueueMutex->Unlock();
859 virtual const char* OnRequest(Request* request)
861 if(strcmp(SQLREQID, request->GetId()) == 0)
863 SQLrequest* req = (SQLrequest*)request;
867 ConnMap::iterator iter;
869 const char* returnval = NULL;
871 if((iter = connections.find(req->dbid)) != connections.end())
874 iter->second->queue.push(*req);
875 returnval= SQLSUCCESS;
879 req->error.Id(SQL_BAD_DBID);
882 QueueMutex->Unlock();
889 unsigned long NewID()
897 virtual Version GetVersion()
899 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
904 void ResultNotifier::Dispatch()
909 void QueryThread::Run()
911 while (this->GetExitFlag() == false)
913 SQLConn* conn = NULL;
915 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
917 if (i->second->queue.totalsize())
923 QueueMutex->Unlock();
926 conn->DoLeadingQuery();
929 QueueMutex->Unlock();
935 MODULE_INIT(ModuleMsSQL)