X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=src%2Fmodules%2Fextra%2Fm_sqlite3.cpp;h=1e3a65a18fdea27e4483daff11f05fd366534116;hb=64faca29b377185c4615c8f2e4eecedc7ad045d1;hp=b0a0afbe5787b2f6ed186f3d55e8125051fc2503;hpb=f9f475b090b2607ba2b6fa07d978f9cf374295af;p=user%2Fhenk%2Fcode%2Finspircd.git diff --git a/src/modules/extra/m_sqlite3.cpp b/src/modules/extra/m_sqlite3.cpp index b0a0afbe5..1e3a65a18 100644 --- a/src/modules/extra/m_sqlite3.cpp +++ b/src/modules/extra/m_sqlite3.cpp @@ -1,59 +1,50 @@ -/* +------------------------------------+ - * | Inspire Internet Relay Chat Daemon | - * +------------------------------------+ +/* + * InspIRCd -- Internet Relay Chat Daemon * - * InspIRCd: (C) 2002-2007 InspIRCd Development Team - * See: http://www.inspircd.org/wiki/index.php/Credits + * Copyright (C) 2009-2010 Daniel De Graaf + * Copyright (C) 2007-2009 Dennis Friis + * Copyright (C) 2007, 2009 Craig Edwards + * Copyright (C) 2008 Pippijn van Steenhoven * - * This program is free but copyrighted software; see - * the file COPYING for details. + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. * - * --------------------------------------------------- + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ -#include -#include -#include -#include -#include "users.h" -#include "channels.h" -#include "modules.h" #include "inspircd.h" -#include "configreader.h" +#include +#include "sql.h" -#include "m_sqlv2.h" +#ifdef _WIN32 +# pragma comment(lib, "sqlite3.lib") +#endif /* $ModDesc: sqlite3 provider */ -/* $CompileFlags: pkgconfincludes("sqlite3","/sqlite3.h","") */ +/* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */ /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */ -/* $ModDep: m_sqlv2.h */ - +/* $NoPedantic */ class SQLConn; -class SQLite3Result; - typedef std::map ConnMap; -typedef std::deque paramlist; -typedef std::deque ResultQueue; -class SQLite3Result : public SQLresult +class SQLite3Result : public SQLResult { - private: + public: int currentrow; int rows; - int cols; - - std::vector colnames; - std::vector fieldlists; - SQLfieldList emptyfieldlist; + std::vector columns; + std::vector fieldlists; - SQLfieldList* fieldlist; - SQLfieldMap* fieldmap; - - public: - SQLite3Result(Module* self, Module* to, unsigned int id) - : SQLresult(self, to, id), currentrow(0), rows(0), cols(0) + SQLite3Result() : currentrow(0), rows(0) { } @@ -61,472 +52,218 @@ class SQLite3Result : public SQLresult { } - void AddRow(int colsnum, char **data, char **colname) - { - colnames.clear(); - cols = colsnum; - for (int i = 0; i < colsnum; i++) - { - fieldlists.resize(fieldlists.size()+1); - colnames.push_back(colname[i]); - SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true); - fieldlists[rows].push_back(sf); - } - rows++; - } - virtual int Rows() { return rows; } - virtual int Cols() - { - return cols; - } - - virtual std::string ColName(int column) + virtual bool GetRow(SQLEntries& result) { - if (column < (int)colnames.size()) + if (currentrow < rows) { - return colnames[column]; + result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end()); + currentrow++; + return true; } else { - throw SQLbadColName(); + result.clear(); + return false; } - return ""; } - virtual int ColNum(const std::string &column) + virtual void GetCols(std::vector& result) { - for (unsigned int i = 0; i < colnames.size(); i++) - { - if (column == colnames[i]) - return i; - } - throw SQLbadColName(); - return 0; + result.assign(columns.begin(), columns.end()); } +}; - virtual SQLfield GetValue(int row, int column) +class SQLConn : public SQLProvider +{ + private: + sqlite3* conn; + reference config; + + public: + SQLConn(Module* Parent, ConfigTag* tag) : SQLProvider(Parent, "SQL/" + tag->getString("id")), config(tag) { - if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols())) + std::string host = tag->getString("hostname"); + if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK) { - return fieldlists[row][column]; + ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id")); + conn = NULL; } - - throw SQLbadColName(); - - /* XXX: We never actually get here because of the throw */ - return SQLfield("",true); } - virtual SQLfieldList& GetRow() + ~SQLConn() { - if (currentrow < rows) - return fieldlists[currentrow]; - else - return emptyfieldlist; + if (conn) + { + sqlite3_interrupt(conn); + sqlite3_close(conn); + } } - virtual SQLfieldMap& GetRowMap() + void Query(SQLQuery* query, const std::string& q) { - /* In an effort to reduce overhead we don't actually allocate the map - * until the first time it's needed...so... - */ - if(fieldmap) + SQLite3Result res; + sqlite3_stmt *stmt; + int err = sqlite3_prepare_v2(conn, q.c_str(), q.length(), &stmt, NULL); + if (err != SQLITE_OK) { - fieldmap->clear(); + SQLerror error(SQL_QSEND_FAIL, sqlite3_errmsg(conn)); + query->OnError(error); + return; } - else + int cols = sqlite3_column_count(stmt); + res.columns.resize(cols); + for(int i=0; i < cols; i++) { - fieldmap = new SQLfieldMap; + res.columns[i] = sqlite3_column_name(stmt, i); } - - if (currentrow < rows) + while (1) { - for (int i = 0; i < Cols(); i++) + err = sqlite3_step(stmt); + if (err == SQLITE_ROW) { - fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); + // Add the row + res.fieldlists.resize(res.rows + 1); + res.fieldlists[res.rows].resize(cols); + for(int i=0; i < cols; i++) + { + const char* txt = (const char*)sqlite3_column_text(stmt, i); + if (txt) + res.fieldlists[res.rows][i] = SQLEntry(txt); + } + res.rows++; } - currentrow++; - } - - return *fieldmap; - } - - virtual SQLfieldList* GetRowPtr() - { - fieldlist = new SQLfieldList(); - - if (currentrow < rows) - { - for (int i = 0; i < Rows(); i++) + else if (err == SQLITE_DONE) { - fieldlist->push_back(fieldlists[currentrow][i]); + query->OnResult(res); + break; } - currentrow++; - } - return fieldlist; - } - - virtual SQLfieldMap* GetRowMapPtr() - { - fieldmap = new SQLfieldMap(); - - if (currentrow < rows) - { - for (int i = 0; i < Cols(); i++) + else { - fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i))); + SQLerror error(SQL_QREPLY_FAIL, sqlite3_errmsg(conn)); + query->OnError(error); + break; } - currentrow++; } - - return fieldmap; - } - - virtual void Free(SQLfieldMap* fm) - { - delete fm; - } - - virtual void Free(SQLfieldList* fl) - { - delete fl; + sqlite3_finalize(stmt); } - -}; - -class SQLConn : public classbase -{ - private: - ResultQueue results; - InspIRCd* Instance; - Module* mod; - SQLhost host; - sqlite3* conn; - - public: - SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi) - : Instance(SI), mod(m), host(hi) + virtual void submit(SQLQuery* query, const std::string& q) { - int result; - if ((result = OpenDB()) == SQLITE_OK) - { - Instance->Log(DEBUG, "Opened sqlite DB: " + host.host); - } - else - { - Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id); - CloseDB(); - } + Query(query, q); + delete query; } - SQLerror Query(SQLrequest &req) + virtual void submit(SQLQuery* query, const std::string& q, const ParamL& p) { - /* Pointer to the buffer we screw around with substitution in */ - char* query; - - /* Pointer to the current end of query, where we append new stuff */ - char* queryend; - - /* Total length of the unescaped parameters */ - unsigned long paramlen; - - /* Total length of query, used for binary-safety in mysql_real_query */ - unsigned long querylength = 0; - - paramlen = 0; - for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) - { - paramlen += i->size(); - } - - /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. - * sizeofquery + (totalparamlength*2) + 1 - * - * The +1 is for null-terminating the string for mysql_real_escape_string - */ - - query = new char[req.query.q.length() + (paramlen*2) + 1]; - queryend = query; - - for(unsigned long i = 0; i < req.query.q.length(); i++) + std::string res; + unsigned int param = 0; + for(std::string::size_type i = 0; i < q.length(); i++) { - if(req.query.q[i] == '?') + if (q[i] != '?') + res.push_back(q[i]); + else { - if(req.query.p.size()) + if (param < p.size()) { - char* escaped; - escaped = sqlite3_mprintf("%q", req.query.p.front().c_str()); - for (char* n = escaped; *n; n++) - { - *queryend = *n; - queryend++; - } + char* escaped = sqlite3_mprintf("%q", p[param++].c_str()); + res.append(escaped); sqlite3_free(escaped); - req.query.p.pop_front(); } - else - break; - } - else - { - *queryend = req.query.q[i]; - queryend++; } - querylength++; } - *queryend = 0; - req.query.q = query; - -// Instance->Log(DEBUG, "<******> Doing query: " + ConvToStr(req.query.q.data())); - - SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id); - res->query = req.query.q; - paramlist params; - params.push_back(this); - params.push_back(res); - - char *errmsg = 0; - if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK) - { - Instance->Log(DEBUG, "Query failed: " + ConvToStr(errmsg)); - sqlite3_free(errmsg); - delete[] query; - delete res; - return SQLerror(QSEND_FAIL, ConvToStr(errmsg)); - } - Instance->Log(DEBUG, "Dispatched query successfully. ID: %d resulting rows %d", req.id, res->Rows()); - delete[] query; - - results.push_back(res); - - return SQLerror(); - } - - static int QueryResult(void *params, int argc, char **argv, char **azColName) - { - paramlist* p = (paramlist*)params; - ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName); - return 0; - } - - void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames) - { - res->AddRow(cols, data, colnames); - } - - void QueryDone(SQLrequest* req, int rows) - { - SQLite3Result* r = new SQLite3Result(mod, req->GetSource(), req->id); - r->dbid = host.id; - r->query = req->query.q; - } - - int OpenDB() - { - return sqlite3_open(host.host.c_str(), &conn); - } - - void CloseDB() - { - sqlite3_interrupt(conn); - sqlite3_close(conn); - } - - SQLhost GetConfHost() - { - return host; + submit(query, res); } - void SendResults() + virtual void submit(SQLQuery* query, const std::string& q, const ParamM& p) { - if (results.size()) + std::string res; + for(std::string::size_type i = 0; i < q.length(); i++) { - SQLite3Result* res = results[0]; - if (res->GetDest()) - { - res->Send(); - } + if (q[i] != '$') + res.push_back(q[i]); else { - /* If the client module is unloaded partway through a query then the provider will set - * the pointer to NULL. We cannot just cancel the query as the result will still come - * through at some point...and it could get messy if we play with invalid pointers... - */ - Instance->Log(DEBUG, "Looks like we're handling a zombie query from a module which unloaded before it got a result..fun. ID: " + ConvToStr(res->GetId())); - delete res; + std::string field; + i++; + while (i < q.length() && isalnum(q[i])) + field.push_back(q[i++]); + i--; + + ParamM::const_iterator it = p.find(field); + if (it != p.end()) + { + char* escaped = sqlite3_mprintf("%q", it->second.c_str()); + res.append(escaped); + sqlite3_free(escaped); + } } - results.pop_front(); } + submit(query, res); } - }; - class ModuleSQLite3 : public Module { - private: - ConnMap connections; - unsigned long currid; + private: + ConnMap conns; - public: - ModuleSQLite3(InspIRCd* Me) - : Module::Module(Me), currid(0) + public: + ModuleSQLite3() { - ServerInstance->UseInterface("SQLutils"); - - if (!ServerInstance->PublishFeature("SQL", this)) - { - throw ModuleException("m_mysql: Unable to publish feature 'SQL'"); - } - - ReadConf(); - - ServerInstance->PublishInterface("SQL", this); } - virtual ~ModuleSQLite3() + void init() { - ServerInstance->UnpublishInterface("SQL", this); - ServerInstance->UnpublishFeature("SQL"); - ServerInstance->DoneWithInterface("SQLutils"); - } + ReadConf(); - void Implements(char* List) - { - List[I_OnRequest] = 1; + Implementation eventlist[] = { I_OnRehash }; + ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - bool HasHost(const SQLhost &host) + virtual ~ModuleSQLite3() { - for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) - { - if (host == iter->second->GetConfHost()) - return true; - } - return false; + ClearConns(); } - bool HostInConf(const SQLhost &h) + void ClearConns() { - ConfigReader conf(ServerInstance); - for(int i = 0; i < conf.Enumerate("database"); i++) + for(ConnMap::iterator i = conns.begin(); i != conns.end(); i++) { - SQLhost host; - host.id = conf.ReadValue("database", "id", i); - host.host = conf.ReadValue("database", "hostname", i); - host.port = conf.ReadInteger("database", "port", i, true); - host.name = conf.ReadValue("database", "name", i); - host.user = conf.ReadValue("database", "username", i); - host.pass = conf.ReadValue("database", "password", i); - host.ssl = conf.ReadFlag("database", "ssl", "0", i); - if (h == host) - return true; + SQLConn* conn = i->second; + ServerInstance->Modules->DelService(*conn); + delete conn; } - return false; + conns.clear(); } void ReadConf() { - //ClearOldConnections(); - - ConfigReader conf(ServerInstance); - for(int i = 0; i < conf.Enumerate("database"); i++) + ClearConns(); + ConfigTagList tags = ServerInstance->Config->ConfTags("database"); + for(ConfigIter i = tags.first; i != tags.second; i++) { - SQLhost host; - - host.id = conf.ReadValue("database", "id", i); - host.host = conf.ReadValue("database", "hostname", i); - host.port = conf.ReadInteger("database", "port", i, true); - host.name = conf.ReadValue("database", "name", i); - host.user = conf.ReadValue("database", "username", i); - host.pass = conf.ReadValue("database", "password", i); - host.ssl = conf.ReadFlag("database", "ssl", "0", i); - - if (HasHost(host)) + if (i->second->getString("module", "sqlite") != "sqlite") continue; - - this->AddConn(host); - } - } - - void AddConn(const SQLhost& hi) - { - if (HasHost(hi)) - { - ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str()); - return; - } - - SQLConn* newconn; - - newconn = new SQLConn(ServerInstance, this, hi); - - connections.insert(std::make_pair(hi.id, newconn)); - } - - virtual char* OnRequest(Request* request) - { - if(strcmp(SQLREQID, request->GetId()) == 0) - { - SQLrequest* req = (SQLrequest*)request; - ConnMap::iterator iter; - ServerInstance->Log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str()); - if((iter = connections.find(req->dbid)) != connections.end()) - { - req->id = NewID(); - req->error = iter->second->Query(*req); - return SQLSUCCESS; - } - else - { - req->error.Id(BAD_DBID); - return NULL; - } + SQLConn* conn = new SQLConn(this, i->second); + conns.insert(std::make_pair(i->second->getString("id"), conn)); + ServerInstance->Modules->AddService(*conn); } - ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId()); - return NULL; } - unsigned long NewID() - { - if (currid+1 == 0) - currid++; - - return ++currid; - } - - virtual Version GetVersion() - { - return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION); - } - -}; - - -class ModuleSQLite3Factory : public ModuleFactory -{ - public: - ModuleSQLite3Factory() - { - } - - ~ModuleSQLite3Factory() + void OnRehash(User* user) { + ReadConf(); } - virtual Module * CreateModule(InspIRCd* Me) + Version GetVersion() { - return new ModuleSQLite3(Me); + return Version("sqlite3 provider", VF_VENDOR); } }; -extern "C" void * init_module( void ) -{ - return new ModuleSQLite3Factory; -} +MODULE_INIT(ModuleSQLite3)