1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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 unsigned long count(const char * const str, char a)
37 const char *p = reinterpret_cast<const char *>(str);
39 while ((p = strchr(p, a)) != NULL)
47 ResultNotifier* notifier = NULL;
48 SQLiteListener* listener = NULL;
51 class ResultNotifier : public BufferedSocket
56 ResultNotifier(ModuleSQLite3* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
60 virtual bool OnDataReady()
63 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
74 class SQLiteListener : public ListenSocketBase
76 ModuleSQLite3* Parent;
77 irc::sockets::insp_sockaddr sock_us;
82 SQLiteListener(ModuleSQLite3* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
84 uslen = sizeof(sock_us);
85 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
87 throw ModuleException("Could not getsockname() to find out port number for ITC port");
91 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
93 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
96 /* Using getsockname and ntohs, we can determine which port number we were allocated */
100 return ntohs(sock_us.sin6_port);
102 return ntohs(sock_us.sin_port);
107 class SQLite3Result : public SQLresult
114 std::vector<std::string> colnames;
115 std::vector<SQLfieldList> fieldlists;
116 SQLfieldList emptyfieldlist;
118 SQLfieldList* fieldlist;
119 SQLfieldMap* fieldmap;
122 SQLite3Result(Module* self, Module* to, unsigned int rid)
123 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
131 void AddRow(int colsnum, char **dat, char **colname)
135 for (int i = 0; i < colsnum; i++)
137 fieldlists.resize(fieldlists.size()+1);
138 colnames.push_back(colname[i]);
139 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
140 fieldlists[rows].push_back(sf);
145 void UpdateAffectedCount()
160 virtual std::string ColName(int column)
162 if (column < (int)colnames.size())
164 return colnames[column];
168 throw SQLbadColName();
173 virtual int ColNum(const std::string &column)
175 for (unsigned int i = 0; i < colnames.size(); i++)
177 if (column == colnames[i])
180 throw SQLbadColName();
184 virtual SQLfield GetValue(int row, int column)
186 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
188 return fieldlists[row][column];
191 throw SQLbadColName();
193 /* XXX: We never actually get here because of the throw */
194 return SQLfield("",true);
197 virtual SQLfieldList& GetRow()
199 if (currentrow < rows)
200 return fieldlists[currentrow];
202 return emptyfieldlist;
205 virtual SQLfieldMap& GetRowMap()
207 /* In an effort to reduce overhead we don't actually allocate the map
208 * until the first time it's needed...so...
216 fieldmap = new SQLfieldMap;
219 if (currentrow < rows)
221 for (int i = 0; i < Cols(); i++)
223 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
231 virtual SQLfieldList* GetRowPtr()
233 fieldlist = new SQLfieldList();
235 if (currentrow < rows)
237 for (int i = 0; i < Rows(); i++)
239 fieldlist->push_back(fieldlists[currentrow][i]);
246 virtual SQLfieldMap* GetRowMapPtr()
248 fieldmap = new SQLfieldMap();
250 if (currentrow < rows)
252 for (int i = 0; i < Cols(); i++)
254 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
262 virtual void Free(SQLfieldMap* fm)
267 virtual void Free(SQLfieldList* fl)
275 class SQLConn : public classbase
279 InspIRCd* ServerInstance;
285 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
286 : ServerInstance(SI), mod(m), host(hi)
288 if (OpenDB() != SQLITE_OK)
290 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
300 SQLerror Query(SQLrequest &req)
302 /* Pointer to the buffer we screw around with substitution in */
305 /* Pointer to the current end of query, where we append new stuff */
308 /* Total length of the unescaped parameters */
309 unsigned long maxparamlen, paramcount;
311 /* Total length of query, used for binary-safety */
312 unsigned long querylength = 0;
314 /* The length of the longest parameter */
317 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
319 if (i->size() > maxparamlen)
320 maxparamlen = i->size();
323 /* How many params are there in the query? */
324 paramcount = count(req.query.q.c_str(), '?');
326 /* This stores copy of params to be inserted with using numbered params 1;3B*/
327 ParamL paramscopy(req.query.p);
329 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
330 * sizeofquery + (maxtotalparamlength*2) + 1
332 * The +1 is for null-terminating the string
335 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
338 for(unsigned long i = 0; i < req.query.q.length(); i++)
340 if(req.query.q[i] == '?')
342 /* We found a place to substitute..what fun.
343 * use sqlite calls to escape and write the
344 * escaped string onto the end of our query buffer,
345 * then we "just" need to make sure queryend is
346 * pointing at the right place.
349 /* Is it numbered parameter?
355 /* Numbered parameter number :|
357 unsigned int paramnum;
360 /* Let's check if it's a numbered param. And also calculate it's number.
363 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
367 paramnum = paramnum * 10 + req.query.q[i] - '0';
370 if (paramnum > paramscopy.size() - 1)
372 /* index is out of range!
381 escaped = sqlite3_mprintf("%q", paramscopy[paramnum].c_str());
382 for (char* n = escaped; *n; n++)
387 sqlite3_free(escaped);
389 else if (req.query.p.size())
392 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
393 for (char* n = escaped; *n; n++)
398 sqlite3_free(escaped);
399 req.query.p.pop_front();
406 *queryend = req.query.q[i];
414 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
416 res->query = req.query.q;
418 params.push_back(this);
419 params.push_back(res);
422 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
423 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
425 std::string error(errmsg);
426 sqlite3_free(errmsg);
429 return SQLerror(SQL_QSEND_FAIL, error);
433 results.push_back(res);
438 static int QueryResult(void *params, int argc, char **argv, char **azColName)
440 paramlist* p = (paramlist*)params;
441 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
445 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
447 paramlist* p = (paramlist*)params;
448 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
451 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
453 res->AddRow(cols, data, colnames);
456 void AffectedReady(SQLite3Result *res)
458 res->UpdateAffectedCount();
463 return sqlite3_open(host.host.c_str(), &conn);
468 sqlite3_interrupt(conn);
472 SQLhost GetConfHost()
479 while (results.size())
481 SQLite3Result* res = results[0];
488 /* If the client module is unloaded partway through a query then the provider will set
489 * the pointer to NULL. We cannot just cancel the query as the result will still come
490 * through at some point...and it could get messy if we play with invalid pointers...
500 while (results.size())
502 SQLite3Result* res = results[0];
512 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
514 /* crap, we're out of sockets... */
518 irc::sockets::insp_sockaddr addr;
521 irc::sockets::insp_aton("::1", &addr.sin6_addr);
522 addr.sin6_family = AF_FAMILY;
523 addr.sin6_port = htons(listener->GetPort());
525 irc::sockets::insp_inaddr ia;
526 irc::sockets::insp_aton("127.0.0.1", &ia);
527 addr.sin_family = AF_FAMILY;
529 addr.sin_port = htons(listener->GetPort());
532 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
534 /* wtf, we cant connect to it, but we just created it! */
539 send(QueueFD, &id, 1, 0);
545 class ModuleSQLite3 : public Module
549 unsigned long currid;
552 ModuleSQLite3(InspIRCd* Me)
553 : Module(Me), currid(0)
555 ServerInstance->Modules->UseInterface("SQLutils");
557 if (!ServerInstance->Modules->PublishFeature("SQL", this))
559 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
562 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
564 listener = new SQLiteListener(this, ServerInstance, 0, "::1");
566 listener = new SQLiteListener(this, ServerInstance, 0, "127.0.0.1");
569 if (listener->GetFd() == -1)
571 ServerInstance->Modules->DoneWithInterface("SQLutils");
572 throw ModuleException("m_sqlite3: unable to create ITC pipe");
576 ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
581 ServerInstance->Modules->PublishInterface("SQL", this);
582 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
583 ServerInstance->Modules->Attach(eventlist, this, 2);
586 virtual ~ModuleSQLite3()
589 ClearAllConnections();
591 ServerInstance->SE->DelFd(listener);
592 ServerInstance->BufferedSocketCull();
596 shutdown(QueueFD, 2);
602 ServerInstance->SE->DelFd(notifier);
604 ServerInstance->BufferedSocketCull();
607 ServerInstance->Modules->UnpublishInterface("SQL", this);
608 ServerInstance->Modules->UnpublishFeature("SQL");
609 ServerInstance->Modules->DoneWithInterface("SQLutils");
615 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
617 iter->second->SendResults();
623 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
625 iter->second->ClearResults();
629 bool HasHost(const SQLhost &host)
631 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
633 if (host == iter->second->GetConfHost())
639 bool HostInConf(const SQLhost &h)
641 ConfigReader conf(ServerInstance);
642 for(int i = 0; i < conf.Enumerate("database"); i++)
645 host.id = conf.ReadValue("database", "id", i);
646 host.host = conf.ReadValue("database", "hostname", i);
647 host.port = conf.ReadInteger("database", "port", i, true);
648 host.name = conf.ReadValue("database", "name", i);
649 host.user = conf.ReadValue("database", "username", i);
650 host.pass = conf.ReadValue("database", "password", i);
659 ClearOldConnections();
661 ConfigReader conf(ServerInstance);
662 for(int i = 0; i < conf.Enumerate("database"); i++)
666 host.id = conf.ReadValue("database", "id", i);
667 host.host = conf.ReadValue("database", "hostname", i);
668 host.port = conf.ReadInteger("database", "port", i, true);
669 host.name = conf.ReadValue("database", "name", i);
670 host.user = conf.ReadValue("database", "username", i);
671 host.pass = conf.ReadValue("database", "password", i);
680 void AddConn(const SQLhost& hi)
684 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
690 newconn = new SQLConn(ServerInstance, this, hi);
692 connections.insert(std::make_pair(hi.id, newconn));
695 void ClearOldConnections()
697 ConnMap::iterator iter,safei;
698 for (iter = connections.begin(); iter != connections.end(); iter++)
700 if (!HostInConf(iter->second->GetConfHost()))
705 connections.erase(safei);
710 void ClearAllConnections()
713 while ((i = connections.begin()) != connections.end())
715 connections.erase(i);
720 virtual void OnRehash(User* user, const std::string ¶meter)
725 virtual const char* OnRequest(Request* request)
727 if(strcmp(SQLREQID, request->GetId()) == 0)
729 SQLrequest* req = (SQLrequest*)request;
730 ConnMap::iterator iter;
731 if((iter = connections.find(req->dbid)) != connections.end())
734 req->error = iter->second->Query(*req);
739 req->error.Id(SQL_BAD_DBID);
746 unsigned long NewID()
754 virtual Version GetVersion()
756 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
761 void ResultNotifier::Dispatch()
766 MODULE_INIT(ModuleSQLite3)