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 * ---------------------------------------------------
21 /* $ModDesc: sqlite3 provider */
22 /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
23 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
24 /* $ModDep: m_sqlv2.h */
31 typedef std::map<std::string, SQLConn*> ConnMap;
32 typedef std::deque<classbase*> paramlist;
33 typedef std::deque<SQLite3Result*> ResultQueue;
35 ResultNotifier* resultnotify = NULL;
36 ResultNotifier* resultdispatch = NULL;
39 class ResultNotifier : public BufferedSocket
42 insp_sockaddr sock_us;
46 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
48 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "::1", 0, true, 3000), mod(m)
50 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
53 uslen = sizeof(sock_us);
54 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
56 throw ModuleException("Could not create random listening port on localhost");
60 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
64 /* Using getsockname and ntohs, we can determine which port number we were allocated */
68 return ntohs(sock_us.sin6_port);
70 return ntohs(sock_us.sin_port);
74 virtual int OnIncomingConnection(int newsock, char* ip)
76 resultdispatch = new ResultNotifier(Instance, mod, newsock, ip);
80 virtual bool OnDataReady()
83 if (Instance->SE->Recv(this, &data, 1, 0) > 0)
95 class SQLite3Result : public SQLresult
102 std::vector<std::string> colnames;
103 std::vector<SQLfieldList> fieldlists;
104 SQLfieldList emptyfieldlist;
106 SQLfieldList* fieldlist;
107 SQLfieldMap* fieldmap;
110 SQLite3Result(Module* self, Module* to, unsigned int rid)
111 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
119 void AddRow(int colsnum, char **dat, char **colname)
123 for (int i = 0; i < colsnum; i++)
125 fieldlists.resize(fieldlists.size()+1);
126 colnames.push_back(colname[i]);
127 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
128 fieldlists[rows].push_back(sf);
133 void UpdateAffectedCount()
148 virtual std::string ColName(int column)
150 if (column < (int)colnames.size())
152 return colnames[column];
156 throw SQLbadColName();
161 virtual int ColNum(const std::string &column)
163 for (unsigned int i = 0; i < colnames.size(); i++)
165 if (column == colnames[i])
168 throw SQLbadColName();
172 virtual SQLfield GetValue(int row, int column)
174 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
176 return fieldlists[row][column];
179 throw SQLbadColName();
181 /* XXX: We never actually get here because of the throw */
182 return SQLfield("",true);
185 virtual SQLfieldList& GetRow()
187 if (currentrow < rows)
188 return fieldlists[currentrow];
190 return emptyfieldlist;
193 virtual SQLfieldMap& GetRowMap()
195 /* In an effort to reduce overhead we don't actually allocate the map
196 * until the first time it's needed...so...
204 fieldmap = new SQLfieldMap;
207 if (currentrow < rows)
209 for (int i = 0; i < Cols(); i++)
211 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
219 virtual SQLfieldList* GetRowPtr()
221 fieldlist = new SQLfieldList();
223 if (currentrow < rows)
225 for (int i = 0; i < Rows(); i++)
227 fieldlist->push_back(fieldlists[currentrow][i]);
234 virtual SQLfieldMap* GetRowMapPtr()
236 fieldmap = new SQLfieldMap();
238 if (currentrow < rows)
240 for (int i = 0; i < Cols(); i++)
242 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
250 virtual void Free(SQLfieldMap* fm)
255 virtual void Free(SQLfieldList* fl)
263 class SQLConn : public classbase
273 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
274 : Instance(SI), mod(m), host(hi)
276 if (OpenDB() != SQLITE_OK)
278 Instance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
288 SQLerror Query(SQLrequest &req)
290 /* Pointer to the buffer we screw around with substitution in */
293 /* Pointer to the current end of query, where we append new stuff */
296 /* Total length of the unescaped parameters */
297 unsigned long paramlen;
299 /* Total length of query, used for binary-safety in mysql_real_query */
300 unsigned long querylength = 0;
303 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
305 paramlen += i->size();
308 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
309 * sizeofquery + (totalparamlength*2) + 1
311 * The +1 is for null-terminating the string for mysql_real_escape_string
313 query = new char[req.query.q.length() + (paramlen*2) + 1];
316 for(unsigned long i = 0; i < req.query.q.length(); i++)
318 if(req.query.q[i] == '?')
320 if(req.query.p.size())
323 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
324 for (char* n = escaped; *n; n++)
329 sqlite3_free(escaped);
330 req.query.p.pop_front();
337 *queryend = req.query.q[i];
345 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
347 res->query = req.query.q;
349 params.push_back(this);
350 params.push_back(res);
353 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
354 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
356 std::string error(errmsg);
357 sqlite3_free(errmsg);
360 return SQLerror(QSEND_FAIL, error);
364 results.push_back(res);
369 static int QueryResult(void *params, int argc, char **argv, char **azColName)
371 paramlist* p = (paramlist*)params;
372 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
376 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
378 paramlist* p = (paramlist*)params;
379 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
382 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
384 res->AddRow(cols, data, colnames);
387 void AffectedReady(SQLite3Result *res)
389 res->UpdateAffectedCount();
394 return sqlite3_open(host.host.c_str(), &conn);
399 sqlite3_interrupt(conn);
403 SQLhost GetConfHost()
410 while (results.size())
412 SQLite3Result* res = results[0];
419 /* If the client module is unloaded partway through a query then the provider will set
420 * the pointer to NULL. We cannot just cancel the query as the result will still come
421 * through at some point...and it could get messy if we play with invalid pointers...
431 while (results.size())
433 SQLite3Result* res = results[0];
443 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
445 /* crap, we're out of sockets... */
452 insp_aton("::1", &addr.sin6_addr);
453 addr.sin6_family = AF_FAMILY;
454 addr.sin6_port = htons(resultnotify->GetPort());
457 insp_aton("127.0.0.1", &ia);
458 addr.sin_family = AF_FAMILY;
460 addr.sin_port = htons(resultnotify->GetPort());
463 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
465 /* wtf, we cant connect to it, but we just created it! */
470 send(QueueFD, &id, 1, 0);
476 class ModuleSQLite3 : public Module
480 unsigned long currid;
483 ModuleSQLite3(InspIRCd* Me)
484 : Module::Module(Me), currid(0)
486 ServerInstance->Modules->UseInterface("SQLutils");
488 if (!ServerInstance->Modules->PublishFeature("SQL", this))
490 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
493 resultnotify = new ResultNotifier(ServerInstance, this);
497 ServerInstance->Modules->PublishInterface("SQL", this);
498 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
499 ServerInstance->Modules->Attach(eventlist, this, 2);
502 virtual ~ModuleSQLite3()
505 ClearAllConnections();
507 ServerInstance->SE->DelFd(resultnotify);
508 resultnotify->Close();
509 ServerInstance->BufferedSocketCull();
513 shutdown(QueueFD, 2);
519 ServerInstance->SE->DelFd(resultdispatch);
520 resultdispatch->Close();
521 ServerInstance->BufferedSocketCull();
524 ServerInstance->Modules->UnpublishInterface("SQL", this);
525 ServerInstance->Modules->UnpublishFeature("SQL");
526 ServerInstance->Modules->DoneWithInterface("SQLutils");
532 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
534 iter->second->SendResults();
540 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
542 iter->second->ClearResults();
546 bool HasHost(const SQLhost &host)
548 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
550 if (host == iter->second->GetConfHost())
556 bool HostInConf(const SQLhost &h)
558 ConfigReader conf(ServerInstance);
559 for(int i = 0; i < conf.Enumerate("database"); i++)
562 host.id = conf.ReadValue("database", "id", i);
563 host.host = conf.ReadValue("database", "hostname", i);
564 host.port = conf.ReadInteger("database", "port", i, true);
565 host.name = conf.ReadValue("database", "name", i);
566 host.user = conf.ReadValue("database", "username", i);
567 host.pass = conf.ReadValue("database", "password", i);
576 ClearOldConnections();
578 ConfigReader conf(ServerInstance);
579 for(int i = 0; i < conf.Enumerate("database"); i++)
583 host.id = conf.ReadValue("database", "id", i);
584 host.host = conf.ReadValue("database", "hostname", i);
585 host.port = conf.ReadInteger("database", "port", i, true);
586 host.name = conf.ReadValue("database", "name", i);
587 host.user = conf.ReadValue("database", "username", i);
588 host.pass = conf.ReadValue("database", "password", i);
597 void AddConn(const SQLhost& hi)
601 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
607 newconn = new SQLConn(ServerInstance, this, hi);
609 connections.insert(std::make_pair(hi.id, newconn));
612 void ClearOldConnections()
614 ConnMap::iterator iter,safei;
615 for (iter = connections.begin(); iter != connections.end(); iter++)
617 if (!HostInConf(iter->second->GetConfHost()))
622 connections.erase(safei);
627 void ClearAllConnections()
630 while ((i = connections.begin()) != connections.end())
632 connections.erase(i);
637 virtual void OnRehash(User* user, const std::string ¶meter)
642 virtual const char* OnRequest(Request* request)
644 if(strcmp(SQLREQID, request->GetId()) == 0)
646 SQLrequest* req = (SQLrequest*)request;
647 ConnMap::iterator iter;
648 if((iter = connections.find(req->dbid)) != connections.end())
651 req->error = iter->second->Query(*req);
656 req->error.Id(BAD_DBID);
663 unsigned long NewID()
671 virtual Version GetVersion()
673 return Version(1,2,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
678 void ResultNotifier::Dispatch()
680 ((ModuleSQLite3*)mod)->SendQueue();
683 MODULE_INIT(ModuleSQLite3)