1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/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 = str; *p; ++p)
58 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
60 std::string SQLhost::GetDSN()
62 std::ostringstream conninfo("connect_timeout = '5'");
65 conninfo << " host = '" << host << "'";
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(Module* m)
97 : Timer(5, SI->Time(), false), mod(m)
100 virtual void Tick(time_t TIME);
104 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
105 * All SQL providers must create their own subclass and define it's methods using that
106 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
107 * of converting all data to a common format before it reaches the result structure. This way
108 * data is passes to the module nearly as directly as if it was using the API directly itself.
111 class PgSQLresult : public SQLresult
118 SQLfieldList* fieldlist;
119 SQLfieldMap* fieldmap;
121 PgSQLresult(Module* self, Module* to, unsigned long rid, PGresult* result)
122 : SQLresult(self, to, rid), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
124 rows = PQntuples(res);
125 cols = PQnfields(res);
130 /* If we allocated these, free them... */
144 return atoi(PQcmdTuples(res));
154 return PQnfields(res);
157 virtual std::string ColName(int column)
159 char* name = PQfname(res, column);
161 return (name) ? name : "";
164 virtual int ColNum(const std::string &column)
166 int n = PQfnumber(res, column.c_str());
170 throw SQLbadColName();
178 virtual SQLfield GetValue(int row, int column)
180 char* v = PQgetvalue(res, row, column);
184 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
188 throw SQLbadColName();
192 virtual SQLfieldList& GetRow()
194 /* In an effort to reduce overhead we don't actually allocate the list
195 * until the first time it's needed...so...
203 fieldlist = new SQLfieldList;
206 if(currentrow < PQntuples(res))
208 int ncols = PQnfields(res);
210 for(int i = 0; i < ncols; i++)
212 fieldlist->push_back(GetValue(currentrow, i));
221 virtual SQLfieldMap& GetRowMap()
223 /* In an effort to reduce overhead we don't actually allocate the map
224 * until the first time it's needed...so...
232 fieldmap = new SQLfieldMap;
235 if(currentrow < PQntuples(res))
237 int ncols = PQnfields(res);
239 for(int i = 0; i < ncols; i++)
241 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
250 virtual SQLfieldList* GetRowPtr()
252 SQLfieldList* fl = new SQLfieldList;
254 if(currentrow < PQntuples(res))
256 int ncols = PQnfields(res);
258 for(int i = 0; i < ncols; i++)
260 fl->push_back(GetValue(currentrow, i));
269 virtual SQLfieldMap* GetRowMapPtr()
271 SQLfieldMap* fm = new SQLfieldMap;
273 if(currentrow < PQntuples(res))
275 int ncols = PQnfields(res);
277 for(int i = 0; i < ncols; i++)
279 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
288 virtual void Free(SQLfieldMap* fm)
293 virtual void Free(SQLfieldList* fl)
299 /** SQLConn represents one SQL session.
301 class SQLConn : public EventHandler
304 SQLhost confhost; /* The <database> entry */
305 Module* us; /* Pointer to the SQL provider itself */
306 PGconn* sql; /* PgSQL database connection handle */
307 SQLstatus status; /* PgSQL database connection status */
308 bool qinprog; /* If there is currently a query in progress */
309 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
310 time_t idle; /* Time we last heard from the database */
313 SQLConn(Module* self, const SQLhost& hi)
314 : EventHandler(), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
316 idle = this->ServerInstance->Time();
319 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
329 virtual void HandleEvent(EventType et, int errornum)
352 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
355 if(PQstatus(sql) == CONNECTION_BAD)
358 if(PQsetnonblocking(sql, 1) == -1)
361 /* OK, we've initalised the connection, now to get it hooked into the socket engine
362 * and then start polling it.
364 this->fd = PQsocket(sql);
369 if (!this->ServerInstance->SE->AddFd(this))
371 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
375 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
381 switch(PQconnectPoll(sql))
383 case PGRES_POLLING_WRITING:
384 ServerInstance->SE->WantWrite(this);
387 case PGRES_POLLING_READING:
390 case PGRES_POLLING_FAILED:
392 case PGRES_POLLING_OK:
394 return DoConnectedPoll();
400 bool DoConnectedPoll()
402 if(!qinprog && queue.totalsize())
404 /* There's no query currently in progress, and there's queries in the queue. */
405 SQLrequest& query = queue.front();
409 if(PQconsumeInput(sql))
411 /* We just read stuff from the server, that counts as it being alive
412 * so update the idle-since time :p
414 idle = this->ServerInstance->Time();
418 /* Nothing happens here */
422 /* Grab the request we're processing */
423 SQLrequest& query = queue.front();
425 /* Get a pointer to the module we're about to return the result to */
426 Module* to = query.GetSource();
428 /* Fetch the result.. */
429 PGresult* result = PQgetResult(sql);
431 /* PgSQL would allow a query string to be sent which has multiple
432 * queries in it, this isn't portable across database backends and
433 * we don't want modules doing it. But just in case we make sure we
434 * drain any results there are and just use the last one.
435 * If the module devs are behaving there will only be one result.
437 while (PGresult* temp = PQgetResult(sql))
445 /* ..and the result */
446 PgSQLresult reply(us, to, query.id, result);
448 /* Fix by brain, make sure the original query gets sent back in the reply */
449 reply.query = query.query.q;
451 switch(PQresultStatus(result))
453 case PGRES_EMPTY_QUERY:
454 case PGRES_BAD_RESPONSE:
455 case PGRES_FATAL_ERROR:
456 reply.error.Id(SQL_QREPLY_FAIL);
457 reply.error.Str(PQresultErrorMessage(result));
460 /* No action, other values are not errors */
465 /* PgSQLresult's destructor will free the PGresult */
469 /* If the client module is unloaded partway through a query then the provider will set
470 * the pointer to NULL. We cannot just cancel the query as the result will still come
471 * through at some point...and it could get messy if we play with invalid pointers...
483 /* I think we'll assume this means the server died...it might not,
484 * but I think that any error serious enough we actually get here
485 * deserves to reconnect [/excuse]
486 * Returning true so the core doesn't try and close the connection.
495 switch(PQresetPoll(sql))
497 case PGRES_POLLING_WRITING:
498 ServerInstance->SE->WantWrite(this);
501 case PGRES_POLLING_READING:
504 case PGRES_POLLING_FAILED:
506 case PGRES_POLLING_OK:
508 return DoConnectedPoll();
516 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
522 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
531 void DelayReconnect();
537 if((status == CREAD) || (status == CWRITE))
541 else if((status == RREAD) || (status == RWRITE))
547 ret = DoConnectedPoll();
552 SQLerror DoQuery(SQLrequest &req)
554 if((status == WREAD) || (status == WWRITE))
558 /* Parse the command string and dispatch it */
560 /* Pointer to the buffer we screw around with substitution in */
562 /* Pointer to the current end of query, where we append new stuff */
565 /* Total length of the unescaped parameters */
566 unsigned long maxparamlen, paramcount;
568 /* The length of the longest parameter */
571 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
573 if (i->size() > maxparamlen)
574 maxparamlen = i->size();
577 /* How many params are there in the query? */
578 paramcount = count(req.query.q.c_str(), '?');
580 /* This stores copy of params to be inserted with using numbered params 1;3B*/
581 ParamL paramscopy(req.query.p);
583 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
584 * sizeofquery + (maxtotalparamlength*2) + 1
586 * The +1 is for null-terminating the string for PQsendQuery()
589 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
592 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
593 * the parameters into it...
596 for(unsigned int i = 0; i < req.query.q.length(); i++)
598 if(req.query.q[i] == '?')
600 /* We found a place to substitute..what fun.
601 * Use the PgSQL calls to escape and write the
602 * escaped string onto the end of our query buffer,
603 * then we "just" need to make sure queryend is
604 * pointing at the right place.
607 /* Is it numbered parameter?
613 /* Numbered parameter number :|
615 unsigned int paramnum;
618 /* Let's check if it's a numbered param. And also calculate it's number.
621 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
625 paramnum = paramnum * 10 + req.query.q[i] - '0';
628 if (paramnum > paramscopy.size() - 1)
630 /* index is out of range!
640 #ifdef PGSQL_HAS_ESCAPECONN
641 len = PQescapeStringConn(sql, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length(), &error);
643 len = PQescapeString (queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
647 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
650 /* Incremenet queryend to the end of the newly escaped parameter */
653 else if (req.query.p.size())
658 #ifdef PGSQL_HAS_ESCAPECONN
659 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
661 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
665 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
668 /* Incremenet queryend to the end of the newly escaped parameter */
671 /* Remove the parameter we just substituted in */
672 req.query.p.pop_front();
676 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
682 *queryend = req.query.q[i];
687 /* Null-terminate the query */
691 if(PQsendQuery(sql, query))
700 return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
704 return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
707 SQLerror Query(const SQLrequest &req)
711 if(!qinprog && queue.totalsize())
713 /* There's no query currently in progress, and there's queries in the queue. */
714 SQLrequest& query = queue.front();
715 return DoQuery(query);
723 void OnUnloadModule(Module* mod)
725 queue.PurgeModule(mod);
728 const SQLhost GetConfHost()
735 if (!this->ServerInstance->SE->DelFd(this))
737 if (sql && PQstatus(sql) == CONNECTION_BAD)
739 this->ServerInstance->SE->DelFd(this, true);
743 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: PQsocket cant be removed from socket engine!");
756 class ModulePgSQL : public Module
760 unsigned long currid;
762 ReconnectTimer* retimer;
768 ServerInstance->Modules->UseInterface("SQLutils");
770 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
772 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
774 if (!ServerInstance->Modules->PublishFeature("SQL", this))
776 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
781 ServerInstance->Modules->PublishInterface("SQL", this);
782 Implementation eventlist[] = { I_OnUnloadModule, I_OnRequest, I_OnRehash };
783 ServerInstance->Modules->Attach(eventlist, this, 3);
786 virtual ~ModulePgSQL()
789 ServerInstance->Timers->DelTimer(retimer);
790 ClearAllConnections();
792 ServerInstance->Modules->UnpublishInterface("SQL", this);
793 ServerInstance->Modules->UnpublishFeature("SQL");
794 ServerInstance->Modules->DoneWithInterface("SQLutils");
798 virtual void OnRehash(User* user)
803 bool HasHost(const SQLhost &host)
805 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
807 if (host == iter->second->GetConfHost())
813 bool HostInConf(const SQLhost &h)
816 for(int i = 0; i < conf.Enumerate("database"); i++)
819 host.id = conf.ReadValue("database", "id", i);
820 host.host = conf.ReadValue("database", "hostname", i);
821 host.port = conf.ReadInteger("database", "port", i, true);
822 host.name = conf.ReadValue("database", "name", i);
823 host.user = conf.ReadValue("database", "username", i);
824 host.pass = conf.ReadValue("database", "password", i);
825 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
834 ClearOldConnections();
837 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 void ClearOldConnections()
858 ConnMap::iterator iter,safei;
859 for (iter = connections.begin(); iter != connections.end(); iter++)
861 if (!HostInConf(iter->second->GetConfHost()))
866 connections.erase(safei);
871 void ClearAllConnections()
874 while ((i = connections.begin()) != connections.end())
876 connections.erase(i);
881 void AddConn(const SQLhost& hi)
885 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: A pgsql connection with id: %s already exists. Aborting connection attempt.", hi.id.c_str());
891 newconn = new SQLConn(this, hi);
893 connections.insert(std::make_pair(hi.id, newconn));
896 void ReconnectConn(SQLConn* conn)
898 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
900 if (conn == iter->second)
903 connections.erase(iter);
907 retimer = new ReconnectTimer(this);
908 ServerInstance->Timers->AddTimer(retimer);
911 virtual const char* OnRequest(Request* request)
913 if(strcmp(SQLREQID, request->GetId()) == 0)
915 SQLrequest* req = (SQLrequest*)request;
916 ConnMap::iterator iter;
917 if((iter = connections.find(req->dbid)) != connections.end())
921 req->error = iter->second->Query(*req);
923 return (req->error.Id() == SQL_NO_ERROR) ? sqlsuccess : NULL;
927 req->error.Id(SQL_BAD_DBID);
934 virtual void OnUnloadModule(Module* mod, const std::string& name)
936 /* When a module unloads we have to check all the pending queries for all our connections
937 * and set the Module* specifying where the query came from to NULL. If the query has already
938 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
940 * If the queries we find are not already being executed then we can simply remove them immediately.
942 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
944 iter->second->OnUnloadModule(mod);
948 unsigned long NewID()
956 virtual Version GetVersion()
958 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
962 void ReconnectTimer::Tick(time_t time)
964 ((ModulePgSQL*)mod)->ReadConf();
967 void SQLConn::DelayReconnect()
969 ((ModulePgSQL*)us)->ReconnectConn(this);
972 MODULE_INIT(ModulePgSQL)