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 */
35 /* $ModDep: m_sqlv2.h */
41 typedef std::map<std::string, SQLConn*> ConnMap;
42 typedef std::deque<MsSQLResult*> ResultQueue;
44 unsigned long count(const char * const str, char a)
47 for (const char *p = str; *p; ++p)
59 class QueryThread : public SocketThread
62 ModuleMsSQL* const Parent;
64 QueryThread(ModuleMsSQL* mod) : Parent(mod) { }
70 class MsSQLResult : public SQLresult
77 std::vector<std::string> colnames;
78 std::vector<SQLfieldList> fieldlists;
79 SQLfieldList emptyfieldlist;
81 SQLfieldList* fieldlist;
82 SQLfieldMap* fieldmap;
85 MsSQLResult(Module* self, Module* to, unsigned int rid)
86 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
90 void AddRow(int colsnum, char **dat, char **colname)
94 for (int i = 0; i < colsnum; i++)
96 fieldlists.resize(fieldlists.size()+1);
97 colnames.push_back(colname[i]);
98 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
99 fieldlists[rows].push_back(sf);
104 void UpdateAffectedCount()
119 std::string ColName(int column)
121 if (column < (int)colnames.size())
123 return colnames[column];
127 throw SQLbadColName();
132 int ColNum(const std::string &column)
134 for (unsigned int i = 0; i < colnames.size(); i++)
136 if (column == colnames[i])
139 throw SQLbadColName();
143 SQLfield GetValue(int row, int column)
145 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
147 return fieldlists[row][column];
150 throw SQLbadColName();
152 /* XXX: We never actually get here because of the throw */
153 return SQLfield("",true);
156 SQLfieldList& GetRow()
158 if (currentrow < rows)
159 return fieldlists[currentrow];
161 return emptyfieldlist;
164 SQLfieldMap& GetRowMap()
166 /* In an effort to reduce overhead we don't actually allocate the map
167 * until the first time it's needed...so...
175 fieldmap = new SQLfieldMap;
178 if (currentrow < rows)
180 for (int i = 0; i < Cols(); i++)
182 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
190 SQLfieldList* GetRowPtr()
192 fieldlist = new SQLfieldList();
194 if (currentrow < rows)
196 for (int i = 0; i < Rows(); i++)
198 fieldlist->push_back(fieldlists[currentrow][i]);
205 SQLfieldMap* GetRowMapPtr()
207 fieldmap = new SQLfieldMap();
209 if (currentrow < rows)
211 for (int i = 0; i < Cols(); i++)
213 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
221 void Free(SQLfieldMap* fm)
226 void Free(SQLfieldList* fl)
232 class SQLConn : public classbase
245 SQLConn(Module* m, const SQLhost& hi)
246 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
250 std::string query("USE " + host.name);
251 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
253 if (tds_process_simple_query(sock) != TDS_SUCCEED)
255 LoggingMutex->Lock();
256 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
257 LoggingMutex->Unlock();
263 LoggingMutex->Lock();
264 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
265 LoggingMutex->Unlock();
271 LoggingMutex->Lock();
272 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
273 LoggingMutex->Unlock();
283 SQLerror Query(SQLrequest* req)
286 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
288 /* Pointer to the buffer we screw around with substitution in */
291 /* Pointer to the current end of query, where we append new stuff */
294 /* Total length of the unescaped parameters */
295 unsigned long maxparamlen, paramcount;
297 /* The length of the longest parameter */
300 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
302 if (i->size() > maxparamlen)
303 maxparamlen = i->size();
306 /* How many params are there in the query? */
307 paramcount = count(req->query.q.c_str(), '?');
309 /* This stores copy of params to be inserted with using numbered params 1;3B*/
310 ParamL paramscopy(req->query.p);
312 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
313 * sizeofquery + (maxtotalparamlength*2) + 1
315 * The +1 is for null-terminating the string
318 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
321 for(unsigned long i = 0; i < req->query.q.length(); i++)
323 if(req->query.q[i] == '?')
325 /* We found a place to substitute..what fun.
326 * use mssql calls to escape and write the
327 * escaped string onto the end of our query buffer,
328 * then we "just" need to make sure queryend is
329 * pointing at the right place.
332 /* Is it numbered parameter?
338 /* Numbered parameter number :|
340 unsigned int paramnum;
343 /* Let's check if it's a numbered param. And also calculate it's number.
346 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
350 paramnum = paramnum * 10 + req->query.q[i] - '0';
353 if (paramnum > paramscopy.size() - 1)
355 /* index is out of range!
362 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
364 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
365 char* escend = escaped;
366 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
379 for (char* n = escaped; *n; n++)
386 else if (req->query.p.size())
388 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
390 char* escaped = new char[(req->query.p.front().length() * 2) + 1];
391 char* escend = escaped;
392 for (std::string::iterator p = req->query.p.front().begin(); p < req->query.p.front().end(); p++)
405 for (char* n = escaped; *n; n++)
411 req->query.p.pop_front();
418 *queryend = req->query.q[i];
423 req->query.q = query;
425 MsSQLResult* res = new MsSQLResult((Module*)mod, req->source, req->id);
427 res->query = req->query.q;
429 char* msquery = strdup(req->query.q.data());
430 LoggingMutex->Lock();
431 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "doing Query: %s",msquery);
432 LoggingMutex->Unlock();
433 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
435 std::string error("failed to execute: "+std::string(req->query.q.data()));
439 return SQLerror(SQL_QSEND_FAIL, error);
445 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
447 //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "<******> result type: %d", tds_res);
448 //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "AFFECTED ROWS: %d", sock->rows_affected);
451 case TDS_ROWFMT_RESULT:
454 case TDS_DONE_RESULT:
455 if (sock->rows_affected > -1)
457 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
463 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
465 if (tds_res != TDS_ROW_RESULT)
468 if (!sock->current_results)
471 if (sock->res_info->row_count > 0)
473 int cols = sock->res_info->num_cols;
474 char** name = new char*[512];
475 char** data = new char*[512];
476 for (int j=0; j<cols; j++)
478 TDSCOLUMN* col = sock->current_results->columns[j];
479 name[j] = col->column_name;
485 ctype = tds_get_conversion_type(col->column_type, col->column_size);
487 src = col->column_data;
489 src = &(sock->current_results->current_row[col->column_offset]);
491 srclen = col->column_cur_size;
492 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
493 data[j] = (char*)dres.ib;
495 ResultReady(res, cols, data, name);
504 ResultsMutex->Lock();
505 results.push_back(res);
506 ResultsMutex->Unlock();
510 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
512 SQLConn* sc = (SQLConn*)pContext->parent;
513 LoggingMutex->Lock();
514 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
515 LoggingMutex->Unlock();
519 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
521 SQLConn* sc = (SQLConn*)pContext->parent;
522 LoggingMutex->Lock();
523 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
524 LoggingMutex->Unlock();
528 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
530 res->AddRow(cols, data, colnames);
533 void AffectedReady(MsSQLResult *res)
535 res->UpdateAffectedCount();
542 TDSCONNECTION* conn = NULL;
544 login = tds_alloc_login();
545 tds_set_app(login, "TSQL");
546 tds_set_library(login,"TDS-Library");
547 tds_set_host(login, "");
548 tds_set_server(login, host.host.c_str());
549 tds_set_server_addr(login, host.host.c_str());
550 tds_set_user(login, host.user.c_str());
551 tds_set_passwd(login, host.pass.c_str());
552 tds_set_port(login, host.port);
553 tds_set_packet(login, 512);
555 context = tds_alloc_context(this);
556 context->msg_handler = HandleMessage;
557 context->err_handler = HandleError;
559 sock = tds_alloc_socket(context, 512);
560 tds_set_parent(sock, NULL);
562 conn = tds_read_config_info(NULL, login, context->locale);
564 if (tds_connect(sock, conn) == TDS_SUCCEED)
566 tds_free_connection(conn);
569 tds_free_connection(conn);
577 tds_free_socket(sock);
582 tds_free_context(context);
587 tds_free_login(login);
592 SQLhost GetConfHost()
599 while (results.size())
601 MsSQLResult* res = results[0];
602 ResultsMutex->Lock();
609 /* If the client module is unloaded partway through a query then the provider will set
610 * the pointer to NULL. We cannot just cancel the query as the result will still come
611 * through at some point...and it could get messy if we play with invalid pointers...
616 ResultsMutex->Unlock();
622 while (results.size())
624 MsSQLResult* res = results[0];
630 void DoLeadingQuery()
632 SQLrequest* req = queue.front();
633 req->error = Query(req);
639 class ModuleMsSQL : public Module
642 unsigned long currid;
643 QueryThread* queryDispatcher;
644 ServiceProvider sqlserv;
648 : currid(0), sqlserv(this, "SQL/mssql", SERVICE_DATA)
650 LoggingMutex = new Mutex();
651 ResultsMutex = new Mutex();
652 queryDispatcher = new QueryThread(this);
655 void init() CXX11_OVERRIDE
659 ServerInstance->Threads->Start(queryDispatcher);
661 Implementation eventlist[] = { I_OnRehash };
662 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
663 ServerInstance->Modules->AddService(sqlserv);
668 queryDispatcher->join();
669 delete queryDispatcher;
671 ClearAllConnections();
679 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
681 iter->second->SendResults();
687 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
689 iter->second->ClearResults();
693 bool HasHost(const SQLhost &host)
695 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
697 if (host == iter->second->GetConfHost())
703 bool HostInConf(const SQLhost &h)
705 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
706 for (ConfigIter i = tags.first; i != tags.second; ++i)
708 ConfigTag* tag = i->second;
710 host.id = tag->getString("id");
711 host.host = tag->getString("hostname");
712 host.port = tag->getInt("port", 1433);
713 host.name = tag->getString("name");
714 host.user = tag->getString("username");
715 host.pass = tag->getString("password");
724 ClearOldConnections();
726 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
727 for (ConfigIter i = tags.first; i != tags.second; ++i)
729 ConfigTag* tag = i->second;
732 host.id = tag->getString("id");
733 host.host = tag->getString("hostname");
734 host.port = tag->getInt("port", 1433);
735 host.name = tag->getString("name");
736 host.user = tag->getString("username");
737 host.pass = tag->getString("password");
746 void AddConn(const SQLhost& hi)
750 LoggingMutex->Lock();
751 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
752 LoggingMutex->Unlock();
758 newconn = new SQLConn(this, hi);
760 connections.insert(std::make_pair(hi.id, newconn));
763 void ClearOldConnections()
765 ConnMap::iterator iter,safei;
766 for (iter = connections.begin(); iter != connections.end(); iter++)
768 if (!HostInConf(iter->second->GetConfHost()))
773 connections.erase(safei);
778 void ClearAllConnections()
780 for(ConnMap::iterator i = connections.begin(); i != connections.end(); ++i)
785 void OnRehash(User* user) CXX11_OVERRIDE
787 queryDispatcher->LockQueue();
789 queryDispatcher->UnlockQueueWakeup();
792 void OnRequest(Request& request) CXX11_OVERRIDE
794 if(strcmp(SQLREQID, request.id) == 0)
796 SQLrequest* req = (SQLrequest*)&request;
798 queryDispatcher->LockQueue();
800 ConnMap::iterator iter;
802 if((iter = connections.find(req->dbid)) != connections.end())
805 iter->second->queue.push(new SQLrequest(*req));
809 req->error.Id(SQL_BAD_DBID);
811 queryDispatcher->UnlockQueueWakeup();
815 unsigned long NewID()
823 Version GetVersion() CXX11_OVERRIDE
825 return Version("MsSQL provider", VF_VENDOR);
830 void QueryThread::OnNotify()
835 void QueryThread::Run()
838 while (this->GetExitFlag() == false)
840 SQLConn* conn = NULL;
841 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
843 if (i->second->queue.totalsize())
852 conn->DoLeadingQuery();
853 this->NotifyParent();
859 this->WaitForQueue();
865 MODULE_INIT(ModuleMsSQL)