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 = NULL;
37 MsSQLListener* listener = NULL;
45 class QueryThread : public Thread
51 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
52 : Thread(), Parent(mod), Instance(si)
59 class ResultNotifier : public BufferedSocket
64 ResultNotifier(ModuleMsSQL* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
68 virtual bool OnDataReady()
71 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
82 class MsSQLListener : public ListenSocketBase
85 irc::sockets::insp_sockaddr sock_us;
90 MsSQLListener(ModuleMsSQL* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
92 uslen = sizeof(sock_us);
93 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
95 throw ModuleException("Could not getsockname() to find out port number for ITC port");
99 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
101 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
104 /* Using getsockname and ntohs, we can determine which port number we were allocated */
108 return ntohs(sock_us.sin6_port);
110 return ntohs(sock_us.sin_port);
116 class MsSQLResult : public SQLresult
123 std::vector<std::string> colnames;
124 std::vector<SQLfieldList> fieldlists;
125 SQLfieldList emptyfieldlist;
127 SQLfieldList* fieldlist;
128 SQLfieldMap* fieldmap;
131 MsSQLResult(Module* self, Module* to, unsigned int rid)
132 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
140 void AddRow(int colsnum, char **dat, char **colname)
144 for (int i = 0; i < colsnum; i++)
146 fieldlists.resize(fieldlists.size()+1);
147 colnames.push_back(colname[i]);
148 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
149 fieldlists[rows].push_back(sf);
154 void UpdateAffectedCount()
169 virtual std::string ColName(int column)
171 if (column < (int)colnames.size())
173 return colnames[column];
177 throw SQLbadColName();
182 virtual int ColNum(const std::string &column)
184 for (unsigned int i = 0; i < colnames.size(); i++)
186 if (column == colnames[i])
189 throw SQLbadColName();
193 virtual SQLfield GetValue(int row, int column)
195 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
197 return fieldlists[row][column];
200 throw SQLbadColName();
202 /* XXX: We never actually get here because of the throw */
203 return SQLfield("",true);
206 virtual SQLfieldList& GetRow()
208 if (currentrow < rows)
209 return fieldlists[currentrow];
211 return emptyfieldlist;
214 virtual SQLfieldMap& GetRowMap()
216 /* In an effort to reduce overhead we don't actually allocate the map
217 * until the first time it's needed...so...
225 fieldmap = new SQLfieldMap;
228 if (currentrow < rows)
230 for (int i = 0; i < Cols(); i++)
232 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
240 virtual SQLfieldList* GetRowPtr()
242 fieldlist = new SQLfieldList();
244 if (currentrow < rows)
246 for (int i = 0; i < Rows(); i++)
248 fieldlist->push_back(fieldlists[currentrow][i]);
255 virtual SQLfieldMap* GetRowMapPtr()
257 fieldmap = new SQLfieldMap();
259 if (currentrow < rows)
261 for (int i = 0; i < Cols(); i++)
263 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
271 virtual void Free(SQLfieldMap* fm)
276 virtual void Free(SQLfieldList* fl)
284 class SQLConn : public classbase
298 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
299 : Instance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
303 std::string query("USE " + host.name);
304 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
306 if (tds_process_simple_query(sock) != TDS_SUCCEED)
308 LoggingMutex->Lock();
309 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
310 LoggingMutex->Unlock();
316 LoggingMutex->Lock();
317 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
318 LoggingMutex->Unlock();
324 LoggingMutex->Lock();
325 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
326 LoggingMutex->Unlock();
336 SQLerror Query(SQLrequest &req)
339 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
341 /* Pointer to the buffer we screw around with substitution in */
344 /* Pointer to the current end of query, where we append new stuff */
347 /* Total length of the unescaped parameters */
348 unsigned long paramlen;
350 /* Total length of query, used for binary-safety */
351 unsigned long querylength = 0;
354 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
356 paramlen += i->size();
359 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
360 * sizeofquery + (totalparamlength*2) + 1
362 * The +1 is for null-terminating the string
364 query = new char[req.query.q.length() + (paramlen*2) + 1];
367 for(unsigned long i = 0; i < req.query.q.length(); i++)
369 if(req.query.q[i] == '?')
371 if(req.query.p.size())
373 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
375 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
376 char* escend = escaped;
377 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
390 for (char* n = escaped; *n; n++)
396 req.query.p.pop_front();
403 *queryend = req.query.q[i];
411 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
413 res->query = req.query.q;
415 char* msquery = strdup(req.query.q.data());
416 LoggingMutex->Lock();
417 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
418 LoggingMutex->Unlock();
419 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
421 std::string error("failed to execute: "+std::string(req.query.q.data()));
425 return SQLerror(SQL_QSEND_FAIL, error);
431 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
433 //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
434 //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
437 case TDS_ROWFMT_RESULT:
440 case TDS_DONE_RESULT:
441 if (sock->rows_affected > -1)
443 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
449 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
451 if (tds_res != TDS_ROW_RESULT)
454 if (!sock->current_results)
457 if (sock->res_info->row_count > 0)
459 int cols = sock->res_info->num_cols;
460 char** name = new char*[MAXBUF];
461 char** data = new char*[MAXBUF];
462 for (int j=0; j<cols; j++)
464 TDSCOLUMN* col = sock->current_results->columns[j];
465 name[j] = col->column_name;
471 ctype = tds_get_conversion_type(col->column_type, col->column_size);
472 src = &(sock->current_results->current_row[col->column_offset]);
473 srclen = col->column_cur_size;
474 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
475 data[j] = (char*)dres.ib;
477 ResultReady(res, cols, data, name);
486 ResultsMutex->Lock();
487 results.push_back(res);
488 ResultsMutex->Unlock();
493 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
495 SQLConn* sc = (SQLConn*)pContext->parent;
496 LoggingMutex->Lock();
497 sc->Instance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
498 LoggingMutex->Unlock();
502 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
504 SQLConn* sc = (SQLConn*)pContext->parent;
505 LoggingMutex->Lock();
506 sc->Instance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
507 LoggingMutex->Unlock();
511 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
513 res->AddRow(cols, data, colnames);
516 void AffectedReady(MsSQLResult *res)
518 res->UpdateAffectedCount();
525 TDSCONNECTION* conn = NULL;
527 login = tds_alloc_login();
528 tds_set_app(login, "TSQL");
529 tds_set_library(login,"TDS-Library");
530 tds_set_host(login, "");
531 tds_set_server(login, host.host.c_str());
532 tds_set_server_addr(login, host.host.c_str());
533 tds_set_user(login, host.user.c_str());
534 tds_set_passwd(login, host.pass.c_str());
535 tds_set_port(login, host.port);
536 tds_set_packet(login, 512);
538 context = tds_alloc_context(this);
539 context->msg_handler = HandleMessage;
540 context->err_handler = HandleError;
542 sock = tds_alloc_socket(context, 512);
543 tds_set_parent(sock, NULL);
545 conn = tds_read_config_info(NULL, login, context->locale);
547 if (tds_connect(sock, conn) == TDS_SUCCEED)
549 tds_free_connection(conn);
552 tds_free_connection(conn);
560 tds_free_socket(sock);
565 tds_free_context(context);
570 tds_free_login(login);
575 SQLhost GetConfHost()
582 while (results.size())
584 MsSQLResult* res = results[0];
585 ResultsMutex->Lock();
592 /* If the client module is unloaded partway through a query then the provider will set
593 * the pointer to NULL. We cannot just cancel the query as the result will still come
594 * through at some point...and it could get messy if we play with invalid pointers...
599 ResultsMutex->Unlock();
605 while (results.size())
607 MsSQLResult* res = results[0];
617 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
619 /* crap, we're out of sockets... */
623 irc::sockets::insp_sockaddr addr;
626 irc::sockets::insp_aton("::1", &addr.sin6_addr);
627 addr.sin6_family = AF_FAMILY;
628 addr.sin6_port = htons(listener->GetPort());
630 irc::sockets::insp_inaddr ia;
631 irc::sockets::insp_aton("127.0.0.1", &ia);
632 addr.sin_family = AF_FAMILY;
634 addr.sin_port = htons(listener->GetPort());
637 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
639 /* wtf, we cant connect to it, but we just created it! */
644 send(QueueFD, &id, 1, 0);
647 void DoLeadingQuery()
649 SQLrequest& req = queue.front();
650 req.error = Query(req);
656 class ModuleMsSQL : public Module
659 unsigned long currid;
660 QueryThread* queryDispatcher;
663 ModuleMsSQL(InspIRCd* Me)
664 : Module(Me), currid(0)
666 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
667 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
668 QueueMutex = ServerInstance->Mutexes->CreateMutex();
670 ServerInstance->Modules->UseInterface("SQLutils");
672 if (!ServerInstance->Modules->PublishFeature("SQL", this))
674 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
677 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
679 listener = new MsSQLListener(this, ServerInstance, 0, "::1");
681 listener = new MsSQLListener(this, ServerInstance, 0, "127.0.0.1");
684 if (listener->GetFd() == -1)
686 ServerInstance->Modules->DoneWithInterface("SQLutils");
687 throw ModuleException("m_mssql: unable to create ITC pipe");
691 LoggingMutex->Lock();
692 ServerInstance->Logs->Log("m_mssql", DEBUG, "MsSQL: Interthread comms port is %d", listener->GetPort());
693 LoggingMutex->Unlock();
698 queryDispatcher = new QueryThread(ServerInstance, this);
699 ServerInstance->Threads->Create(queryDispatcher);
701 ServerInstance->Modules->PublishInterface("SQL", this);
702 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
703 ServerInstance->Modules->Attach(eventlist, this, 2);
706 virtual ~ModuleMsSQL()
708 delete queryDispatcher;
710 ClearAllConnections();
712 ServerInstance->SE->DelFd(listener);
713 ServerInstance->BufferedSocketCull();
717 shutdown(QueueFD, 2);
723 ServerInstance->SE->DelFd(notifier);
725 ServerInstance->BufferedSocketCull();
728 ServerInstance->Modules->UnpublishInterface("SQL", this);
729 ServerInstance->Modules->UnpublishFeature("SQL");
730 ServerInstance->Modules->DoneWithInterface("SQLutils");
740 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
742 iter->second->SendResults();
748 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
750 iter->second->ClearResults();
754 bool HasHost(const SQLhost &host)
756 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
758 if (host == iter->second->GetConfHost())
764 bool HostInConf(const SQLhost &h)
766 ConfigReader conf(ServerInstance);
767 for(int i = 0; i < conf.Enumerate("database"); i++)
770 host.id = conf.ReadValue("database", "id", i);
771 host.host = conf.ReadValue("database", "hostname", i);
772 host.port = conf.ReadInteger("database", "port", "1433", i, true);
773 host.name = conf.ReadValue("database", "name", i);
774 host.user = conf.ReadValue("database", "username", i);
775 host.pass = conf.ReadValue("database", "password", i);
784 ClearOldConnections();
786 ConfigReader conf(ServerInstance);
787 for(int i = 0; i < conf.Enumerate("database"); i++)
791 host.id = conf.ReadValue("database", "id", i);
792 host.host = conf.ReadValue("database", "hostname", i);
793 host.port = conf.ReadInteger("database", "port", "1433", i, true);
794 host.name = conf.ReadValue("database", "name", i);
795 host.user = conf.ReadValue("database", "username", i);
796 host.pass = conf.ReadValue("database", "password", i);
805 void AddConn(const SQLhost& hi)
809 LoggingMutex->Lock();
810 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
811 LoggingMutex->Unlock();
817 newconn = new SQLConn(ServerInstance, this, hi);
819 connections.insert(std::make_pair(hi.id, newconn));
822 void ClearOldConnections()
824 ConnMap::iterator iter,safei;
825 for (iter = connections.begin(); iter != connections.end(); iter++)
827 if (!HostInConf(iter->second->GetConfHost()))
832 connections.erase(safei);
837 void ClearAllConnections()
840 while ((i = connections.begin()) != connections.end())
842 connections.erase(i);
847 virtual void OnRehash(User* user, const std::string ¶meter)
851 QueueMutex->Unlock();
854 virtual const char* OnRequest(Request* request)
856 if(strcmp(SQLREQID, request->GetId()) == 0)
858 SQLrequest* req = (SQLrequest*)request;
862 ConnMap::iterator iter;
864 const char* returnval = NULL;
866 if((iter = connections.find(req->dbid)) != connections.end())
869 iter->second->queue.push(*req);
870 returnval= SQLSUCCESS;
874 req->error.Id(SQL_BAD_DBID);
877 QueueMutex->Unlock();
884 unsigned long NewID()
892 virtual Version GetVersion()
894 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
899 void ResultNotifier::Dispatch()
904 void QueryThread::Run()
906 while (this->GetExitFlag() == false)
908 SQLConn* conn = NULL;
910 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
912 if (i->second->queue.totalsize())
918 QueueMutex->Unlock();
921 conn->DoLeadingQuery();
924 QueueMutex->Unlock();
930 MODULE_INIT(ModuleMsSQL)