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)
272 if (OpenDB() == SQLITE_OK)
274 Instance->Log(DEBUG, "Opened sqlite DB: " + host.host);
278 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
288 SQLerror Query(SQLrequest &req)
290 /* Pointer to the buffer we screw around with substitution in */
293 /* Pointer to the current end of query, where we append new stuff */
296 /* Total length of the unescaped parameters */
297 unsigned long paramlen;
299 /* Total length of query, used for binary-safety in mysql_real_query */
300 unsigned long querylength = 0;
303 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
305 paramlen += i->size();
308 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
309 * sizeofquery + (totalparamlength*2) + 1
311 * The +1 is for null-terminating the string for mysql_real_escape_string
313 query = new char[req.query.q.length() + (paramlen*2) + 1];
316 for(unsigned long i = 0; i < req.query.q.length(); i++)
318 if(req.query.q[i] == '?')
320 if(req.query.p.size())
323 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
324 for (char* n = escaped; *n; n++)
329 sqlite3_free(escaped);
330 req.query.p.pop_front();
337 *queryend = req.query.q[i];
345 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
347 res->query = req.query.q;
349 params.push_back(this);
350 params.push_back(res);
353 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
354 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
356 std::string error(errmsg);
357 sqlite3_free(errmsg);
358 Instance->Log(DEBUG, "Query failed: " + ConvToStr(errmsg));
361 return SQLerror(QSEND_FAIL, error);
363 Instance->Log(DEBUG, "Dispatched query successfully. ID: %d resulting rows %d", req.id, res->Rows());
366 results.push_back(res);
371 static int QueryResult(void *params, int argc, char **argv, char **azColName)
373 paramlist* p = (paramlist*)params;
374 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
378 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
380 paramlist* p = (paramlist*)params;
381 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
384 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
386 res->AddRow(cols, data, colnames);
389 void AffectedReady(SQLite3Result *res)
391 res->UpdateAffectedCount();
396 return sqlite3_open(host.host.c_str(), &conn);
401 sqlite3_interrupt(conn);
403 Instance->Log(DEBUG, "Closed sqlite DB: " + host.host);
406 SQLhost GetConfHost()
413 while (results.size())
415 SQLite3Result* res = results[0];
422 /* If the client module is unloaded partway through a query then the provider will set
423 * the pointer to NULL. We cannot just cancel the query as the result will still come
424 * through at some point...and it could get messy if we play with invalid pointers...
426 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()));
435 while (results.size())
437 SQLite3Result* res = results[0];
446 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
448 /* crap, we're out of sockets... */
455 insp_aton("::1", &addr.sin6_addr);
456 addr.sin6_family = AF_FAMILY;
457 addr.sin6_port = htons(resultnotify->GetPort());
460 insp_aton("127.0.0.1", &ia);
461 addr.sin_family = AF_FAMILY;
463 addr.sin_port = htons(resultnotify->GetPort());
466 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
468 /* wtf, we cant connect to it, but we just created it! */
476 class ModuleSQLite3 : public Module
480 unsigned long currid;
483 ModuleSQLite3(InspIRCd* Me)
484 : Module::Module(Me), currid(0)
486 ServerInstance->UseInterface("SQLutils");
488 if (!ServerInstance->PublishFeature("SQL", this))
490 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
493 resultnotify = new ResultNotifier(ServerInstance, this);
494 ServerInstance->Log(DEBUG,"Bound notifier to 127.0.0.1:%d",resultnotify->GetPort());
498 ServerInstance->PublishInterface("SQL", this);
501 virtual ~ModuleSQLite3()
504 ClearAllConnections();
505 resultnotify->SetFd(-1);
506 resultnotify->state = I_ERROR;
507 resultnotify->OnError(I_ERR_SOCKET);
508 resultnotify->ClosePending = true;
510 ServerInstance->UnpublishInterface("SQL", this);
511 ServerInstance->UnpublishFeature("SQL");
512 ServerInstance->DoneWithInterface("SQLutils");
515 void Implements(char* List)
517 List[I_OnRequest] = List[I_OnRehash] = 1;
522 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
524 iter->second->SendResults();
530 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
532 iter->second->ClearResults();
536 bool HasHost(const SQLhost &host)
538 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
540 if (host == iter->second->GetConfHost())
546 bool HostInConf(const SQLhost &h)
548 ConfigReader conf(ServerInstance);
549 for(int i = 0; i < conf.Enumerate("database"); i++)
552 host.id = conf.ReadValue("database", "id", i);
553 host.host = conf.ReadValue("database", "hostname", i);
554 host.port = conf.ReadInteger("database", "port", i, true);
555 host.name = conf.ReadValue("database", "name", i);
556 host.user = conf.ReadValue("database", "username", i);
557 host.pass = conf.ReadValue("database", "password", i);
558 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
567 ClearOldConnections();
569 ConfigReader conf(ServerInstance);
570 for(int i = 0; i < conf.Enumerate("database"); i++)
574 host.id = conf.ReadValue("database", "id", i);
575 host.host = conf.ReadValue("database", "hostname", i);
576 host.port = conf.ReadInteger("database", "port", i, true);
577 host.name = conf.ReadValue("database", "name", i);
578 host.user = conf.ReadValue("database", "username", i);
579 host.pass = conf.ReadValue("database", "password", i);
580 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
589 void AddConn(const SQLhost& hi)
593 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
599 newconn = new SQLConn(ServerInstance, this, hi);
601 connections.insert(std::make_pair(hi.id, newconn));
604 void ClearOldConnections()
606 ConnMap::iterator iter,safei;
607 for (iter = connections.begin(); iter != connections.end(); iter++)
609 if (!HostInConf(iter->second->GetConfHost()))
611 DELETE(iter->second);
614 connections.erase(safei);
619 void ClearAllConnections()
622 while ((i = connections.begin()) != connections.end())
624 connections.erase(i);
629 virtual void OnRehash(userrec* user, const std::string ¶meter)
634 virtual char* OnRequest(Request* request)
636 if(strcmp(SQLREQID, request->GetId()) == 0)
638 SQLrequest* req = (SQLrequest*)request;
639 ConnMap::iterator iter;
640 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());
641 if((iter = connections.find(req->dbid)) != connections.end())
644 req->error = iter->second->Query(*req);
649 req->error.Id(BAD_DBID);
653 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
657 unsigned long NewID()
665 virtual Version GetVersion()
667 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
672 void ResultNotifier::Dispatch()
674 ((ModuleSQLite3*)mod)->SendQueue();
677 class ModuleSQLite3Factory : public ModuleFactory
680 ModuleSQLite3Factory()
684 ~ModuleSQLite3Factory()
688 virtual Module * CreateModule(InspIRCd* Me)
690 return new ModuleSQLite3(Me);
694 extern "C" void * init_module( void )
696 return new ModuleSQLite3Factory;