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, int newfd) : BufferedSocket(newfd), mod(m)
64 void OnError(BufferedSocketError) {}
69 class SQLiteListener : public ListenSocketBase
71 ModuleSQLite3* Parent;
72 irc::sockets::sockaddrs sock_us;
77 SQLiteListener(ModuleSQLite3* P, int port, const std::string &addr) : ListenSocketBase(port, addr, "ITC", "none"), Parent(P)
79 uslen = sizeof(sock_us);
80 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
82 throw ModuleException("Could not getsockname() to find out port number for ITC port");
86 void OnAcceptReady(int nfd)
88 new ResultNotifier(Parent, nfd);
95 irc::sockets::satoap(&sock_us, addr, port);
100 class SQLite3Result : public SQLresult
107 std::vector<std::string> colnames;
108 std::vector<SQLfieldList> fieldlists;
109 SQLfieldList emptyfieldlist;
111 SQLfieldList* fieldlist;
112 SQLfieldMap* fieldmap;
115 SQLite3Result(Module* self, Module* to, unsigned int rid)
116 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
124 void AddRow(int colsnum, char **dat, char **colname)
128 for (int i = 0; i < colsnum; i++)
130 fieldlists.resize(fieldlists.size()+1);
131 colnames.push_back(colname[i]);
132 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
133 fieldlists[rows].push_back(sf);
138 void UpdateAffectedCount()
153 virtual std::string ColName(int column)
155 if (column < (int)colnames.size())
157 return colnames[column];
161 throw SQLbadColName();
166 virtual int ColNum(const std::string &column)
168 for (unsigned int i = 0; i < colnames.size(); i++)
170 if (column == colnames[i])
173 throw SQLbadColName();
177 virtual SQLfield GetValue(int row, int column)
179 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
181 return fieldlists[row][column];
184 throw SQLbadColName();
186 /* XXX: We never actually get here because of the throw */
187 return SQLfield("",true);
190 virtual SQLfieldList& GetRow()
192 if (currentrow < rows)
193 return fieldlists[currentrow];
195 return emptyfieldlist;
198 virtual SQLfieldMap& GetRowMap()
200 /* In an effort to reduce overhead we don't actually allocate the map
201 * until the first time it's needed...so...
209 fieldmap = new SQLfieldMap;
212 if (currentrow < rows)
214 for (int i = 0; i < Cols(); i++)
216 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
224 virtual SQLfieldList* GetRowPtr()
226 fieldlist = new SQLfieldList();
228 if (currentrow < rows)
230 for (int i = 0; i < Rows(); i++)
232 fieldlist->push_back(fieldlists[currentrow][i]);
239 virtual SQLfieldMap* GetRowMapPtr()
241 fieldmap = new SQLfieldMap();
243 if (currentrow < rows)
245 for (int i = 0; i < Cols(); i++)
247 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
255 virtual void Free(SQLfieldMap* fm)
260 virtual void Free(SQLfieldList* fl)
268 class SQLConn : public classbase
277 SQLConn(Module* m, const SQLhost& hi)
280 if (OpenDB() != SQLITE_OK)
282 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
292 SQLerror Query(SQLrequest &req)
294 /* Pointer to the buffer we screw around with substitution in */
297 /* Pointer to the current end of query, where we append new stuff */
300 /* Total length of the unescaped parameters */
301 unsigned long maxparamlen, paramcount;
303 /* The length of the longest parameter */
306 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
308 if (i->size() > maxparamlen)
309 maxparamlen = i->size();
312 /* How many params are there in the query? */
313 paramcount = count(req.query.q.c_str(), '?');
315 /* This stores copy of params to be inserted with using numbered params 1;3B*/
316 ParamL paramscopy(req.query.p);
318 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
319 * sizeofquery + (maxtotalparamlength*2) + 1
321 * The +1 is for null-terminating the string
324 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
327 for(unsigned long i = 0; i < req.query.q.length(); i++)
329 if(req.query.q[i] == '?')
331 /* We found a place to substitute..what fun.
332 * use sqlite calls to escape and write the
333 * escaped string onto the end of our query buffer,
334 * then we "just" need to make sure queryend is
335 * pointing at the right place.
338 /* Is it numbered parameter?
344 /* Numbered parameter number :|
346 unsigned int paramnum;
349 /* Let's check if it's a numbered param. And also calculate it's number.
352 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
356 paramnum = paramnum * 10 + req.query.q[i] - '0';
359 if (paramnum > paramscopy.size() - 1)
361 /* index is out of range!
370 escaped = sqlite3_mprintf("%q", paramscopy[paramnum].c_str());
371 for (char* n = escaped; *n; n++)
376 sqlite3_free(escaped);
378 else if (req.query.p.size())
381 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
382 for (char* n = escaped; *n; n++)
387 sqlite3_free(escaped);
388 req.query.p.pop_front();
395 *queryend = req.query.q[i];
402 SQLite3Result* res = new SQLite3Result(mod, req.source, req.id);
404 res->query = req.query.q;
406 params.push_back(this);
407 params.push_back(res);
410 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
411 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
413 std::string error(errmsg);
414 sqlite3_free(errmsg);
417 return SQLerror(SQL_QSEND_FAIL, error);
421 results.push_back(res);
426 static int QueryResult(void *params, int argc, char **argv, char **azColName)
428 paramlist* p = (paramlist*)params;
429 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
433 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
435 paramlist* p = (paramlist*)params;
436 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
439 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
441 res->AddRow(cols, data, colnames);
444 void AffectedReady(SQLite3Result *res)
446 res->UpdateAffectedCount();
451 return sqlite3_open_v2(host.host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0);
456 sqlite3_interrupt(conn);
460 SQLhost GetConfHost()
467 while (results.size())
469 SQLite3Result* res = results[0];
476 /* If the client module is unloaded partway through a query then the provider will set
477 * the pointer to NULL. We cannot just cancel the query as the result will still come
478 * through at some point...and it could get messy if we play with invalid pointers...
488 while (results.size())
490 SQLite3Result* res = results[0];
500 if ((QueueFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
502 /* crap, we're out of sockets... */
506 irc::sockets::sockaddrs addr;
507 irc::sockets::aptosa("127.0.0.1", listener->GetPort(), &addr);
509 if (connect(QueueFD, &addr.sa, sa_size(addr)) == -1)
511 /* wtf, we cant connect to it, but we just created it! */
516 send(QueueFD, &id, 1, 0);
522 class ModuleSQLite3 : public Module
526 unsigned long currid;
532 ServerInstance->Modules->UseInterface("SQLutils");
534 if (!ServerInstance->Modules->PublishFeature("SQL", this))
536 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
539 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
540 listener = new SQLiteListener(this, 0, "127.0.0.1");
542 if (listener->GetFd() == -1)
544 ServerInstance->Modules->DoneWithInterface("SQLutils");
545 throw ModuleException("m_sqlite3: unable to create ITC pipe");
549 ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
554 ServerInstance->Modules->PublishInterface("SQL", this);
555 Implementation eventlist[] = { I_OnRehash };
556 ServerInstance->Modules->Attach(eventlist, this, 1);
559 virtual ~ModuleSQLite3()
562 ClearAllConnections();
564 ServerInstance->SE->DelFd(listener);
568 shutdown(QueueFD, 2);
574 ServerInstance->SE->DelFd(notifier);
578 ServerInstance->GlobalCulls.Apply();
580 ServerInstance->Modules->UnpublishInterface("SQL", this);
581 ServerInstance->Modules->UnpublishFeature("SQL");
582 ServerInstance->Modules->DoneWithInterface("SQLutils");
588 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
590 iter->second->SendResults();
596 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
598 iter->second->ClearResults();
602 bool HasHost(const SQLhost &host)
604 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
606 if (host == iter->second->GetConfHost())
612 bool HostInConf(const SQLhost &h)
615 for(int i = 0; i < conf.Enumerate("database"); i++)
618 host.id = conf.ReadValue("database", "id", i);
619 host.host = conf.ReadValue("database", "hostname", i);
620 host.port = conf.ReadInteger("database", "port", i, true);
621 host.name = conf.ReadValue("database", "name", i);
622 host.user = conf.ReadValue("database", "username", i);
623 host.pass = conf.ReadValue("database", "password", i);
632 ClearOldConnections();
635 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 void AddConn(const SQLhost& hi)
657 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
663 newconn = new SQLConn(this, hi);
665 connections.insert(std::make_pair(hi.id, newconn));
668 void ClearOldConnections()
670 ConnMap::iterator iter,safei;
671 for (iter = connections.begin(); iter != connections.end(); iter++)
673 if (!HostInConf(iter->second->GetConfHost()))
678 connections.erase(safei);
683 void ClearAllConnections()
686 while ((i = connections.begin()) != connections.end())
688 connections.erase(i);
693 virtual void OnRehash(User* user)
698 void OnRequest(Request& request)
700 if(strcmp(SQLREQID, request.id) == 0)
702 SQLrequest* req = (SQLrequest*)&request;
703 ConnMap::iterator iter;
704 if((iter = connections.find(req->dbid)) != connections.end())
707 req->error = iter->second->Query(*req);
711 req->error.Id(SQL_BAD_DBID);
716 unsigned long NewID()
724 virtual Version GetVersion()
726 return Version("sqlite3 provider", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
731 void ResultNotifier::Dispatch()
736 MODULE_INIT(ModuleSQLite3)