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 */
31 typedef std::map<std::string, SQLConn*> ConnMap;
32 typedef std::deque<classbase*> paramlist;
33 typedef std::deque<MsSQLResult*> ResultQueue;
35 ResultNotifier* resultnotify = NULL;
38 class ResultNotifier : public BufferedSocket
41 insp_sockaddr sock_us;
45 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
47 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "::1", 0, true, 3000), mod(m)
49 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
52 uslen = sizeof(sock_us);
53 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
55 throw ModuleException("Could not create random listening port on localhost");
59 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
63 /* Using getsockname and ntohs, we can determine which port number we were allocated */
67 return ntohs(sock_us.sin6_port);
69 return ntohs(sock_us.sin_port);
73 virtual int OnIncomingConnection(int newsock, char* ip)
83 class MsSQLResult : public SQLresult
90 std::vector<std::string> colnames;
91 std::vector<SQLfieldList> fieldlists;
92 SQLfieldList emptyfieldlist;
94 SQLfieldList* fieldlist;
95 SQLfieldMap* fieldmap;
98 MsSQLResult(Module* self, Module* to, unsigned int rid)
99 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
107 void AddRow(int colsnum, char **dat, char **colname)
111 for (int i = 0; i < colsnum; i++)
113 fieldlists.resize(fieldlists.size()+1);
114 colnames.push_back(colname[i]);
115 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
116 fieldlists[rows].push_back(sf);
121 void UpdateAffectedCount()
136 virtual std::string ColName(int column)
138 if (column < (int)colnames.size())
140 return colnames[column];
144 throw SQLbadColName();
149 virtual int ColNum(const std::string &column)
151 for (unsigned int i = 0; i < colnames.size(); i++)
153 if (column == colnames[i])
156 throw SQLbadColName();
160 virtual SQLfield GetValue(int row, int column)
162 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
164 return fieldlists[row][column];
167 throw SQLbadColName();
169 /* XXX: We never actually get here because of the throw */
170 return SQLfield("",true);
173 virtual SQLfieldList& GetRow()
175 if (currentrow < rows)
176 return fieldlists[currentrow];
178 return emptyfieldlist;
181 virtual SQLfieldMap& GetRowMap()
183 /* In an effort to reduce overhead we don't actually allocate the map
184 * until the first time it's needed...so...
192 fieldmap = new SQLfieldMap;
195 if (currentrow < rows)
197 for (int i = 0; i < Cols(); i++)
199 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
207 virtual SQLfieldList* GetRowPtr()
209 fieldlist = new SQLfieldList();
211 if (currentrow < rows)
213 for (int i = 0; i < Rows(); i++)
215 fieldlist->push_back(fieldlists[currentrow][i]);
222 virtual SQLfieldMap* GetRowMapPtr()
224 fieldmap = new SQLfieldMap();
226 if (currentrow < rows)
228 for (int i = 0; i < Cols(); i++)
230 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
238 virtual void Free(SQLfieldMap* fm)
243 virtual void Free(SQLfieldList* fl)
251 class SQLConn : public classbase
263 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
264 : Instance(SI), mod(m), host(hi)
266 if (OpenDB() == TDS_SUCCEED)
268 std::string query("USE " + host.name);
269 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
271 if (tds_process_simple_query(sock) != TDS_SUCCEED)
273 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
279 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
285 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
295 SQLerror Query(SQLrequest &req)
297 /* Pointer to the buffer we screw around with substitution in */
300 /* Pointer to the current end of query, where we append new stuff */
303 /* Total length of the unescaped parameters */
304 unsigned long paramlen;
306 /* Total length of query, used for binary-safety in mysql_real_query */
307 unsigned long querylength = 0;
310 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
312 paramlen += i->size();
315 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
316 * sizeofquery + (totalparamlength*2) + 1
318 * The +1 is for null-terminating the string
320 query = new char[req.query.q.length() + (paramlen*2) + 1];
323 for(unsigned long i = 0; i < req.query.q.length(); i++)
325 if(req.query.q[i] == '?')
327 if(req.query.p.size())
329 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
331 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
332 char* escend = escaped;
333 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
346 for (char* n = escaped; *n; n++)
352 req.query.p.pop_front();
359 *queryend = req.query.q[i];
367 MsSQLResult* res = new MsSQLResult(mod, req.GetSource(), req.id);
369 res->query = req.query.q;
371 char* msquery = strdup(req.query.q.data());
372 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
373 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
375 std::string error("failed to execute: "+std::string(req.query.q.data()));
379 return SQLerror(QSEND_FAIL, error);
385 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
387 //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
388 //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
391 case TDS_ROWFMT_RESULT:
394 case TDS_DONE_RESULT:
395 if (sock->rows_affected > -1)
397 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
403 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
405 if (tds_res != TDS_ROW_RESULT)
408 if (!sock->current_results)
411 if (sock->res_info->row_count > 0)
413 int cols = sock->res_info->num_cols;
414 char** name = new char*[MAXBUF];
415 char** data = new char*[MAXBUF];
416 for (int j=0; j<cols; j++)
418 TDSCOLUMN* col = sock->current_results->columns[j];
419 name[j] = col->column_name;
425 ctype = tds_get_conversion_type(col->column_type, col->column_size);
426 src = &(sock->current_results->current_row[col->column_offset]);
427 srclen = col->column_cur_size;
428 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
429 data[j] = (char*)dres.ib;
431 ResultReady(res, cols, data, name);
440 results.push_back(res);
445 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
448 //Instance->Logs->Log("m_mssql",DEBUG,pMessage->message);
449 //printf("Message: %s\n", pMessage->message);
453 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
456 //Instance->Logs->Log("m_mssql",DEBUG,pMessage->message);
457 //printf("Error: %s\n", pMessage->message);
461 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
463 res->AddRow(cols, data, colnames);
466 void AffectedReady(MsSQLResult *res)
468 res->UpdateAffectedCount();
476 cont = tds_alloc_context(NULL);
477 cont->msg_handler = HandleMessage;
478 cont->err_handler = HandleError;
480 login = tds_alloc_login();
481 tds_set_library(login,"TDS-Library");
482 tds_set_host(login, "");
483 tds_set_server(login, host.host.c_str());
484 tds_set_server_addr(login, host.host.c_str());
485 tds_set_user(login, host.user.c_str());
486 tds_set_passwd(login, host.pass.c_str());
487 tds_set_port(login, host.port);
488 tds_set_packet(login, 512);
490 sock = tds_alloc_socket(cont, 512);
491 conn = tds_read_config_info(NULL, login, cont->locale);
492 return tds_connect(sock, conn);
498 tds_free_login(login);
500 tds_free_socket(sock);
502 tds_free_connection(conn);
505 SQLhost GetConfHost()
512 while (results.size())
514 MsSQLResult* res = results[0];
521 /* If the client module is unloaded partway through a query then the provider will set
522 * the pointer to NULL. We cannot just cancel the query as the result will still come
523 * through at some point...and it could get messy if we play with invalid pointers...
533 while (results.size())
535 MsSQLResult* res = results[0];
544 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
546 /* crap, we're out of sockets... */
553 insp_aton("::1", &addr.sin6_addr);
554 addr.sin6_family = AF_FAMILY;
555 addr.sin6_port = htons(resultnotify->GetPort());
558 insp_aton("127.0.0.1", &ia);
559 addr.sin_family = AF_FAMILY;
561 addr.sin_port = htons(resultnotify->GetPort());
564 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
566 /* wtf, we cant connect to it, but we just created it! */
574 class ModuleMsSQL : public Module
578 unsigned long currid;
581 ModuleMsSQL(InspIRCd* Me)
582 : Module::Module(Me), currid(0)
584 ServerInstance->Modules->UseInterface("SQLutils");
586 if (!ServerInstance->Modules->PublishFeature("SQL", this))
588 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
591 resultnotify = new ResultNotifier(ServerInstance, this);
595 ServerInstance->Modules->PublishInterface("SQL", this);
596 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
597 ServerInstance->Modules->Attach(eventlist, this, 2);
600 virtual ~ModuleMsSQL()
603 ClearAllConnections();
604 resultnotify->SetFd(-1);
605 resultnotify->state = I_ERROR;
606 resultnotify->OnError(I_ERR_SOCKET);
607 resultnotify->ClosePending = true;
609 ServerInstance->Modules->UnpublishInterface("SQL", this);
610 ServerInstance->Modules->UnpublishFeature("SQL");
611 ServerInstance->Modules->DoneWithInterface("SQLutils");
617 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
619 iter->second->SendResults();
625 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
627 iter->second->ClearResults();
631 bool HasHost(const SQLhost &host)
633 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
635 if (host == iter->second->GetConfHost())
641 bool HostInConf(const SQLhost &h)
643 ConfigReader conf(ServerInstance);
644 for(int i = 0; i < conf.Enumerate("database"); i++)
647 host.id = conf.ReadValue("database", "id", i);
648 host.host = conf.ReadValue("database", "hostname", i);
649 host.port = conf.ReadInteger("database", "port", "1433", i, true);
650 host.name = conf.ReadValue("database", "name", i);
651 host.user = conf.ReadValue("database", "username", i);
652 host.pass = conf.ReadValue("database", "password", i);
653 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
662 ClearOldConnections();
664 ConfigReader conf(ServerInstance);
665 for(int i = 0; i < conf.Enumerate("database"); i++)
669 host.id = conf.ReadValue("database", "id", i);
670 host.host = conf.ReadValue("database", "hostname", i);
671 host.port = conf.ReadInteger("database", "port", "1433", i, true);
672 host.name = conf.ReadValue("database", "name", i);
673 host.user = conf.ReadValue("database", "username", i);
674 host.pass = conf.ReadValue("database", "password", i);
675 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
684 void AddConn(const SQLhost& hi)
688 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
694 newconn = new SQLConn(ServerInstance, this, hi);
696 connections.insert(std::make_pair(hi.id, newconn));
699 void ClearOldConnections()
701 ConnMap::iterator iter,safei;
702 for (iter = connections.begin(); iter != connections.end(); iter++)
704 if (!HostInConf(iter->second->GetConfHost()))
709 connections.erase(safei);
714 void ClearAllConnections()
717 while ((i = connections.begin()) != connections.end())
719 connections.erase(i);
724 virtual void OnRehash(User* user, const std::string ¶meter)
729 virtual const char* OnRequest(Request* request)
731 if(strcmp(SQLREQID, request->GetId()) == 0)
733 SQLrequest* req = (SQLrequest*)request;
734 ConnMap::iterator iter;
735 if((iter = connections.find(req->dbid)) != connections.end())
738 req->error = iter->second->Query(*req);
743 req->error.Id(BAD_DBID);
750 unsigned long NewID()
758 virtual Version GetVersion()
760 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
765 void ResultNotifier::Dispatch()
767 ((ModuleMsSQL*)mod)->SendQueue();
770 MODULE_INIT(ModuleMsSQL)