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 for (const char *p = reinterpret_cast<const char *>(str); *p; ++p)
58 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
60 std::string SQLhost::GetDSN()
62 std::ostringstream conninfo("connect_timeout = '2'");
65 conninfo << " hostaddr = '" << ip << "'";
68 conninfo << " port = '" << port << "'";
71 conninfo << " dbname = '" << name << "'";
74 conninfo << " user = '" << user << "'";
77 conninfo << " password = '" << pass << "'";
81 conninfo << " sslmode = 'require'";
85 conninfo << " sslmode = 'disable'";
88 return conninfo.str();
91 class ReconnectTimer : public Timer
96 ReconnectTimer(InspIRCd* SI, Module* m)
97 : Timer(5, SI->Time(), false), mod(m)
100 virtual void Tick(time_t TIME);
104 /** Used to resolve sql server hostnames
106 class SQLresolver : public Resolver
112 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
113 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
117 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached, int resultnum = 0);
119 virtual void OnError(ResolverError e, const std::string &errormessage)
121 ServerInstance->Logs->Log("m_pgsql",DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str());
125 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
126 * All SQL providers must create their own subclass and define it's methods using that
127 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
128 * of converting all data to a common format before it reaches the result structure. This way
129 * data is passes to the module nearly as directly as if it was using the API directly itself.
132 class PgSQLresult : public SQLresult
139 SQLfieldList* fieldlist;
140 SQLfieldMap* fieldmap;
142 PgSQLresult(Module* self, Module* to, unsigned long rid, PGresult* result)
143 : SQLresult(self, to, rid), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
145 rows = PQntuples(res);
146 cols = PQnfields(res);
151 /* If we allocated these, free them... */
165 return atoi(PQcmdTuples(res));
175 return PQnfields(res);
178 virtual std::string ColName(int column)
180 char* name = PQfname(res, column);
182 return (name) ? name : "";
185 virtual int ColNum(const std::string &column)
187 int n = PQfnumber(res, column.c_str());
191 throw SQLbadColName();
199 virtual SQLfield GetValue(int row, int column)
201 char* v = PQgetvalue(res, row, column);
205 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
209 throw SQLbadColName();
213 virtual SQLfieldList& GetRow()
215 /* In an effort to reduce overhead we don't actually allocate the list
216 * until the first time it's needed...so...
224 fieldlist = new SQLfieldList;
227 if(currentrow < PQntuples(res))
229 int ncols = PQnfields(res);
231 for(int i = 0; i < ncols; i++)
233 fieldlist->push_back(GetValue(currentrow, i));
242 virtual SQLfieldMap& GetRowMap()
244 /* In an effort to reduce overhead we don't actually allocate the map
245 * until the first time it's needed...so...
253 fieldmap = new SQLfieldMap;
256 if(currentrow < PQntuples(res))
258 int ncols = PQnfields(res);
260 for(int i = 0; i < ncols; i++)
262 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
271 virtual SQLfieldList* GetRowPtr()
273 SQLfieldList* fl = new SQLfieldList;
275 if(currentrow < PQntuples(res))
277 int ncols = PQnfields(res);
279 for(int i = 0; i < ncols; i++)
281 fl->push_back(GetValue(currentrow, i));
290 virtual SQLfieldMap* GetRowMapPtr()
292 SQLfieldMap* fm = new SQLfieldMap;
294 if(currentrow < PQntuples(res))
296 int ncols = PQnfields(res);
298 for(int i = 0; i < ncols; i++)
300 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
309 virtual void Free(SQLfieldMap* fm)
314 virtual void Free(SQLfieldList* fl)
320 /** SQLConn represents one SQL session.
322 class SQLConn : public EventHandler
325 InspIRCd* ServerInstance;
326 SQLhost confhost; /* The <database> entry */
327 Module* us; /* Pointer to the SQL provider itself */
328 PGconn* sql; /* PgSQL database connection handle */
329 SQLstatus status; /* PgSQL database connection status */
330 bool qinprog; /* If there is currently a query in progress */
331 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
332 time_t idle; /* Time we last heard from the database */
335 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
336 : EventHandler(), ServerInstance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
338 idle = this->ServerInstance->Time();
341 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
351 virtual void HandleEvent(EventType et, int errornum)
374 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
377 if(PQstatus(sql) == CONNECTION_BAD)
380 if(PQsetnonblocking(sql, 1) == -1)
383 /* OK, we've initalised the connection, now to get it hooked into the socket engine
384 * and then start polling it.
386 this->fd = PQsocket(sql);
391 if (!this->ServerInstance->SE->AddFd(this))
393 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
397 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
403 switch(PQconnectPoll(sql))
405 case PGRES_POLLING_WRITING:
406 ServerInstance->SE->WantWrite(this);
409 case PGRES_POLLING_READING:
412 case PGRES_POLLING_FAILED:
414 case PGRES_POLLING_OK:
416 return DoConnectedPoll();
422 bool DoConnectedPoll()
424 if(!qinprog && queue.totalsize())
426 /* There's no query currently in progress, and there's queries in the queue. */
427 SQLrequest& query = queue.front();
431 if(PQconsumeInput(sql))
433 /* We just read stuff from the server, that counts as it being alive
434 * so update the idle-since time :p
436 idle = this->ServerInstance->Time();
440 /* Nothing happens here */
444 /* Grab the request we're processing */
445 SQLrequest& query = queue.front();
447 /* Get a pointer to the module we're about to return the result to */
448 Module* to = query.GetSource();
450 /* Fetch the result.. */
451 PGresult* result = PQgetResult(sql);
453 /* PgSQL would allow a query string to be sent which has multiple
454 * queries in it, this isn't portable across database backends and
455 * we don't want modules doing it. But just in case we make sure we
456 * drain any results there are and just use the last one.
457 * If the module devs are behaving there will only be one result.
459 while (PGresult* temp = PQgetResult(sql))
467 /* ..and the result */
468 PgSQLresult reply(us, to, query.id, result);
470 /* Fix by brain, make sure the original query gets sent back in the reply */
471 reply.query = query.query.q;
473 switch(PQresultStatus(result))
475 case PGRES_EMPTY_QUERY:
476 case PGRES_BAD_RESPONSE:
477 case PGRES_FATAL_ERROR:
478 reply.error.Id(SQL_QREPLY_FAIL);
479 reply.error.Str(PQresultErrorMessage(result));
482 /* No action, other values are not errors */
487 /* PgSQLresult's destructor will free the PGresult */
491 /* If the client module is unloaded partway through a query then the provider will set
492 * the pointer to NULL. We cannot just cancel the query as the result will still come
493 * through at some point...and it could get messy if we play with invalid pointers...
505 /* I think we'll assume this means the server died...it might not,
506 * but I think that any error serious enough we actually get here
507 * deserves to reconnect [/excuse]
508 * Returning true so the core doesn't try and close the connection.
517 switch(PQresetPoll(sql))
519 case PGRES_POLLING_WRITING:
520 ServerInstance->SE->WantWrite(this);
523 case PGRES_POLLING_READING:
526 case PGRES_POLLING_FAILED:
528 case PGRES_POLLING_OK:
530 return DoConnectedPoll();
538 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
544 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
553 void DelayReconnect();
559 if((status == CREAD) || (status == CWRITE))
563 else if((status == RREAD) || (status == RWRITE))
569 ret = DoConnectedPoll();
574 SQLerror DoQuery(SQLrequest &req)
576 if((status == WREAD) || (status == WWRITE))
580 /* Parse the command string and dispatch it */
582 /* Pointer to the buffer we screw around with substitution in */
584 /* Pointer to the current end of query, where we append new stuff */
587 /* Total length of the unescaped parameters */
588 unsigned long maxparamlen, paramcount;
590 /* The length of the longest parameter */
593 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
595 if (i->size() > maxparamlen)
596 maxparamlen = i->size();
599 /* How many params are there in the query? */
600 paramcount = count(req.query.q.c_str(), '?');
602 /* This stores copy of params to be inserted with using numbered params 1;3B*/
603 ParamL paramscopy(req.query.p);
605 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
606 * sizeofquery + (maxtotalparamlength*2) + 1
608 * The +1 is for null-terminating the string for PQsendQuery()
611 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
614 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
615 * the parameters into it...
618 for(unsigned int i = 0; i < req.query.q.length(); i++)
620 if(req.query.q[i] == '?')
622 /* We found a place to substitute..what fun.
623 * Use the PgSQL calls to escape and write the
624 * escaped string onto the end of our query buffer,
625 * then we "just" need to make sure queryend is
626 * pointing at the right place.
629 /* Is it numbered parameter?
635 /* Numbered parameter number :|
637 unsigned int paramnum;
640 /* Let's check if it's a numbered param. And also calculate it's number.
643 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
647 paramnum = paramnum * 10 + req.query.q[i] - '0';
650 if (paramnum > paramscopy.size() - 1)
652 /* index is out of range!
662 #ifdef PGSQL_HAS_ESCAPECONN
663 len = PQescapeStringConn(sql, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length(), &error);
665 len = PQescapeString (queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
669 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
672 /* Incremenet queryend to the end of the newly escaped parameter */
675 else if (req.query.p.size())
680 #ifdef PGSQL_HAS_ESCAPECONN
681 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
683 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
687 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
690 /* Incremenet queryend to the end of the newly escaped parameter */
693 /* Remove the parameter we just substituted in */
694 req.query.p.pop_front();
698 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
704 *queryend = req.query.q[i];
709 /* Null-terminate the query */
713 if(PQsendQuery(sql, query))
722 return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
726 return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
729 SQLerror Query(const SQLrequest &req)
733 if(!qinprog && queue.totalsize())
735 /* There's no query currently in progress, and there's queries in the queue. */
736 SQLrequest& query = queue.front();
737 return DoQuery(query);
745 void OnUnloadModule(Module* mod)
747 queue.PurgeModule(mod);
750 const SQLhost GetConfHost()
757 if (!this->ServerInstance->SE->DelFd(this))
759 if (sql && PQstatus(sql) == CONNECTION_BAD)
761 this->ServerInstance->SE->DelFd(this, true);
765 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: PQsocket cant be removed from socket engine!");
778 class ModulePgSQL : public Module
782 unsigned long currid;
784 ReconnectTimer* retimer;
787 ModulePgSQL(InspIRCd* Me)
788 : Module(Me), currid(0)
790 ServerInstance->Modules->UseInterface("SQLutils");
792 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
794 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
796 if (!ServerInstance->Modules->PublishFeature("SQL", this))
798 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
803 ServerInstance->Modules->PublishInterface("SQL", this);
804 Implementation eventlist[] = { I_OnUnloadModule, I_OnRequest, I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnUserDisconnect };
805 ServerInstance->Modules->Attach(eventlist, this, 6);
808 virtual ~ModulePgSQL()
811 ServerInstance->Timers->DelTimer(retimer);
812 ClearAllConnections();
814 ServerInstance->Modules->UnpublishInterface("SQL", this);
815 ServerInstance->Modules->UnpublishFeature("SQL");
816 ServerInstance->Modules->DoneWithInterface("SQLutils");
820 virtual void OnRehash(User* user, const std::string ¶meter)
825 bool HasHost(const SQLhost &host)
827 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
829 if (host == iter->second->GetConfHost())
835 bool HostInConf(const SQLhost &h)
837 ConfigReader conf(ServerInstance);
838 for(int i = 0; i < conf.Enumerate("database"); i++)
841 host.id = conf.ReadValue("database", "id", i);
842 host.host = conf.ReadValue("database", "hostname", i);
843 host.port = conf.ReadInteger("database", "port", i, true);
844 host.name = conf.ReadValue("database", "name", i);
845 host.user = conf.ReadValue("database", "username", i);
846 host.pass = conf.ReadValue("database", "password", i);
847 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
856 ClearOldConnections();
858 ConfigReader conf(ServerInstance);
859 for(int i = 0; i < conf.Enumerate("database"); i++)
864 host.id = conf.ReadValue("database", "id", i);
865 host.host = conf.ReadValue("database", "hostname", i);
866 host.port = conf.ReadInteger("database", "port", i, true);
867 host.name = conf.ReadValue("database", "name", i);
868 host.user = conf.ReadValue("database", "username", i);
869 host.pass = conf.ReadValue("database", "password", i);
870 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
876 if (strchr(host.host.c_str(),':'))
879 ipvalid = inet_pton(AF_INET6, host.host.c_str(), &blargle);
885 ipvalid = inet_aton(host.host.c_str(), &blargle);
890 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
894 else if(ipvalid == 0)
896 /* Conversion failed, assume it's a host */
897 SQLresolver* resolver;
902 resolver = new SQLresolver(this, ServerInstance, host, cached);
903 ServerInstance->AddResolver(resolver, cached);
907 /* THE WORLD IS COMING TO AN END! */
912 /* Invalid address family, die horribly. */
913 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: insp_aton failed returning -1, oh noes.");
918 void ClearOldConnections()
920 ConnMap::iterator iter,safei;
921 for (iter = connections.begin(); iter != connections.end(); iter++)
923 if (!HostInConf(iter->second->GetConfHost()))
928 connections.erase(safei);
933 void ClearAllConnections()
936 while ((i = connections.begin()) != connections.end())
938 connections.erase(i);
943 void AddConn(const SQLhost& hi)
947 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());
953 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
954 newconn = new SQLConn(ServerInstance, this, hi);
956 connections.insert(std::make_pair(hi.id, newconn));
959 void ReconnectConn(SQLConn* conn)
961 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
963 if (conn == iter->second)
966 connections.erase(iter);
970 retimer = new ReconnectTimer(ServerInstance, this);
971 ServerInstance->Timers->AddTimer(retimer);
974 virtual const char* OnRequest(Request* request)
976 if(strcmp(SQLREQID, request->GetId()) == 0)
978 SQLrequest* req = (SQLrequest*)request;
979 ConnMap::iterator iter;
980 if((iter = connections.find(req->dbid)) != connections.end())
984 req->error = iter->second->Query(*req);
986 return (req->error.Id() == SQL_NO_ERROR) ? sqlsuccess : NULL;
990 req->error.Id(SQL_BAD_DBID);
997 virtual void OnUnloadModule(Module* mod, const std::string& name)
999 /* When a module unloads we have to check all the pending queries for all our connections
1000 * and set the Module* specifying where the query came from to NULL. If the query has already
1001 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1003 * If the queries we find are not already being executed then we can simply remove them immediately.
1005 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1007 iter->second->OnUnloadModule(mod);
1011 unsigned long NewID()
1019 virtual Version GetVersion()
1021 return Version("$Id$", VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1025 /* move this here to use AddConn, rather that than having the whole
1026 * module above SQLConn, since this is buggin me right now :/
1028 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached, int resultnum)
1033 ((ModulePgSQL*)mod)->AddConn(host);
1034 ((ModulePgSQL*)mod)->ClearOldConnections();
1038 void ReconnectTimer::Tick(time_t time)
1040 ((ModulePgSQL*)mod)->ReadConf();
1043 void SQLConn::DelayReconnect()
1045 ((ModulePgSQL*)us)->ReconnectConn(this);
1048 MODULE_INIT(ModulePgSQL)