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);
129 void UpdateAffectedCount()
144 virtual std::string ColName(int column)
146 if (column < (int)colnames.size())
148 return colnames[column];
152 throw SQLbadColName();
157 virtual int ColNum(const std::string &column)
159 for (unsigned int i = 0; i < colnames.size(); i++)
161 if (column == colnames[i])
164 throw SQLbadColName();
168 virtual SQLfield GetValue(int row, int column)
170 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
172 return fieldlists[row][column];
175 throw SQLbadColName();
177 /* XXX: We never actually get here because of the throw */
178 return SQLfield("",true);
181 virtual SQLfieldList& GetRow()
183 if (currentrow < rows)
184 return fieldlists[currentrow];
186 return emptyfieldlist;
189 virtual SQLfieldMap& GetRowMap()
191 /* In an effort to reduce overhead we don't actually allocate the map
192 * until the first time it's needed...so...
200 fieldmap = new SQLfieldMap;
203 if (currentrow < rows)
205 for (int i = 0; i < Cols(); i++)
207 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
215 virtual SQLfieldList* GetRowPtr()
217 fieldlist = new SQLfieldList();
219 if (currentrow < rows)
221 for (int i = 0; i < Rows(); i++)
223 fieldlist->push_back(fieldlists[currentrow][i]);
230 virtual SQLfieldMap* GetRowMapPtr()
232 fieldmap = new SQLfieldMap();
234 if (currentrow < rows)
236 for (int i = 0; i < Cols(); i++)
238 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
246 virtual void Free(SQLfieldMap* fm)
251 virtual void Free(SQLfieldList* fl)
259 class SQLConn : public classbase
269 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
270 : Instance(SI), mod(m), host(hi)
273 if ((result = OpenDB()) == SQLITE_OK)
275 Instance->Log(DEBUG, "Opened sqlite DB: " + host.host);
279 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
289 SQLerror Query(SQLrequest &req)
291 /* Pointer to the buffer we screw around with substitution in */
294 /* Pointer to the current end of query, where we append new stuff */
297 /* Total length of the unescaped parameters */
298 unsigned long paramlen;
300 /* Total length of query, used for binary-safety in mysql_real_query */
301 unsigned long querylength = 0;
304 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
306 paramlen += i->size();
309 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
310 * sizeofquery + (totalparamlength*2) + 1
312 * The +1 is for null-terminating the string for mysql_real_escape_string
315 query = new char[req.query.q.length() + (paramlen*2) + 1];
318 for(unsigned long i = 0; i < req.query.q.length(); i++)
320 if(req.query.q[i] == '?')
322 if(req.query.p.size())
325 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
326 for (char* n = escaped; *n; n++)
331 sqlite3_free(escaped);
332 req.query.p.pop_front();
339 *queryend = req.query.q[i];
347 //Instance->Log(DEBUG, "<******> Doing query: " + ConvToStr(req.query.q.data()));
348 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
350 res->query = req.query.q;
352 params.push_back(this);
353 params.push_back(res);
356 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
357 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
359 Instance->Log(DEBUG, "Query failed: " + ConvToStr(errmsg));
360 sqlite3_free(errmsg);
363 return SQLerror(QSEND_FAIL, ConvToStr(errmsg));
365 Instance->Log(DEBUG, "Dispatched query successfully. ID: %d resulting rows %d", req.id, res->Rows());
368 results.push_back(res);
373 static int QueryResult(void *params, int argc, char **argv, char **azColName)
375 paramlist* p = (paramlist*)params;
376 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
380 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
382 paramlist* p = (paramlist*)params;
383 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
386 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
388 res->AddRow(cols, data, colnames);
391 void AffectedReady(SQLite3Result *res)
393 res->UpdateAffectedCount();
398 return sqlite3_open(host.host.c_str(), &conn);
403 sqlite3_interrupt(conn);
405 Instance->Log(DEBUG, "Closed sqlite DB: " + host.host);
408 SQLhost GetConfHost()
415 while (results.size())
417 SQLite3Result* res = results[0];
424 /* If the client module is unloaded partway through a query then the provider will set
425 * the pointer to NULL. We cannot just cancel the query as the result will still come
426 * through at some point...and it could get messy if we play with invalid pointers...
428 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()));
437 while (results.size())
439 SQLite3Result* res = results[0];
448 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
450 /* crap, we're out of sockets... */
457 insp_aton("::1", &addr.sin6_addr);
458 addr.sin6_family = AF_FAMILY;
459 addr.sin6_port = htons(resultnotify->GetPort());
462 insp_aton("127.0.0.1", &ia);
463 addr.sin_family = AF_FAMILY;
465 addr.sin_port = htons(resultnotify->GetPort());
468 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
470 /* wtf, we cant connect to it, but we just created it! */
478 class ModuleSQLite3 : public Module
482 unsigned long currid;
485 ModuleSQLite3(InspIRCd* Me)
486 : Module::Module(Me), currid(0)
488 ServerInstance->UseInterface("SQLutils");
490 if (!ServerInstance->PublishFeature("SQL", this))
492 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
495 resultnotify = new ResultNotifier(ServerInstance, this);
496 ServerInstance->Log(DEBUG,"Bound notifier to 127.0.0.1:%d",resultnotify->GetPort());
500 ServerInstance->PublishInterface("SQL", this);
503 virtual ~ModuleSQLite3()
506 ClearAllConnections();
507 resultnotify->SetFd(-1);
508 resultnotify->state = I_ERROR;
509 resultnotify->OnError(I_ERR_SOCKET);
510 resultnotify->ClosePending = true;
512 ServerInstance->UnpublishInterface("SQL", this);
513 ServerInstance->UnpublishFeature("SQL");
514 ServerInstance->DoneWithInterface("SQLutils");
517 void Implements(char* List)
519 List[I_OnRequest] = List[I_OnRehash] = 1;
524 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
526 iter->second->SendResults();
532 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
534 iter->second->ClearResults();
538 bool HasHost(const SQLhost &host)
540 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
542 if (host == iter->second->GetConfHost())
548 bool HostInConf(const SQLhost &h)
550 ConfigReader conf(ServerInstance);
551 for(int i = 0; i < conf.Enumerate("database"); i++)
554 host.id = conf.ReadValue("database", "id", i);
555 host.host = conf.ReadValue("database", "hostname", i);
556 host.port = conf.ReadInteger("database", "port", i, true);
557 host.name = conf.ReadValue("database", "name", i);
558 host.user = conf.ReadValue("database", "username", i);
559 host.pass = conf.ReadValue("database", "password", i);
560 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
569 ClearOldConnections();
571 ConfigReader conf(ServerInstance);
572 for(int i = 0; i < conf.Enumerate("database"); i++)
576 host.id = conf.ReadValue("database", "id", i);
577 host.host = conf.ReadValue("database", "hostname", i);
578 host.port = conf.ReadInteger("database", "port", i, true);
579 host.name = conf.ReadValue("database", "name", i);
580 host.user = conf.ReadValue("database", "username", i);
581 host.pass = conf.ReadValue("database", "password", i);
582 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
591 void AddConn(const SQLhost& hi)
595 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
601 newconn = new SQLConn(ServerInstance, this, hi);
603 connections.insert(std::make_pair(hi.id, newconn));
606 void ClearOldConnections()
608 ConnMap::iterator iter,safei;
609 for (iter = connections.begin(); iter != connections.end(); iter++)
611 if (!HostInConf(iter->second->GetConfHost()))
613 DELETE(iter->second);
616 connections.erase(safei);
621 void ClearAllConnections()
624 while ((i = connections.begin()) != connections.end())
626 connections.erase(i);
631 virtual void OnRehash(userrec* user, const std::string ¶meter)
636 virtual char* OnRequest(Request* request)
638 if(strcmp(SQLREQID, request->GetId()) == 0)
640 SQLrequest* req = (SQLrequest*)request;
641 ConnMap::iterator iter;
642 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());
643 if((iter = connections.find(req->dbid)) != connections.end())
646 req->error = iter->second->Query(*req);
651 req->error.Id(BAD_DBID);
655 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
659 unsigned long NewID()
667 virtual Version GetVersion()
669 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
674 void ResultNotifier::Dispatch()
676 ((ModuleSQLite3*)mod)->SendQueue();
679 class ModuleSQLite3Factory : public ModuleFactory
682 ModuleSQLite3Factory()
686 ~ModuleSQLite3Factory()
690 virtual Module * CreateModule(InspIRCd* Me)
692 return new ModuleSQLite3(Me);
696 extern "C" void * init_module( void )
698 return new ModuleSQLite3Factory;