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)
298 return SQLerror(BAD_CONN, "Socket was NULL, check if SQL server is running.");
300 /* Pointer to the buffer we screw around with substitution in */
303 /* Pointer to the current end of query, where we append new stuff */
306 /* Total length of the unescaped parameters */
307 unsigned long paramlen;
309 /* Total length of query, used for binary-safety in mysql_real_query */
310 unsigned long querylength = 0;
313 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
315 paramlen += i->size();
318 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
319 * sizeofquery + (totalparamlength*2) + 1
321 * The +1 is for null-terminating the string
323 query = new char[req.query.q.length() + (paramlen*2) + 1];
326 for(unsigned long i = 0; i < req.query.q.length(); i++)
328 if(req.query.q[i] == '?')
330 if(req.query.p.size())
332 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
334 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
335 char* escend = escaped;
336 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
349 for (char* n = escaped; *n; n++)
355 req.query.p.pop_front();
362 *queryend = req.query.q[i];
370 MsSQLResult* res = new MsSQLResult(mod, req.GetSource(), req.id);
372 res->query = req.query.q;
374 char* msquery = strdup(req.query.q.data());
375 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
376 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
378 std::string error("failed to execute: "+std::string(req.query.q.data()));
382 return SQLerror(QSEND_FAIL, error);
388 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
390 //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
391 //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
394 case TDS_ROWFMT_RESULT:
397 case TDS_DONE_RESULT:
398 if (sock->rows_affected > -1)
400 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
406 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
408 if (tds_res != TDS_ROW_RESULT)
411 if (!sock->current_results)
414 if (sock->res_info->row_count > 0)
416 int cols = sock->res_info->num_cols;
417 char** name = new char*[MAXBUF];
418 char** data = new char*[MAXBUF];
419 for (int j=0; j<cols; j++)
421 TDSCOLUMN* col = sock->current_results->columns[j];
422 name[j] = col->column_name;
428 ctype = tds_get_conversion_type(col->column_type, col->column_size);
429 src = &(sock->current_results->current_row[col->column_offset]);
430 srclen = col->column_cur_size;
431 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
432 data[j] = (char*)dres.ib;
434 ResultReady(res, cols, data, name);
443 results.push_back(res);
448 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
450 SQLConn* sc = (SQLConn*)pContext->parent;
451 sc->Instance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
455 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
457 SQLConn* sc = (SQLConn*)pContext->parent;
458 sc->Instance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
462 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
464 res->AddRow(cols, data, colnames);
467 void AffectedReady(MsSQLResult *res)
469 res->UpdateAffectedCount();
477 cont = tds_alloc_context(this);
478 cont->msg_handler = HandleMessage;
479 cont->err_handler = HandleError;
481 login = tds_alloc_login();
482 tds_set_library(login,"TDS-Library");
483 tds_set_host(login, "");
484 tds_set_server(login, host.host.c_str());
485 tds_set_server_addr(login, host.host.c_str());
486 tds_set_user(login, host.user.c_str());
487 tds_set_passwd(login, host.pass.c_str());
488 tds_set_port(login, host.port);
489 tds_set_packet(login, 512);
491 sock = tds_alloc_socket(cont, 512);
492 conn = tds_read_config_info(NULL, login, cont->locale);
493 return tds_connect(sock, conn);
499 tds_free_login(login);
501 tds_free_socket(sock);
503 tds_free_connection(conn);
509 SQLhost GetConfHost()
516 while (results.size())
518 MsSQLResult* res = results[0];
525 /* If the client module is unloaded partway through a query then the provider will set
526 * the pointer to NULL. We cannot just cancel the query as the result will still come
527 * through at some point...and it could get messy if we play with invalid pointers...
537 while (results.size())
539 MsSQLResult* res = results[0];
548 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
550 /* crap, we're out of sockets... */
557 insp_aton("::1", &addr.sin6_addr);
558 addr.sin6_family = AF_FAMILY;
559 addr.sin6_port = htons(resultnotify->GetPort());
562 insp_aton("127.0.0.1", &ia);
563 addr.sin_family = AF_FAMILY;
565 addr.sin_port = htons(resultnotify->GetPort());
568 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
570 /* wtf, we cant connect to it, but we just created it! */
578 class ModuleMsSQL : public Module
582 unsigned long currid;
585 ModuleMsSQL(InspIRCd* Me)
586 : Module::Module(Me), currid(0)
588 ServerInstance->Modules->UseInterface("SQLutils");
590 if (!ServerInstance->Modules->PublishFeature("SQL", this))
592 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
595 resultnotify = new ResultNotifier(ServerInstance, this);
599 ServerInstance->Modules->PublishInterface("SQL", this);
600 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
601 ServerInstance->Modules->Attach(eventlist, this, 2);
604 virtual ~ModuleMsSQL()
607 ClearAllConnections();
608 resultnotify->SetFd(-1);
609 resultnotify->state = I_ERROR;
610 resultnotify->OnError(I_ERR_SOCKET);
611 resultnotify->ClosePending = true;
613 ServerInstance->Modules->UnpublishInterface("SQL", this);
614 ServerInstance->Modules->UnpublishFeature("SQL");
615 ServerInstance->Modules->DoneWithInterface("SQLutils");
621 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
623 iter->second->SendResults();
629 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
631 iter->second->ClearResults();
635 bool HasHost(const SQLhost &host)
637 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
639 if (host == iter->second->GetConfHost())
645 bool HostInConf(const SQLhost &h)
647 ConfigReader conf(ServerInstance);
648 for(int i = 0; i < conf.Enumerate("database"); i++)
651 host.id = conf.ReadValue("database", "id", i);
652 host.host = conf.ReadValue("database", "hostname", i);
653 host.port = conf.ReadInteger("database", "port", "1433", i, true);
654 host.name = conf.ReadValue("database", "name", i);
655 host.user = conf.ReadValue("database", "username", i);
656 host.pass = conf.ReadValue("database", "password", i);
665 ClearOldConnections();
667 ConfigReader conf(ServerInstance);
668 for(int i = 0; i < conf.Enumerate("database"); i++)
672 host.id = conf.ReadValue("database", "id", i);
673 host.host = conf.ReadValue("database", "hostname", i);
674 host.port = conf.ReadInteger("database", "port", "1433", i, true);
675 host.name = conf.ReadValue("database", "name", i);
676 host.user = conf.ReadValue("database", "username", i);
677 host.pass = conf.ReadValue("database", "password", i);
686 void AddConn(const SQLhost& hi)
690 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
696 newconn = new SQLConn(ServerInstance, this, hi);
698 connections.insert(std::make_pair(hi.id, newconn));
701 void ClearOldConnections()
703 ConnMap::iterator iter,safei;
704 for (iter = connections.begin(); iter != connections.end(); iter++)
706 if (!HostInConf(iter->second->GetConfHost()))
711 connections.erase(safei);
716 void ClearAllConnections()
719 while ((i = connections.begin()) != connections.end())
721 connections.erase(i);
726 virtual void OnRehash(User* user, const std::string ¶meter)
731 virtual const char* OnRequest(Request* request)
733 if(strcmp(SQLREQID, request->GetId()) == 0)
735 SQLrequest* req = (SQLrequest*)request;
736 ConnMap::iterator iter;
737 if((iter = connections.find(req->dbid)) != connections.end())
740 req->error = iter->second->Query(*req);
745 req->error.Id(BAD_DBID);
752 unsigned long NewID()
760 virtual Version GetVersion()
762 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
767 void ResultNotifier::Dispatch()
769 ((ModuleMsSQL*)mod)->SendQueue();
772 MODULE_INIT(ModuleMsSQL)