1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/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 /* The length of the longest parameter */
365 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
367 if (i->size() > maxparamlen)
368 maxparamlen = i->size();
371 /* How many params are there in the query? */
372 paramcount = count(req.query.q.c_str(), '?');
374 /* This stores copy of params to be inserted with using numbered params 1;3B*/
375 ParamL paramscopy(req.query.p);
377 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
378 * sizeofquery + (maxtotalparamlength*2) + 1
380 * The +1 is for null-terminating the string
383 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
386 for(unsigned long i = 0; i < req.query.q.length(); i++)
388 if(req.query.q[i] == '?')
390 /* We found a place to substitute..what fun.
391 * use mssql calls to escape and write the
392 * escaped string onto the end of our query buffer,
393 * then we "just" need to make sure queryend is
394 * pointing at the right place.
397 /* Is it numbered parameter?
403 /* Numbered parameter number :|
405 unsigned int paramnum;
408 /* Let's check if it's a numbered param. And also calculate it's number.
411 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
415 paramnum = paramnum * 10 + req.query.q[i] - '0';
418 if (paramnum > paramscopy.size() - 1)
420 /* index is out of range!
427 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
429 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
430 char* escend = escaped;
431 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
444 for (char* n = escaped; *n; n++)
451 else if (req.query.p.size())
453 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
455 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
456 char* escend = escaped;
457 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
470 for (char* n = escaped; *n; n++)
476 req.query.p.pop_front();
483 *queryend = req.query.q[i];
490 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
492 res->query = req.query.q;
494 char* msquery = strdup(req.query.q.data());
495 LoggingMutex->Lock();
496 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
497 LoggingMutex->Unlock();
498 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
500 std::string error("failed to execute: "+std::string(req.query.q.data()));
504 return SQLerror(SQL_QSEND_FAIL, error);
510 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
512 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
513 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
516 case TDS_ROWFMT_RESULT:
519 case TDS_DONE_RESULT:
520 if (sock->rows_affected > -1)
522 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
528 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
530 if (tds_res != TDS_ROW_RESULT)
533 if (!sock->current_results)
536 if (sock->res_info->row_count > 0)
538 int cols = sock->res_info->num_cols;
539 char** name = new char*[MAXBUF];
540 char** data = new char*[MAXBUF];
541 for (int j=0; j<cols; j++)
543 TDSCOLUMN* col = sock->current_results->columns[j];
544 name[j] = col->column_name;
550 ctype = tds_get_conversion_type(col->column_type, col->column_size);
552 src = col->column_data;
554 src = &(sock->current_results->current_row[col->column_offset]);
556 srclen = col->column_cur_size;
557 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
558 data[j] = (char*)dres.ib;
560 ResultReady(res, cols, data, name);
569 ResultsMutex->Lock();
570 results.push_back(res);
571 ResultsMutex->Unlock();
576 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
578 SQLConn* sc = (SQLConn*)pContext->parent;
579 LoggingMutex->Lock();
580 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
581 LoggingMutex->Unlock();
585 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
587 SQLConn* sc = (SQLConn*)pContext->parent;
588 LoggingMutex->Lock();
589 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
590 LoggingMutex->Unlock();
594 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
596 res->AddRow(cols, data, colnames);
599 void AffectedReady(MsSQLResult *res)
601 res->UpdateAffectedCount();
608 TDSCONNECTION* conn = NULL;
610 login = tds_alloc_login();
611 tds_set_app(login, "TSQL");
612 tds_set_library(login,"TDS-Library");
613 tds_set_host(login, "");
614 tds_set_server(login, host.host.c_str());
615 tds_set_server_addr(login, host.host.c_str());
616 tds_set_user(login, host.user.c_str());
617 tds_set_passwd(login, host.pass.c_str());
618 tds_set_port(login, host.port);
619 tds_set_packet(login, 512);
621 context = tds_alloc_context(this);
622 context->msg_handler = HandleMessage;
623 context->err_handler = HandleError;
625 sock = tds_alloc_socket(context, 512);
626 tds_set_parent(sock, NULL);
628 conn = tds_read_config_info(NULL, login, context->locale);
630 if (tds_connect(sock, conn) == TDS_SUCCEED)
632 tds_free_connection(conn);
635 tds_free_connection(conn);
643 tds_free_socket(sock);
648 tds_free_context(context);
653 tds_free_login(login);
658 SQLhost GetConfHost()
665 while (results.size())
667 MsSQLResult* res = results[0];
668 ResultsMutex->Lock();
675 /* If the client module is unloaded partway through a query then the provider will set
676 * the pointer to NULL. We cannot just cancel the query as the result will still come
677 * through at some point...and it could get messy if we play with invalid pointers...
682 ResultsMutex->Unlock();
688 while (results.size())
690 MsSQLResult* res = results[0];
700 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
702 /* crap, we're out of sockets... */
706 irc::sockets::insp_sockaddr addr;
709 irc::sockets::insp_aton("::1", &addr.sin6_addr);
710 addr.sin6_family = AF_FAMILY;
711 addr.sin6_port = htons(listener->GetPort());
713 irc::sockets::insp_inaddr ia;
714 irc::sockets::insp_aton("127.0.0.1", &ia);
715 addr.sin_family = AF_FAMILY;
717 addr.sin_port = htons(listener->GetPort());
720 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
722 /* wtf, we cant connect to it, but we just created it! */
727 send(QueueFD, &id, 1, 0);
730 void DoLeadingQuery()
732 SQLrequest& req = queue.front();
733 req.error = Query(req);
739 class ModuleMsSQL : public Module
742 unsigned long currid;
743 QueryThread* queryDispatcher;
746 ModuleMsSQL(InspIRCd* Me)
747 : Module(Me), currid(0)
749 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
750 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
751 QueueMutex = ServerInstance->Mutexes->CreateMutex();
753 ServerInstance->Modules->UseInterface("SQLutils");
755 if (!ServerInstance->Modules->PublishFeature("SQL", this))
757 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
760 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
762 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
764 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
767 if (listener->GetFd() == -1)
769 ServerInstance->Modules->DoneWithInterface("SQLutils");
770 throw ModuleException("m_mssql: unable to create ITC pipe");
774 LoggingMutex->Lock();
775 ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
776 LoggingMutex->Unlock();
781 queryDispatcher = new QueryThread(ServerInstance, this);
782 ServerInstance->Threads->Start(queryDispatcher);
784 ServerInstance->Modules->PublishInterface("SQL", this);
785 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
786 ServerInstance->Modules->Attach(eventlist, this, 2);
789 virtual ~ModuleMsSQL()
791 delete queryDispatcher;
793 ClearAllConnections();
795 ServerInstance->SE->DelFd(listener);
796 ServerInstance->BufferedSocketCull();
800 shutdown(QueueFD, 2);
806 ServerInstance->SE->DelFd(notifier);
808 ServerInstance->BufferedSocketCull();
811 ServerInstance->Modules->UnpublishInterface("SQL", this);
812 ServerInstance->Modules->UnpublishFeature("SQL");
813 ServerInstance->Modules->DoneWithInterface("SQLutils");
823 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
825 iter->second->SendResults();
831 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
833 iter->second->ClearResults();
837 bool HasHost(const SQLhost &host)
839 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
841 if (host == iter->second->GetConfHost())
847 bool HostInConf(const SQLhost &h)
849 ConfigReader conf(ServerInstance);
850 for(int i = 0; i < conf.Enumerate("database"); i++)
853 host.id = conf.ReadValue("database", "id", i);
854 host.host = conf.ReadValue("database", "hostname", i);
855 host.port = conf.ReadInteger("database", "port", "1433", i, true);
856 host.name = conf.ReadValue("database", "name", i);
857 host.user = conf.ReadValue("database", "username", i);
858 host.pass = conf.ReadValue("database", "password", i);
867 ClearOldConnections();
869 ConfigReader conf(ServerInstance);
870 for(int i = 0; i < conf.Enumerate("database"); i++)
874 host.id = conf.ReadValue("database", "id", i);
875 host.host = conf.ReadValue("database", "hostname", i);
876 host.port = conf.ReadInteger("database", "port", "1433", i, true);
877 host.name = conf.ReadValue("database", "name", i);
878 host.user = conf.ReadValue("database", "username", i);
879 host.pass = conf.ReadValue("database", "password", i);
888 void AddConn(const SQLhost& hi)
892 LoggingMutex->Lock();
893 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
894 LoggingMutex->Unlock();
900 newconn = new SQLConn(ServerInstance, this, hi);
902 connections.insert(std::make_pair(hi.id, newconn));
905 void ClearOldConnections()
907 ConnMap::iterator iter,safei;
908 for (iter = connections.begin(); iter != connections.end(); iter++)
910 if (!HostInConf(iter->second->GetConfHost()))
915 connections.erase(safei);
920 void ClearAllConnections()
923 while ((i = connections.begin()) != connections.end())
925 connections.erase(i);
930 virtual void OnRehash(User* user, const std::string ¶meter)
934 QueueMutex->Unlock();
937 virtual const char* OnRequest(Request* request)
939 if(strcmp(SQLREQID, request->GetId()) == 0)
941 SQLrequest* req = (SQLrequest*)request;
945 ConnMap::iterator iter;
947 const char* returnval = NULL;
949 if((iter = connections.find(req->dbid)) != connections.end())
952 iter->second->queue.push(*req);
953 returnval= SQLSUCCESS;
957 req->error.Id(SQL_BAD_DBID);
960 QueueMutex->Unlock();
967 unsigned long NewID()
975 virtual Version GetVersion()
977 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
982 void ResultNotifier::Dispatch()
987 void QueryThread::Run()
989 while (this->GetExitFlag() == false)
991 SQLConn* conn = NULL;
993 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
995 if (i->second->queue.totalsize())
1001 QueueMutex->Unlock();
1004 conn->DoLeadingQuery();
1007 QueueMutex->Unlock();
1013 MODULE_INIT(ModuleMsSQL)