2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2008-2009 Dennis Friis <peavey@inspircd.org>
5 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
6 * Copyright (C) 2008-2009 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
8 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include <tdsconvert.h>
33 /* $ModDesc: MsSQL provider */
34 /* $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);'") */
35 /* $LinkerFlags: -ltds */
36 /* $ModDep: m_sqlv2.h */
42 typedef std::map<std::string, SQLConn*> ConnMap;
43 typedef std::deque<MsSQLResult*> ResultQueue;
45 unsigned long count(const char * const str, char a)
48 for (const char *p = str; *p; ++p)
60 class QueryThread : public SocketThread
63 ModuleMsSQL* const Parent;
65 QueryThread(ModuleMsSQL* mod) : Parent(mod) { }
71 class MsSQLResult : public SQLresult
78 std::vector<std::string> colnames;
79 std::vector<SQLfieldList> fieldlists;
80 SQLfieldList emptyfieldlist;
82 SQLfieldList* fieldlist;
83 SQLfieldMap* fieldmap;
86 MsSQLResult(Module* self, Module* to, unsigned int rid)
87 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
91 void AddRow(int colsnum, char **dat, char **colname)
95 for (int i = 0; i < colsnum; i++)
97 fieldlists.resize(fieldlists.size()+1);
98 colnames.push_back(colname[i]);
99 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
100 fieldlists[rows].push_back(sf);
105 void UpdateAffectedCount()
120 std::string ColName(int column)
122 if (column < (int)colnames.size())
124 return colnames[column];
128 throw SQLbadColName();
133 int ColNum(const std::string &column)
135 for (unsigned int i = 0; i < colnames.size(); i++)
137 if (column == colnames[i])
140 throw SQLbadColName();
144 SQLfield GetValue(int row, int column)
146 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
148 return fieldlists[row][column];
151 throw SQLbadColName();
153 /* XXX: We never actually get here because of the throw */
154 return SQLfield("",true);
157 SQLfieldList& GetRow()
159 if (currentrow < rows)
160 return fieldlists[currentrow];
162 return emptyfieldlist;
165 SQLfieldMap& GetRowMap()
167 /* In an effort to reduce overhead we don't actually allocate the map
168 * until the first time it's needed...so...
176 fieldmap = new SQLfieldMap;
179 if (currentrow < rows)
181 for (int i = 0; i < Cols(); i++)
183 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
191 SQLfieldList* GetRowPtr()
193 fieldlist = new SQLfieldList();
195 if (currentrow < rows)
197 for (int i = 0; i < Rows(); i++)
199 fieldlist->push_back(fieldlists[currentrow][i]);
206 SQLfieldMap* GetRowMapPtr()
208 fieldmap = new SQLfieldMap();
210 if (currentrow < rows)
212 for (int i = 0; i < Cols(); i++)
214 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
222 void Free(SQLfieldMap* fm)
227 void Free(SQLfieldList* fl)
233 class SQLConn : public classbase
246 SQLConn(Module* m, const SQLhost& hi)
247 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
251 std::string query("USE " + host.name);
252 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
254 if (tds_process_simple_query(sock) != TDS_SUCCEED)
256 LoggingMutex->Lock();
257 ServerInstance->Logs->Log("m_mssql",LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
258 LoggingMutex->Unlock();
264 LoggingMutex->Lock();
265 ServerInstance->Logs->Log("m_mssql",LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
266 LoggingMutex->Unlock();
272 LoggingMutex->Lock();
273 ServerInstance->Logs->Log("m_mssql",LOG_DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
274 LoggingMutex->Unlock();
284 SQLerror Query(SQLrequest* req)
287 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
289 /* Pointer to the buffer we screw around with substitution in */
292 /* Pointer to the current end of query, where we append new stuff */
295 /* Total length of the unescaped parameters */
296 unsigned long maxparamlen, paramcount;
298 /* The length of the longest parameter */
301 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
303 if (i->size() > maxparamlen)
304 maxparamlen = i->size();
307 /* How many params are there in the query? */
308 paramcount = count(req->query.q.c_str(), '?');
310 /* This stores copy of params to be inserted with using numbered params 1;3B*/
311 ParamL paramscopy(req->query.p);
313 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
314 * sizeofquery + (maxtotalparamlength*2) + 1
316 * The +1 is for null-terminating the string
319 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
322 for(unsigned long i = 0; i < req->query.q.length(); i++)
324 if(req->query.q[i] == '?')
326 /* We found a place to substitute..what fun.
327 * use mssql calls to escape and write the
328 * escaped string onto the end of our query buffer,
329 * then we "just" need to make sure queryend is
330 * pointing at the right place.
333 /* Is it numbered parameter?
339 /* Numbered parameter number :|
341 unsigned int paramnum;
344 /* Let's check if it's a numbered param. And also calculate it's number.
347 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
351 paramnum = paramnum * 10 + req->query.q[i] - '0';
354 if (paramnum > paramscopy.size() - 1)
356 /* index is out of range!
363 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
365 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
366 char* escend = escaped;
367 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
380 for (char* n = escaped; *n; n++)
387 else if (req->query.p.size())
389 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
391 char* escaped = new char[(req->query.p.front().length() * 2) + 1];
392 char* escend = escaped;
393 for (std::string::iterator p = req->query.p.front().begin(); p < req->query.p.front().end(); p++)
406 for (char* n = escaped; *n; n++)
412 req->query.p.pop_front();
419 *queryend = req->query.q[i];
424 req->query.q = query;
426 MsSQLResult* res = new MsSQLResult((Module*)mod, req->source, req->id);
428 res->query = req->query.q;
430 char* msquery = strdup(req->query.q.data());
431 LoggingMutex->Lock();
432 ServerInstance->Logs->Log("m_mssql",LOG_DEBUG,"doing Query: %s",msquery);
433 LoggingMutex->Unlock();
434 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
436 std::string error("failed to execute: "+std::string(req->query.q.data()));
440 return SQLerror(SQL_QSEND_FAIL, error);
446 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
448 //ServerInstance->Logs->Log("m_mssql",LOG_DEBUG,"<******> result type: %d", tds_res);
449 //ServerInstance->Logs->Log("m_mssql",LOG_DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
452 case TDS_ROWFMT_RESULT:
455 case TDS_DONE_RESULT:
456 if (sock->rows_affected > -1)
458 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
464 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
466 if (tds_res != TDS_ROW_RESULT)
469 if (!sock->current_results)
472 if (sock->res_info->row_count > 0)
474 int cols = sock->res_info->num_cols;
475 char** name = new char*[MAXBUF];
476 char** data = new char*[MAXBUF];
477 for (int j=0; j<cols; j++)
479 TDSCOLUMN* col = sock->current_results->columns[j];
480 name[j] = col->column_name;
486 ctype = tds_get_conversion_type(col->column_type, col->column_size);
488 src = col->column_data;
490 src = &(sock->current_results->current_row[col->column_offset]);
492 srclen = col->column_cur_size;
493 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
494 data[j] = (char*)dres.ib;
496 ResultReady(res, cols, data, name);
505 ResultsMutex->Lock();
506 results.push_back(res);
507 ResultsMutex->Unlock();
511 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
513 SQLConn* sc = (SQLConn*)pContext->parent;
514 LoggingMutex->Lock();
515 ServerInstance->Logs->Log("m_mssql", LOG_DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
516 LoggingMutex->Unlock();
520 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
522 SQLConn* sc = (SQLConn*)pContext->parent;
523 LoggingMutex->Lock();
524 ServerInstance->Logs->Log("m_mssql", LOG_DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
525 LoggingMutex->Unlock();
529 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
531 res->AddRow(cols, data, colnames);
534 void AffectedReady(MsSQLResult *res)
536 res->UpdateAffectedCount();
543 TDSCONNECTION* conn = NULL;
545 login = tds_alloc_login();
546 tds_set_app(login, "TSQL");
547 tds_set_library(login,"TDS-Library");
548 tds_set_host(login, "");
549 tds_set_server(login, host.host.c_str());
550 tds_set_server_addr(login, host.host.c_str());
551 tds_set_user(login, host.user.c_str());
552 tds_set_passwd(login, host.pass.c_str());
553 tds_set_port(login, host.port);
554 tds_set_packet(login, 512);
556 context = tds_alloc_context(this);
557 context->msg_handler = HandleMessage;
558 context->err_handler = HandleError;
560 sock = tds_alloc_socket(context, 512);
561 tds_set_parent(sock, NULL);
563 conn = tds_read_config_info(NULL, login, context->locale);
565 if (tds_connect(sock, conn) == TDS_SUCCEED)
567 tds_free_connection(conn);
570 tds_free_connection(conn);
578 tds_free_socket(sock);
583 tds_free_context(context);
588 tds_free_login(login);
593 SQLhost GetConfHost()
600 while (results.size())
602 MsSQLResult* res = results[0];
603 ResultsMutex->Lock();
610 /* If the client module is unloaded partway through a query then the provider will set
611 * the pointer to NULL. We cannot just cancel the query as the result will still come
612 * through at some point...and it could get messy if we play with invalid pointers...
617 ResultsMutex->Unlock();
623 while (results.size())
625 MsSQLResult* res = results[0];
631 void DoLeadingQuery()
633 SQLrequest* req = queue.front();
634 req->error = Query(req);
640 class ModuleMsSQL : public Module
643 unsigned long currid;
644 QueryThread* queryDispatcher;
645 ServiceProvider sqlserv;
649 : currid(0), sqlserv(this, "SQL/mssql", SERVICE_DATA)
651 LoggingMutex = new Mutex();
652 ResultsMutex = new Mutex();
653 queryDispatcher = new QueryThread(this);
656 void init() CXX11_OVERRIDE
660 ServerInstance->Threads->Start(queryDispatcher);
662 Implementation eventlist[] = { I_OnRehash };
663 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
664 ServerInstance->Modules->AddService(sqlserv);
669 queryDispatcher->join();
670 delete queryDispatcher;
672 ClearAllConnections();
680 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
682 iter->second->SendResults();
688 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
690 iter->second->ClearResults();
694 bool HasHost(const SQLhost &host)
696 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
698 if (host == iter->second->GetConfHost())
704 bool HostInConf(const SQLhost &h)
706 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
707 for (ConfigIter i = tags.first; i != tags.second; ++i)
709 ConfigTag* tag = i->second;
711 host.id = tag->getString("id");
712 host.host = tag->getString("hostname");
713 host.port = tag->getInt("port", 1433);
714 host.name = tag->getString("name");
715 host.user = tag->getString("username");
716 host.pass = tag->getString("password");
725 ClearOldConnections();
727 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
728 for (ConfigIter i = tags.first; i != tags.second; ++i)
730 ConfigTag* tag = i->second;
733 host.id = tag->getString("id");
734 host.host = tag->getString("hostname");
735 host.port = tag->getInt("port", 1433);
736 host.name = tag->getString("name");
737 host.user = tag->getString("username");
738 host.pass = tag->getString("password");
747 void AddConn(const SQLhost& hi)
751 LoggingMutex->Lock();
752 ServerInstance->Logs->Log("m_mssql",LOG_DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
753 LoggingMutex->Unlock();
759 newconn = new SQLConn(this, hi);
761 connections.insert(std::make_pair(hi.id, newconn));
764 void ClearOldConnections()
766 ConnMap::iterator iter,safei;
767 for (iter = connections.begin(); iter != connections.end(); iter++)
769 if (!HostInConf(iter->second->GetConfHost()))
774 connections.erase(safei);
779 void ClearAllConnections()
781 for(ConnMap::iterator i = connections.begin(); i != connections.end(); ++i)
786 void OnRehash(User* user) CXX11_OVERRIDE
788 queryDispatcher->LockQueue();
790 queryDispatcher->UnlockQueueWakeup();
793 void OnRequest(Request& request) CXX11_OVERRIDE
795 if(strcmp(SQLREQID, request.id) == 0)
797 SQLrequest* req = (SQLrequest*)&request;
799 queryDispatcher->LockQueue();
801 ConnMap::iterator iter;
803 if((iter = connections.find(req->dbid)) != connections.end())
806 iter->second->queue.push(new SQLrequest(*req));
810 req->error.Id(SQL_BAD_DBID);
812 queryDispatcher->UnlockQueueWakeup();
816 unsigned long NewID()
824 Version GetVersion() CXX11_OVERRIDE
826 return Version("MsSQL provider", VF_VENDOR);
831 void QueryThread::OnNotify()
836 void QueryThread::Run()
839 while (this->GetExitFlag() == false)
841 SQLConn* conn = NULL;
842 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
844 if (i->second->queue.totalsize())
853 conn->DoLeadingQuery();
854 this->NotifyParent();
860 this->WaitForQueue();
866 MODULE_INIT(ModuleMsSQL)