1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include <tdsconvert.h>
23 /* $ModDesc: MsSQL provider */
24 /* $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);'") */
25 /* $LinkerFlags: -ltds */
26 /* $ModDep: m_sqlv2.h */
32 typedef std::map<std::string, SQLConn*> ConnMap;
33 typedef std::deque<MsSQLResult*> ResultQueue;
35 unsigned long count(const char * const str, char a)
38 for (const char *p = str; *p; ++p)
50 class QueryThread : public SocketThread
53 ModuleMsSQL* const Parent;
55 QueryThread(ModuleMsSQL* mod) : Parent(mod) { }
58 virtual void OnNotify();
61 class MsSQLResult : public SQLresult
68 std::vector<std::string> colnames;
69 std::vector<SQLfieldList> fieldlists;
70 SQLfieldList emptyfieldlist;
72 SQLfieldList* fieldlist;
73 SQLfieldMap* fieldmap;
76 MsSQLResult(Module* self, Module* to, unsigned int rid)
77 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
85 void AddRow(int colsnum, char **dat, char **colname)
89 for (int i = 0; i < colsnum; i++)
91 fieldlists.resize(fieldlists.size()+1);
92 colnames.push_back(colname[i]);
93 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
94 fieldlists[rows].push_back(sf);
99 void UpdateAffectedCount()
114 virtual std::string ColName(int column)
116 if (column < (int)colnames.size())
118 return colnames[column];
122 throw SQLbadColName();
127 virtual int ColNum(const std::string &column)
129 for (unsigned int i = 0; i < colnames.size(); i++)
131 if (column == colnames[i])
134 throw SQLbadColName();
138 virtual SQLfield GetValue(int row, int column)
140 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
142 return fieldlists[row][column];
145 throw SQLbadColName();
147 /* XXX: We never actually get here because of the throw */
148 return SQLfield("",true);
151 virtual SQLfieldList& GetRow()
153 if (currentrow < rows)
154 return fieldlists[currentrow];
156 return emptyfieldlist;
159 virtual SQLfieldMap& GetRowMap()
161 /* In an effort to reduce overhead we don't actually allocate the map
162 * until the first time it's needed...so...
170 fieldmap = new SQLfieldMap;
173 if (currentrow < rows)
175 for (int i = 0; i < Cols(); i++)
177 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
185 virtual SQLfieldList* GetRowPtr()
187 fieldlist = new SQLfieldList();
189 if (currentrow < rows)
191 for (int i = 0; i < Rows(); i++)
193 fieldlist->push_back(fieldlists[currentrow][i]);
200 virtual SQLfieldMap* GetRowMapPtr()
202 fieldmap = new SQLfieldMap();
204 if (currentrow < rows)
206 for (int i = 0; i < Cols(); i++)
208 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
216 virtual void Free(SQLfieldMap* fm)
221 virtual void Free(SQLfieldList* fl)
227 class SQLConn : public classbase
240 SQLConn(Module* m, const SQLhost& hi)
241 : mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
245 std::string query("USE " + host.name);
246 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
248 if (tds_process_simple_query(sock) != TDS_SUCCEED)
250 LoggingMutex->Lock();
251 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
252 LoggingMutex->Unlock();
258 LoggingMutex->Lock();
259 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
260 LoggingMutex->Unlock();
266 LoggingMutex->Lock();
267 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
268 LoggingMutex->Unlock();
278 SQLerror Query(SQLrequest* req)
281 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
283 /* Pointer to the buffer we screw around with substitution in */
286 /* Pointer to the current end of query, where we append new stuff */
289 /* Total length of the unescaped parameters */
290 unsigned long maxparamlen, paramcount;
292 /* The length of the longest parameter */
295 for(ParamL::iterator i = req->query.p.begin(); i != req->query.p.end(); i++)
297 if (i->size() > maxparamlen)
298 maxparamlen = i->size();
301 /* How many params are there in the query? */
302 paramcount = count(req->query.q.c_str(), '?');
304 /* This stores copy of params to be inserted with using numbered params 1;3B*/
305 ParamL paramscopy(req->query.p);
307 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
308 * sizeofquery + (maxtotalparamlength*2) + 1
310 * The +1 is for null-terminating the string
313 query = new char[req->query.q.length() + (maxparamlen*paramcount*2) + 1];
316 for(unsigned long i = 0; i < req->query.q.length(); i++)
318 if(req->query.q[i] == '?')
320 /* We found a place to substitute..what fun.
321 * use mssql calls to escape and write the
322 * escaped string onto the end of our query buffer,
323 * then we "just" need to make sure queryend is
324 * pointing at the right place.
327 /* Is it numbered parameter?
333 /* Numbered parameter number :|
335 unsigned int paramnum;
338 /* Let's check if it's a numbered param. And also calculate it's number.
341 while ((i < req->query.q.length() - 1) && (req->query.q[i+1] >= '0') && (req->query.q[i+1] <= '9'))
345 paramnum = paramnum * 10 + req->query.q[i] - '0';
348 if (paramnum > paramscopy.size() - 1)
350 /* index is out of range!
357 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
359 char* escaped = new char[(paramscopy[paramnum].length() * 2) + 1];
360 char* escend = escaped;
361 for (std::string::iterator p = paramscopy[paramnum].begin(); p < paramscopy[paramnum].end(); p++)
374 for (char* n = escaped; *n; n++)
381 else if (req->query.p.size())
383 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
385 char* escaped = new char[(req->query.p.front().length() * 2) + 1];
386 char* escend = escaped;
387 for (std::string::iterator p = req->query.p.front().begin(); p < req->query.p.front().end(); p++)
400 for (char* n = escaped; *n; n++)
406 req->query.p.pop_front();
413 *queryend = req->query.q[i];
418 req->query.q = query;
420 MsSQLResult* res = new MsSQLResult((Module*)mod, req->source, req->id);
422 res->query = req->query.q;
424 char* msquery = strdup(req->query.q.data());
425 LoggingMutex->Lock();
426 ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
427 LoggingMutex->Unlock();
428 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
430 std::string error("failed to execute: "+std::string(req->query.q.data()));
434 return SQLerror(SQL_QSEND_FAIL, error);
440 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
442 //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
443 //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
446 case TDS_ROWFMT_RESULT:
449 case TDS_DONE_RESULT:
450 if (sock->rows_affected > -1)
452 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
458 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
460 if (tds_res != TDS_ROW_RESULT)
463 if (!sock->current_results)
466 if (sock->res_info->row_count > 0)
468 int cols = sock->res_info->num_cols;
469 char** name = new char*[MAXBUF];
470 char** data = new char*[MAXBUF];
471 for (int j=0; j<cols; j++)
473 TDSCOLUMN* col = sock->current_results->columns[j];
474 name[j] = col->column_name;
480 ctype = tds_get_conversion_type(col->column_type, col->column_size);
482 src = col->column_data;
484 src = &(sock->current_results->current_row[col->column_offset]);
486 srclen = col->column_cur_size;
487 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
488 data[j] = (char*)dres.ib;
490 ResultReady(res, cols, data, name);
499 ResultsMutex->Lock();
500 results.push_back(res);
501 ResultsMutex->Unlock();
505 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
507 SQLConn* sc = (SQLConn*)pContext->parent;
508 LoggingMutex->Lock();
509 ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
510 LoggingMutex->Unlock();
514 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
516 SQLConn* sc = (SQLConn*)pContext->parent;
517 LoggingMutex->Lock();
518 ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
519 LoggingMutex->Unlock();
523 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
525 res->AddRow(cols, data, colnames);
528 void AffectedReady(MsSQLResult *res)
530 res->UpdateAffectedCount();
537 TDSCONNECTION* conn = NULL;
539 login = tds_alloc_login();
540 tds_set_app(login, "TSQL");
541 tds_set_library(login,"TDS-Library");
542 tds_set_host(login, "");
543 tds_set_server(login, host.host.c_str());
544 tds_set_server_addr(login, host.host.c_str());
545 tds_set_user(login, host.user.c_str());
546 tds_set_passwd(login, host.pass.c_str());
547 tds_set_port(login, host.port);
548 tds_set_packet(login, 512);
550 context = tds_alloc_context(this);
551 context->msg_handler = HandleMessage;
552 context->err_handler = HandleError;
554 sock = tds_alloc_socket(context, 512);
555 tds_set_parent(sock, NULL);
557 conn = tds_read_config_info(NULL, login, context->locale);
559 if (tds_connect(sock, conn) == TDS_SUCCEED)
561 tds_free_connection(conn);
564 tds_free_connection(conn);
572 tds_free_socket(sock);
577 tds_free_context(context);
582 tds_free_login(login);
587 SQLhost GetConfHost()
594 while (results.size())
596 MsSQLResult* res = results[0];
597 ResultsMutex->Lock();
604 /* If the client module is unloaded partway through a query then the provider will set
605 * the pointer to NULL. We cannot just cancel the query as the result will still come
606 * through at some point...and it could get messy if we play with invalid pointers...
611 ResultsMutex->Unlock();
617 while (results.size())
619 MsSQLResult* res = results[0];
625 void DoLeadingQuery()
627 SQLrequest* req = queue.front();
628 req->error = Query(req);
634 class ModuleMsSQL : public Module
637 unsigned long currid;
638 QueryThread* queryDispatcher;
639 ServiceProvider sqlserv;
643 : currid(0), sqlserv(this, "SQL/mssql", SERVICE_DATA)
645 LoggingMutex = new Mutex();
646 ResultsMutex = new Mutex();
647 queryDispatcher = new QueryThread(this);
654 ServerInstance->Threads->Start(queryDispatcher);
656 Implementation eventlist[] = { I_OnRehash };
657 ServerInstance->Modules->Attach(eventlist, this, 1);
658 ServerInstance->Modules->AddService(sqlserv);
661 virtual ~ModuleMsSQL()
663 queryDispatcher->join();
664 delete queryDispatcher;
666 ClearAllConnections();
674 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
676 iter->second->SendResults();
682 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
684 iter->second->ClearResults();
688 bool HasHost(const SQLhost &host)
690 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
692 if (host == iter->second->GetConfHost())
698 bool HostInConf(const SQLhost &h)
701 for(int i = 0; i < conf.Enumerate("database"); i++)
704 host.id = conf.ReadValue("database", "id", i);
705 host.host = conf.ReadValue("database", "hostname", i);
706 host.port = conf.ReadInteger("database", "port", "1433", i, true);
707 host.name = conf.ReadValue("database", "name", i);
708 host.user = conf.ReadValue("database", "username", i);
709 host.pass = conf.ReadValue("database", "password", i);
718 ClearOldConnections();
721 for(int i = 0; i < conf.Enumerate("database"); i++)
725 host.id = conf.ReadValue("database", "id", i);
726 host.host = conf.ReadValue("database", "hostname", i);
727 host.port = conf.ReadInteger("database", "port", "1433", i, true);
728 host.name = conf.ReadValue("database", "name", i);
729 host.user = conf.ReadValue("database", "username", i);
730 host.pass = conf.ReadValue("database", "password", i);
739 void AddConn(const SQLhost& hi)
743 LoggingMutex->Lock();
744 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
745 LoggingMutex->Unlock();
751 newconn = new SQLConn(this, hi);
753 connections.insert(std::make_pair(hi.id, newconn));
756 void ClearOldConnections()
758 ConnMap::iterator iter,safei;
759 for (iter = connections.begin(); iter != connections.end(); iter++)
761 if (!HostInConf(iter->second->GetConfHost()))
766 connections.erase(safei);
771 void ClearAllConnections()
774 while ((i = connections.begin()) != connections.end())
776 connections.erase(i);
781 virtual void OnRehash(User* user)
783 queryDispatcher->LockQueue();
785 queryDispatcher->UnlockQueueWakeup();
788 void OnRequest(Request& request)
790 if(strcmp(SQLREQID, request.id) == 0)
792 SQLrequest* req = (SQLrequest*)&request;
794 queryDispatcher->LockQueue();
796 ConnMap::iterator iter;
798 if((iter = connections.find(req->dbid)) != connections.end())
801 iter->second->queue.push(new SQLrequest(*req));
805 req->error.Id(SQL_BAD_DBID);
807 queryDispatcher->UnlockQueueWakeup();
811 unsigned long NewID()
819 virtual Version GetVersion()
821 return Version("MsSQL provider", VF_VENDOR);
826 void QueryThread::OnNotify()
831 void QueryThread::Run()
834 while (this->GetExitFlag() == false)
836 SQLConn* conn = NULL;
837 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
839 if (i->second->queue.totalsize())
848 conn->DoLeadingQuery();
849 this->NotifyParent();
855 this->WaitForQueue();
861 MODULE_INIT(ModuleMsSQL)