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 * ---------------------------------------------------
22 /* $ModDesc: sqlite3 provider */
23 /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
24 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
25 /* $ModDep: m_sqlv2.h */
32 typedef std::map<std::string, SQLConn*> ConnMap;
33 typedef std::deque<classbase*> paramlist;
34 typedef std::deque<SQLite3Result*> ResultQueue;
36 ResultNotifier* resultnotify = NULL;
39 class ResultNotifier : public InspSocket
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) : InspSocket(SI, "::1", 0, true, 3000), mod(m)
50 ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(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) : InspSocket(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)
84 class SQLite3Result : public SQLresult
91 std::vector<std::string> colnames;
92 std::vector<SQLfieldList> fieldlists;
93 SQLfieldList emptyfieldlist;
95 SQLfieldList* fieldlist;
96 SQLfieldMap* fieldmap;
99 SQLite3Result(Module* self, Module* to, unsigned int id)
100 : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
108 void AddRow(int colsnum, char **data, char **colname)
112 for (int i = 0; i < colsnum; i++)
114 fieldlists.resize(fieldlists.size()+1);
115 colnames.push_back(colname[i]);
116 SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true);
117 fieldlists[rows].push_back(sf);
122 void UpdateAffectedCount()
137 virtual std::string ColName(int column)
139 if (column < (int)colnames.size())
141 return colnames[column];
145 throw SQLbadColName();
150 virtual int ColNum(const std::string &column)
152 for (unsigned int i = 0; i < colnames.size(); i++)
154 if (column == colnames[i])
157 throw SQLbadColName();
161 virtual SQLfield GetValue(int row, int column)
163 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
165 return fieldlists[row][column];
168 throw SQLbadColName();
170 /* XXX: We never actually get here because of the throw */
171 return SQLfield("",true);
174 virtual SQLfieldList& GetRow()
176 if (currentrow < rows)
177 return fieldlists[currentrow];
179 return emptyfieldlist;
182 virtual SQLfieldMap& GetRowMap()
184 /* In an effort to reduce overhead we don't actually allocate the map
185 * until the first time it's needed...so...
193 fieldmap = new SQLfieldMap;
196 if (currentrow < rows)
198 for (int i = 0; i < Cols(); i++)
200 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
208 virtual SQLfieldList* GetRowPtr()
210 fieldlist = new SQLfieldList();
212 if (currentrow < rows)
214 for (int i = 0; i < Rows(); i++)
216 fieldlist->push_back(fieldlists[currentrow][i]);
223 virtual SQLfieldMap* GetRowMapPtr()
225 fieldmap = new SQLfieldMap();
227 if (currentrow < rows)
229 for (int i = 0; i < Cols(); i++)
231 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
239 virtual void Free(SQLfieldMap* fm)
244 virtual void Free(SQLfieldList* fl)
252 class SQLConn : public classbase
262 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
263 : Instance(SI), mod(m), host(hi)
265 if (OpenDB() != SQLITE_OK)
267 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
277 SQLerror Query(SQLrequest &req)
279 /* Pointer to the buffer we screw around with substitution in */
282 /* Pointer to the current end of query, where we append new stuff */
285 /* Total length of the unescaped parameters */
286 unsigned long paramlen;
288 /* Total length of query, used for binary-safety in mysql_real_query */
289 unsigned long querylength = 0;
292 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
294 paramlen += i->size();
297 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
298 * sizeofquery + (totalparamlength*2) + 1
300 * The +1 is for null-terminating the string for mysql_real_escape_string
302 query = new char[req.query.q.length() + (paramlen*2) + 1];
305 for(unsigned long i = 0; i < req.query.q.length(); i++)
307 if(req.query.q[i] == '?')
309 if(req.query.p.size())
312 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
313 for (char* n = escaped; *n; n++)
318 sqlite3_free(escaped);
319 req.query.p.pop_front();
326 *queryend = req.query.q[i];
334 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
336 res->query = req.query.q;
338 params.push_back(this);
339 params.push_back(res);
342 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
343 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
345 std::string error(errmsg);
346 sqlite3_free(errmsg);
349 return SQLerror(QSEND_FAIL, error);
353 results.push_back(res);
358 static int QueryResult(void *params, int argc, char **argv, char **azColName)
360 paramlist* p = (paramlist*)params;
361 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
365 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
367 paramlist* p = (paramlist*)params;
368 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
371 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
373 res->AddRow(cols, data, colnames);
376 void AffectedReady(SQLite3Result *res)
378 res->UpdateAffectedCount();
383 return sqlite3_open(host.host.c_str(), &conn);
388 sqlite3_interrupt(conn);
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...
420 while (results.size())
422 SQLite3Result* res = results[0];
431 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
433 /* crap, we're out of sockets... */
440 insp_aton("::1", &addr.sin6_addr);
441 addr.sin6_family = AF_FAMILY;
442 addr.sin6_port = htons(resultnotify->GetPort());
445 insp_aton("127.0.0.1", &ia);
446 addr.sin_family = AF_FAMILY;
448 addr.sin_port = htons(resultnotify->GetPort());
451 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
453 /* wtf, we cant connect to it, but we just created it! */
461 class ModuleSQLite3 : public Module
465 unsigned long currid;
468 ModuleSQLite3(InspIRCd* Me)
469 : Module::Module(Me), currid(0)
471 ServerInstance->UseInterface("SQLutils");
473 if (!ServerInstance->PublishFeature("SQL", this))
475 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
478 resultnotify = new ResultNotifier(ServerInstance, this);
482 ServerInstance->PublishInterface("SQL", this);
485 virtual ~ModuleSQLite3()
488 ClearAllConnections();
489 resultnotify->SetFd(-1);
490 resultnotify->state = I_ERROR;
491 resultnotify->OnError(I_ERR_SOCKET);
492 resultnotify->ClosePending = true;
494 ServerInstance->UnpublishInterface("SQL", this);
495 ServerInstance->UnpublishFeature("SQL");
496 ServerInstance->DoneWithInterface("SQLutils");
499 void Implements(char* List)
501 List[I_OnRequest] = List[I_OnRehash] = 1;
506 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
508 iter->second->SendResults();
514 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
516 iter->second->ClearResults();
520 bool HasHost(const SQLhost &host)
522 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
524 if (host == iter->second->GetConfHost())
530 bool HostInConf(const SQLhost &h)
532 ConfigReader conf(ServerInstance);
533 for(int i = 0; i < conf.Enumerate("database"); i++)
536 host.id = conf.ReadValue("database", "id", i);
537 host.host = conf.ReadValue("database", "hostname", i);
538 host.port = conf.ReadInteger("database", "port", i, true);
539 host.name = conf.ReadValue("database", "name", i);
540 host.user = conf.ReadValue("database", "username", i);
541 host.pass = conf.ReadValue("database", "password", i);
542 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
551 ClearOldConnections();
553 ConfigReader conf(ServerInstance);
554 for(int i = 0; i < conf.Enumerate("database"); i++)
558 host.id = conf.ReadValue("database", "id", i);
559 host.host = conf.ReadValue("database", "hostname", i);
560 host.port = conf.ReadInteger("database", "port", i, true);
561 host.name = conf.ReadValue("database", "name", i);
562 host.user = conf.ReadValue("database", "username", i);
563 host.pass = conf.ReadValue("database", "password", i);
564 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
573 void AddConn(const SQLhost& hi)
577 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
583 newconn = new SQLConn(ServerInstance, this, hi);
585 connections.insert(std::make_pair(hi.id, newconn));
588 void ClearOldConnections()
590 ConnMap::iterator iter,safei;
591 for (iter = connections.begin(); iter != connections.end(); iter++)
593 if (!HostInConf(iter->second->GetConfHost()))
595 DELETE(iter->second);
598 connections.erase(safei);
603 void ClearAllConnections()
606 while ((i = connections.begin()) != connections.end())
608 connections.erase(i);
613 virtual void OnRehash(userrec* user, const std::string ¶meter)
618 virtual char* OnRequest(Request* request)
620 if(strcmp(SQLREQID, request->GetId()) == 0)
622 SQLrequest* req = (SQLrequest*)request;
623 ConnMap::iterator iter;
624 if((iter = connections.find(req->dbid)) != connections.end())
627 req->error = iter->second->Query(*req);
632 req->error.Id(BAD_DBID);
639 unsigned long NewID()
647 virtual Version GetVersion()
649 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
654 void ResultNotifier::Dispatch()
656 ((ModuleSQLite3*)mod)->SendQueue();
659 MODULE_INIT(ModuleSQLite3);