1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
23 #include "configreader.h"
27 /* $ModDesc: sqlite3 provider */
28 /* $CompileFlags: pkgconfincludes("sqlite3","/sqlite3.h","") */
29 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
30 /* $ModDep: m_sqlv2.h */
37 typedef std::map<std::string, SQLConn*> ConnMap;
38 typedef std::deque<classbase*> paramlist;
39 typedef std::deque<SQLite3Result*> ResultQueue;
41 ResultNotifier* resultnotify = NULL;
44 class ResultNotifier : public InspSocket
47 insp_sockaddr sock_us;
51 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
53 ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "::1", 0, true, 3000), mod(m)
55 ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
58 uslen = sizeof(sock_us);
59 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
61 throw ModuleException("Could not create random listening port on localhost");
65 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : InspSocket(SI, newfd, ip), mod(m)
67 Instance->Log(DEBUG,"Constructor of new socket");
70 /* Using getsockname and ntohs, we can determine which port number we were allocated */
74 return ntohs(sock_us.sin6_port);
76 return ntohs(sock_us.sin_port);
80 virtual int OnIncomingConnection(int newsock, char* ip)
82 Instance->Log(DEBUG,"Inbound connection on fd %d!",newsock);
91 class SQLite3Result : public SQLresult
98 std::vector<std::string> colnames;
99 std::vector<SQLfieldList> fieldlists;
100 SQLfieldList emptyfieldlist;
102 SQLfieldList* fieldlist;
103 SQLfieldMap* fieldmap;
106 SQLite3Result(Module* self, Module* to, unsigned int id)
107 : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
115 void AddRow(int colsnum, char **data, char **colname)
119 for (int i = 0; i < colsnum; i++)
121 fieldlists.resize(fieldlists.size()+1);
122 colnames.push_back(colname[i]);
123 SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true);
124 fieldlists[rows].push_back(sf);
139 virtual std::string ColName(int column)
141 if (column < (int)colnames.size())
143 return colnames[column];
147 throw SQLbadColName();
152 virtual int ColNum(const std::string &column)
154 for (unsigned int i = 0; i < colnames.size(); i++)
156 if (column == colnames[i])
159 throw SQLbadColName();
163 virtual SQLfield GetValue(int row, int column)
165 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
167 return fieldlists[row][column];
170 throw SQLbadColName();
172 /* XXX: We never actually get here because of the throw */
173 return SQLfield("",true);
176 virtual SQLfieldList& GetRow()
178 if (currentrow < rows)
179 return fieldlists[currentrow];
181 return emptyfieldlist;
184 virtual SQLfieldMap& GetRowMap()
186 /* In an effort to reduce overhead we don't actually allocate the map
187 * until the first time it's needed...so...
195 fieldmap = new SQLfieldMap;
198 if (currentrow < rows)
200 for (int i = 0; i < Cols(); i++)
202 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
210 virtual SQLfieldList* GetRowPtr()
212 fieldlist = new SQLfieldList();
214 if (currentrow < rows)
216 for (int i = 0; i < Rows(); i++)
218 fieldlist->push_back(fieldlists[currentrow][i]);
225 virtual SQLfieldMap* GetRowMapPtr()
227 fieldmap = new SQLfieldMap();
229 if (currentrow < rows)
231 for (int i = 0; i < Cols(); i++)
233 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
241 virtual void Free(SQLfieldMap* fm)
246 virtual void Free(SQLfieldList* fl)
254 class SQLConn : public classbase
264 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
265 : Instance(SI), mod(m), host(hi)
268 if ((result = OpenDB()) == SQLITE_OK)
270 Instance->Log(DEBUG, "Opened sqlite DB: " + host.host);
274 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
284 SQLerror Query(SQLrequest &req)
286 /* Pointer to the buffer we screw around with substitution in */
289 /* Pointer to the current end of query, where we append new stuff */
292 /* Total length of the unescaped parameters */
293 unsigned long paramlen;
295 /* Total length of query, used for binary-safety in mysql_real_query */
296 unsigned long querylength = 0;
299 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
301 paramlen += i->size();
304 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
305 * sizeofquery + (totalparamlength*2) + 1
307 * The +1 is for null-terminating the string for mysql_real_escape_string
310 query = new char[req.query.q.length() + (paramlen*2) + 1];
313 for(unsigned long i = 0; i < req.query.q.length(); i++)
315 if(req.query.q[i] == '?')
317 if(req.query.p.size())
320 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
321 for (char* n = escaped; *n; n++)
326 sqlite3_free(escaped);
327 req.query.p.pop_front();
334 *queryend = req.query.q[i];
342 // Instance->Log(DEBUG, "<******> Doing query: " + ConvToStr(req.query.q.data()));
344 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
346 res->query = req.query.q;
348 params.push_back(this);
349 params.push_back(res);
352 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
354 Instance->Log(DEBUG, "Query failed: " + ConvToStr(errmsg));
355 sqlite3_free(errmsg);
358 return SQLerror(QSEND_FAIL, ConvToStr(errmsg));
360 Instance->Log(DEBUG, "Dispatched query successfully. ID: %d resulting rows %d", req.id, res->Rows());
363 results.push_back(res);
368 static int QueryResult(void *params, int argc, char **argv, char **azColName)
370 paramlist* p = (paramlist*)params;
371 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
375 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
377 res->AddRow(cols, data, colnames);
382 return sqlite3_open(host.host.c_str(), &conn);
387 sqlite3_interrupt(conn);
391 SQLhost GetConfHost()
398 while (results.size())
400 SQLite3Result* res = results[0];
407 /* If the client module is unloaded partway through a query then the provider will set
408 * the pointer to NULL. We cannot just cancel the query as the result will still come
409 * through at some point...and it could get messy if we play with invalid pointers...
411 Instance->Log(DEBUG, "Looks like we're handling a zombie query from a module which unloaded before it got a result..fun. ID: " + ConvToStr(res->GetId()));
420 while (results.size())
422 SQLite3Result* res = results[0];
431 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
433 /* crap, we're out of sockets... */
440 insp_aton("::1", &addr.sin6_addr);
441 addr.sin6_family = AF_FAMILY;
442 addr.sin6_port = htons(resultnotify->GetPort());
445 insp_aton("127.0.0.1", &ia);
446 addr.sin_family = AF_FAMILY;
448 addr.sin_port = htons(resultnotify->GetPort());
451 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
453 /* wtf, we cant connect to it, but we just created it! */
456 send(QueueFD, "\n", 2, 0);
462 class ModuleSQLite3 : public Module
466 unsigned long currid;
469 ModuleSQLite3(InspIRCd* Me)
470 : Module::Module(Me), currid(0)
472 ServerInstance->UseInterface("SQLutils");
474 if (!ServerInstance->PublishFeature("SQL", this))
476 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
479 resultnotify = new ResultNotifier(ServerInstance, this);
480 ServerInstance->Log(DEBUG,"Bound notifier to 127.0.0.1:%d",resultnotify->GetPort());
484 ServerInstance->PublishInterface("SQL", this);
487 virtual ~ModuleSQLite3()
490 ClearAllConnections();
491 resultnotify->SetFd(-1);
492 resultnotify->state = I_ERROR;
493 resultnotify->OnError(I_ERR_SOCKET);
494 resultnotify->ClosePending = true;
495 if (!ServerInstance->SE->DelFd(resultnotify))
497 ServerInstance->Log(DEBUG, "m_sqlite3: unable to remove notifier from socket engine!");
500 ServerInstance->UnpublishInterface("SQL", this);
501 ServerInstance->UnpublishFeature("SQL");
502 ServerInstance->DoneWithInterface("SQLutils");
505 void Implements(char* List)
507 List[I_OnRequest] = List[I_OnRequest] = 1;
512 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
514 iter->second->SendResults();
520 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
522 iter->second->ClearResults();
526 bool HasHost(const SQLhost &host)
528 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
530 if (host == iter->second->GetConfHost())
536 bool HostInConf(const SQLhost &h)
538 ConfigReader conf(ServerInstance);
539 for(int i = 0; i < conf.Enumerate("database"); i++)
542 host.id = conf.ReadValue("database", "id", i);
543 host.host = conf.ReadValue("database", "hostname", i);
544 host.port = conf.ReadInteger("database", "port", i, true);
545 host.name = conf.ReadValue("database", "name", i);
546 host.user = conf.ReadValue("database", "username", i);
547 host.pass = conf.ReadValue("database", "password", i);
548 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
557 ClearOldConnections();
559 ConfigReader conf(ServerInstance);
560 for(int i = 0; i < conf.Enumerate("database"); i++)
564 host.id = conf.ReadValue("database", "id", i);
565 host.host = conf.ReadValue("database", "hostname", i);
566 host.port = conf.ReadInteger("database", "port", i, true);
567 host.name = conf.ReadValue("database", "name", i);
568 host.user = conf.ReadValue("database", "username", i);
569 host.pass = conf.ReadValue("database", "password", i);
570 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
579 void AddConn(const SQLhost& hi)
583 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
589 newconn = new SQLConn(ServerInstance, this, hi);
591 connections.insert(std::make_pair(hi.id, newconn));
594 void ClearOldConnections()
596 ConnMap::iterator iter,safei;
597 for (iter = connections.begin(); iter != connections.end(); iter++)
599 if (!HostInConf(iter->second->GetConfHost()))
601 DELETE(iter->second);
604 connections.erase(safei);
609 void ClearAllConnections()
612 while ((i = connections.begin()) != connections.end())
614 connections.erase(i);
619 virtual void OnRehash(userrec* user, const std::string ¶meter)
624 virtual char* OnRequest(Request* request)
626 if(strcmp(SQLREQID, request->GetId()) == 0)
628 SQLrequest* req = (SQLrequest*)request;
629 ConnMap::iterator iter;
630 ServerInstance->Log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
631 if((iter = connections.find(req->dbid)) != connections.end())
634 req->error = iter->second->Query(*req);
639 req->error.Id(BAD_DBID);
643 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
647 unsigned long NewID()
655 virtual Version GetVersion()
657 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
662 void ResultNotifier::Dispatch()
664 ((ModuleSQLite3*)mod)->SendQueue();
667 class ModuleSQLite3Factory : public ModuleFactory
670 ModuleSQLite3Factory()
674 ~ModuleSQLite3Factory()
678 virtual Module * CreateModule(InspIRCd* Me)
680 return new ModuleSQLite3(Me);
684 extern "C" void * init_module( void )
686 return new ModuleSQLite3Factory;