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 unsigned long count(const char * const str, char a)
50 const char *p = reinterpret_cast<const char *>(str);
52 while ((p = strchr(p, a)) != NULL)
60 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
62 std::string SQLhost::GetDSN()
64 std::ostringstream conninfo("connect_timeout = '2'");
67 conninfo << " hostaddr = '" << ip << "'";
70 conninfo << " port = '" << port << "'";
73 conninfo << " dbname = '" << name << "'";
76 conninfo << " user = '" << user << "'";
79 conninfo << " password = '" << pass << "'";
83 conninfo << " sslmode = 'require'";
87 conninfo << " sslmode = 'disable'";
90 return conninfo.str();
93 class ReconnectTimer : public Timer
98 ReconnectTimer(InspIRCd* SI, Module* m)
99 : Timer(5, SI->Time(), false), mod(m)
102 virtual void Tick(time_t TIME);
106 /** Used to resolve sql server hostnames
108 class SQLresolver : public Resolver
114 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
115 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
119 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached, int resultnum = 0);
121 virtual void OnError(ResolverError e, const std::string &errormessage)
123 ServerInstance->Logs->Log("m_pgsql",DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str());
127 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
128 * All SQL providers must create their own subclass and define it's methods using that
129 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
130 * of converting all data to a common format before it reaches the result structure. This way
131 * data is passes to the module nearly as directly as if it was using the API directly itself.
134 class PgSQLresult : public SQLresult
141 SQLfieldList* fieldlist;
142 SQLfieldMap* fieldmap;
144 PgSQLresult(Module* self, Module* to, unsigned long rid, PGresult* result)
145 : SQLresult(self, to, rid), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
147 rows = PQntuples(res);
148 cols = PQnfields(res);
153 /* If we allocated these, free them... */
167 return atoi(PQcmdTuples(res));
177 return PQnfields(res);
180 virtual std::string ColName(int column)
182 char* name = PQfname(res, column);
184 return (name) ? name : "";
187 virtual int ColNum(const std::string &column)
189 int n = PQfnumber(res, column.c_str());
193 throw SQLbadColName();
201 virtual SQLfield GetValue(int row, int column)
203 char* v = PQgetvalue(res, row, column);
207 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
211 throw SQLbadColName();
215 virtual SQLfieldList& GetRow()
217 /* In an effort to reduce overhead we don't actually allocate the list
218 * until the first time it's needed...so...
226 fieldlist = new SQLfieldList;
229 if(currentrow < PQntuples(res))
231 int ncols = PQnfields(res);
233 for(int i = 0; i < ncols; i++)
235 fieldlist->push_back(GetValue(currentrow, i));
244 virtual SQLfieldMap& GetRowMap()
246 /* In an effort to reduce overhead we don't actually allocate the map
247 * until the first time it's needed...so...
255 fieldmap = new SQLfieldMap;
258 if(currentrow < PQntuples(res))
260 int ncols = PQnfields(res);
262 for(int i = 0; i < ncols; i++)
264 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
273 virtual SQLfieldList* GetRowPtr()
275 SQLfieldList* fl = new SQLfieldList;
277 if(currentrow < PQntuples(res))
279 int ncols = PQnfields(res);
281 for(int i = 0; i < ncols; i++)
283 fl->push_back(GetValue(currentrow, i));
292 virtual SQLfieldMap* GetRowMapPtr()
294 SQLfieldMap* fm = new SQLfieldMap;
296 if(currentrow < PQntuples(res))
298 int ncols = PQnfields(res);
300 for(int i = 0; i < ncols; i++)
302 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
311 virtual void Free(SQLfieldMap* fm)
316 virtual void Free(SQLfieldList* fl)
322 /** SQLConn represents one SQL session.
324 class SQLConn : public EventHandler
327 InspIRCd* ServerInstance;
328 SQLhost confhost; /* The <database> entry */
329 Module* us; /* Pointer to the SQL provider itself */
330 PGconn* sql; /* PgSQL database connection handle */
331 SQLstatus status; /* PgSQL database connection status */
332 bool qinprog; /* If there is currently a query in progress */
333 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
334 time_t idle; /* Time we last heard from the database */
337 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
338 : EventHandler(), ServerInstance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
340 idle = this->ServerInstance->Time();
343 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
353 virtual void HandleEvent(EventType et, int errornum)
376 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
379 if(PQstatus(sql) == CONNECTION_BAD)
382 if(PQsetnonblocking(sql, 1) == -1)
385 /* OK, we've initalised the connection, now to get it hooked into the socket engine
386 * and then start polling it.
388 this->fd = PQsocket(sql);
393 if (!this->ServerInstance->SE->AddFd(this))
395 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
399 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
405 switch(PQconnectPoll(sql))
407 case PGRES_POLLING_WRITING:
408 ServerInstance->SE->WantWrite(this);
411 case PGRES_POLLING_READING:
414 case PGRES_POLLING_FAILED:
416 case PGRES_POLLING_OK:
418 return DoConnectedPoll();
424 bool DoConnectedPoll()
426 if(!qinprog && queue.totalsize())
428 /* There's no query currently in progress, and there's queries in the queue. */
429 SQLrequest& query = queue.front();
433 if(PQconsumeInput(sql))
435 /* We just read stuff from the server, that counts as it being alive
436 * so update the idle-since time :p
438 idle = this->ServerInstance->Time();
442 /* Nothing happens here */
446 /* Grab the request we're processing */
447 SQLrequest& query = queue.front();
449 /* Get a pointer to the module we're about to return the result to */
450 Module* to = query.GetSource();
452 /* Fetch the result.. */
453 PGresult* result = PQgetResult(sql);
455 /* PgSQL would allow a query string to be sent which has multiple
456 * queries in it, this isn't portable across database backends and
457 * we don't want modules doing it. But just in case we make sure we
458 * drain any results there are and just use the last one.
459 * If the module devs are behaving there will only be one result.
461 while (PGresult* temp = PQgetResult(sql))
469 /* ..and the result */
470 PgSQLresult reply(us, to, query.id, result);
472 /* Fix by brain, make sure the original query gets sent back in the reply */
473 reply.query = query.query.q;
475 switch(PQresultStatus(result))
477 case PGRES_EMPTY_QUERY:
478 case PGRES_BAD_RESPONSE:
479 case PGRES_FATAL_ERROR:
480 reply.error.Id(SQL_QREPLY_FAIL);
481 reply.error.Str(PQresultErrorMessage(result));
484 /* No action, other values are not errors */
489 /* PgSQLresult's destructor will free the PGresult */
493 /* If the client module is unloaded partway through a query then the provider will set
494 * the pointer to NULL. We cannot just cancel the query as the result will still come
495 * through at some point...and it could get messy if we play with invalid pointers...
507 /* I think we'll assume this means the server died...it might not,
508 * but I think that any error serious enough we actually get here
509 * deserves to reconnect [/excuse]
510 * Returning true so the core doesn't try and close the connection.
519 switch(PQresetPoll(sql))
521 case PGRES_POLLING_WRITING:
522 ServerInstance->SE->WantWrite(this);
525 case PGRES_POLLING_READING:
528 case PGRES_POLLING_FAILED:
530 case PGRES_POLLING_OK:
532 return DoConnectedPoll();
540 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
546 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
555 void DelayReconnect();
561 if((status == CREAD) || (status == CWRITE))
565 else if((status == RREAD) || (status == RWRITE))
571 ret = DoConnectedPoll();
576 SQLerror DoQuery(SQLrequest &req)
578 if((status == WREAD) || (status == WWRITE))
582 /* Parse the command string and dispatch it */
584 /* Pointer to the buffer we screw around with substitution in */
586 /* Pointer to the current end of query, where we append new stuff */
589 /* Total length of the unescaped parameters */
590 unsigned long maxparamlen, paramcount;
592 /* Total length of query, used for binary-safety */
593 unsigned long querylength = 0;
595 /* The length of the longest parameter */
598 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
600 if (i->size() > maxparamlen)
601 maxparamlen = i->size();
604 /* How many params are there in the query? */
605 paramcount = count(req.query.q.c_str(), '?');
607 /* This stores copy of params to be inserted with using numbered params 1;3B*/
608 ParamL paramscopy(req.query.p);
610 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
611 * sizeofquery + (maxtotalparamlength*2) + 1
613 * The +1 is for null-terminating the string for PQsendQuery()
616 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
619 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
620 * the parameters into it...
623 for(unsigned int i = 0; i < req.query.q.length(); i++)
625 if(req.query.q[i] == '?')
627 /* We found a place to substitute..what fun.
628 * Use the PgSQL calls to escape and write the
629 * escaped string onto the end of our query buffer,
630 * then we "just" need to make sure queryend is
631 * pointing at the right place.
634 /* Is it numbered parameter?
640 /* Numbered parameter number :|
642 unsigned int paramnum;
645 /* Let's check if it's a numbered param. And also calculate it's number.
648 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
652 paramnum = paramnum * 10 + req.query.q[i] - '0';
655 if (paramnum > paramscopy.size() - 1)
657 /* index is out of range!
667 #ifdef PGSQL_HAS_ESCAPECONN
668 len = PQescapeStringConn(sql, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length(), &error);
670 len = PQescapeString (queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
674 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
677 /* Incremenet queryend to the end of the newly escaped parameter */
680 else if (req.query.p.size())
685 #ifdef PGSQL_HAS_ESCAPECONN
686 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
688 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
692 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
695 /* Incremenet queryend to the end of the newly escaped parameter */
698 /* Remove the parameter we just substituted in */
699 req.query.p.pop_front();
703 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
709 *queryend = req.query.q[i];
714 /* Null-terminate the query */
718 if(PQsendQuery(sql, query))
727 return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
731 return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
734 SQLerror Query(const SQLrequest &req)
738 if(!qinprog && queue.totalsize())
740 /* There's no query currently in progress, and there's queries in the queue. */
741 SQLrequest& query = queue.front();
742 return DoQuery(query);
750 void OnUnloadModule(Module* mod)
752 queue.PurgeModule(mod);
755 const SQLhost GetConfHost()
762 if (!this->ServerInstance->SE->DelFd(this))
764 if (sql && PQstatus(sql) == CONNECTION_BAD)
766 this->ServerInstance->SE->DelFd(this, true);
770 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: PQsocket cant be removed from socket engine!");
783 class ModulePgSQL : public Module
787 unsigned long currid;
789 ReconnectTimer* retimer;
792 ModulePgSQL(InspIRCd* Me)
793 : Module(Me), currid(0)
795 ServerInstance->Modules->UseInterface("SQLutils");
797 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
799 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
801 if (!ServerInstance->Modules->PublishFeature("SQL", this))
803 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
808 ServerInstance->Modules->PublishInterface("SQL", this);
809 Implementation eventlist[] = { I_OnUnloadModule, I_OnRequest, I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnUserDisconnect };
810 ServerInstance->Modules->Attach(eventlist, this, 6);
813 virtual ~ModulePgSQL()
816 ServerInstance->Timers->DelTimer(retimer);
817 ClearAllConnections();
819 ServerInstance->Modules->UnpublishInterface("SQL", this);
820 ServerInstance->Modules->UnpublishFeature("SQL");
821 ServerInstance->Modules->DoneWithInterface("SQLutils");
825 virtual void OnRehash(User* user, const std::string ¶meter)
830 bool HasHost(const SQLhost &host)
832 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
834 if (host == iter->second->GetConfHost())
840 bool HostInConf(const SQLhost &h)
842 ConfigReader conf(ServerInstance);
843 for(int i = 0; i < conf.Enumerate("database"); i++)
846 host.id = conf.ReadValue("database", "id", i);
847 host.host = conf.ReadValue("database", "hostname", i);
848 host.port = conf.ReadInteger("database", "port", i, true);
849 host.name = conf.ReadValue("database", "name", i);
850 host.user = conf.ReadValue("database", "username", i);
851 host.pass = conf.ReadValue("database", "password", i);
852 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
861 ClearOldConnections();
863 ConfigReader conf(ServerInstance);
864 for(int i = 0; i < conf.Enumerate("database"); i++)
869 host.id = conf.ReadValue("database", "id", i);
870 host.host = conf.ReadValue("database", "hostname", i);
871 host.port = conf.ReadInteger("database", "port", i, true);
872 host.name = conf.ReadValue("database", "name", i);
873 host.user = conf.ReadValue("database", "username", i);
874 host.pass = conf.ReadValue("database", "password", i);
875 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
881 if (strchr(host.host.c_str(),':'))
884 ipvalid = inet_pton(AF_INET6, host.host.c_str(), &blargle);
890 ipvalid = inet_aton(host.host.c_str(), &blargle);
895 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
899 else if(ipvalid == 0)
901 /* Conversion failed, assume it's a host */
902 SQLresolver* resolver;
907 resolver = new SQLresolver(this, ServerInstance, host, cached);
908 ServerInstance->AddResolver(resolver, cached);
912 /* THE WORLD IS COMING TO AN END! */
917 /* Invalid address family, die horribly. */
918 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: insp_aton failed returning -1, oh noes.");
923 void ClearOldConnections()
925 ConnMap::iterator iter,safei;
926 for (iter = connections.begin(); iter != connections.end(); iter++)
928 if (!HostInConf(iter->second->GetConfHost()))
933 connections.erase(safei);
938 void ClearAllConnections()
941 while ((i = connections.begin()) != connections.end())
943 connections.erase(i);
948 void AddConn(const SQLhost& hi)
952 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());
958 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
959 newconn = new SQLConn(ServerInstance, this, hi);
961 connections.insert(std::make_pair(hi.id, newconn));
964 void ReconnectConn(SQLConn* conn)
966 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
968 if (conn == iter->second)
971 connections.erase(iter);
975 retimer = new ReconnectTimer(ServerInstance, this);
976 ServerInstance->Timers->AddTimer(retimer);
979 virtual const char* OnRequest(Request* request)
981 if(strcmp(SQLREQID, request->GetId()) == 0)
983 SQLrequest* req = (SQLrequest*)request;
984 ConnMap::iterator iter;
985 if((iter = connections.find(req->dbid)) != connections.end())
989 req->error = iter->second->Query(*req);
991 return (req->error.Id() == SQL_NO_ERROR) ? sqlsuccess : NULL;
995 req->error.Id(SQL_BAD_DBID);
1002 virtual void OnUnloadModule(Module* mod, const std::string& name)
1004 /* When a module unloads we have to check all the pending queries for all our connections
1005 * and set the Module* specifying where the query came from to NULL. If the query has already
1006 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1008 * If the queries we find are not already being executed then we can simply remove them immediately.
1010 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1012 iter->second->OnUnloadModule(mod);
1016 unsigned long NewID()
1024 virtual Version GetVersion()
1026 return Version("$Id$", VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1030 /* move this here to use AddConn, rather that than having the whole
1031 * module above SQLConn, since this is buggin me right now :/
1033 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached, int resultnum)
1038 ((ModulePgSQL*)mod)->AddConn(host);
1039 ((ModulePgSQL*)mod)->ClearOldConnections();
1043 void ReconnectTimer::Tick(time_t time)
1045 ((ModulePgSQL*)mod)->ReadConf();
1048 void SQLConn::DelayReconnect()
1050 ((ModulePgSQL*)us)->ReconnectConn(this);
1053 MODULE_INIT(ModulePgSQL)