1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
23 #include "configreader.h"
27 /* $ModDesc: sqlite3 provider */
28 /* $CompileFlags: pkgconfincludes("sqlite3","/sqlite3.h","") */
29 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
30 /* $ModDep: m_sqlv2.h */
37 typedef std::map<std::string, SQLConn*> ConnMap;
38 typedef std::deque<classbase*> paramlist;
39 typedef std::deque<SQLite3Result*> ResultQueue;
41 ResultNotifier* resultnotify = NULL;
44 class ResultNotifier : public InspSocket
47 insp_sockaddr sock_us;
51 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
53 ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "::1", 0, true, 3000), mod(m)
55 ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
58 uslen = sizeof(sock_us);
59 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
61 throw ModuleException("Could not create random listening port on localhost");
65 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : InspSocket(SI, newfd, ip), mod(m)
67 Instance->Log(DEBUG,"Constructor of new socket");
70 /* Using getsockname and ntohs, we can determine which port number we were allocated */
74 return ntohs(sock_us.sin6_port);
76 return ntohs(sock_us.sin_port);
80 virtual int OnIncomingConnection(int newsock, char* ip)
82 Instance->Log(DEBUG,"Inbound connection on fd %d!",newsock);
91 class SQLite3Result : public SQLresult
98 std::vector<std::string> colnames;
99 std::vector<SQLfieldList> fieldlists;
100 SQLfieldList emptyfieldlist;
102 SQLfieldList* fieldlist;
103 SQLfieldMap* fieldmap;
106 SQLite3Result(Module* self, Module* to, unsigned int id)
107 : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
115 void AddRow(int colsnum, char **data, char **colname)
119 for (int i = 0; i < colsnum; i++)
121 fieldlists.resize(fieldlists.size()+1);
122 colnames.push_back(colname[i]);
123 SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true);
124 fieldlists[rows].push_back(sf);
139 virtual std::string ColName(int column)
141 if (column < (int)colnames.size())
143 return colnames[column];
147 throw SQLbadColName();
152 virtual int ColNum(const std::string &column)
154 for (unsigned int i = 0; i < colnames.size(); i++)
156 if (column == colnames[i])
159 throw SQLbadColName();
163 virtual SQLfield GetValue(int row, int column)
165 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
167 return fieldlists[row][column];
170 throw SQLbadColName();
172 /* XXX: We never actually get here because of the throw */
173 return SQLfield("",true);
176 virtual SQLfieldList& GetRow()
178 if (currentrow < rows)
179 return fieldlists[currentrow];
181 return emptyfieldlist;
184 virtual SQLfieldMap& GetRowMap()
186 /* In an effort to reduce overhead we don't actually allocate the map
187 * until the first time it's needed...so...
195 fieldmap = new SQLfieldMap;
198 if (currentrow < rows)
200 for (int i = 0; i < Cols(); i++)
202 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
210 virtual SQLfieldList* GetRowPtr()
212 fieldlist = new SQLfieldList();
214 if (currentrow < rows)
216 for (int i = 0; i < Rows(); i++)
218 fieldlist->push_back(fieldlists[currentrow][i]);
225 virtual SQLfieldMap* GetRowMapPtr()
227 fieldmap = new SQLfieldMap();
229 if (currentrow < rows)
231 for (int i = 0; i < Cols(); i++)
233 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
241 virtual void Free(SQLfieldMap* fm)
246 virtual void Free(SQLfieldList* fl)
254 class SQLConn : public classbase
264 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
265 : Instance(SI), mod(m), host(hi)
268 if ((result = OpenDB()) == SQLITE_OK)
270 Instance->Log(DEBUG, "Opened sqlite DB: " + host.host);
274 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
284 SQLerror Query(SQLrequest &req)
286 /* Pointer to the buffer we screw around with substitution in */
289 /* Pointer to the current end of query, where we append new stuff */
292 /* Total length of the unescaped parameters */
293 unsigned long paramlen;
295 /* Total length of query, used for binary-safety in mysql_real_query */
296 unsigned long querylength = 0;
299 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
301 paramlen += i->size();
304 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
305 * sizeofquery + (totalparamlength*2) + 1
307 * The +1 is for null-terminating the string for mysql_real_escape_string
310 query = new char[req.query.q.length() + (paramlen*2) + 1];
313 for(unsigned long i = 0; i < req.query.q.length(); i++)
315 if(req.query.q[i] == '?')
317 if(req.query.p.size())
320 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
321 for (char* n = escaped; *n; n++)
326 sqlite3_free(escaped);
327 req.query.p.pop_front();
334 *queryend = req.query.q[i];
342 // Instance->Log(DEBUG, "<******> Doing query: " + ConvToStr(req.query.q.data()));
344 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
346 res->query = req.query.q;
348 params.push_back(this);
349 params.push_back(res);
352 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
354 Instance->Log(DEBUG, "Query failed: " + ConvToStr(errmsg));
355 sqlite3_free(errmsg);
358 return SQLerror(QSEND_FAIL, ConvToStr(errmsg));
360 Instance->Log(DEBUG, "Dispatched query successfully. ID: %d resulting rows %d", req.id, res->Rows());
363 results.push_back(res);
368 static int QueryResult(void *params, int argc, char **argv, char **azColName)
370 paramlist* p = (paramlist*)params;
371 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
375 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
377 res->AddRow(cols, data, colnames);
382 return sqlite3_open(host.host.c_str(), &conn);
387 sqlite3_interrupt(conn);
389 Instance->Log(DEBUG, "Closed sqlite DB: " + host.host);
392 SQLhost GetConfHost()
399 while (results.size())
401 SQLite3Result* res = results[0];
408 /* If the client module is unloaded partway through a query then the provider will set
409 * the pointer to NULL. We cannot just cancel the query as the result will still come
410 * through at some point...and it could get messy if we play with invalid pointers...
412 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()));
421 while (results.size())
423 SQLite3Result* res = results[0];
432 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
434 /* crap, we're out of sockets... */
441 insp_aton("::1", &addr.sin6_addr);
442 addr.sin6_family = AF_FAMILY;
443 addr.sin6_port = htons(resultnotify->GetPort());
446 insp_aton("127.0.0.1", &ia);
447 addr.sin_family = AF_FAMILY;
449 addr.sin_port = htons(resultnotify->GetPort());
452 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
454 /* wtf, we cant connect to it, but we just created it! */
462 class ModuleSQLite3 : public Module
466 unsigned long currid;
469 ModuleSQLite3(InspIRCd* Me)
470 : Module::Module(Me), currid(0)
472 ServerInstance->UseInterface("SQLutils");
474 if (!ServerInstance->PublishFeature("SQL", this))
476 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
479 resultnotify = new ResultNotifier(ServerInstance, this);
480 ServerInstance->Log(DEBUG,"Bound notifier to 127.0.0.1:%d",resultnotify->GetPort());
484 ServerInstance->PublishInterface("SQL", this);
487 virtual ~ModuleSQLite3()
490 ClearAllConnections();
491 resultnotify->SetFd(-1);
492 resultnotify->state = I_ERROR;
493 resultnotify->OnError(I_ERR_SOCKET);
494 resultnotify->ClosePending = true;
496 ServerInstance->UnpublishInterface("SQL", this);
497 ServerInstance->UnpublishFeature("SQL");
498 ServerInstance->DoneWithInterface("SQLutils");
501 void Implements(char* List)
503 List[I_OnRequest] = List[I_OnRehash] = 1;
508 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
510 iter->second->SendResults();
516 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
518 iter->second->ClearResults();
522 bool HasHost(const SQLhost &host)
524 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
526 if (host == iter->second->GetConfHost())
532 bool HostInConf(const SQLhost &h)
534 ConfigReader conf(ServerInstance);
535 for(int i = 0; i < conf.Enumerate("database"); i++)
538 host.id = conf.ReadValue("database", "id", i);
539 host.host = conf.ReadValue("database", "hostname", i);
540 host.port = conf.ReadInteger("database", "port", i, true);
541 host.name = conf.ReadValue("database", "name", i);
542 host.user = conf.ReadValue("database", "username", i);
543 host.pass = conf.ReadValue("database", "password", i);
544 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
553 ClearOldConnections();
555 ConfigReader conf(ServerInstance);
556 for(int i = 0; i < conf.Enumerate("database"); i++)
560 host.id = conf.ReadValue("database", "id", i);
561 host.host = conf.ReadValue("database", "hostname", i);
562 host.port = conf.ReadInteger("database", "port", i, true);
563 host.name = conf.ReadValue("database", "name", i);
564 host.user = conf.ReadValue("database", "username", i);
565 host.pass = conf.ReadValue("database", "password", i);
566 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
575 void AddConn(const SQLhost& hi)
579 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
585 newconn = new SQLConn(ServerInstance, this, hi);
587 connections.insert(std::make_pair(hi.id, newconn));
590 void ClearOldConnections()
592 ConnMap::iterator iter,safei;
593 for (iter = connections.begin(); iter != connections.end(); iter++)
595 if (!HostInConf(iter->second->GetConfHost()))
597 DELETE(iter->second);
600 connections.erase(safei);
605 void ClearAllConnections()
608 while ((i = connections.begin()) != connections.end())
610 connections.erase(i);
615 virtual void OnRehash(userrec* user, const std::string ¶meter)
620 virtual char* OnRequest(Request* request)
622 if(strcmp(SQLREQID, request->GetId()) == 0)
624 SQLrequest* req = (SQLrequest*)request;
625 ConnMap::iterator iter;
626 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());
627 if((iter = connections.find(req->dbid)) != connections.end())
630 req->error = iter->second->Query(*req);
635 req->error.Id(BAD_DBID);
639 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
643 unsigned long NewID()
651 virtual Version GetVersion()
653 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
658 void ResultNotifier::Dispatch()
660 ((ModuleSQLite3*)mod)->SendQueue();
663 class ModuleSQLite3Factory : public ModuleFactory
666 ModuleSQLite3Factory()
670 ~ModuleSQLite3Factory()
674 virtual Module * CreateModule(InspIRCd* Me)
676 return new ModuleSQLite3(Me);
680 extern "C" void * init_module( void )
682 return new ModuleSQLite3Factory;