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 * ---------------------------------------------------
25 #include "configreader.h"
29 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
30 /* $CompileFlags: -Iexec("pg_config --includedir") eval("my $s = `pg_config --version`;$s =~ /^.*?(\d+)\.(\d+)\.(\d+).*?$/;my $v = hex(sprintf("0x%02x%02x%02x", $1, $2, $3));print "-DPGSQL_HAS_ESCAPECONN" if(($v >= 0x080104) || ($v >= 0x07030F && $v < 0x070400) || ($v >= 0x07040D && $v < 0x080000) || ($v >= 0x080008 && $v < 0x080100));") */
31 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
32 /* $ModDep: m_sqlv2.h */
35 /* SQLConn rewritten by peavey to
36 * use EventHandler instead of
37 * InspSocket. This is much neater
38 * and gives total control of destroy
39 * and delete of resources.
42 /* Forward declare, so we can have the typedef neatly at the top */
45 typedef std::map<std::string, SQLConn*> ConnMap;
47 /* CREAD, Connecting and wants read event
48 * CWRITE, Connecting and wants write event
49 * WREAD, Connected/Working and wants read event
50 * WWRITE, Connected/Working and wants write event
51 * RREAD, Resetting and wants read event
52 * RWRITE, Resetting and wants write event
54 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
56 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
58 std::string SQLhost::GetDSN()
60 std::ostringstream conninfo("connect_timeout = '2'");
63 conninfo << " hostaddr = '" << ip << "'";
66 conninfo << " port = '" << port << "'";
69 conninfo << " dbname = '" << name << "'";
72 conninfo << " user = '" << user << "'";
75 conninfo << " password = '" << pass << "'";
79 conninfo << " sslmode = 'require'";
83 conninfo << " sslmode = 'disable'";
86 return conninfo.str();
89 class ReconnectTimer : public InspTimer
94 ReconnectTimer(InspIRCd* SI, Module* m)
95 : InspTimer(5, SI->Time(), false), mod(m)
98 virtual void Tick(time_t TIME);
102 /** Used to resolve sql server hostnames
104 class SQLresolver : public Resolver
110 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
111 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
115 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached);
117 virtual void OnError(ResolverError e, const std::string &errormessage)
119 ServerInstance->Log(DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str());
123 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
124 * All SQL providers must create their own subclass and define it's methods using that
125 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
126 * of converting all data to a common format before it reaches the result structure. This way
127 * data is passes to the module nearly as directly as if it was using the API directly itself.
130 class PgSQLresult : public SQLresult
137 SQLfieldList* fieldlist;
138 SQLfieldMap* fieldmap;
140 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
141 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
143 rows = PQntuples(res);
144 cols = PQnfields(res);
149 /* If we allocated these, free them... */
163 return atoi(PQcmdTuples(res));
173 return PQnfields(res);
176 virtual std::string ColName(int column)
178 char* name = PQfname(res, column);
180 return (name) ? name : "";
183 virtual int ColNum(const std::string &column)
185 int n = PQfnumber(res, column.c_str());
189 throw SQLbadColName();
197 virtual SQLfield GetValue(int row, int column)
199 char* v = PQgetvalue(res, row, column);
203 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
207 throw SQLbadColName();
211 virtual SQLfieldList& GetRow()
213 /* In an effort to reduce overhead we don't actually allocate the list
214 * until the first time it's needed...so...
222 fieldlist = new SQLfieldList;
225 if(currentrow < PQntuples(res))
227 int cols = PQnfields(res);
229 for(int i = 0; i < cols; i++)
231 fieldlist->push_back(GetValue(currentrow, i));
240 virtual SQLfieldMap& GetRowMap()
242 /* In an effort to reduce overhead we don't actually allocate the map
243 * until the first time it's needed...so...
251 fieldmap = new SQLfieldMap;
254 if(currentrow < PQntuples(res))
256 int cols = PQnfields(res);
258 for(int i = 0; i < cols; i++)
260 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
269 virtual SQLfieldList* GetRowPtr()
271 SQLfieldList* fl = new SQLfieldList;
273 if(currentrow < PQntuples(res))
275 int cols = PQnfields(res);
277 for(int i = 0; i < cols; i++)
279 fl->push_back(GetValue(currentrow, i));
288 virtual SQLfieldMap* GetRowMapPtr()
290 SQLfieldMap* fm = new SQLfieldMap;
292 if(currentrow < PQntuples(res))
294 int cols = PQnfields(res);
296 for(int i = 0; i < cols; i++)
298 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
307 virtual void Free(SQLfieldMap* fm)
312 virtual void Free(SQLfieldList* fl)
318 /** SQLConn represents one SQL session.
320 class SQLConn : public EventHandler
324 SQLhost confhost; /* The <database> entry */
325 Module* us; /* Pointer to the SQL provider itself */
326 PGconn* sql; /* PgSQL database connection handle */
327 SQLstatus status; /* PgSQL database connection status */
328 bool qinprog; /* If there is currently a query in progress */
329 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
330 time_t idle; /* Time we last heard from the database */
333 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
334 : EventHandler(), Instance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
336 idle = this->Instance->Time();
339 Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
349 virtual void HandleEvent(EventType et, int errornum)
372 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
375 if(PQstatus(sql) == CONNECTION_BAD)
378 if(PQsetnonblocking(sql, 1) == -1)
381 /* OK, we've initalised the connection, now to get it hooked into the socket engine
382 * and then start polling it.
384 this->fd = PQsocket(sql);
389 if (!this->Instance->SE->AddFd(this))
391 Instance->Log(DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
395 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
401 switch(PQconnectPoll(sql))
403 case PGRES_POLLING_WRITING:
404 Instance->SE->WantWrite(this);
407 case PGRES_POLLING_READING:
410 case PGRES_POLLING_FAILED:
412 case PGRES_POLLING_OK:
414 return DoConnectedPoll();
420 bool DoConnectedPoll()
422 if(!qinprog && queue.totalsize())
424 /* There's no query currently in progress, and there's queries in the queue. */
425 SQLrequest& query = queue.front();
429 if(PQconsumeInput(sql))
431 /* We just read stuff from the server, that counts as it being alive
432 * so update the idle-since time :p
434 idle = this->Instance->Time();
438 /* Nothing happens here */
442 /* Grab the request we're processing */
443 SQLrequest& query = queue.front();
445 /* Get a pointer to the module we're about to return the result to */
446 Module* to = query.GetSource();
448 /* Fetch the result.. */
449 PGresult* result = PQgetResult(sql);
451 /* PgSQL would allow a query string to be sent which has multiple
452 * queries in it, this isn't portable across database backends and
453 * we don't want modules doing it. But just in case we make sure we
454 * drain any results there are and just use the last one.
455 * If the module devs are behaving there will only be one result.
457 while (PGresult* temp = PQgetResult(sql))
465 /* ..and the result */
466 PgSQLresult reply(us, to, query.id, result);
468 /* Fix by brain, make sure the original query gets sent back in the reply */
469 reply.query = query.query.q;
471 switch(PQresultStatus(result))
473 case PGRES_EMPTY_QUERY:
474 case PGRES_BAD_RESPONSE:
475 case PGRES_FATAL_ERROR:
476 reply.error.Id(QREPLY_FAIL);
477 reply.error.Str(PQresultErrorMessage(result));
479 /* No action, other values are not errors */
484 /* PgSQLresult's destructor will free the PGresult */
488 /* If the client module is unloaded partway through a query then the provider will set
489 * the pointer to NULL. We cannot just cancel the query as the result will still come
490 * through at some point...and it could get messy if we play with invalid pointers...
502 /* I think we'll assume this means the server died...it might not,
503 * but I think that any error serious enough we actually get here
504 * deserves to reconnect [/excuse]
505 * Returning true so the core doesn't try and close the connection.
514 switch(PQresetPoll(sql))
516 case PGRES_POLLING_WRITING:
517 Instance->SE->WantWrite(this);
520 case PGRES_POLLING_READING:
523 case PGRES_POLLING_FAILED:
525 case PGRES_POLLING_OK:
527 return DoConnectedPoll();
535 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
541 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
550 void DelayReconnect();
556 if((status == CREAD) || (status == CWRITE))
560 else if((status == RREAD) || (status == RWRITE))
566 ret = DoConnectedPoll();
571 SQLerror DoQuery(SQLrequest &req)
573 if((status == WREAD) || (status == WWRITE))
577 /* Parse the command string and dispatch it */
579 /* Pointer to the buffer we screw around with substitution in */
581 /* Pointer to the current end of query, where we append new stuff */
583 /* Total length of the unescaped parameters */
584 unsigned int paramlen;
588 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
590 paramlen += i->size();
593 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
594 * sizeofquery + (totalparamlength*2) + 1
596 * The +1 is for null-terminating the string for PQsendQuery()
599 query = new char[req.query.q.length() + (paramlen*2) + 1];
602 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
603 * the parameters into it...
606 for(unsigned int i = 0; i < req.query.q.length(); i++)
608 if(req.query.q[i] == '?')
610 /* We found a place to substitute..what fun.
611 * Use the PgSQL calls to escape and write the
612 * escaped string onto the end of our query buffer,
613 * then we "just" need to make sure queryend is
614 * pointing at the right place.
617 if(req.query.p.size())
622 #ifdef PGSQL_HAS_ESCAPECONN
623 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
625 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
629 Instance->Log(DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
632 /* Incremenet queryend to the end of the newly escaped parameter */
635 /* Remove the parameter we just substituted in */
636 req.query.p.pop_front();
640 Instance->Log(DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
646 *queryend = req.query.q[i];
651 /* Null-terminate the query */
655 if(PQsendQuery(sql, query))
664 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
668 return SQLerror(BAD_CONN, "Can't query until connection is complete");
671 SQLerror Query(const SQLrequest &req)
675 if(!qinprog && queue.totalsize())
677 /* There's no query currently in progress, and there's queries in the queue. */
678 SQLrequest& query = queue.front();
679 return DoQuery(query);
687 void OnUnloadModule(Module* mod)
689 queue.PurgeModule(mod);
692 const SQLhost GetConfHost()
698 if (!this->Instance->SE->DelFd(this))
700 if (sql && PQstatus(sql) == CONNECTION_BAD)
702 this->Instance->SE->DelFd(this, true);
706 Instance->Log(DEBUG, "BUG: PQsocket cant be removed from socket engine!");
719 class ModulePgSQL : public Module
723 unsigned long currid;
725 ReconnectTimer* retimer;
728 ModulePgSQL(InspIRCd* Me)
729 : Module::Module(Me), currid(0)
731 ServerInstance->UseInterface("SQLutils");
733 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
735 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
737 if (!ServerInstance->PublishFeature("SQL", this))
739 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
744 ServerInstance->PublishInterface("SQL", this);
747 virtual ~ModulePgSQL()
750 ServerInstance->Timers->DelTimer(retimer);
751 ClearAllConnections();
753 ServerInstance->UnpublishInterface("SQL", this);
754 ServerInstance->UnpublishFeature("SQL");
755 ServerInstance->DoneWithInterface("SQLutils");
758 void Implements(char* List)
760 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
763 virtual void OnRehash(userrec* user, const std::string ¶meter)
768 bool HasHost(const SQLhost &host)
770 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
772 if (host == iter->second->GetConfHost())
778 bool HostInConf(const SQLhost &h)
780 ConfigReader conf(ServerInstance);
781 for(int i = 0; i < conf.Enumerate("database"); i++)
784 host.id = conf.ReadValue("database", "id", i);
785 host.host = conf.ReadValue("database", "hostname", i);
786 host.port = conf.ReadInteger("database", "port", i, true);
787 host.name = conf.ReadValue("database", "name", i);
788 host.user = conf.ReadValue("database", "username", i);
789 host.pass = conf.ReadValue("database", "password", i);
790 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
799 ClearOldConnections();
801 ConfigReader conf(ServerInstance);
802 for(int i = 0; i < conf.Enumerate("database"); i++)
807 host.id = conf.ReadValue("database", "id", i);
808 host.host = conf.ReadValue("database", "hostname", i);
809 host.port = conf.ReadInteger("database", "port", i, true);
810 host.name = conf.ReadValue("database", "name", i);
811 host.user = conf.ReadValue("database", "username", i);
812 host.pass = conf.ReadValue("database", "password", i);
813 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
819 if (strchr(host.host.c_str(),':'))
822 ipvalid = inet_pton(AF_INET6, host.host.c_str(), &blargle);
827 ipvalid = inet_aton(host.host.c_str(), &blargle);
831 ipvalid = inet_aton(host.host.c_str(), &blargle);
836 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
840 else if(ipvalid == 0)
842 /* Conversion failed, assume it's a host */
843 SQLresolver* resolver;
848 resolver = new SQLresolver(this, ServerInstance, host, cached);
849 ServerInstance->AddResolver(resolver, cached);
853 /* THE WORLD IS COMING TO AN END! */
858 /* Invalid address family, die horribly. */
859 ServerInstance->Log(DEBUG, "BUG: insp_aton failed returning -1, oh noes.");
864 void ClearOldConnections()
866 ConnMap::iterator iter,safei;
867 for (iter = connections.begin(); iter != connections.end(); iter++)
869 if (!HostInConf(iter->second->GetConfHost()))
871 DELETE(iter->second);
874 connections.erase(safei);
879 void ClearAllConnections()
882 while ((i = connections.begin()) != connections.end())
884 connections.erase(i);
889 void AddConn(const SQLhost& hi)
893 ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
899 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
900 newconn = new SQLConn(ServerInstance, this, hi);
902 connections.insert(std::make_pair(hi.id, newconn));
905 void ReconnectConn(SQLConn* conn)
907 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
909 if (conn == iter->second)
911 DELETE(iter->second);
912 connections.erase(iter);
916 retimer = new ReconnectTimer(ServerInstance, this);
917 ServerInstance->Timers->AddTimer(retimer);
920 virtual char* OnRequest(Request* request)
922 if(strcmp(SQLREQID, request->GetId()) == 0)
924 SQLrequest* req = (SQLrequest*)request;
925 ConnMap::iterator iter;
926 if((iter = connections.find(req->dbid)) != connections.end())
930 req->error = iter->second->Query(*req);
932 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
936 req->error.Id(BAD_DBID);
943 virtual void OnUnloadModule(Module* mod, const std::string& name)
945 /* When a module unloads we have to check all the pending queries for all our connections
946 * and set the Module* specifying where the query came from to NULL. If the query has already
947 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
949 * If the queries we find are not already being executed then we can simply remove them immediately.
951 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
953 iter->second->OnUnloadModule(mod);
957 unsigned long NewID()
965 virtual Version GetVersion()
967 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
971 /* move this here to use AddConn, rather that than having the whole
972 * module above SQLConn, since this is buggin me right now :/
974 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
977 ((ModulePgSQL*)mod)->AddConn(host);
978 ((ModulePgSQL*)mod)->ClearOldConnections();
981 void ReconnectTimer::Tick(time_t time)
983 ((ModulePgSQL*)mod)->ReadConf();
986 void SQLConn::DelayReconnect()
988 ((ModulePgSQL*)us)->ReconnectConn(this);
992 class ModulePgSQLFactory : public ModuleFactory
999 ~ModulePgSQLFactory()
1003 virtual Module * CreateModule(InspIRCd* Me)
1005 return new ModulePgSQL(Me);
1010 extern "C" void * init_module( void )
1012 return new ModulePgSQLFactory;