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>
30 /* $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);'") */
31 /* $LinkerFlags: -ltds */
37 typedef std::map<std::string, SQLConn*> ConnMap;
38 typedef std::deque<MsSQLResult*> ResultQueue;
40 unsigned long count(const char * const str, char a)
43 for (const char *p = str; *p; ++p)
55 class QueryThread : public SocketThread
58 ModuleMsSQL* const Parent;
60 QueryThread(ModuleMsSQL* mod) : Parent(mod) { }
66 class MsSQLResult : public SQLresult
73 std::vector<std::string> colnames;
74 std::vector<SQLfieldList> fieldlists;
75 SQLfieldList emptyfieldlist;
77 SQLfieldList* fieldlist;
78 SQLfieldMap* fieldmap;
81 MsSQLResult(Module* self, Module* to, unsigned int rid)
82 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
86 void AddRow(int colsnum, char **dat, char **colname)
90 for (int i = 0; i < colsnum; i++)
92 fieldlists.resize(fieldlists.size()+1);
93 colnames.push_back(colname[i]);
94 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
95 fieldlists[rows].push_back(sf);
100 void UpdateAffectedCount()
115 std::string ColName(int column)
117 if (column < (int)colnames.size())
119 return colnames[column];
123 throw SQLbadColName();
128 int ColNum(const std::string &column)
130 for (unsigned int i = 0; i < colnames.size(); i++)
132 if (column == colnames[i])
135 throw SQLbadColName();
139 SQLfield GetValue(int row, int column)
141 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
143 return fieldlists[row][column];
146 throw SQLbadColName();
148 /* XXX: We never actually get here because of the throw */
149 return SQLfield("",true);
152 SQLfieldList& GetRow()
154 if (currentrow < rows)
155 return fieldlists[currentrow];
157 return emptyfieldlist;
160 SQLfieldMap& GetRowMap()
162 /* In an effort to reduce overhead we don't actually allocate the map
163 * until the first time it's needed...so...
171 fieldmap = new SQLfieldMap;
174 if (currentrow < rows)
176 for (int i = 0; i < Cols(); i++)
178 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
186 SQLfieldList* GetRowPtr()
188 fieldlist = new SQLfieldList();
190 if (currentrow < rows)
192 for (int i = 0; i < Rows(); i++)
194 fieldlist->push_back(fieldlists[currentrow][i]);
201 SQLfieldMap* GetRowMapPtr()
203 fieldmap = new SQLfieldMap();
205 if (currentrow < rows)
207 for (int i = 0; i < Cols(); i++)
209 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
217 void Free(SQLfieldMap* fm)
222 void Free(SQLfieldList* fl)
228 class SQLConn : public classbase
241 SQLConn(Module* m, const SQLhost& hi)
242 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
246 std::string query("USE " + host.name);
247 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
249 if (tds_process_simple_query(sock) != TDS_SUCCEED)
251 LoggingMutex->Lock();
252 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
253 LoggingMutex->Unlock();
259 LoggingMutex->Lock();
260 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
261 LoggingMutex->Unlock();
267 LoggingMutex->Lock();
268 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
269 LoggingMutex->Unlock();
279 SQLerror Query(SQLrequest* req)
282 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
284 /* Pointer to the buffer we screw around with substitution in */
287 /* Pointer to the current end of query, where we append new stuff */
290 /* Total length of the unescaped parameters */
291 unsigned long maxparamlen, paramcount;
293 /* The length of the longest parameter */
296 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
298 if (i->size() > maxparamlen)
299 maxparamlen = i->size();
302 /* How many params are there in the query? */
303 paramcount = count(req->query.q.c_str(), '?');
305 /* This stores copy of params to be inserted with using numbered params 1;3B*/
306 ParamL paramscopy(req->query.p);
308 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
309 * sizeofquery + (maxtotalparamlength*2) + 1
311 * The +1 is for null-terminating the string
314 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
317 for(unsigned long i = 0; i < req->query.q.length(); i++)
319 if(req->query.q[i] == '?')
321 /* We found a place to substitute..what fun.
322 * use mssql calls to escape and write the
323 * escaped string onto the end of our query buffer,
324 * then we "just" need to make sure queryend is
325 * pointing at the right place.
328 /* Is it numbered parameter?
334 /* Numbered parameter number :|
336 unsigned int paramnum;
339 /* Let's check if it's a numbered param. And also calculate it's number.
342 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
346 paramnum = paramnum * 10 + req->query.q[i] - '0';
349 if (paramnum > paramscopy.size() - 1)
351 /* index is out of range!
358 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
360 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
361 char* escend = escaped;
362 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
375 for (char* n = escaped; *n; n++)
382 else if (req->query.p.size())
384 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
386 char* escaped = new char[(req->query.p.front().length() * 2) + 1];
387 char* escend = escaped;
388 for (std::string::iterator p = req->query.p.front().begin(); p < req->query.p.front().end(); p++)
401 for (char* n = escaped; *n; n++)
407 req->query.p.pop_front();
414 *queryend = req->query.q[i];
419 req->query.q = query;
421 MsSQLResult* res = new MsSQLResult((Module*)mod, req->source, req->id);
423 res->query = req->query.q;
425 char* msquery = strdup(req->query.q.data());
426 LoggingMutex->Lock();
427 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "doing Query: %s",msquery);
428 LoggingMutex->Unlock();
429 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
431 std::string error("failed to execute: "+std::string(req->query.q.data()));
435 return SQLerror(SQL_QSEND_FAIL, error);
441 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
443 //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "<******> result type: %d", tds_res);
444 //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "AFFECTED ROWS: %d", sock->rows_affected);
447 case TDS_ROWFMT_RESULT:
450 case TDS_DONE_RESULT:
451 if (sock->rows_affected > -1)
453 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
459 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
461 if (tds_res != TDS_ROW_RESULT)
464 if (!sock->current_results)
467 if (sock->res_info->row_count > 0)
469 int cols = sock->res_info->num_cols;
470 char** name = new char*[512];
471 char** data = new char*[512];
472 for (int j=0; j<cols; j++)
474 TDSCOLUMN* col = sock->current_results->columns[j];
475 name[j] = col->column_name;
481 ctype = tds_get_conversion_type(col->column_type, col->column_size);
483 src = col->column_data;
485 src = &(sock->current_results->current_row[col->column_offset]);
487 srclen = col->column_cur_size;
488 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
489 data[j] = (char*)dres.ib;
491 ResultReady(res, cols, data, name);
500 ResultsMutex->Lock();
501 results.push_back(res);
502 ResultsMutex->Unlock();
506 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
508 SQLConn* sc = (SQLConn*)pContext->parent;
509 LoggingMutex->Lock();
510 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
511 LoggingMutex->Unlock();
515 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
517 SQLConn* sc = (SQLConn*)pContext->parent;
518 LoggingMutex->Lock();
519 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
520 LoggingMutex->Unlock();
524 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
526 res->AddRow(cols, data, colnames);
529 void AffectedReady(MsSQLResult *res)
531 res->UpdateAffectedCount();
538 TDSCONNECTION* conn = NULL;
540 login = tds_alloc_login();
541 tds_set_app(login, "TSQL");
542 tds_set_library(login,"TDS-Library");
543 tds_set_host(login, "");
544 tds_set_server(login, host.host.c_str());
545 tds_set_server_addr(login, host.host.c_str());
546 tds_set_user(login, host.user.c_str());
547 tds_set_passwd(login, host.pass.c_str());
548 tds_set_port(login, host.port);
549 tds_set_packet(login, 512);
551 context = tds_alloc_context(this);
552 context->msg_handler = HandleMessage;
553 context->err_handler = HandleError;
555 sock = tds_alloc_socket(context, 512);
556 tds_set_parent(sock, NULL);
558 conn = tds_read_config_info(NULL, login, context->locale);
560 if (tds_connect(sock, conn) == TDS_SUCCEED)
562 tds_free_connection(conn);
565 tds_free_connection(conn);
573 tds_free_socket(sock);
578 tds_free_context(context);
583 tds_free_login(login);
588 SQLhost GetConfHost()
595 while (results.size())
597 MsSQLResult* res = results[0];
598 ResultsMutex->Lock();
605 /* If the client module is unloaded partway through a query then the provider will set
606 * the pointer to NULL. We cannot just cancel the query as the result will still come
607 * through at some point...and it could get messy if we play with invalid pointers...
612 ResultsMutex->Unlock();
618 while (results.size())
620 MsSQLResult* res = results[0];
626 void DoLeadingQuery()
628 SQLrequest* req = queue.front();
629 req->error = Query(req);
635 class ModuleMsSQL : public Module
638 unsigned long currid;
639 QueryThread* queryDispatcher;
640 ServiceProvider sqlserv;
644 : currid(0), sqlserv(this, "SQL/mssql", SERVICE_DATA)
646 LoggingMutex = new Mutex();
647 ResultsMutex = new Mutex();
648 queryDispatcher = new QueryThread(this);
651 void init() CXX11_OVERRIDE
655 ServerInstance->Threads.Start(queryDispatcher);
660 queryDispatcher->join();
661 delete queryDispatcher;
663 ClearAllConnections();
671 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
673 iter->second->SendResults();
679 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
681 iter->second->ClearResults();
685 bool HasHost(const SQLhost &host)
687 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
689 if (host == iter->second->GetConfHost())
695 bool HostInConf(const SQLhost &h)
697 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
698 for (ConfigIter i = tags.first; i != tags.second; ++i)
700 ConfigTag* tag = i->second;
702 host.id = tag->getString("id");
703 host.host = tag->getString("hostname");
704 host.port = tag->getInt("port", 1433);
705 host.name = tag->getString("name");
706 host.user = tag->getString("username");
707 host.pass = tag->getString("password");
716 ClearOldConnections();
718 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
719 for (ConfigIter i = tags.first; i != tags.second; ++i)
721 ConfigTag* tag = i->second;
724 host.id = tag->getString("id");
725 host.host = tag->getString("hostname");
726 host.port = tag->getInt("port", 1433);
727 host.name = tag->getString("name");
728 host.user = tag->getString("username");
729 host.pass = tag->getString("password");
738 void AddConn(const SQLhost& hi)
742 LoggingMutex->Lock();
743 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
744 LoggingMutex->Unlock();
750 newconn = new SQLConn(this, hi);
752 connections.insert(std::make_pair(hi.id, newconn));
755 void ClearOldConnections()
757 ConnMap::iterator iter,safei;
758 for (iter = connections.begin(); iter != connections.end(); iter++)
760 if (!HostInConf(iter->second->GetConfHost()))
765 connections.erase(safei);
770 void ClearAllConnections()
772 for(ConnMap::iterator i = connections.begin(); i != connections.end(); ++i)
777 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
779 queryDispatcher->LockQueue();
781 queryDispatcher->UnlockQueueWakeup();
784 void OnRequest(Request& request) CXX11_OVERRIDE
786 if(strcmp(SQLREQID, request.id) == 0)
788 SQLrequest* req = (SQLrequest*)&request;
790 queryDispatcher->LockQueue();
792 ConnMap::iterator iter;
794 if((iter = connections.find(req->dbid)) != connections.end())
797 iter->second->queue.push(new SQLrequest(*req));
801 req->error.Id(SQL_BAD_DBID);
803 queryDispatcher->UnlockQueueWakeup();
807 unsigned long NewID()
815 Version GetVersion() CXX11_OVERRIDE
817 return Version("MsSQL provider", VF_VENDOR);
822 void QueryThread::OnNotify()
827 void QueryThread::Run()
830 while (this->GetExitFlag() == false)
832 SQLConn* conn = NULL;
833 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
835 if (i->second->queue.totalsize())
844 conn->DoLeadingQuery();
845 this->NotifyParent();
851 this->WaitForQueue();
857 MODULE_INIT(ModuleMsSQL)