1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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 /* $LinkerFlags: -ltds */
25 /* $ModDep: m_sqlv2.h */
32 typedef std::map<std::string, SQLConn*> ConnMap;
33 typedef std::deque<MsSQLResult*> ResultQueue;
35 ResultNotifier* resultnotify = NULL;
36 ResultNotifier* resultdispatch = NULL;
44 class QueryThread : public Thread
50 QueryThread(InspIRCd* si, ModuleMsSQL* mod)
51 : Thread(), Parent(mod), Instance(si)
58 class ResultNotifier : public BufferedSocket
61 insp_sockaddr sock_us;
65 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
67 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "::1", 0, true, 3000), mod(m)
69 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
72 uslen = sizeof(sock_us);
73 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
75 throw ModuleException("Could not create random listening port on localhost");
79 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
83 /* Using getsockname and ntohs, we can determine which port number we were allocated */
87 return ntohs(sock_us.sin6_port);
89 return ntohs(sock_us.sin_port);
93 virtual int OnIncomingConnection(int newsock, char* ip)
95 resultdispatch = new ResultNotifier(Instance, mod, newsock, ip);
99 virtual bool OnDataReady()
102 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
114 class MsSQLResult : public SQLresult
121 std::vector<std::string> colnames;
122 std::vector<SQLfieldList> fieldlists;
123 SQLfieldList emptyfieldlist;
125 SQLfieldList* fieldlist;
126 SQLfieldMap* fieldmap;
129 MsSQLResult(Module* self, Module* to, unsigned int rid)
130 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
138 void AddRow(int colsnum, char **dat, char **colname)
142 for (int i = 0; i < colsnum; i++)
144 fieldlists.resize(fieldlists.size()+1);
145 colnames.push_back(colname[i]);
146 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
147 fieldlists[rows].push_back(sf);
152 void UpdateAffectedCount()
167 virtual std::string ColName(int column)
169 if (column < (int)colnames.size())
171 return colnames[column];
175 throw SQLbadColName();
180 virtual int ColNum(const std::string &column)
182 for (unsigned int i = 0; i < colnames.size(); i++)
184 if (column == colnames[i])
187 throw SQLbadColName();
191 virtual SQLfield GetValue(int row, int column)
193 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
195 return fieldlists[row][column];
198 throw SQLbadColName();
200 /* XXX: We never actually get here because of the throw */
201 return SQLfield("",true);
204 virtual SQLfieldList& GetRow()
206 if (currentrow < rows)
207 return fieldlists[currentrow];
209 return emptyfieldlist;
212 virtual SQLfieldMap& GetRowMap()
214 /* In an effort to reduce overhead we don't actually allocate the map
215 * until the first time it's needed...so...
223 fieldmap = new SQLfieldMap;
226 if (currentrow < rows)
228 for (int i = 0; i < Cols(); i++)
230 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
238 virtual SQLfieldList* GetRowPtr()
240 fieldlist = new SQLfieldList();
242 if (currentrow < rows)
244 for (int i = 0; i < Rows(); i++)
246 fieldlist->push_back(fieldlists[currentrow][i]);
253 virtual SQLfieldMap* GetRowMapPtr()
255 fieldmap = new SQLfieldMap();
257 if (currentrow < rows)
259 for (int i = 0; i < Cols(); i++)
261 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
269 virtual void Free(SQLfieldMap* fm)
274 virtual void Free(SQLfieldList* fl)
282 class SQLConn : public classbase
296 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
297 : Instance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
301 std::string query("USE " + host.name);
302 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
304 if (tds_process_simple_query(sock) != TDS_SUCCEED)
306 LoggingMutex->Lock();
307 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
308 LoggingMutex->Unlock();
314 LoggingMutex->Lock();
315 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
316 LoggingMutex->Unlock();
322 LoggingMutex->Lock();
323 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
324 LoggingMutex->Unlock();
334 SQLerror Query(SQLrequest &req)
337 return SQLerror(SQL_BAD_CONN, "Socket was NULL, check if SQL server is running.");
339 /* Pointer to the buffer we screw around with substitution in */
342 /* Pointer to the current end of query, where we append new stuff */
345 /* Total length of the unescaped parameters */
346 unsigned long paramlen;
348 /* Total length of query, used for binary-safety in mysql_real_query */
349 unsigned long querylength = 0;
352 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
354 paramlen += i->size();
357 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
358 * sizeofquery + (totalparamlength*2) + 1
360 * The +1 is for null-terminating the string
362 query = new char[req.query.q.length() + (paramlen*2) + 1];
365 for(unsigned long i = 0; i < req.query.q.length(); i++)
367 if(req.query.q[i] == '?')
369 if(req.query.p.size())
371 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
373 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
374 char* escend = escaped;
375 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
388 for (char* n = escaped; *n; n++)
394 req.query.p.pop_front();
401 *queryend = req.query.q[i];
409 MsSQLResult* res = new MsSQLResult((Module*)mod, req.GetSource(), req.id);
411 res->query = req.query.q;
413 char* msquery = strdup(req.query.q.data());
414 LoggingMutex->Lock();
415 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
416 LoggingMutex->Unlock();
417 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
419 std::string error("failed to execute: "+std::string(req.query.q.data()));
423 return SQLerror(SQL_QSEND_FAIL, error);
429 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
431 //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
432 //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
435 case TDS_ROWFMT_RESULT:
438 case TDS_DONE_RESULT:
439 if (sock->rows_affected > -1)
441 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
447 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
449 if (tds_res != TDS_ROW_RESULT)
452 if (!sock->current_results)
455 if (sock->res_info->row_count > 0)
457 int cols = sock->res_info->num_cols;
458 char** name = new char*[MAXBUF];
459 char** data = new char*[MAXBUF];
460 for (int j=0; j<cols; j++)
462 TDSCOLUMN* col = sock->current_results->columns[j];
463 name[j] = col->column_name;
469 ctype = tds_get_conversion_type(col->column_type, col->column_size);
470 src = &(sock->current_results->current_row[col->column_offset]);
471 srclen = col->column_cur_size;
472 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
473 data[j] = (char*)dres.ib;
475 ResultReady(res, cols, data, name);
484 ResultsMutex->Lock();
485 results.push_back(res);
486 ResultsMutex->Unlock();
491 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
493 SQLConn* sc = (SQLConn*)pContext->parent;
494 LoggingMutex->Lock();
495 sc->Instance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
496 LoggingMutex->Unlock();
500 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
502 SQLConn* sc = (SQLConn*)pContext->parent;
503 LoggingMutex->Lock();
504 sc->Instance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
505 LoggingMutex->Unlock();
509 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
511 res->AddRow(cols, data, colnames);
514 void AffectedReady(MsSQLResult *res)
516 res->UpdateAffectedCount();
523 TDSCONNECTION* conn = NULL;
525 login = tds_alloc_login();
526 tds_set_app(login, "TSQL");
527 tds_set_library(login,"TDS-Library");
528 tds_set_host(login, "");
529 tds_set_server(login, host.host.c_str());
530 tds_set_server_addr(login, host.host.c_str());
531 tds_set_user(login, host.user.c_str());
532 tds_set_passwd(login, host.pass.c_str());
533 tds_set_port(login, host.port);
534 tds_set_packet(login, 512);
536 context = tds_alloc_context(this);
537 context->msg_handler = HandleMessage;
538 context->err_handler = HandleError;
540 sock = tds_alloc_socket(context, 512);
541 tds_set_parent(sock, NULL);
543 conn = tds_read_config_info(NULL, login, context->locale);
545 if (tds_connect(sock, conn) == TDS_SUCCEED)
547 tds_free_connection(conn);
550 tds_free_connection(conn);
558 tds_free_socket(sock);
563 tds_free_context(context);
568 tds_free_login(login);
573 SQLhost GetConfHost()
580 while (results.size())
582 MsSQLResult* res = results[0];
583 ResultsMutex->Lock();
590 /* If the client module is unloaded partway through a query then the provider will set
591 * the pointer to NULL. We cannot just cancel the query as the result will still come
592 * through at some point...and it could get messy if we play with invalid pointers...
597 ResultsMutex->Unlock();
603 while (results.size())
605 MsSQLResult* res = results[0];
615 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
617 /* crap, we're out of sockets... */
624 insp_aton("::1", &addr.sin6_addr);
625 addr.sin6_family = AF_FAMILY;
626 addr.sin6_port = htons(resultnotify->GetPort());
629 insp_aton("127.0.0.1", &ia);
630 addr.sin_family = AF_FAMILY;
632 addr.sin_port = htons(resultnotify->GetPort());
635 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
637 /* wtf, we cant connect to it, but we just created it! */
642 send(QueueFD, &id, 1, 0);
645 void DoLeadingQuery()
647 SQLrequest& req = queue.front();
648 req.error = Query(req);
654 class ModuleMsSQL : public Module
657 unsigned long currid;
658 QueryThread* Dispatcher;
661 ModuleMsSQL(InspIRCd* Me)
662 : Module(Me), currid(0)
664 LoggingMutex = ServerInstance->Mutexes->CreateMutex();
665 ResultsMutex = ServerInstance->Mutexes->CreateMutex();
666 QueueMutex = ServerInstance->Mutexes->CreateMutex();
668 ServerInstance->Modules->UseInterface("SQLutils");
670 if (!ServerInstance->Modules->PublishFeature("SQL", this))
672 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
675 resultnotify = new ResultNotifier(ServerInstance, this);
679 Dispatcher = new QueryThread(ServerInstance, this);
680 ServerInstance->Threads->Create(Dispatcher);
682 ServerInstance->Modules->PublishInterface("SQL", this);
683 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
684 ServerInstance->Modules->Attach(eventlist, this, 2);
687 virtual ~ModuleMsSQL()
691 ClearAllConnections();
693 ServerInstance->SE->DelFd(resultnotify);
694 resultnotify->Close();
695 ServerInstance->BufferedSocketCull();
699 shutdown(QueueFD, 2);
705 ServerInstance->SE->DelFd(resultdispatch);
706 resultdispatch->Close();
707 ServerInstance->BufferedSocketCull();
710 ServerInstance->Modules->UnpublishInterface("SQL", this);
711 ServerInstance->Modules->UnpublishFeature("SQL");
712 ServerInstance->Modules->DoneWithInterface("SQLutils");
722 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
724 iter->second->SendResults();
730 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
732 iter->second->ClearResults();
736 bool HasHost(const SQLhost &host)
738 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
740 if (host == iter->second->GetConfHost())
746 bool HostInConf(const SQLhost &h)
748 ConfigReader conf(ServerInstance);
749 for(int i = 0; i < conf.Enumerate("database"); i++)
752 host.id = conf.ReadValue("database", "id", i);
753 host.host = conf.ReadValue("database", "hostname", i);
754 host.port = conf.ReadInteger("database", "port", "1433", i, true);
755 host.name = conf.ReadValue("database", "name", i);
756 host.user = conf.ReadValue("database", "username", i);
757 host.pass = conf.ReadValue("database", "password", i);
766 ClearOldConnections();
768 ConfigReader conf(ServerInstance);
769 for(int i = 0; i < conf.Enumerate("database"); i++)
773 host.id = conf.ReadValue("database", "id", i);
774 host.host = conf.ReadValue("database", "hostname", i);
775 host.port = conf.ReadInteger("database", "port", "1433", i, true);
776 host.name = conf.ReadValue("database", "name", i);
777 host.user = conf.ReadValue("database", "username", i);
778 host.pass = conf.ReadValue("database", "password", i);
787 void AddConn(const SQLhost& hi)
791 LoggingMutex->Lock();
792 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
793 LoggingMutex->Unlock();
799 newconn = new SQLConn(ServerInstance, this, hi);
801 connections.insert(std::make_pair(hi.id, newconn));
804 void ClearOldConnections()
806 ConnMap::iterator iter,safei;
807 for (iter = connections.begin(); iter != connections.end(); iter++)
809 if (!HostInConf(iter->second->GetConfHost()))
814 connections.erase(safei);
819 void ClearAllConnections()
822 while ((i = connections.begin()) != connections.end())
824 connections.erase(i);
829 virtual void OnRehash(User* user, const std::string ¶meter)
833 QueueMutex->Unlock();
836 virtual const char* OnRequest(Request* request)
838 if(strcmp(SQLREQID, request->GetId()) == 0)
840 SQLrequest* req = (SQLrequest*)request;
844 ConnMap::iterator iter;
846 const char* returnval = NULL;
848 if((iter = connections.find(req->dbid)) != connections.end())
851 iter->second->queue.push(*req);
852 returnval= SQLSUCCESS;
856 req->error.Id(SQL_BAD_DBID);
859 QueueMutex->Unlock();
866 unsigned long NewID()
874 virtual Version GetVersion()
876 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
881 void ResultNotifier::Dispatch()
883 ((ModuleMsSQL*)mod)->SendQueue();
886 void QueryThread::Run()
888 while (this->GetExitFlag() == false)
890 SQLConn* conn = NULL;
892 for (ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
894 if (i->second->queue.totalsize())
900 QueueMutex->Unlock();
903 conn->DoLeadingQuery();
906 QueueMutex->Unlock();
912 MODULE_INIT(ModuleMsSQL)