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;
36 ResultNotifier* resultdispatch = NULL;
39 class ResultNotifier : public BufferedSocket
42 insp_sockaddr sock_us;
46 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
48 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "::1", 0, true, 3000), mod(m)
50 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
53 uslen = sizeof(sock_us);
54 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
56 throw ModuleException("Could not create random listening port on localhost");
60 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
64 /* Using getsockname and ntohs, we can determine which port number we were allocated */
68 return ntohs(sock_us.sin6_port);
70 return ntohs(sock_us.sin_port);
74 virtual int OnIncomingConnection(int newsock, char* ip)
76 resultdispatch = new ResultNotifier(Instance, mod, newsock, ip);
80 virtual bool OnDataReady()
83 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
95 class MsSQLResult : public SQLresult
102 std::vector<std::string> colnames;
103 std::vector<SQLfieldList> fieldlists;
104 SQLfieldList emptyfieldlist;
106 SQLfieldList* fieldlist;
107 SQLfieldMap* fieldmap;
110 MsSQLResult(Module* self, Module* to, unsigned int rid)
111 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
119 void AddRow(int colsnum, char **dat, char **colname)
123 for (int i = 0; i < colsnum; i++)
125 fieldlists.resize(fieldlists.size()+1);
126 colnames.push_back(colname[i]);
127 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
128 fieldlists[rows].push_back(sf);
133 void UpdateAffectedCount()
148 virtual std::string ColName(int column)
150 if (column < (int)colnames.size())
152 return colnames[column];
156 throw SQLbadColName();
161 virtual int ColNum(const std::string &column)
163 for (unsigned int i = 0; i < colnames.size(); i++)
165 if (column == colnames[i])
168 throw SQLbadColName();
172 virtual SQLfield GetValue(int row, int column)
174 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
176 return fieldlists[row][column];
179 throw SQLbadColName();
181 /* XXX: We never actually get here because of the throw */
182 return SQLfield("",true);
185 virtual SQLfieldList& GetRow()
187 if (currentrow < rows)
188 return fieldlists[currentrow];
190 return emptyfieldlist;
193 virtual SQLfieldMap& GetRowMap()
195 /* In an effort to reduce overhead we don't actually allocate the map
196 * until the first time it's needed...so...
204 fieldmap = new SQLfieldMap;
207 if (currentrow < rows)
209 for (int i = 0; i < Cols(); i++)
211 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
219 virtual SQLfieldList* GetRowPtr()
221 fieldlist = new SQLfieldList();
223 if (currentrow < rows)
225 for (int i = 0; i < Rows(); i++)
227 fieldlist->push_back(fieldlists[currentrow][i]);
234 virtual SQLfieldMap* GetRowMapPtr()
236 fieldmap = new SQLfieldMap();
238 if (currentrow < rows)
240 for (int i = 0; i < Cols(); i++)
242 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
250 virtual void Free(SQLfieldMap* fm)
255 virtual void Free(SQLfieldList* fl)
263 class SQLConn : public classbase
275 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
276 : Instance(SI), mod(m), host(hi), login(NULL), sock(NULL), context(NULL)
280 std::string query("USE " + host.name);
281 if (tds_submit_query(sock, query.c_str()) == TDS_SUCCEED)
283 if (tds_process_simple_query(sock) != TDS_SUCCEED)
285 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
291 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id);
297 Instance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id);
307 SQLerror Query(SQLrequest &req)
310 return SQLerror(BAD_CONN, "Socket was NULL, check if SQL server is running.");
312 /* Pointer to the buffer we screw around with substitution in */
315 /* Pointer to the current end of query, where we append new stuff */
318 /* Total length of the unescaped parameters */
319 unsigned long paramlen;
321 /* Total length of query, used for binary-safety in mysql_real_query */
322 unsigned long querylength = 0;
325 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
327 paramlen += i->size();
330 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
331 * sizeofquery + (totalparamlength*2) + 1
333 * The +1 is for null-terminating the string
335 query = new char[req.query.q.length() + (paramlen*2) + 1];
338 for(unsigned long i = 0; i < req.query.q.length(); i++)
340 if(req.query.q[i] == '?')
342 if(req.query.p.size())
344 /* Custom escaping for this one. converting ' to '' should make SQL Server happy. Ugly but fast :]
346 char* escaped = new char[(req.query.p.front().length() * 2) + 1];
347 char* escend = escaped;
348 for (std::string::iterator p = req.query.p.front().begin(); p < req.query.p.front().end(); p++)
361 for (char* n = escaped; *n; n++)
367 req.query.p.pop_front();
374 *queryend = req.query.q[i];
382 MsSQLResult* res = new MsSQLResult(mod, req.GetSource(), req.id);
384 res->query = req.query.q;
386 char* msquery = strdup(req.query.q.data());
387 Instance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery);
388 if (tds_submit_query(sock, msquery) != TDS_SUCCEED)
390 std::string error("failed to execute: "+std::string(req.query.q.data()));
394 return SQLerror(QSEND_FAIL, error);
400 while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED)
402 //Instance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res);
403 //Instance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected);
406 case TDS_ROWFMT_RESULT:
409 case TDS_DONE_RESULT:
410 if (sock->rows_affected > -1)
412 for (int c = 0; c < sock->rows_affected; c++) res->UpdateAffectedCount();
418 while (tds_process_tokens(sock, &tds_res, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW) == TDS_SUCCEED)
420 if (tds_res != TDS_ROW_RESULT)
423 if (!sock->current_results)
426 if (sock->res_info->row_count > 0)
428 int cols = sock->res_info->num_cols;
429 char** name = new char*[MAXBUF];
430 char** data = new char*[MAXBUF];
431 for (int j=0; j<cols; j++)
433 TDSCOLUMN* col = sock->current_results->columns[j];
434 name[j] = col->column_name;
440 ctype = tds_get_conversion_type(col->column_type, col->column_size);
441 src = &(sock->current_results->current_row[col->column_offset]);
442 srclen = col->column_cur_size;
443 tds_convert(sock->tds_ctx, ctype, (TDS_CHAR *) src, srclen, SYBCHAR, &dres);
444 data[j] = (char*)dres.ib;
446 ResultReady(res, cols, data, name);
455 results.push_back(res);
460 static int HandleMessage(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
462 SQLConn* sc = (SQLConn*)pContext->parent;
463 sc->Instance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
467 static int HandleError(const TDSCONTEXT * pContext, TDSSOCKET * pTdsSocket, TDSMESSAGE * pMessage)
469 SQLConn* sc = (SQLConn*)pContext->parent;
470 sc->Instance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message);
474 void ResultReady(MsSQLResult *res, int cols, char **data, char **colnames)
476 res->AddRow(cols, data, colnames);
479 void AffectedReady(MsSQLResult *res)
481 res->UpdateAffectedCount();
488 TDSCONNECTION* conn = NULL;
490 login = tds_alloc_login();
491 tds_set_app(login, "TSQL");
492 tds_set_library(login,"TDS-Library");
493 tds_set_host(login, "");
494 tds_set_server(login, host.host.c_str());
495 tds_set_server_addr(login, host.host.c_str());
496 tds_set_user(login, host.user.c_str());
497 tds_set_passwd(login, host.pass.c_str());
498 tds_set_port(login, host.port);
499 tds_set_packet(login, 512);
501 context = tds_alloc_context(this);
502 context->msg_handler = HandleMessage;
503 context->err_handler = HandleError;
505 sock = tds_alloc_socket(context, 512);
506 tds_set_parent(sock, NULL);
508 conn = tds_read_config_info(NULL, login, context->locale);
510 if (tds_connect(sock, conn) == TDS_SUCCEED)
512 tds_free_connection(conn);
515 tds_free_connection(conn);
523 tds_free_socket(sock);
528 tds_free_context(context);
533 tds_free_login(login);
538 SQLhost GetConfHost()
545 while (results.size())
547 MsSQLResult* res = results[0];
554 /* If the client module is unloaded partway through a query then the provider will set
555 * the pointer to NULL. We cannot just cancel the query as the result will still come
556 * through at some point...and it could get messy if we play with invalid pointers...
566 while (results.size())
568 MsSQLResult* res = results[0];
578 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
580 /* crap, we're out of sockets... */
587 insp_aton("::1", &addr.sin6_addr);
588 addr.sin6_family = AF_FAMILY;
589 addr.sin6_port = htons(resultnotify->GetPort());
592 insp_aton("127.0.0.1", &ia);
593 addr.sin_family = AF_FAMILY;
595 addr.sin_port = htons(resultnotify->GetPort());
598 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
600 /* wtf, we cant connect to it, but we just created it! */
605 send(QueueFD, &id, 1, 0);
611 class ModuleMsSQL : public Module
615 unsigned long currid;
618 ModuleMsSQL(InspIRCd* Me)
619 : Module::Module(Me), currid(0)
621 ServerInstance->Modules->UseInterface("SQLutils");
623 if (!ServerInstance->Modules->PublishFeature("SQL", this))
625 throw ModuleException("m_mssql: Unable to publish feature 'SQL'");
628 resultnotify = new ResultNotifier(ServerInstance, this);
632 ServerInstance->Modules->PublishInterface("SQL", this);
633 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
634 ServerInstance->Modules->Attach(eventlist, this, 2);
637 virtual ~ModuleMsSQL()
640 ClearAllConnections();
642 ServerInstance->SE->DelFd(resultnotify);
643 resultnotify->Close();
644 ServerInstance->BufferedSocketCull();
648 shutdown(QueueFD, 2);
654 ServerInstance->SE->DelFd(resultdispatch);
655 resultdispatch->Close();
656 ServerInstance->BufferedSocketCull();
659 ServerInstance->Modules->UnpublishInterface("SQL", this);
660 ServerInstance->Modules->UnpublishFeature("SQL");
661 ServerInstance->Modules->DoneWithInterface("SQLutils");
667 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
669 iter->second->SendResults();
675 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
677 iter->second->ClearResults();
681 bool HasHost(const SQLhost &host)
683 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
685 if (host == iter->second->GetConfHost())
691 bool HostInConf(const SQLhost &h)
693 ConfigReader conf(ServerInstance);
694 for(int i = 0; i < conf.Enumerate("database"); i++)
697 host.id = conf.ReadValue("database", "id", i);
698 host.host = conf.ReadValue("database", "hostname", i);
699 host.port = conf.ReadInteger("database", "port", "1433", i, true);
700 host.name = conf.ReadValue("database", "name", i);
701 host.user = conf.ReadValue("database", "username", i);
702 host.pass = conf.ReadValue("database", "password", i);
711 ClearOldConnections();
713 ConfigReader conf(ServerInstance);
714 for(int i = 0; i < conf.Enumerate("database"); i++)
718 host.id = conf.ReadValue("database", "id", i);
719 host.host = conf.ReadValue("database", "hostname", i);
720 host.port = conf.ReadInteger("database", "port", "1433", i, true);
721 host.name = conf.ReadValue("database", "name", i);
722 host.user = conf.ReadValue("database", "username", i);
723 host.pass = conf.ReadValue("database", "password", i);
732 void AddConn(const SQLhost& hi)
736 ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
742 newconn = new SQLConn(ServerInstance, this, hi);
744 connections.insert(std::make_pair(hi.id, newconn));
747 void ClearOldConnections()
749 ConnMap::iterator iter,safei;
750 for (iter = connections.begin(); iter != connections.end(); iter++)
752 if (!HostInConf(iter->second->GetConfHost()))
757 connections.erase(safei);
762 void ClearAllConnections()
765 while ((i = connections.begin()) != connections.end())
767 connections.erase(i);
772 virtual void OnRehash(User* user, const std::string ¶meter)
777 virtual const char* OnRequest(Request* request)
779 if(strcmp(SQLREQID, request->GetId()) == 0)
781 SQLrequest* req = (SQLrequest*)request;
782 ConnMap::iterator iter;
783 if((iter = connections.find(req->dbid)) != connections.end())
786 req->error = iter->second->Query(*req);
791 req->error.Id(BAD_DBID);
798 unsigned long NewID()
806 virtual Version GetVersion()
808 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
813 void ResultNotifier::Dispatch()
815 ((ModuleMsSQL*)mod)->SendQueue();
818 MODULE_INIT(ModuleMsSQL)