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) { }
68 virtual void OnNotify();
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)
95 void AddRow(int colsnum, char **dat, char **colname)
99 for (int i = 0; i < colsnum; i++)
101 fieldlists.resize(fieldlists.size()+1);
102 colnames.push_back(colname[i]);
103 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
104 fieldlists[rows].push_back(sf);
109 void UpdateAffectedCount()
124 virtual std::string ColName(int column)
126 if (column < (int)colnames.size())
128 return colnames[column];
132 throw SQLbadColName();
137 virtual int ColNum(const std::string &column)
139 for (unsigned int i = 0; i < colnames.size(); i++)
141 if (column == colnames[i])
144 throw SQLbadColName();
148 virtual SQLfield GetValue(int row, int column)
150 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
152 return fieldlists[row][column];
155 throw SQLbadColName();
157 /* XXX: We never actually get here because of the throw */
158 return SQLfield("",true);
161 virtual SQLfieldList& GetRow()
163 if (currentrow < rows)
164 return fieldlists[currentrow];
166 return emptyfieldlist;
169 virtual SQLfieldMap& GetRowMap()
171 /* In an effort to reduce overhead we don't actually allocate the map
172 * until the first time it's needed...so...
180 fieldmap = new SQLfieldMap;
183 if (currentrow < rows)
185 for (int i = 0; i < Cols(); i++)
187 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
195 virtual SQLfieldList* GetRowPtr()
197 fieldlist = new SQLfieldList();
199 if (currentrow < rows)
201 for (int i = 0; i < Rows(); i++)
203 fieldlist->push_back(fieldlists[currentrow][i]);
210 virtual SQLfieldMap* GetRowMapPtr()
212 fieldmap = new SQLfieldMap();
214 if (currentrow < rows)
216 for (int i = 0; i < Cols(); i++)
218 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
226 virtual void Free(SQLfieldMap* fm)
231 virtual void Free(SQLfieldList* fl)
237 class SQLConn : public classbase
250 SQLConn(Module* m, const SQLhost& hi)
251 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
255 std::string query("USE " + host.name);
256 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
258 if (tds_process_simple_query(sock) != TDS_SUCCEED)
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 select database " + host.name + " for DB with id: " + host.id);
270 LoggingMutex->Unlock();
276 LoggingMutex->Lock();
277 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
278 LoggingMutex->Unlock();
288 SQLerror Query(SQLrequest* req)
291 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
293 /* Pointer to the buffer we screw around with substitution in */
296 /* Pointer to the current end of query, where we append new stuff */
299 /* Total length of the unescaped parameters */
300 unsigned long maxparamlen, paramcount;
302 /* The length of the longest parameter */
305 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
307 if (i->size() > maxparamlen)
308 maxparamlen = i->size();
311 /* How many params are there in the query? */
312 paramcount = count(req->query.q.c_str(), '?');
314 /* This stores copy of params to be inserted with using numbered params 1;3B*/
315 ParamL paramscopy(req->query.p);
317 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
318 * sizeofquery + (maxtotalparamlength*2) + 1
320 * The +1 is for null-terminating the string
323 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
326 for(unsigned long i = 0; i < req->query.q.length(); i++)
328 if(req->query.q[i] == '?')
330 /* We found a place to substitute..what fun.
331 * use mssql calls to escape and write the
332 * escaped string onto the end of our query buffer,
333 * then we "just" need to make sure queryend is
334 * pointing at the right place.
337 /* Is it numbered parameter?
343 /* Numbered parameter number :|
345 unsigned int paramnum;
348 /* Let's check if it's a numbered param. And also calculate it's number.
351 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
355 paramnum = paramnum * 10 + req->query.q[i] - '0';
358 if (paramnum > paramscopy.size() - 1)
360 /* index is out of range!
367 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
369 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
370 char* escend = escaped;
371 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
384 for (char* n = escaped; *n; n++)
391 else if (req->query.p.size())
393 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
395 char* escaped = new char[(req->query.p.front().length() * 2) + 1];
396 char* escend = escaped;
397 for (std::string::iterator p = req->query.p.front().begin(); p < req->query.p.front().end(); p++)
410 for (char* n = escaped; *n; n++)
416 req->query.p.pop_front();
423 *queryend = req->query.q[i];
428 req->query.q = query;
430 MsSQLResult* res = new MsSQLResult((Module*)mod, req->source, req->id);
432 res->query = req->query.q;
434 char* msquery = strdup(req->query.q.data());
435 LoggingMutex->Lock();
436 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
437 LoggingMutex->Unlock();
438 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
440 std::string error("failed to execute: "+std::string(req->query.q.data()));
444 return SQLerror(SQL_QSEND_FAIL, error);
450 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
452 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
453 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
456 case TDS_ROWFMT_RESULT:
459 case TDS_DONE_RESULT:
460 if (sock->rows_affected > -1)
462 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
468 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
470 if (tds_res != TDS_ROW_RESULT)
473 if (!sock->current_results)
476 if (sock->res_info->row_count > 0)
478 int cols = sock->res_info->num_cols;
479 char** name = new char*[MAXBUF];
480 char** data = new char*[MAXBUF];
481 for (int j=0; j<cols; j++)
483 TDSCOLUMN* col = sock->current_results->columns[j];
484 name[j] = col->column_name;
490 ctype = tds_get_conversion_type(col->column_type, col->column_size);
492 src = col->column_data;
494 src = &(sock->current_results->current_row[col->column_offset]);
496 srclen = col->column_cur_size;
497 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
498 data[j] = (char*)dres.ib;
500 ResultReady(res, cols, data, name);
509 ResultsMutex->Lock();
510 results.push_back(res);
511 ResultsMutex->Unlock();
515 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
517 SQLConn* sc = (SQLConn*)pContext->parent;
518 LoggingMutex->Lock();
519 ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
520 LoggingMutex->Unlock();
524 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
526 SQLConn* sc = (SQLConn*)pContext->parent;
527 LoggingMutex->Lock();
528 ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
529 LoggingMutex->Unlock();
533 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
535 res->AddRow(cols, data, colnames);
538 void AffectedReady(MsSQLResult *res)
540 res->UpdateAffectedCount();
547 TDSCONNECTION* conn = NULL;
549 login = tds_alloc_login();
550 tds_set_app(login, "TSQL");
551 tds_set_library(login,"TDS-Library");
552 tds_set_host(login, "");
553 tds_set_server(login, host.host.c_str());
554 tds_set_server_addr(login, host.host.c_str());
555 tds_set_user(login, host.user.c_str());
556 tds_set_passwd(login, host.pass.c_str());
557 tds_set_port(login, host.port);
558 tds_set_packet(login, 512);
560 context = tds_alloc_context(this);
561 context->msg_handler = HandleMessage;
562 context->err_handler = HandleError;
564 sock = tds_alloc_socket(context, 512);
565 tds_set_parent(sock, NULL);
567 conn = tds_read_config_info(NULL, login, context->locale);
569 if (tds_connect(sock, conn) == TDS_SUCCEED)
571 tds_free_connection(conn);
574 tds_free_connection(conn);
582 tds_free_socket(sock);
587 tds_free_context(context);
592 tds_free_login(login);
597 SQLhost GetConfHost()
604 while (results.size())
606 MsSQLResult* res = results[0];
607 ResultsMutex->Lock();
614 /* If the client module is unloaded partway through a query then the provider will set
615 * the pointer to NULL. We cannot just cancel the query as the result will still come
616 * through at some point...and it could get messy if we play with invalid pointers...
621 ResultsMutex->Unlock();
627 while (results.size())
629 MsSQLResult* res = results[0];
635 void DoLeadingQuery()
637 SQLrequest* req = queue.front();
638 req->error = Query(req);
644 class ModuleMsSQL : public Module
647 unsigned long currid;
648 QueryThread* queryDispatcher;
649 ServiceProvider sqlserv;
653 : currid(0), sqlserv(this, "SQL/mssql", SERVICE_DATA)
655 LoggingMutex = new Mutex();
656 ResultsMutex = new Mutex();
657 queryDispatcher = new QueryThread(this);
664 ServerInstance->Threads->Start(queryDispatcher);
666 Implementation eventlist[] = { I_OnRehash };
667 ServerInstance->Modules->Attach(eventlist, this, 1);
668 ServerInstance->Modules->AddService(sqlserv);
671 virtual ~ModuleMsSQL()
673 queryDispatcher->join();
674 delete queryDispatcher;
676 ClearAllConnections();
684 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
686 iter->second->SendResults();
692 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
694 iter->second->ClearResults();
698 bool HasHost(const SQLhost &host)
700 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
702 if (host == iter->second->GetConfHost())
708 bool HostInConf(const SQLhost &h)
710 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
711 for (ConfigIter i = tags.first; i != tags.second; ++i)
713 ConfigTag* tag = i->second;
715 host.id = tag->getString("id");
716 host.host = tag->getString("hostname");
717 host.port = tag->getInt("port", 1433);
718 host.name = tag->getString("name");
719 host.user = tag->getString("username");
720 host.pass = tag->getString("password");
729 ClearOldConnections();
731 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
732 for (ConfigIter i = tags.first; i != tags.second; ++i)
734 ConfigTag* tag = i->second;
737 host.id = tag->getString("id");
738 host.host = tag->getString("hostname");
739 host.port = tag->getInt("port", 1433);
740 host.name = tag->getString("name");
741 host.user = tag->getString("username");
742 host.pass = tag->getString("password");
751 void AddConn(const SQLhost& hi)
755 LoggingMutex->Lock();
756 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
757 LoggingMutex->Unlock();
763 newconn = new SQLConn(this, hi);
765 connections.insert(std::make_pair(hi.id, newconn));
768 void ClearOldConnections()
770 ConnMap::iterator iter,safei;
771 for (iter = connections.begin(); iter != connections.end(); iter++)
773 if (!HostInConf(iter->second->GetConfHost()))
778 connections.erase(safei);
783 void ClearAllConnections()
785 for(ConnMap::iterator i = connections.begin(); i != connections.end(); ++i)
790 virtual void OnRehash(User* user)
792 queryDispatcher->LockQueue();
794 queryDispatcher->UnlockQueueWakeup();
797 void OnRequest(Request& request)
799 if(strcmp(SQLREQID, request.id) == 0)
801 SQLrequest* req = (SQLrequest*)&request;
803 queryDispatcher->LockQueue();
805 ConnMap::iterator iter;
807 if((iter = connections.find(req->dbid)) != connections.end())
810 iter->second->queue.push(new SQLrequest(*req));
814 req->error.Id(SQL_BAD_DBID);
816 queryDispatcher->UnlockQueueWakeup();
820 unsigned long NewID()
828 virtual Version GetVersion()
830 return Version("MsSQL provider", VF_VENDOR);
835 void QueryThread::OnNotify()
840 void QueryThread::Run()
843 while (this->GetExitFlag() == false)
845 SQLConn* conn = NULL;
846 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
848 if (i->second->queue.totalsize())
857 conn->DoLeadingQuery();
858 this->NotifyParent();
864 this->WaitForQueue();
870 MODULE_INIT(ModuleMsSQL)