1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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 * ---------------------------------------------------
20 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
21 /* $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));") */
22 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
23 /* $ModDep: m_sqlv2.h */
26 /* SQLConn rewritten by peavey to
27 * use EventHandler instead of
28 * BufferedSocket. This is much neater
29 * and gives total control of destroy
30 * and delete of resources.
33 /* Forward declare, so we can have the typedef neatly at the top */
36 typedef std::map<std::string, SQLConn*> ConnMap;
38 /* CREAD, Connecting and wants read event
39 * CWRITE, Connecting and wants write event
40 * WREAD, Connected/Working and wants read event
41 * WWRITE, Connected/Working and wants write event
42 * RREAD, Resetting and wants read event
43 * RWRITE, Resetting and wants write event
45 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
47 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
49 std::string SQLhost::GetDSN()
51 std::ostringstream conninfo("connect_timeout = '2'");
54 conninfo << " hostaddr = '" << ip << "'";
57 conninfo << " port = '" << port << "'";
60 conninfo << " dbname = '" << name << "'";
63 conninfo << " user = '" << user << "'";
66 conninfo << " password = '" << pass << "'";
70 conninfo << " sslmode = 'require'";
74 conninfo << " sslmode = 'disable'";
77 return conninfo.str();
80 class ReconnectTimer : public Timer
85 ReconnectTimer(InspIRCd* SI, Module* m)
86 : Timer(5, SI->Time(), false), mod(m)
89 virtual void Tick(time_t TIME);
93 /** Used to resolve sql server hostnames
95 class SQLresolver : public Resolver
101 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
102 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
106 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached, int resultnum = 0);
108 virtual void OnError(ResolverError e, const std::string &errormessage)
110 ServerInstance->Logs->Log("m_pgsql",DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str());
114 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
115 * All SQL providers must create their own subclass and define it's methods using that
116 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
117 * of converting all data to a common format before it reaches the result structure. This way
118 * data is passes to the module nearly as directly as if it was using the API directly itself.
121 class PgSQLresult : public SQLresult
128 SQLfieldList* fieldlist;
129 SQLfieldMap* fieldmap;
131 PgSQLresult(Module* self, Module* to, unsigned long rid, PGresult* result)
132 : SQLresult(self, to, rid), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
134 rows = PQntuples(res);
135 cols = PQnfields(res);
140 /* If we allocated these, free them... */
154 return atoi(PQcmdTuples(res));
164 return PQnfields(res);
167 virtual std::string ColName(int column)
169 char* name = PQfname(res, column);
171 return (name) ? name : "";
174 virtual int ColNum(const std::string &column)
176 int n = PQfnumber(res, column.c_str());
180 throw SQLbadColName();
188 virtual SQLfield GetValue(int row, int column)
190 char* v = PQgetvalue(res, row, column);
194 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
198 throw SQLbadColName();
202 virtual SQLfieldList& GetRow()
204 /* In an effort to reduce overhead we don't actually allocate the list
205 * until the first time it's needed...so...
213 fieldlist = new SQLfieldList;
216 if(currentrow < PQntuples(res))
218 int ncols = PQnfields(res);
220 for(int i = 0; i < ncols; i++)
222 fieldlist->push_back(GetValue(currentrow, i));
231 virtual SQLfieldMap& GetRowMap()
233 /* In an effort to reduce overhead we don't actually allocate the map
234 * until the first time it's needed...so...
242 fieldmap = new SQLfieldMap;
245 if(currentrow < PQntuples(res))
247 int ncols = PQnfields(res);
249 for(int i = 0; i < ncols; i++)
251 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
260 virtual SQLfieldList* GetRowPtr()
262 SQLfieldList* fl = new SQLfieldList;
264 if(currentrow < PQntuples(res))
266 int ncols = PQnfields(res);
268 for(int i = 0; i < ncols; i++)
270 fl->push_back(GetValue(currentrow, i));
279 virtual SQLfieldMap* GetRowMapPtr()
281 SQLfieldMap* fm = new SQLfieldMap;
283 if(currentrow < PQntuples(res))
285 int ncols = PQnfields(res);
287 for(int i = 0; i < ncols; i++)
289 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
298 virtual void Free(SQLfieldMap* fm)
303 virtual void Free(SQLfieldList* fl)
309 /** SQLConn represents one SQL session.
311 class SQLConn : public EventHandler
314 InspIRCd* ServerInstance;
315 SQLhost confhost; /* The <database> entry */
316 Module* us; /* Pointer to the SQL provider itself */
317 PGconn* sql; /* PgSQL database connection handle */
318 SQLstatus status; /* PgSQL database connection status */
319 bool qinprog; /* If there is currently a query in progress */
320 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
321 time_t idle; /* Time we last heard from the database */
324 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
325 : EventHandler(), ServerInstance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
327 idle = this->ServerInstance->Time();
330 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
340 virtual void HandleEvent(EventType et, int errornum)
363 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
366 if(PQstatus(sql) == CONNECTION_BAD)
369 if(PQsetnonblocking(sql, 1) == -1)
372 /* OK, we've initalised the connection, now to get it hooked into the socket engine
373 * and then start polling it.
375 this->fd = PQsocket(sql);
380 if (!this->ServerInstance->SE->AddFd(this))
382 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
386 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
392 switch(PQconnectPoll(sql))
394 case PGRES_POLLING_WRITING:
395 ServerInstance->SE->WantWrite(this);
398 case PGRES_POLLING_READING:
401 case PGRES_POLLING_FAILED:
403 case PGRES_POLLING_OK:
405 return DoConnectedPoll();
411 bool DoConnectedPoll()
413 if(!qinprog && queue.totalsize())
415 /* There's no query currently in progress, and there's queries in the queue. */
416 SQLrequest& query = queue.front();
420 if(PQconsumeInput(sql))
422 /* We just read stuff from the server, that counts as it being alive
423 * so update the idle-since time :p
425 idle = this->ServerInstance->Time();
429 /* Nothing happens here */
433 /* Grab the request we're processing */
434 SQLrequest& query = queue.front();
436 /* Get a pointer to the module we're about to return the result to */
437 Module* to = query.GetSource();
439 /* Fetch the result.. */
440 PGresult* result = PQgetResult(sql);
442 /* PgSQL would allow a query string to be sent which has multiple
443 * queries in it, this isn't portable across database backends and
444 * we don't want modules doing it. But just in case we make sure we
445 * drain any results there are and just use the last one.
446 * If the module devs are behaving there will only be one result.
448 while (PGresult* temp = PQgetResult(sql))
456 /* ..and the result */
457 PgSQLresult reply(us, to, query.id, result);
459 /* Fix by brain, make sure the original query gets sent back in the reply */
460 reply.query = query.query.q;
462 switch(PQresultStatus(result))
464 case PGRES_EMPTY_QUERY:
465 case PGRES_BAD_RESPONSE:
466 case PGRES_FATAL_ERROR:
467 reply.error.Id(SQL_QREPLY_FAIL);
468 reply.error.Str(PQresultErrorMessage(result));
470 /* No action, other values are not errors */
475 /* PgSQLresult's destructor will free the PGresult */
479 /* If the client module is unloaded partway through a query then the provider will set
480 * the pointer to NULL. We cannot just cancel the query as the result will still come
481 * through at some point...and it could get messy if we play with invalid pointers...
493 /* I think we'll assume this means the server died...it might not,
494 * but I think that any error serious enough we actually get here
495 * deserves to reconnect [/excuse]
496 * Returning true so the core doesn't try and close the connection.
505 switch(PQresetPoll(sql))
507 case PGRES_POLLING_WRITING:
508 ServerInstance->SE->WantWrite(this);
511 case PGRES_POLLING_READING:
514 case PGRES_POLLING_FAILED:
516 case PGRES_POLLING_OK:
518 return DoConnectedPoll();
526 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
532 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
541 void DelayReconnect();
547 if((status == CREAD) || (status == CWRITE))
551 else if((status == RREAD) || (status == RWRITE))
557 ret = DoConnectedPoll();
562 SQLerror DoQuery(SQLrequest &req)
564 if((status == WREAD) || (status == WWRITE))
568 /* Parse the command string and dispatch it */
570 /* Pointer to the buffer we screw around with substitution in */
572 /* Pointer to the current end of query, where we append new stuff */
574 /* Total length of the unescaped parameters */
575 unsigned int paramlen;
579 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
581 paramlen += i->size();
584 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
585 * sizeofquery + (totalparamlength*2) + 1
587 * The +1 is for null-terminating the string for PQsendQuery()
590 query = new char[req.query.q.length() + (paramlen*2) + 1];
593 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
594 * the parameters into it...
597 for(unsigned int i = 0; i < req.query.q.length(); i++)
599 if(req.query.q[i] == '?')
601 /* We found a place to substitute..what fun.
602 * Use the PgSQL calls to escape and write the
603 * escaped string onto the end of our query buffer,
604 * then we "just" need to make sure queryend is
605 * pointing at the right place.
608 if(req.query.p.size())
613 #ifdef PGSQL_HAS_ESCAPECONN
614 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
616 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
620 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
623 /* Incremenet queryend to the end of the newly escaped parameter */
626 /* Remove the parameter we just substituted in */
627 req.query.p.pop_front();
631 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
637 *queryend = req.query.q[i];
642 /* Null-terminate the query */
646 if(PQsendQuery(sql, query))
655 return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
659 return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
662 SQLerror Query(const SQLrequest &req)
666 if(!qinprog && queue.totalsize())
668 /* There's no query currently in progress, and there's queries in the queue. */
669 SQLrequest& query = queue.front();
670 return DoQuery(query);
678 void OnUnloadModule(Module* mod)
680 queue.PurgeModule(mod);
683 const SQLhost GetConfHost()
689 if (!this->ServerInstance->SE->DelFd(this))
691 if (sql && PQstatus(sql) == CONNECTION_BAD)
693 this->ServerInstance->SE->DelFd(this, true);
697 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: PQsocket cant be removed from socket engine!");
710 class ModulePgSQL : public Module
714 unsigned long currid;
716 ReconnectTimer* retimer;
719 ModulePgSQL(InspIRCd* Me)
720 : Module(Me), currid(0)
722 ServerInstance->Modules->UseInterface("SQLutils");
724 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
726 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
728 if (!ServerInstance->Modules->PublishFeature("SQL", this))
730 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
735 ServerInstance->Modules->PublishInterface("SQL", this);
736 Implementation eventlist[] = { I_OnUnloadModule, I_OnRequest, I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnUserDisconnect };
737 ServerInstance->Modules->Attach(eventlist, this, 6);
740 virtual ~ModulePgSQL()
743 ServerInstance->Timers->DelTimer(retimer);
744 ClearAllConnections();
746 ServerInstance->Modules->UnpublishInterface("SQL", this);
747 ServerInstance->Modules->UnpublishFeature("SQL");
748 ServerInstance->Modules->DoneWithInterface("SQLutils");
752 virtual void OnRehash(User* user, const std::string ¶meter)
757 bool HasHost(const SQLhost &host)
759 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
761 if (host == iter->second->GetConfHost())
767 bool HostInConf(const SQLhost &h)
769 ConfigReader conf(ServerInstance);
770 for(int i = 0; i < conf.Enumerate("database"); i++)
773 host.id = conf.ReadValue("database", "id", i);
774 host.host = conf.ReadValue("database", "hostname", i);
775 host.port = conf.ReadInteger("database", "port", i, true);
776 host.name = conf.ReadValue("database", "name", i);
777 host.user = conf.ReadValue("database", "username", i);
778 host.pass = conf.ReadValue("database", "password", i);
779 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
788 ClearOldConnections();
790 ConfigReader conf(ServerInstance);
791 for(int i = 0; i < conf.Enumerate("database"); i++)
796 host.id = conf.ReadValue("database", "id", i);
797 host.host = conf.ReadValue("database", "hostname", i);
798 host.port = conf.ReadInteger("database", "port", i, true);
799 host.name = conf.ReadValue("database", "name", i);
800 host.user = conf.ReadValue("database", "username", i);
801 host.pass = conf.ReadValue("database", "password", i);
802 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
808 if (strchr(host.host.c_str(),':'))
811 ipvalid = inet_pton(AF_INET6, host.host.c_str(), &blargle);
817 ipvalid = inet_aton(host.host.c_str(), &blargle);
822 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
826 else if(ipvalid == 0)
828 /* Conversion failed, assume it's a host */
829 SQLresolver* resolver;
834 resolver = new SQLresolver(this, ServerInstance, host, cached);
835 ServerInstance->AddResolver(resolver, cached);
839 /* THE WORLD IS COMING TO AN END! */
844 /* Invalid address family, die horribly. */
845 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: insp_aton failed returning -1, oh noes.");
850 void ClearOldConnections()
852 ConnMap::iterator iter,safei;
853 for (iter = connections.begin(); iter != connections.end(); iter++)
855 if (!HostInConf(iter->second->GetConfHost()))
860 connections.erase(safei);
865 void ClearAllConnections()
868 while ((i = connections.begin()) != connections.end())
870 connections.erase(i);
875 void AddConn(const SQLhost& hi)
879 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
885 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
886 newconn = new SQLConn(ServerInstance, this, hi);
888 connections.insert(std::make_pair(hi.id, newconn));
891 void ReconnectConn(SQLConn* conn)
893 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
895 if (conn == iter->second)
898 connections.erase(iter);
902 retimer = new ReconnectTimer(ServerInstance, this);
903 ServerInstance->Timers->AddTimer(retimer);
906 virtual const char* OnRequest(Request* request)
908 if(strcmp(SQLREQID, request->GetId()) == 0)
910 SQLrequest* req = (SQLrequest*)request;
911 ConnMap::iterator iter;
912 if((iter = connections.find(req->dbid)) != connections.end())
916 req->error = iter->second->Query(*req);
918 return (req->error.Id() == SQL_NO_ERROR) ? sqlsuccess : NULL;
922 req->error.Id(SQL_BAD_DBID);
929 virtual void OnUnloadModule(Module* mod, const std::string& name)
931 /* When a module unloads we have to check all the pending queries for all our connections
932 * and set the Module* specifying where the query came from to NULL. If the query has already
933 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
935 * If the queries we find are not already being executed then we can simply remove them immediately.
937 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
939 iter->second->OnUnloadModule(mod);
943 unsigned long NewID()
951 virtual Version GetVersion()
953 return Version("$Id$", VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
957 /* move this here to use AddConn, rather that than having the whole
958 * module above SQLConn, since this is buggin me right now :/
960 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached, int resultnum)
965 ((ModulePgSQL*)mod)->AddConn(host);
966 ((ModulePgSQL*)mod)->ClearOldConnections();
970 void ReconnectTimer::Tick(time_t time)
972 ((ModulePgSQL*)mod)->ReadConf();
975 void SQLConn::DelayReconnect()
977 ((ModulePgSQL*)us)->ReconnectConn(this);
980 MODULE_INIT(ModulePgSQL)