1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/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 unsigned long count(const char * const str, char a)
37 for (const char *p = str; *p; ++p)
45 ResultNotifier* notifier = NULL;
46 SQLiteListener* listener = NULL;
49 class ResultNotifier : public BufferedSocket
54 ResultNotifier(ModuleSQLite3* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
58 virtual bool OnDataReady()
61 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
72 class SQLiteListener : public ListenSocketBase
74 ModuleSQLite3* Parent;
75 irc::sockets::insp_sockaddr sock_us;
80 SQLiteListener(ModuleSQLite3* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
82 uslen = sizeof(sock_us);
83 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
85 throw ModuleException("Could not getsockname() to find out port number for ITC port");
89 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
91 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
94 /* Using getsockname and ntohs, we can determine which port number we were allocated */
98 return ntohs(sock_us.sin6_port);
100 return ntohs(sock_us.sin_port);
105 class SQLite3Result : public SQLresult
112 std::vector<std::string> colnames;
113 std::vector<SQLfieldList> fieldlists;
114 SQLfieldList emptyfieldlist;
116 SQLfieldList* fieldlist;
117 SQLfieldMap* fieldmap;
120 SQLite3Result(Module* self, Module* to, unsigned int rid)
121 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
129 void AddRow(int colsnum, char **dat, char **colname)
133 for (int i = 0; i < colsnum; i++)
135 fieldlists.resize(fieldlists.size()+1);
136 colnames.push_back(colname[i]);
137 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
138 fieldlists[rows].push_back(sf);
143 void UpdateAffectedCount()
158 virtual std::string ColName(int column)
160 if (column < (int)colnames.size())
162 return colnames[column];
166 throw SQLbadColName();
171 virtual int ColNum(const std::string &column)
173 for (unsigned int i = 0; i < colnames.size(); i++)
175 if (column == colnames[i])
178 throw SQLbadColName();
182 virtual SQLfield GetValue(int row, int column)
184 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
186 return fieldlists[row][column];
189 throw SQLbadColName();
191 /* XXX: We never actually get here because of the throw */
192 return SQLfield("",true);
195 virtual SQLfieldList& GetRow()
197 if (currentrow < rows)
198 return fieldlists[currentrow];
200 return emptyfieldlist;
203 virtual SQLfieldMap& GetRowMap()
205 /* In an effort to reduce overhead we don't actually allocate the map
206 * until the first time it's needed...so...
214 fieldmap = new SQLfieldMap;
217 if (currentrow < rows)
219 for (int i = 0; i < Cols(); i++)
221 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
229 virtual SQLfieldList* GetRowPtr()
231 fieldlist = new SQLfieldList();
233 if (currentrow < rows)
235 for (int i = 0; i < Rows(); i++)
237 fieldlist->push_back(fieldlists[currentrow][i]);
244 virtual SQLfieldMap* GetRowMapPtr()
246 fieldmap = new SQLfieldMap();
248 if (currentrow < rows)
250 for (int i = 0; i < Cols(); i++)
252 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
260 virtual void Free(SQLfieldMap* fm)
265 virtual void Free(SQLfieldList* fl)
273 class SQLConn : public classbase
277 InspIRCd* ServerInstance;
283 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
284 : ServerInstance(SI), mod(m), host(hi)
286 if (OpenDB() != SQLITE_OK)
288 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
298 SQLerror Query(SQLrequest &req)
300 /* Pointer to the buffer we screw around with substitution in */
303 /* Pointer to the current end of query, where we append new stuff */
306 /* Total length of the unescaped parameters */
307 unsigned long maxparamlen, paramcount;
309 /* The length of the longest parameter */
312 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
314 if (i->size() > maxparamlen)
315 maxparamlen = i->size();
318 /* How many params are there in the query? */
319 paramcount = count(req.query.q.c_str(), '?');
321 /* This stores copy of params to be inserted with using numbered params 1;3B*/
322 ParamL paramscopy(req.query.p);
324 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
325 * sizeofquery + (maxtotalparamlength*2) + 1
327 * The +1 is for null-terminating the string
330 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
333 for(unsigned long i = 0; i < req.query.q.length(); i++)
335 if(req.query.q[i] == '?')
337 /* We found a place to substitute..what fun.
338 * use sqlite calls to escape and write the
339 * escaped string onto the end of our query buffer,
340 * then we "just" need to make sure queryend is
341 * pointing at the right place.
344 /* Is it numbered parameter?
350 /* Numbered parameter number :|
352 unsigned int paramnum;
355 /* Let's check if it's a numbered param. And also calculate it's number.
358 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
362 paramnum = paramnum * 10 + req.query.q[i] - '0';
365 if (paramnum > paramscopy.size() - 1)
367 /* index is out of range!
376 escaped = sqlite3_mprintf("%q", paramscopy[paramnum].c_str());
377 for (char* n = escaped; *n; n++)
382 sqlite3_free(escaped);
384 else if (req.query.p.size())
387 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
388 for (char* n = escaped; *n; n++)
393 sqlite3_free(escaped);
394 req.query.p.pop_front();
401 *queryend = req.query.q[i];
408 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
410 res->query = req.query.q;
412 params.push_back(this);
413 params.push_back(res);
416 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
417 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
419 std::string error(errmsg);
420 sqlite3_free(errmsg);
423 return SQLerror(SQL_QSEND_FAIL, error);
427 results.push_back(res);
432 static int QueryResult(void *params, int argc, char **argv, char **azColName)
434 paramlist* p = (paramlist*)params;
435 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
439 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
441 paramlist* p = (paramlist*)params;
442 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
445 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
447 res->AddRow(cols, data, colnames);
450 void AffectedReady(SQLite3Result *res)
452 res->UpdateAffectedCount();
457 return sqlite3_open_v2(host.host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0);
462 sqlite3_interrupt(conn);
466 SQLhost GetConfHost()
473 while (results.size())
475 SQLite3Result* res = results[0];
482 /* If the client module is unloaded partway through a query then the provider will set
483 * the pointer to NULL. We cannot just cancel the query as the result will still come
484 * through at some point...and it could get messy if we play with invalid pointers...
494 while (results.size())
496 SQLite3Result* res = results[0];
506 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
508 /* crap, we're out of sockets... */
512 irc::sockets::insp_sockaddr addr;
515 irc::sockets::insp_aton("::1", &addr.sin6_addr);
516 addr.sin6_family = AF_FAMILY;
517 addr.sin6_port = htons(listener->GetPort());
519 irc::sockets::insp_inaddr ia;
520 irc::sockets::insp_aton("127.0.0.1", &ia);
521 addr.sin_family = AF_FAMILY;
523 addr.sin_port = htons(listener->GetPort());
526 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
528 /* wtf, we cant connect to it, but we just created it! */
533 send(QueueFD, &id, 1, 0);
539 class ModuleSQLite3 : public Module
543 unsigned long currid;
546 ModuleSQLite3(InspIRCd* Me)
547 : Module(Me), currid(0)
549 ServerInstance->Modules->UseInterface("SQLutils");
551 if (!ServerInstance->Modules->PublishFeature("SQL", this))
553 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
556 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
558 listener = new SQLiteListener(this, ServerInstance, 0, "::1");
560 listener = new SQLiteListener(this, ServerInstance, 0, "127.0.0.1");
563 if (listener->GetFd() == -1)
565 ServerInstance->Modules->DoneWithInterface("SQLutils");
566 throw ModuleException("m_sqlite3: unable to create ITC pipe");
570 ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
575 ServerInstance->Modules->PublishInterface("SQL", this);
576 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
577 ServerInstance->Modules->Attach(eventlist, this, 2);
580 virtual ~ModuleSQLite3()
583 ClearAllConnections();
585 ServerInstance->SE->DelFd(listener);
586 ServerInstance->BufferedSocketCull();
590 shutdown(QueueFD, 2);
596 ServerInstance->SE->DelFd(notifier);
598 ServerInstance->BufferedSocketCull();
601 ServerInstance->Modules->UnpublishInterface("SQL", this);
602 ServerInstance->Modules->UnpublishFeature("SQL");
603 ServerInstance->Modules->DoneWithInterface("SQLutils");
609 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
611 iter->second->SendResults();
617 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
619 iter->second->ClearResults();
623 bool HasHost(const SQLhost &host)
625 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
627 if (host == iter->second->GetConfHost())
633 bool HostInConf(const SQLhost &h)
635 ConfigReader conf(ServerInstance);
636 for(int i = 0; i < conf.Enumerate("database"); i++)
639 host.id = conf.ReadValue("database", "id", i);
640 host.host = conf.ReadValue("database", "hostname", i);
641 host.port = conf.ReadInteger("database", "port", i, true);
642 host.name = conf.ReadValue("database", "name", i);
643 host.user = conf.ReadValue("database", "username", i);
644 host.pass = conf.ReadValue("database", "password", i);
653 ClearOldConnections();
655 ConfigReader conf(ServerInstance);
656 for(int i = 0; i < conf.Enumerate("database"); i++)
660 host.id = conf.ReadValue("database", "id", i);
661 host.host = conf.ReadValue("database", "hostname", i);
662 host.port = conf.ReadInteger("database", "port", i, true);
663 host.name = conf.ReadValue("database", "name", i);
664 host.user = conf.ReadValue("database", "username", i);
665 host.pass = conf.ReadValue("database", "password", i);
674 void AddConn(const SQLhost& hi)
678 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
684 newconn = new SQLConn(ServerInstance, this, hi);
686 connections.insert(std::make_pair(hi.id, newconn));
689 void ClearOldConnections()
691 ConnMap::iterator iter,safei;
692 for (iter = connections.begin(); iter != connections.end(); iter++)
694 if (!HostInConf(iter->second->GetConfHost()))
699 connections.erase(safei);
704 void ClearAllConnections()
707 while ((i = connections.begin()) != connections.end())
709 connections.erase(i);
714 virtual void OnRehash(User* user)
719 virtual const char* OnRequest(Request* request)
721 if(strcmp(SQLREQID, request->GetId()) == 0)
723 SQLrequest* req = (SQLrequest*)request;
724 ConnMap::iterator iter;
725 if((iter = connections.find(req->dbid)) != connections.end())
728 req->error = iter->second->Query(*req);
733 req->error.Id(SQL_BAD_DBID);
740 unsigned long NewID()
748 virtual Version GetVersion()
750 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
755 void ResultNotifier::Dispatch()
760 MODULE_INIT(ModuleSQLite3)