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)
69 /* Using getsockname and ntohs, we can determine which port number we were allocated */
73 return ntohs(sock_us.sin6_port);
75 return ntohs(sock_us.sin_port);
79 virtual int OnIncomingConnection(int newsock, char* ip)
89 class SQLite3Result : public SQLresult
96 std::vector<std::string> colnames;
97 std::vector<SQLfieldList> fieldlists;
98 SQLfieldList emptyfieldlist;
100 SQLfieldList* fieldlist;
101 SQLfieldMap* fieldmap;
104 SQLite3Result(Module* self, Module* to, unsigned int id)
105 : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
113 void AddRow(int colsnum, char **data, char **colname)
117 for (int i = 0; i < colsnum; i++)
119 fieldlists.resize(fieldlists.size()+1);
120 colnames.push_back(colname[i]);
121 SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true);
122 fieldlists[rows].push_back(sf);
127 void UpdateAffectedCount()
142 virtual std::string ColName(int column)
144 if (column < (int)colnames.size())
146 return colnames[column];
150 throw SQLbadColName();
155 virtual int ColNum(const std::string &column)
157 for (unsigned int i = 0; i < colnames.size(); i++)
159 if (column == colnames[i])
162 throw SQLbadColName();
166 virtual SQLfield GetValue(int row, int column)
168 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
170 return fieldlists[row][column];
173 throw SQLbadColName();
175 /* XXX: We never actually get here because of the throw */
176 return SQLfield("",true);
179 virtual SQLfieldList& GetRow()
181 if (currentrow < rows)
182 return fieldlists[currentrow];
184 return emptyfieldlist;
187 virtual SQLfieldMap& GetRowMap()
189 /* In an effort to reduce overhead we don't actually allocate the map
190 * until the first time it's needed...so...
198 fieldmap = new SQLfieldMap;
201 if (currentrow < rows)
203 for (int i = 0; i < Cols(); i++)
205 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
213 virtual SQLfieldList* GetRowPtr()
215 fieldlist = new SQLfieldList();
217 if (currentrow < rows)
219 for (int i = 0; i < Rows(); i++)
221 fieldlist->push_back(fieldlists[currentrow][i]);
228 virtual SQLfieldMap* GetRowMapPtr()
230 fieldmap = new SQLfieldMap();
232 if (currentrow < rows)
234 for (int i = 0; i < Cols(); i++)
236 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
244 virtual void Free(SQLfieldMap* fm)
249 virtual void Free(SQLfieldList* fl)
257 class SQLConn : public classbase
267 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
268 : Instance(SI), mod(m), host(hi)
270 if (OpenDB() != SQLITE_OK)
272 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
282 SQLerror Query(SQLrequest &req)
284 /* Pointer to the buffer we screw around with substitution in */
287 /* Pointer to the current end of query, where we append new stuff */
290 /* Total length of the unescaped parameters */
291 unsigned long paramlen;
293 /* Total length of query, used for binary-safety in mysql_real_query */
294 unsigned long querylength = 0;
297 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
299 paramlen += i->size();
302 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
303 * sizeofquery + (totalparamlength*2) + 1
305 * The +1 is for null-terminating the string for mysql_real_escape_string
307 query = new char[req.query.q.length() + (paramlen*2) + 1];
310 for(unsigned long i = 0; i < req.query.q.length(); i++)
312 if(req.query.q[i] == '?')
314 if(req.query.p.size())
317 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
318 for (char* n = escaped; *n; n++)
323 sqlite3_free(escaped);
324 req.query.p.pop_front();
331 *queryend = req.query.q[i];
339 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
341 res->query = req.query.q;
343 params.push_back(this);
344 params.push_back(res);
347 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
348 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
350 std::string error(errmsg);
351 sqlite3_free(errmsg);
354 return SQLerror(QSEND_FAIL, error);
358 results.push_back(res);
363 static int QueryResult(void *params, int argc, char **argv, char **azColName)
365 paramlist* p = (paramlist*)params;
366 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
370 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
372 paramlist* p = (paramlist*)params;
373 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
376 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
378 res->AddRow(cols, data, colnames);
381 void AffectedReady(SQLite3Result *res)
383 res->UpdateAffectedCount();
388 return sqlite3_open(host.host.c_str(), &conn);
393 sqlite3_interrupt(conn);
397 SQLhost GetConfHost()
404 while (results.size())
406 SQLite3Result* res = results[0];
413 /* If the client module is unloaded partway through a query then the provider will set
414 * the pointer to NULL. We cannot just cancel the query as the result will still come
415 * through at some point...and it could get messy if we play with invalid pointers...
425 while (results.size())
427 SQLite3Result* res = results[0];
436 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
438 /* crap, we're out of sockets... */
445 insp_aton("::1", &addr.sin6_addr);
446 addr.sin6_family = AF_FAMILY;
447 addr.sin6_port = htons(resultnotify->GetPort());
450 insp_aton("127.0.0.1", &ia);
451 addr.sin_family = AF_FAMILY;
453 addr.sin_port = htons(resultnotify->GetPort());
456 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
458 /* wtf, we cant connect to it, but we just created it! */
466 class ModuleSQLite3 : public Module
470 unsigned long currid;
473 ModuleSQLite3(InspIRCd* Me)
474 : Module::Module(Me), currid(0)
476 ServerInstance->UseInterface("SQLutils");
478 if (!ServerInstance->PublishFeature("SQL", this))
480 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
483 resultnotify = new ResultNotifier(ServerInstance, this);
487 ServerInstance->PublishInterface("SQL", this);
490 virtual ~ModuleSQLite3()
493 ClearAllConnections();
494 resultnotify->SetFd(-1);
495 resultnotify->state = I_ERROR;
496 resultnotify->OnError(I_ERR_SOCKET);
497 resultnotify->ClosePending = true;
499 ServerInstance->UnpublishInterface("SQL", this);
500 ServerInstance->UnpublishFeature("SQL");
501 ServerInstance->DoneWithInterface("SQLutils");
504 void Implements(char* List)
506 List[I_OnRequest] = List[I_OnRehash] = 1;
511 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
513 iter->second->SendResults();
519 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
521 iter->second->ClearResults();
525 bool HasHost(const SQLhost &host)
527 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
529 if (host == iter->second->GetConfHost())
535 bool HostInConf(const SQLhost &h)
537 ConfigReader conf(ServerInstance);
538 for(int i = 0; i < conf.Enumerate("database"); i++)
541 host.id = conf.ReadValue("database", "id", i);
542 host.host = conf.ReadValue("database", "hostname", i);
543 host.port = conf.ReadInteger("database", "port", i, true);
544 host.name = conf.ReadValue("database", "name", i);
545 host.user = conf.ReadValue("database", "username", i);
546 host.pass = conf.ReadValue("database", "password", i);
547 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
556 ClearOldConnections();
558 ConfigReader conf(ServerInstance);
559 for(int i = 0; i < conf.Enumerate("database"); i++)
563 host.id = conf.ReadValue("database", "id", i);
564 host.host = conf.ReadValue("database", "hostname", i);
565 host.port = conf.ReadInteger("database", "port", i, true);
566 host.name = conf.ReadValue("database", "name", i);
567 host.user = conf.ReadValue("database", "username", i);
568 host.pass = conf.ReadValue("database", "password", i);
569 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
578 void AddConn(const SQLhost& hi)
582 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
588 newconn = new SQLConn(ServerInstance, this, hi);
590 connections.insert(std::make_pair(hi.id, newconn));
593 void ClearOldConnections()
595 ConnMap::iterator iter,safei;
596 for (iter = connections.begin(); iter != connections.end(); iter++)
598 if (!HostInConf(iter->second->GetConfHost()))
600 DELETE(iter->second);
603 connections.erase(safei);
608 void ClearAllConnections()
611 while ((i = connections.begin()) != connections.end())
613 connections.erase(i);
618 virtual void OnRehash(userrec* user, const std::string ¶meter)
623 virtual char* OnRequest(Request* request)
625 if(strcmp(SQLREQID, request->GetId()) == 0)
627 SQLrequest* req = (SQLrequest*)request;
628 ConnMap::iterator iter;
629 if((iter = connections.find(req->dbid)) != connections.end())
632 req->error = iter->second->Query(*req);
637 req->error.Id(BAD_DBID);
644 unsigned long NewID()
652 virtual Version GetVersion()
654 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
659 void ResultNotifier::Dispatch()
661 ((ModuleSQLite3*)mod)->SendQueue();
664 class ModuleSQLite3Factory : public ModuleFactory
667 ModuleSQLite3Factory()
671 ~ModuleSQLite3Factory()
675 virtual Module * CreateModule(InspIRCd* Me)
677 return new ModuleSQLite3(Me);
681 extern "C" void * init_module( void )
683 return new ModuleSQLite3Factory;