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 * ---------------------------------------------------
18 /* $ModDesc: sqlite3 provider */
19 /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
20 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
21 /* $ModDep: m_sqlv2.h */
30 typedef std::map<std::string, SQLConn*> ConnMap;
31 typedef std::deque<classbase*> paramlist;
32 typedef std::deque<SQLite3Result*> ResultQueue;
34 ResultNotifier* notifier = NULL;
35 SQLiteListener* listener = NULL;
38 class ResultNotifier : public BufferedSocket
43 ResultNotifier(ModuleSQLite3* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
47 virtual bool OnDataReady()
50 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
61 class SQLiteListener : public ListenSocketBase
63 ModuleSQLite3* Parent;
64 irc::sockets::insp_sockaddr sock_us;
69 SQLiteListener(ModuleSQLite3* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
71 uslen = sizeof(sock_us);
72 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
74 throw ModuleException("Could not getsockname() to find out port number for ITC port");
78 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
80 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
83 /* Using getsockname and ntohs, we can determine which port number we were allocated */
87 return ntohs(sock_us.sin6_port);
89 return ntohs(sock_us.sin_port);
94 class SQLite3Result : public SQLresult
101 std::vector<std::string> colnames;
102 std::vector<SQLfieldList> fieldlists;
103 SQLfieldList emptyfieldlist;
105 SQLfieldList* fieldlist;
106 SQLfieldMap* fieldmap;
109 SQLite3Result(Module* self, Module* to, unsigned int rid)
110 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
118 void AddRow(int colsnum, char **dat, char **colname)
122 for (int i = 0; i < colsnum; i++)
124 fieldlists.resize(fieldlists.size()+1);
125 colnames.push_back(colname[i]);
126 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
127 fieldlists[rows].push_back(sf);
132 void UpdateAffectedCount()
147 virtual std::string ColName(int column)
149 if (column < (int)colnames.size())
151 return colnames[column];
155 throw SQLbadColName();
160 virtual int ColNum(const std::string &column)
162 for (unsigned int i = 0; i < colnames.size(); i++)
164 if (column == colnames[i])
167 throw SQLbadColName();
171 virtual SQLfield GetValue(int row, int column)
173 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
175 return fieldlists[row][column];
178 throw SQLbadColName();
180 /* XXX: We never actually get here because of the throw */
181 return SQLfield("",true);
184 virtual SQLfieldList& GetRow()
186 if (currentrow < rows)
187 return fieldlists[currentrow];
189 return emptyfieldlist;
192 virtual SQLfieldMap& GetRowMap()
194 /* In an effort to reduce overhead we don't actually allocate the map
195 * until the first time it's needed...so...
203 fieldmap = new SQLfieldMap;
206 if (currentrow < rows)
208 for (int i = 0; i < Cols(); i++)
210 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
218 virtual SQLfieldList* GetRowPtr()
220 fieldlist = new SQLfieldList();
222 if (currentrow < rows)
224 for (int i = 0; i < Rows(); i++)
226 fieldlist->push_back(fieldlists[currentrow][i]);
233 virtual SQLfieldMap* GetRowMapPtr()
235 fieldmap = new SQLfieldMap();
237 if (currentrow < rows)
239 for (int i = 0; i < Cols(); i++)
241 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
249 virtual void Free(SQLfieldMap* fm)
254 virtual void Free(SQLfieldList* fl)
262 class SQLConn : public classbase
266 InspIRCd* ServerInstance;
272 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
273 : ServerInstance(SI), mod(m), host(hi)
275 if (OpenDB() != SQLITE_OK)
277 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
287 SQLerror Query(SQLrequest &req)
289 /* Pointer to the buffer we screw around with substitution in */
292 /* Pointer to the current end of query, where we append new stuff */
295 /* Total length of the unescaped parameters */
296 unsigned long paramlen;
298 /* Total length of query, used for binary-safety */
299 unsigned long querylength = 0;
302 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
304 paramlen += i->size();
307 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
308 * sizeofquery + (totalparamlength*2) + 1
310 * The +1 is for null-terminating the string
312 query = new char[req.query.q.length() + (paramlen*2) + 1];
315 for(unsigned long i = 0; i < req.query.q.length(); i++)
317 if(req.query.q[i] == '?')
319 if(req.query.p.size())
322 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
323 for (char* n = escaped; *n; n++)
328 sqlite3_free(escaped);
329 req.query.p.pop_front();
336 *queryend = req.query.q[i];
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 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
353 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
355 std::string error(errmsg);
356 sqlite3_free(errmsg);
359 return SQLerror(SQL_QSEND_FAIL, error);
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 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
377 paramlist* p = (paramlist*)params;
378 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
381 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
383 res->AddRow(cols, data, colnames);
386 void AffectedReady(SQLite3Result *res)
388 res->UpdateAffectedCount();
393 return sqlite3_open(host.host.c_str(), &conn);
398 sqlite3_interrupt(conn);
402 SQLhost GetConfHost()
409 while (results.size())
411 SQLite3Result* res = results[0];
418 /* If the client module is unloaded partway through a query then the provider will set
419 * the pointer to NULL. We cannot just cancel the query as the result will still come
420 * through at some point...and it could get messy if we play with invalid pointers...
430 while (results.size())
432 SQLite3Result* res = results[0];
442 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
444 /* crap, we're out of sockets... */
448 irc::sockets::insp_sockaddr addr;
451 irc::sockets::insp_aton("::1", &addr.sin6_addr);
452 addr.sin6_family = AF_FAMILY;
453 addr.sin6_port = htons(listener->GetPort());
455 irc::sockets::insp_inaddr ia;
456 irc::sockets::insp_aton("127.0.0.1", &ia);
457 addr.sin_family = AF_FAMILY;
459 addr.sin_port = htons(listener->GetPort());
462 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
464 /* wtf, we cant connect to it, but we just created it! */
469 send(QueueFD, &id, 1, 0);
475 class ModuleSQLite3 : public Module
479 unsigned long currid;
482 ModuleSQLite3(InspIRCd* Me)
483 : Module(Me), currid(0)
485 ServerInstance->Modules->UseInterface("SQLutils");
487 if (!ServerInstance->Modules->PublishFeature("SQL", this))
489 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
492 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
494 listener = new SQLiteListener(this, ServerInstance, 0, "::1");
496 listener = new SQLiteListener(this, ServerInstance, 0, "127.0.0.1");
499 if (listener->GetFd() == -1)
501 ServerInstance->Modules->DoneWithInterface("SQLutils");
502 throw ModuleException("m_sqlite3: unable to create ITC pipe");
506 ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
511 ServerInstance->Modules->PublishInterface("SQL", this);
512 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
513 ServerInstance->Modules->Attach(eventlist, this, 2);
516 virtual ~ModuleSQLite3()
519 ClearAllConnections();
521 ServerInstance->SE->DelFd(listener);
522 ServerInstance->BufferedSocketCull();
526 shutdown(QueueFD, 2);
532 ServerInstance->SE->DelFd(notifier);
534 ServerInstance->BufferedSocketCull();
537 ServerInstance->Modules->UnpublishInterface("SQL", this);
538 ServerInstance->Modules->UnpublishFeature("SQL");
539 ServerInstance->Modules->DoneWithInterface("SQLutils");
545 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
547 iter->second->SendResults();
553 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
555 iter->second->ClearResults();
559 bool HasHost(const SQLhost &host)
561 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
563 if (host == iter->second->GetConfHost())
569 bool HostInConf(const SQLhost &h)
571 ConfigReader conf(ServerInstance);
572 for(int i = 0; i < conf.Enumerate("database"); i++)
575 host.id = conf.ReadValue("database", "id", i);
576 host.host = conf.ReadValue("database", "hostname", i);
577 host.port = conf.ReadInteger("database", "port", i, true);
578 host.name = conf.ReadValue("database", "name", i);
579 host.user = conf.ReadValue("database", "username", i);
580 host.pass = conf.ReadValue("database", "password", i);
589 ClearOldConnections();
591 ConfigReader conf(ServerInstance);
592 for(int i = 0; i < conf.Enumerate("database"); i++)
596 host.id = conf.ReadValue("database", "id", i);
597 host.host = conf.ReadValue("database", "hostname", i);
598 host.port = conf.ReadInteger("database", "port", i, true);
599 host.name = conf.ReadValue("database", "name", i);
600 host.user = conf.ReadValue("database", "username", i);
601 host.pass = conf.ReadValue("database", "password", i);
610 void AddConn(const SQLhost& hi)
614 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
620 newconn = new SQLConn(ServerInstance, this, hi);
622 connections.insert(std::make_pair(hi.id, newconn));
625 void ClearOldConnections()
627 ConnMap::iterator iter,safei;
628 for (iter = connections.begin(); iter != connections.end(); iter++)
630 if (!HostInConf(iter->second->GetConfHost()))
635 connections.erase(safei);
640 void ClearAllConnections()
643 while ((i = connections.begin()) != connections.end())
645 connections.erase(i);
650 virtual void OnRehash(User* user, const std::string ¶meter)
655 virtual const char* OnRequest(Request* request)
657 if(strcmp(SQLREQID, request->GetId()) == 0)
659 SQLrequest* req = (SQLrequest*)request;
660 ConnMap::iterator iter;
661 if((iter = connections.find(req->dbid)) != connections.end())
664 req->error = iter->second->Query(*req);
669 req->error.Id(SQL_BAD_DBID);
676 unsigned long NewID()
684 virtual Version GetVersion()
686 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
691 void ResultNotifier::Dispatch()
696 MODULE_INIT(ModuleSQLite3)