1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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 = reinterpret_cast<const char *>(str); *p; ++p)
50 class QueryThread : public SocketThread
54 InspIRCd* ServerInstance;
56 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
57 : SocketThread(si), Parent(mod), ServerInstance(si)
62 virtual void OnNotify();
65 class MsSQLResult : public SQLresult
72 std::vector<std::string> colnames;
73 std::vector<SQLfieldList> fieldlists;
74 SQLfieldList emptyfieldlist;
76 SQLfieldList* fieldlist;
77 SQLfieldMap* fieldmap;
80 MsSQLResult(Module* self, Module* to, unsigned int rid)
81 : 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 virtual std::string ColName(int column)
120 if (column < (int)colnames.size())
122 return colnames[column];
126 throw SQLbadColName();
131 virtual 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 virtual 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 virtual SQLfieldList& GetRow()
157 if (currentrow < rows)
158 return fieldlists[currentrow];
160 return emptyfieldlist;
163 virtual 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 virtual 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 virtual 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 virtual void Free(SQLfieldMap* fm)
225 virtual void Free(SQLfieldList* fl)
231 class SQLConn : public classbase
235 InspIRCd* ServerInstance;
245 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
246 : ServerInstance(SI), 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("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
257 LoggingMutex->Unlock();
263 LoggingMutex->Lock();
264 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
265 LoggingMutex->Unlock();
271 LoggingMutex->Lock();
272 ServerInstance->Logs->Log("m_mssql",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];
425 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
427 res->query = req.query.q;
429 char* msquery = strdup(req.query.q.data());
430 LoggingMutex->Lock();
431 ServerInstance->Logs->Log("m_mssql",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("m_mssql",DEBUG,"<******> result type: %d", tds_res);
448 //ServerInstance->Logs->Log("m_mssql",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*[MAXBUF];
475 char** data = new char*[MAXBUF];
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 sc->ServerInstance->Logs->Log("m_mssql", 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 sc->ServerInstance->Logs->Log("m_mssql", 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;
646 ModuleMsSQL(InspIRCd* Me)
647 : Module(Me), currid(0)
649 LoggingMutex = new Mutex();
650 ResultsMutex = new Mutex();
652 ServerInstance->Modules->UseInterface("SQLutils");
654 if (!ServerInstance->Modules->PublishFeature("SQL", this))
656 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
661 queryDispatcher = new QueryThread(ServerInstance, this);
662 ServerInstance->Threads->Start(queryDispatcher);
664 ServerInstance->Modules->PublishInterface("SQL", this);
665 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
666 ServerInstance->Modules->Attach(eventlist, this, 2);
669 virtual ~ModuleMsSQL()
671 delete queryDispatcher;
673 ClearAllConnections();
675 ServerInstance->Modules->UnpublishInterface("SQL", this);
676 ServerInstance->Modules->UnpublishFeature("SQL");
677 ServerInstance->Modules->DoneWithInterface("SQLutils");
685 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
687 iter->second->SendResults();
693 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
695 iter->second->ClearResults();
699 bool HasHost(const SQLhost &host)
701 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
703 if (host == iter->second->GetConfHost())
709 bool HostInConf(const SQLhost &h)
711 ConfigReader conf(ServerInstance);
712 for(int i = 0; i < conf.Enumerate("database"); i++)
715 host.id = conf.ReadValue("database", "id", i);
716 host.host = conf.ReadValue("database", "hostname", i);
717 host.port = conf.ReadInteger("database", "port", "1433", i, true);
718 host.name = conf.ReadValue("database", "name", i);
719 host.user = conf.ReadValue("database", "username", i);
720 host.pass = conf.ReadValue("database", "password", i);
729 ClearOldConnections();
731 ConfigReader conf(ServerInstance);
732 for(int i = 0; i < conf.Enumerate("database"); i++)
736 host.id = conf.ReadValue("database", "id", i);
737 host.host = conf.ReadValue("database", "hostname", i);
738 host.port = conf.ReadInteger("database", "port", "1433", i, true);
739 host.name = conf.ReadValue("database", "name", i);
740 host.user = conf.ReadValue("database", "username", i);
741 host.pass = conf.ReadValue("database", "password", i);
750 void AddConn(const SQLhost& hi)
754 LoggingMutex->Lock();
755 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
756 LoggingMutex->Unlock();
762 newconn = new SQLConn(ServerInstance, this, hi);
764 connections.insert(std::make_pair(hi.id, newconn));
767 void ClearOldConnections()
769 ConnMap::iterator iter,safei;
770 for (iter = connections.begin(); iter != connections.end(); iter++)
772 if (!HostInConf(iter->second->GetConfHost()))
777 connections.erase(safei);
782 void ClearAllConnections()
785 while ((i = connections.begin()) != connections.end())
787 connections.erase(i);
792 virtual void OnRehash(User* user, const std::string ¶meter)
794 queryDispatcher->LockQueue();
796 queryDispatcher->UnlockQueueWakeup();
799 virtual const char* OnRequest(Request* request)
801 if(strcmp(SQLREQID, request->GetId()) == 0)
803 SQLrequest* req = (SQLrequest*)request;
805 queryDispatcher->LockQueue();
807 ConnMap::iterator iter;
809 const char* returnval = NULL;
811 if((iter = connections.find(req->dbid)) != connections.end())
814 iter->second->queue.push(*req);
815 returnval= SQLSUCCESS;
819 req->error.Id(SQL_BAD_DBID);
822 queryDispatcher->UnlockQueueWakeup();
829 unsigned long NewID()
837 virtual Version GetVersion()
839 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
844 void QueryThread::OnNotify()
849 void QueryThread::Run()
852 while (this->GetExitFlag() == false)
854 SQLConn* conn = NULL;
855 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
857 if (i->second->queue.totalsize())
866 conn->DoLeadingQuery();
867 this->NotifyParent();
873 this->WaitForQueue();
879 MODULE_INIT(ModuleMsSQL)