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 /* $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);'") */
34 /* $LinkerFlags: -ltds */
40 typedef std::map<std::string, SQLConn*> ConnMap;
41 typedef std::deque<MsSQLResult*> ResultQueue;
43 unsigned long count(const char * const str, char a)
46 for (const char *p = str; *p; ++p)
58 class QueryThread : public SocketThread
61 ModuleMsSQL* const Parent;
63 QueryThread(ModuleMsSQL* mod) : Parent(mod) { }
69 class MsSQLResult : public SQLresult
76 std::vector<std::string> colnames;
77 std::vector<SQLfieldList> fieldlists;
78 SQLfieldList emptyfieldlist;
80 SQLfieldList* fieldlist;
81 SQLfieldMap* fieldmap;
84 MsSQLResult(Module* self, Module* to, unsigned int rid)
85 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
89 void AddRow(int colsnum, char **dat, char **colname)
93 for (int i = 0; i < colsnum; i++)
95 fieldlists.resize(fieldlists.size()+1);
96 colnames.push_back(colname[i]);
97 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
98 fieldlists[rows].push_back(sf);
103 void UpdateAffectedCount()
118 std::string ColName(int column)
120 if (column < (int)colnames.size())
122 return colnames[column];
126 throw SQLbadColName();
131 int ColNum(const std::string &column)
133 for (unsigned int i = 0; i < colnames.size(); i++)
135 if (column == colnames[i])
138 throw SQLbadColName();
142 SQLfield GetValue(int row, int column)
144 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
146 return fieldlists[row][column];
149 throw SQLbadColName();
151 /* XXX: We never actually get here because of the throw */
152 return SQLfield("",true);
155 SQLfieldList& GetRow()
157 if (currentrow < rows)
158 return fieldlists[currentrow];
160 return emptyfieldlist;
163 SQLfieldMap& GetRowMap()
165 /* In an effort to reduce overhead we don't actually allocate the map
166 * until the first time it's needed...so...
174 fieldmap = new SQLfieldMap;
177 if (currentrow < rows)
179 for (int i = 0; i < Cols(); i++)
181 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
189 SQLfieldList* GetRowPtr()
191 fieldlist = new SQLfieldList();
193 if (currentrow < rows)
195 for (int i = 0; i < Rows(); i++)
197 fieldlist->push_back(fieldlists[currentrow][i]);
204 SQLfieldMap* GetRowMapPtr()
206 fieldmap = new SQLfieldMap();
208 if (currentrow < rows)
210 for (int i = 0; i < Cols(); i++)
212 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
220 void Free(SQLfieldMap* fm)
225 void Free(SQLfieldList* fl)
231 class SQLConn : public classbase
244 SQLConn(Module* m, const SQLhost& hi)
245 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
249 std::string query("USE " + host.name);
250 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
252 if (tds_process_simple_query(sock) != TDS_SUCCEED)
254 LoggingMutex->Lock();
255 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
256 LoggingMutex->Unlock();
262 LoggingMutex->Lock();
263 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
264 LoggingMutex->Unlock();
270 LoggingMutex->Lock();
271 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
272 LoggingMutex->Unlock();
282 SQLerror Query(SQLrequest* req)
285 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
287 /* Pointer to the buffer we screw around with substitution in */
290 /* Pointer to the current end of query, where we append new stuff */
293 /* Total length of the unescaped parameters */
294 unsigned long maxparamlen, paramcount;
296 /* The length of the longest parameter */
299 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
301 if (i->size() > maxparamlen)
302 maxparamlen = i->size();
305 /* How many params are there in the query? */
306 paramcount = count(req->query.q.c_str(), '?');
308 /* This stores copy of params to be inserted with using numbered params 1;3B*/
309 ParamL paramscopy(req->query.p);
311 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
312 * sizeofquery + (maxtotalparamlength*2) + 1
314 * The +1 is for null-terminating the string
317 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
320 for(unsigned long i = 0; i < req->query.q.length(); i++)
322 if(req->query.q[i] == '?')
324 /* We found a place to substitute..what fun.
325 * use mssql calls to escape and write the
326 * escaped string onto the end of our query buffer,
327 * then we "just" need to make sure queryend is
328 * pointing at the right place.
331 /* Is it numbered parameter?
337 /* Numbered parameter number :|
339 unsigned int paramnum;
342 /* Let's check if it's a numbered param. And also calculate it's number.
345 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
349 paramnum = paramnum * 10 + req->query.q[i] - '0';
352 if (paramnum > paramscopy.size() - 1)
354 /* index is out of range!
361 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
363 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
364 char* escend = escaped;
365 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
378 for (char* n = escaped; *n; n++)
385 else if (req->query.p.size())
387 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
389 char* escaped = new char[(req->query.p.front().length() * 2) + 1];
390 char* escend = escaped;
391 for (std::string::iterator p = req->query.p.front().begin(); p < req->query.p.front().end(); p++)
404 for (char* n = escaped; *n; n++)
410 req->query.p.pop_front();
417 *queryend = req->query.q[i];
422 req->query.q = query;
424 MsSQLResult* res = new MsSQLResult((Module*)mod, req->source, req->id);
426 res->query = req->query.q;
428 char* msquery = strdup(req->query.q.data());
429 LoggingMutex->Lock();
430 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "doing Query: %s",msquery);
431 LoggingMutex->Unlock();
432 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
434 std::string error("failed to execute: "+std::string(req->query.q.data()));
438 return SQLerror(SQL_QSEND_FAIL, error);
444 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
446 //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "<******> result type: %d", tds_res);
447 //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "AFFECTED ROWS: %d", sock->rows_affected);
450 case TDS_ROWFMT_RESULT:
453 case TDS_DONE_RESULT:
454 if (sock->rows_affected > -1)
456 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
462 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
464 if (tds_res != TDS_ROW_RESULT)
467 if (!sock->current_results)
470 if (sock->res_info->row_count > 0)
472 int cols = sock->res_info->num_cols;
473 char** name = new char*[512];
474 char** data = new char*[512];
475 for (int j=0; j<cols; j++)
477 TDSCOLUMN* col = sock->current_results->columns[j];
478 name[j] = col->column_name;
484 ctype = tds_get_conversion_type(col->column_type, col->column_size);
486 src = col->column_data;
488 src = &(sock->current_results->current_row[col->column_offset]);
490 srclen = col->column_cur_size;
491 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
492 data[j] = (char*)dres.ib;
494 ResultReady(res, cols, data, name);
503 ResultsMutex->Lock();
504 results.push_back(res);
505 ResultsMutex->Unlock();
509 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
511 SQLConn* sc = (SQLConn*)pContext->parent;
512 LoggingMutex->Lock();
513 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
514 LoggingMutex->Unlock();
518 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
520 SQLConn* sc = (SQLConn*)pContext->parent;
521 LoggingMutex->Lock();
522 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
523 LoggingMutex->Unlock();
527 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
529 res->AddRow(cols, data, colnames);
532 void AffectedReady(MsSQLResult *res)
534 res->UpdateAffectedCount();
541 TDSCONNECTION* conn = NULL;
543 login = tds_alloc_login();
544 tds_set_app(login, "TSQL");
545 tds_set_library(login,"TDS-Library");
546 tds_set_host(login, "");
547 tds_set_server(login, host.host.c_str());
548 tds_set_server_addr(login, host.host.c_str());
549 tds_set_user(login, host.user.c_str());
550 tds_set_passwd(login, host.pass.c_str());
551 tds_set_port(login, host.port);
552 tds_set_packet(login, 512);
554 context = tds_alloc_context(this);
555 context->msg_handler = HandleMessage;
556 context->err_handler = HandleError;
558 sock = tds_alloc_socket(context, 512);
559 tds_set_parent(sock, NULL);
561 conn = tds_read_config_info(NULL, login, context->locale);
563 if (tds_connect(sock, conn) == TDS_SUCCEED)
565 tds_free_connection(conn);
568 tds_free_connection(conn);
576 tds_free_socket(sock);
581 tds_free_context(context);
586 tds_free_login(login);
591 SQLhost GetConfHost()
598 while (results.size())
600 MsSQLResult* res = results[0];
601 ResultsMutex->Lock();
608 /* If the client module is unloaded partway through a query then the provider will set
609 * the pointer to NULL. We cannot just cancel the query as the result will still come
610 * through at some point...and it could get messy if we play with invalid pointers...
615 ResultsMutex->Unlock();
621 while (results.size())
623 MsSQLResult* res = results[0];
629 void DoLeadingQuery()
631 SQLrequest* req = queue.front();
632 req->error = Query(req);
638 class ModuleMsSQL : public Module
641 unsigned long currid;
642 QueryThread* queryDispatcher;
643 ServiceProvider sqlserv;
647 : currid(0), sqlserv(this, "SQL/mssql", SERVICE_DATA)
649 LoggingMutex = new Mutex();
650 ResultsMutex = new Mutex();
651 queryDispatcher = new QueryThread(this);
654 void init() CXX11_OVERRIDE
658 ServerInstance->Threads->Start(queryDispatcher);
660 ServerInstance->Modules->AddService(sqlserv);
665 queryDispatcher->join();
666 delete queryDispatcher;
668 ClearAllConnections();
676 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
678 iter->second->SendResults();
684 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
686 iter->second->ClearResults();
690 bool HasHost(const SQLhost &host)
692 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
694 if (host == iter->second->GetConfHost())
700 bool HostInConf(const SQLhost &h)
702 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
703 for (ConfigIter i = tags.first; i != tags.second; ++i)
705 ConfigTag* tag = i->second;
707 host.id = tag->getString("id");
708 host.host = tag->getString("hostname");
709 host.port = tag->getInt("port", 1433);
710 host.name = tag->getString("name");
711 host.user = tag->getString("username");
712 host.pass = tag->getString("password");
721 ClearOldConnections();
723 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
724 for (ConfigIter i = tags.first; i != tags.second; ++i)
726 ConfigTag* tag = i->second;
729 host.id = tag->getString("id");
730 host.host = tag->getString("hostname");
731 host.port = tag->getInt("port", 1433);
732 host.name = tag->getString("name");
733 host.user = tag->getString("username");
734 host.pass = tag->getString("password");
743 void AddConn(const SQLhost& hi)
747 LoggingMutex->Lock();
748 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
749 LoggingMutex->Unlock();
755 newconn = new SQLConn(this, hi);
757 connections.insert(std::make_pair(hi.id, newconn));
760 void ClearOldConnections()
762 ConnMap::iterator iter,safei;
763 for (iter = connections.begin(); iter != connections.end(); iter++)
765 if (!HostInConf(iter->second->GetConfHost()))
770 connections.erase(safei);
775 void ClearAllConnections()
777 for(ConnMap::iterator i = connections.begin(); i != connections.end(); ++i)
782 void OnRehash(User* user) CXX11_OVERRIDE
784 queryDispatcher->LockQueue();
786 queryDispatcher->UnlockQueueWakeup();
789 void OnRequest(Request& request) CXX11_OVERRIDE
791 if(strcmp(SQLREQID, request.id) == 0)
793 SQLrequest* req = (SQLrequest*)&request;
795 queryDispatcher->LockQueue();
797 ConnMap::iterator iter;
799 if((iter = connections.find(req->dbid)) != connections.end())
802 iter->second->queue.push(new SQLrequest(*req));
806 req->error.Id(SQL_BAD_DBID);
808 queryDispatcher->UnlockQueueWakeup();
812 unsigned long NewID()
820 Version GetVersion() CXX11_OVERRIDE
822 return Version("MsSQL provider", VF_VENDOR);
827 void QueryThread::OnNotify()
832 void QueryThread::Run()
835 while (this->GetExitFlag() == false)
837 SQLConn* conn = NULL;
838 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
840 if (i->second->queue.totalsize())
849 conn->DoLeadingQuery();
850 this->NotifyParent();
856 this->WaitForQueue();
862 MODULE_INIT(ModuleMsSQL)