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 * ---------------------------------------------------
21 /* $ModDesc: sqlite3 provider */
22 /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
23 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
24 /* $ModDep: m_sqlv2.h */
33 typedef std::map<std::string, SQLConn*> ConnMap;
34 typedef std::deque<classbase*> paramlist;
35 typedef std::deque<SQLite3Result*> ResultQueue;
37 ResultNotifier* notifier = NULL;
38 SQLiteListener* listener = NULL;
41 class ResultNotifier : public BufferedSocket
46 ResultNotifier(ModuleSQLite3* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
50 virtual bool OnDataReady()
53 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
64 class SQLiteListener : public ListenSocketBase
66 ModuleSQLite3* Parent;
67 irc::sockets::insp_sockaddr sock_us;
72 SQLiteListener(ModuleSQLite3* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
74 uslen = sizeof(sock_us);
75 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
77 throw ModuleException("Could not getsockname() to find out port number for ITC port");
81 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
83 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
86 /* Using getsockname and ntohs, we can determine which port number we were allocated */
90 return ntohs(sock_us.sin6_port);
92 return ntohs(sock_us.sin_port);
97 class SQLite3Result : public SQLresult
104 std::vector<std::string> colnames;
105 std::vector<SQLfieldList> fieldlists;
106 SQLfieldList emptyfieldlist;
108 SQLfieldList* fieldlist;
109 SQLfieldMap* fieldmap;
112 SQLite3Result(Module* self, Module* to, unsigned int rid)
113 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
121 void AddRow(int colsnum, char **dat, char **colname)
125 for (int i = 0; i < colsnum; i++)
127 fieldlists.resize(fieldlists.size()+1);
128 colnames.push_back(colname[i]);
129 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
130 fieldlists[rows].push_back(sf);
135 void UpdateAffectedCount()
150 virtual std::string ColName(int column)
152 if (column < (int)colnames.size())
154 return colnames[column];
158 throw SQLbadColName();
163 virtual int ColNum(const std::string &column)
165 for (unsigned int i = 0; i < colnames.size(); i++)
167 if (column == colnames[i])
170 throw SQLbadColName();
174 virtual SQLfield GetValue(int row, int column)
176 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
178 return fieldlists[row][column];
181 throw SQLbadColName();
183 /* XXX: We never actually get here because of the throw */
184 return SQLfield("",true);
187 virtual SQLfieldList& GetRow()
189 if (currentrow < rows)
190 return fieldlists[currentrow];
192 return emptyfieldlist;
195 virtual SQLfieldMap& GetRowMap()
197 /* In an effort to reduce overhead we don't actually allocate the map
198 * until the first time it's needed...so...
206 fieldmap = new SQLfieldMap;
209 if (currentrow < rows)
211 for (int i = 0; i < Cols(); i++)
213 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
221 virtual SQLfieldList* GetRowPtr()
223 fieldlist = new SQLfieldList();
225 if (currentrow < rows)
227 for (int i = 0; i < Rows(); i++)
229 fieldlist->push_back(fieldlists[currentrow][i]);
236 virtual SQLfieldMap* GetRowMapPtr()
238 fieldmap = new SQLfieldMap();
240 if (currentrow < rows)
242 for (int i = 0; i < Cols(); i++)
244 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
252 virtual void Free(SQLfieldMap* fm)
257 virtual void Free(SQLfieldList* fl)
265 class SQLConn : public classbase
269 InspIRCd* ServerInstance;
275 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
276 : ServerInstance(SI), mod(m), host(hi)
278 if (OpenDB() != SQLITE_OK)
280 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
290 SQLerror Query(SQLrequest &req)
292 /* Pointer to the buffer we screw around with substitution in */
295 /* Pointer to the current end of query, where we append new stuff */
298 /* Total length of the unescaped parameters */
299 unsigned long paramlen;
301 /* Total length of query, used for binary-safety */
302 unsigned long querylength = 0;
305 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
307 paramlen += i->size();
310 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
311 * sizeofquery + (totalparamlength*2) + 1
313 * The +1 is for null-terminating the 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 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
349 res->query = req.query.q;
351 params.push_back(this);
352 params.push_back(res);
355 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
356 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
358 std::string error(errmsg);
359 sqlite3_free(errmsg);
362 return SQLerror(SQL_QSEND_FAIL, error);
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);
405 SQLhost GetConfHost()
412 while (results.size())
414 SQLite3Result* res = results[0];
421 /* If the client module is unloaded partway through a query then the provider will set
422 * the pointer to NULL. We cannot just cancel the query as the result will still come
423 * through at some point...and it could get messy if we play with invalid pointers...
433 while (results.size())
435 SQLite3Result* res = results[0];
445 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
447 /* crap, we're out of sockets... */
451 irc::sockets::insp_sockaddr addr;
454 irc::sockets::insp_aton("::1", &addr.sin6_addr);
455 addr.sin6_family = AF_FAMILY;
456 addr.sin6_port = htons(listener->GetPort());
458 irc::sockets::insp_inaddr ia;
459 irc::sockets::insp_aton("127.0.0.1", &ia);
460 addr.sin_family = AF_FAMILY;
462 addr.sin_port = htons(listener->GetPort());
465 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
467 /* wtf, we cant connect to it, but we just created it! */
472 send(QueueFD, &id, 1, 0);
478 class ModuleSQLite3 : public Module
482 unsigned long currid;
485 ModuleSQLite3(InspIRCd* Me)
486 : Module(Me), currid(0)
488 ServerInstance->Modules->UseInterface("SQLutils");
490 if (!ServerInstance->Modules->PublishFeature("SQL", this))
492 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
495 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
497 listener = new SQLiteListener(this, ServerInstance, 0, "::1");
499 listener = new SQLiteListener(this, ServerInstance, 0, "127.0.0.1");
502 if (listener->GetFd() == -1)
504 ServerInstance->Modules->DoneWithInterface("SQLutils");
505 throw ModuleException("m_sqlite3: unable to create ITC pipe");
509 ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
514 ServerInstance->Modules->PublishInterface("SQL", this);
515 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
516 ServerInstance->Modules->Attach(eventlist, this, 2);
519 virtual ~ModuleSQLite3()
522 ClearAllConnections();
524 ServerInstance->SE->DelFd(listener);
525 ServerInstance->BufferedSocketCull();
529 shutdown(QueueFD, 2);
535 ServerInstance->SE->DelFd(notifier);
537 ServerInstance->BufferedSocketCull();
540 ServerInstance->Modules->UnpublishInterface("SQL", this);
541 ServerInstance->Modules->UnpublishFeature("SQL");
542 ServerInstance->Modules->DoneWithInterface("SQLutils");
548 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
550 iter->second->SendResults();
556 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
558 iter->second->ClearResults();
562 bool HasHost(const SQLhost &host)
564 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
566 if (host == iter->second->GetConfHost())
572 bool HostInConf(const SQLhost &h)
574 ConfigReader conf(ServerInstance);
575 for(int i = 0; i < conf.Enumerate("database"); i++)
578 host.id = conf.ReadValue("database", "id", i);
579 host.host = conf.ReadValue("database", "hostname", i);
580 host.port = conf.ReadInteger("database", "port", i, true);
581 host.name = conf.ReadValue("database", "name", i);
582 host.user = conf.ReadValue("database", "username", i);
583 host.pass = conf.ReadValue("database", "password", i);
592 ClearOldConnections();
594 ConfigReader conf(ServerInstance);
595 for(int i = 0; i < conf.Enumerate("database"); i++)
599 host.id = conf.ReadValue("database", "id", i);
600 host.host = conf.ReadValue("database", "hostname", i);
601 host.port = conf.ReadInteger("database", "port", i, true);
602 host.name = conf.ReadValue("database", "name", i);
603 host.user = conf.ReadValue("database", "username", i);
604 host.pass = conf.ReadValue("database", "password", i);
613 void AddConn(const SQLhost& hi)
617 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
623 newconn = new SQLConn(ServerInstance, this, hi);
625 connections.insert(std::make_pair(hi.id, newconn));
628 void ClearOldConnections()
630 ConnMap::iterator iter,safei;
631 for (iter = connections.begin(); iter != connections.end(); iter++)
633 if (!HostInConf(iter->second->GetConfHost()))
638 connections.erase(safei);
643 void ClearAllConnections()
646 while ((i = connections.begin()) != connections.end())
648 connections.erase(i);
653 virtual void OnRehash(User* user, const std::string ¶meter)
658 virtual const char* OnRequest(Request* request)
660 if(strcmp(SQLREQID, request->GetId()) == 0)
662 SQLrequest* req = (SQLrequest*)request;
663 ConnMap::iterator iter;
664 if((iter = connections.find(req->dbid)) != connections.end())
667 req->error = iter->second->Query(*req);
672 req->error.Id(SQL_BAD_DBID);
679 unsigned long NewID()
687 virtual Version GetVersion()
689 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
694 void ResultNotifier::Dispatch()
699 MODULE_INIT(ModuleSQLite3)