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 */
31 typedef std::map<std::string, SQLConn*> ConnMap;
32 typedef std::deque<classbase*> paramlist;
33 typedef std::deque<SQLite3Result*> ResultQueue;
35 ResultNotifier* resultnotify = NULL;
38 class ResultNotifier : public BufferedSocket
41 insp_sockaddr sock_us;
45 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
47 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "::1", 0, true, 3000), mod(m)
49 ResultNotifier(InspIRCd* SI, Module* m) : BufferedSocket(SI, "127.0.0.1", 0, true, 3000), mod(m)
52 uslen = sizeof(sock_us);
53 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
55 throw ModuleException("Could not create random listening port on localhost");
59 ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
63 /* Using getsockname and ntohs, we can determine which port number we were allocated */
67 return ntohs(sock_us.sin6_port);
69 return ntohs(sock_us.sin_port);
73 virtual int OnIncomingConnection(int newsock, char* ip)
83 class SQLite3Result : public SQLresult
90 std::vector<std::string> colnames;
91 std::vector<SQLfieldList> fieldlists;
92 SQLfieldList emptyfieldlist;
94 SQLfieldList* fieldlist;
95 SQLfieldMap* fieldmap;
98 SQLite3Result(Module* self, Module* to, unsigned int id)
99 : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
107 void AddRow(int colsnum, char **data, char **colname)
111 for (int i = 0; i < colsnum; i++)
113 fieldlists.resize(fieldlists.size()+1);
114 colnames.push_back(colname[i]);
115 SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true);
116 fieldlists[rows].push_back(sf);
121 void UpdateAffectedCount()
136 virtual std::string ColName(int column)
138 if (column < (int)colnames.size())
140 return colnames[column];
144 throw SQLbadColName();
149 virtual int ColNum(const std::string &column)
151 for (unsigned int i = 0; i < colnames.size(); i++)
153 if (column == colnames[i])
156 throw SQLbadColName();
160 virtual SQLfield GetValue(int row, int column)
162 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
164 return fieldlists[row][column];
167 throw SQLbadColName();
169 /* XXX: We never actually get here because of the throw */
170 return SQLfield("",true);
173 virtual SQLfieldList& GetRow()
175 if (currentrow < rows)
176 return fieldlists[currentrow];
178 return emptyfieldlist;
181 virtual SQLfieldMap& GetRowMap()
183 /* In an effort to reduce overhead we don't actually allocate the map
184 * until the first time it's needed...so...
192 fieldmap = new SQLfieldMap;
195 if (currentrow < rows)
197 for (int i = 0; i < Cols(); i++)
199 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
207 virtual SQLfieldList* GetRowPtr()
209 fieldlist = new SQLfieldList();
211 if (currentrow < rows)
213 for (int i = 0; i < Rows(); i++)
215 fieldlist->push_back(fieldlists[currentrow][i]);
222 virtual SQLfieldMap* GetRowMapPtr()
224 fieldmap = new SQLfieldMap();
226 if (currentrow < rows)
228 for (int i = 0; i < Cols(); i++)
230 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
238 virtual void Free(SQLfieldMap* fm)
243 virtual void Free(SQLfieldList* fl)
251 class SQLConn : public classbase
261 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
262 : Instance(SI), mod(m), host(hi)
264 if (OpenDB() != SQLITE_OK)
266 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
276 SQLerror Query(SQLrequest &req)
278 /* Pointer to the buffer we screw around with substitution in */
281 /* Pointer to the current end of query, where we append new stuff */
284 /* Total length of the unescaped parameters */
285 unsigned long paramlen;
287 /* Total length of query, used for binary-safety in mysql_real_query */
288 unsigned long querylength = 0;
291 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
293 paramlen += i->size();
296 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
297 * sizeofquery + (totalparamlength*2) + 1
299 * The +1 is for null-terminating the string for mysql_real_escape_string
301 query = new char[req.query.q.length() + (paramlen*2) + 1];
304 for(unsigned long i = 0; i < req.query.q.length(); i++)
306 if(req.query.q[i] == '?')
308 if(req.query.p.size())
311 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
312 for (char* n = escaped; *n; n++)
317 sqlite3_free(escaped);
318 req.query.p.pop_front();
325 *queryend = req.query.q[i];
333 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
335 res->query = req.query.q;
337 params.push_back(this);
338 params.push_back(res);
341 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
342 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
344 std::string error(errmsg);
345 sqlite3_free(errmsg);
348 return SQLerror(QSEND_FAIL, error);
352 results.push_back(res);
357 static int QueryResult(void *params, int argc, char **argv, char **azColName)
359 paramlist* p = (paramlist*)params;
360 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
364 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
366 paramlist* p = (paramlist*)params;
367 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
370 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
372 res->AddRow(cols, data, colnames);
375 void AffectedReady(SQLite3Result *res)
377 res->UpdateAffectedCount();
382 return sqlite3_open(host.host.c_str(), &conn);
387 sqlite3_interrupt(conn);
391 SQLhost GetConfHost()
398 while (results.size())
400 SQLite3Result* res = results[0];
407 /* If the client module is unloaded partway through a query then the provider will set
408 * the pointer to NULL. We cannot just cancel the query as the result will still come
409 * through at some point...and it could get messy if we play with invalid pointers...
419 while (results.size())
421 SQLite3Result* res = results[0];
430 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
432 /* crap, we're out of sockets... */
439 insp_aton("::1", &addr.sin6_addr);
440 addr.sin6_family = AF_FAMILY;
441 addr.sin6_port = htons(resultnotify->GetPort());
444 insp_aton("127.0.0.1", &ia);
445 addr.sin_family = AF_FAMILY;
447 addr.sin_port = htons(resultnotify->GetPort());
450 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
452 /* wtf, we cant connect to it, but we just created it! */
460 class ModuleSQLite3 : public Module
464 unsigned long currid;
467 ModuleSQLite3(InspIRCd* Me)
468 : Module::Module(Me), currid(0)
470 ServerInstance->Modules->UseInterface("SQLutils");
472 if (!ServerInstance->Modules->PublishFeature("SQL", this))
474 throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
477 resultnotify = new ResultNotifier(ServerInstance, this);
481 ServerInstance->Modules->PublishInterface("SQL", this);
484 virtual ~ModuleSQLite3()
487 ClearAllConnections();
488 resultnotify->SetFd(-1);
489 resultnotify->state = I_ERROR;
490 resultnotify->OnError(I_ERR_SOCKET);
491 resultnotify->ClosePending = true;
493 ServerInstance->Modules->UnpublishInterface("SQL", this);
494 ServerInstance->Modules->UnpublishFeature("SQL");
495 ServerInstance->Modules->DoneWithInterface("SQLutils");
498 void Implements(char* List)
500 List[I_OnRequest] = List[I_OnRehash] = 1;
505 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
507 iter->second->SendResults();
513 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
515 iter->second->ClearResults();
519 bool HasHost(const SQLhost &host)
521 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
523 if (host == iter->second->GetConfHost())
529 bool HostInConf(const SQLhost &h)
531 ConfigReader conf(ServerInstance);
532 for(int i = 0; i < conf.Enumerate("database"); i++)
535 host.id = conf.ReadValue("database", "id", i);
536 host.host = conf.ReadValue("database", "hostname", i);
537 host.port = conf.ReadInteger("database", "port", i, true);
538 host.name = conf.ReadValue("database", "name", i);
539 host.user = conf.ReadValue("database", "username", i);
540 host.pass = conf.ReadValue("database", "password", i);
541 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
550 ClearOldConnections();
552 ConfigReader conf(ServerInstance);
553 for(int i = 0; i < conf.Enumerate("database"); i++)
557 host.id = conf.ReadValue("database", "id", i);
558 host.host = conf.ReadValue("database", "hostname", i);
559 host.port = conf.ReadInteger("database", "port", i, true);
560 host.name = conf.ReadValue("database", "name", i);
561 host.user = conf.ReadValue("database", "username", i);
562 host.pass = conf.ReadValue("database", "password", i);
563 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
572 void AddConn(const SQLhost& hi)
576 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
582 newconn = new SQLConn(ServerInstance, this, hi);
584 connections.insert(std::make_pair(hi.id, newconn));
587 void ClearOldConnections()
589 ConnMap::iterator iter,safei;
590 for (iter = connections.begin(); iter != connections.end(); iter++)
592 if (!HostInConf(iter->second->GetConfHost()))
594 DELETE(iter->second);
597 connections.erase(safei);
602 void ClearAllConnections()
605 while ((i = connections.begin()) != connections.end())
607 connections.erase(i);
612 virtual void OnRehash(User* user, const std::string ¶meter)
617 virtual char* OnRequest(Request* request)
619 if(strcmp(SQLREQID, request->GetId()) == 0)
621 SQLrequest* req = (SQLrequest*)request;
622 ConnMap::iterator iter;
623 if((iter = connections.find(req->dbid)) != connections.end())
626 req->error = iter->second->Query(*req);
631 req->error.Id(BAD_DBID);
638 unsigned long NewID()
646 virtual Version GetVersion()
648 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
653 void ResultNotifier::Dispatch()
655 ((ModuleSQLite3*)mod)->SendQueue();
658 MODULE_INIT(ModuleSQLite3)