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 */
32 typedef std::map<std::string, SQLConn*> ConnMap;
33 typedef std::deque<MsSQLResult*> ResultQueue;
35 unsigned long count(const char * const str, char a)
38 for (const char *p = str; *p; ++p)
50 class QueryThread : public SocketThread
55 QueryThread(ModuleMsSQL* mod)
56 : SocketThread(si), Parent(mod), {
60 virtual void OnNotify();
63 class MsSQLResult : public SQLresult
70 std::vector<std::string> colnames;
71 std::vector<SQLfieldList> fieldlists;
72 SQLfieldList emptyfieldlist;
74 SQLfieldList* fieldlist;
75 SQLfieldMap* fieldmap;
78 MsSQLResult(Module* self, Module* to, unsigned int rid)
79 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
87 void AddRow(int colsnum, char **dat, char **colname)
91 for (int i = 0; i < colsnum; i++)
93 fieldlists.resize(fieldlists.size()+1);
94 colnames.push_back(colname[i]);
95 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
96 fieldlists[rows].push_back(sf);
101 void UpdateAffectedCount()
116 virtual std::string ColName(int column)
118 if (column < (int)colnames.size())
120 return colnames[column];
124 throw SQLbadColName();
129 virtual int ColNum(const std::string &column)
131 for (unsigned int i = 0; i < colnames.size(); i++)
133 if (column == colnames[i])
136 throw SQLbadColName();
140 virtual SQLfield GetValue(int row, int column)
142 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
144 return fieldlists[row][column];
147 throw SQLbadColName();
149 /* XXX: We never actually get here because of the throw */
150 return SQLfield("",true);
153 virtual SQLfieldList& GetRow()
155 if (currentrow < rows)
156 return fieldlists[currentrow];
158 return emptyfieldlist;
161 virtual SQLfieldMap& GetRowMap()
163 /* In an effort to reduce overhead we don't actually allocate the map
164 * until the first time it's needed...so...
172 fieldmap = new SQLfieldMap;
175 if (currentrow < rows)
177 for (int i = 0; i < Cols(); i++)
179 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
187 virtual SQLfieldList* GetRowPtr()
189 fieldlist = new SQLfieldList();
191 if (currentrow < rows)
193 for (int i = 0; i < Rows(); i++)
195 fieldlist->push_back(fieldlists[currentrow][i]);
202 virtual SQLfieldMap* GetRowMapPtr()
204 fieldmap = new SQLfieldMap();
206 if (currentrow < rows)
208 for (int i = 0; i < Cols(); i++)
210 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
218 virtual void Free(SQLfieldMap* fm)
223 virtual void Free(SQLfieldList* fl)
229 class SQLConn : public classbase
242 SQLConn(Module* m, const SQLhost& hi)
243 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
247 std::string query("USE " + host.name);
248 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
250 if (tds_process_simple_query(sock) != TDS_SUCCEED)
252 LoggingMutex->Lock();
253 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
254 LoggingMutex->Unlock();
260 LoggingMutex->Lock();
261 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
262 LoggingMutex->Unlock();
268 LoggingMutex->Lock();
269 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
270 LoggingMutex->Unlock();
280 SQLerror Query(SQLrequest &req)
283 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
285 /* Pointer to the buffer we screw around with substitution in */
288 /* Pointer to the current end of query, where we append new stuff */
291 /* Total length of the unescaped parameters */
292 unsigned long maxparamlen, paramcount;
294 /* The length of the longest parameter */
297 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
299 if (i->size() > maxparamlen)
300 maxparamlen = i->size();
303 /* How many params are there in the query? */
304 paramcount = count(req.query.q.c_str(), '?');
306 /* This stores copy of params to be inserted with using numbered params 1;3B*/
307 ParamL paramscopy(req.query.p);
309 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
310 * sizeofquery + (maxtotalparamlength*2) + 1
312 * The +1 is for null-terminating the string
315 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
318 for(unsigned long i = 0; i < req.query.q.length(); i++)
320 if(req.query.q[i] == '?')
322 /* We found a place to substitute..what fun.
323 * use mssql calls to escape and write the
324 * escaped string onto the end of our query buffer,
325 * then we "just" need to make sure queryend is
326 * pointing at the right place.
329 /* Is it numbered parameter?
335 /* Numbered parameter number :|
337 unsigned int paramnum;
340 /* Let's check if it's a numbered param. And also calculate it's number.
343 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
347 paramnum = paramnum * 10 + req.query.q[i] - '0';
350 if (paramnum > paramscopy.size() - 1)
352 /* index is out of range!
359 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
361 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
362 char* escend = escaped;
363 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
376 for (char* n = escaped; *n; n++)
383 else if (req.query.p.size())
385 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
387 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
388 char* escend = escaped;
389 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
402 for (char* n = escaped; *n; n++)
408 req.query.p.pop_front();
415 *queryend = req.query.q[i];
422 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
424 res->query = req.query.q;
426 char* msquery = strdup(req.query.q.data());
427 LoggingMutex->Lock();
428 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
429 LoggingMutex->Unlock();
430 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
432 std::string error("failed to execute: "+std::string(req.query.q.data()));
436 return SQLerror(SQL_QSEND_FAIL, error);
442 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
444 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
445 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
448 case TDS_ROWFMT_RESULT:
451 case TDS_DONE_RESULT:
452 if (sock->rows_affected > -1)
454 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
460 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
462 if (tds_res != TDS_ROW_RESULT)
465 if (!sock->current_results)
468 if (sock->res_info->row_count > 0)
470 int cols = sock->res_info->num_cols;
471 char** name = new char*[MAXBUF];
472 char** data = new char*[MAXBUF];
473 for (int j=0; j<cols; j++)
475 TDSCOLUMN* col = sock->current_results->columns[j];
476 name[j] = col->column_name;
482 ctype = tds_get_conversion_type(col->column_type, col->column_size);
484 src = col->column_data;
486 src = &(sock->current_results->current_row[col->column_offset]);
488 srclen = col->column_cur_size;
489 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
490 data[j] = (char*)dres.ib;
492 ResultReady(res, cols, data, name);
501 ResultsMutex->Lock();
502 results.push_back(res);
503 ResultsMutex->Unlock();
507 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
509 SQLConn* sc = (SQLConn*)pContext->parent;
510 LoggingMutex->Lock();
511 sc->ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
512 LoggingMutex->Unlock();
516 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
518 SQLConn* sc = (SQLConn*)pContext->parent;
519 LoggingMutex->Lock();
520 sc->ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
521 LoggingMutex->Unlock();
525 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
527 res->AddRow(cols, data, colnames);
530 void AffectedReady(MsSQLResult *res)
532 res->UpdateAffectedCount();
539 TDSCONNECTION* conn = NULL;
541 login = tds_alloc_login();
542 tds_set_app(login, "TSQL");
543 tds_set_library(login,"TDS-Library");
544 tds_set_host(login, "");
545 tds_set_server(login, host.host.c_str());
546 tds_set_server_addr(login, host.host.c_str());
547 tds_set_user(login, host.user.c_str());
548 tds_set_passwd(login, host.pass.c_str());
549 tds_set_port(login, host.port);
550 tds_set_packet(login, 512);
552 context = tds_alloc_context(this);
553 context->msg_handler = HandleMessage;
554 context->err_handler = HandleError;
556 sock = tds_alloc_socket(context, 512);
557 tds_set_parent(sock, NULL);
559 conn = tds_read_config_info(NULL, login, context->locale);
561 if (tds_connect(sock, conn) == TDS_SUCCEED)
563 tds_free_connection(conn);
566 tds_free_connection(conn);
574 tds_free_socket(sock);
579 tds_free_context(context);
584 tds_free_login(login);
589 SQLhost GetConfHost()
596 while (results.size())
598 MsSQLResult* res = results[0];
599 ResultsMutex->Lock();
606 /* If the client module is unloaded partway through a query then the provider will set
607 * the pointer to NULL. We cannot just cancel the query as the result will still come
608 * through at some point...and it could get messy if we play with invalid pointers...
613 ResultsMutex->Unlock();
619 while (results.size())
621 MsSQLResult* res = results[0];
627 void DoLeadingQuery()
629 SQLrequest& req = queue.front();
630 req.error = Query(req);
636 class ModuleMsSQL : public Module
639 unsigned long currid;
640 QueryThread* queryDispatcher;
646 LoggingMutex = new Mutex();
647 ResultsMutex = new Mutex();
649 ServerInstance->Modules->UseInterface("SQLutils");
651 if (!ServerInstance->Modules->PublishFeature("SQL", this))
653 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
658 queryDispatcher = new QueryThread(this);
659 ServerInstance->Threads->Start(queryDispatcher);
661 ServerInstance->Modules->PublishInterface("SQL", this);
662 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
663 ServerInstance->Modules->Attach(eventlist, this, 2);
666 virtual ~ModuleMsSQL()
668 queryDispatcher->join();
669 delete queryDispatcher;
671 ClearAllConnections();
673 ServerInstance->Modules->UnpublishInterface("SQL", this);
674 ServerInstance->Modules->UnpublishFeature("SQL");
675 ServerInstance->Modules->DoneWithInterface("SQLutils");
683 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
685 iter->second->SendResults();
691 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
693 iter->second->ClearResults();
697 bool HasHost(const SQLhost &host)
699 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
701 if (host == iter->second->GetConfHost())
707 bool HostInConf(const SQLhost &h)
710 for(int i = 0; i < conf.Enumerate("database"); i++)
713 host.id = conf.ReadValue("database", "id", i);
714 host.host = conf.ReadValue("database", "hostname", i);
715 host.port = conf.ReadInteger("database", "port", "1433", i, true);
716 host.name = conf.ReadValue("database", "name", i);
717 host.user = conf.ReadValue("database", "username", i);
718 host.pass = conf.ReadValue("database", "password", i);
727 ClearOldConnections();
730 for(int i = 0; i < conf.Enumerate("database"); i++)
734 host.id = conf.ReadValue("database", "id", i);
735 host.host = conf.ReadValue("database", "hostname", i);
736 host.port = conf.ReadInteger("database", "port", "1433", i, true);
737 host.name = conf.ReadValue("database", "name", i);
738 host.user = conf.ReadValue("database", "username", i);
739 host.pass = conf.ReadValue("database", "password", i);
748 void AddConn(const SQLhost& hi)
752 LoggingMutex->Lock();
753 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
754 LoggingMutex->Unlock();
760 newconn = new SQLConn(this, hi);
762 connections.insert(std::make_pair(hi.id, newconn));
765 void ClearOldConnections()
767 ConnMap::iterator iter,safei;
768 for (iter = connections.begin(); iter != connections.end(); iter++)
770 if (!HostInConf(iter->second->GetConfHost()))
775 connections.erase(safei);
780 void ClearAllConnections()
783 while ((i = connections.begin()) != connections.end())
785 connections.erase(i);
790 virtual void OnRehash(User* user)
792 queryDispatcher->LockQueue();
794 queryDispatcher->UnlockQueueWakeup();
797 virtual const char* OnRequest(Request* request)
799 if(strcmp(SQLREQID, request->GetId()) == 0)
801 SQLrequest* req = (SQLrequest*)request;
803 queryDispatcher->LockQueue();
805 ConnMap::iterator iter;
807 const char* returnval = NULL;
809 if((iter = connections.find(req->dbid)) != connections.end())
812 iter->second->queue.push(*req);
813 returnval= SQLSUCCESS;
817 req->error.Id(SQL_BAD_DBID);
820 queryDispatcher->UnlockQueueWakeup();
827 unsigned long NewID()
835 virtual Version GetVersion()
837 return Version("MsSQL provider", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
842 void QueryThread::OnNotify()
847 void QueryThread::Run()
850 while (this->GetExitFlag() == false)
852 SQLConn* conn = NULL;
853 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
855 if (i->second->queue.totalsize())
864 conn->DoLeadingQuery();
865 this->NotifyParent();
871 this->WaitForQueue();
877 MODULE_INIT(ModuleMsSQL)