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) : Timer(5, ServerInstance->Time(), false), mod(m)
99 virtual void Tick(time_t TIME);
103 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
104 * All SQL providers must create their own subclass and define it's methods using that
105 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
106 * of converting all data to a common format before it reaches the result structure. This way
107 * data is passes to the module nearly as directly as if it was using the API directly itself.
110 class PgSQLresult : public SQLresult
117 SQLfieldList* fieldlist;
118 SQLfieldMap* fieldmap;
120 PgSQLresult(Module* self, Module* to, unsigned long rid, PGresult* result)
121 : SQLresult(self, to, rid), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
123 rows = PQntuples(res);
124 cols = PQnfields(res);
129 /* If we allocated these, free them... */
143 return atoi(PQcmdTuples(res));
153 return PQnfields(res);
156 virtual std::string ColName(int column)
158 char* name = PQfname(res, column);
160 return (name) ? name : "";
163 virtual int ColNum(const std::string &column)
165 int n = PQfnumber(res, column.c_str());
169 throw SQLbadColName();
177 virtual SQLfield GetValue(int row, int column)
179 char* v = PQgetvalue(res, row, column);
183 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
187 throw SQLbadColName();
191 virtual SQLfieldList& GetRow()
193 /* In an effort to reduce overhead we don't actually allocate the list
194 * until the first time it's needed...so...
202 fieldlist = new SQLfieldList;
205 if(currentrow < PQntuples(res))
207 int ncols = PQnfields(res);
209 for(int i = 0; i < ncols; i++)
211 fieldlist->push_back(GetValue(currentrow, i));
220 virtual SQLfieldMap& GetRowMap()
222 /* In an effort to reduce overhead we don't actually allocate the map
223 * until the first time it's needed...so...
231 fieldmap = new SQLfieldMap;
234 if(currentrow < PQntuples(res))
236 int ncols = PQnfields(res);
238 for(int i = 0; i < ncols; i++)
240 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
249 virtual SQLfieldList* GetRowPtr()
251 SQLfieldList* fl = new SQLfieldList;
253 if(currentrow < PQntuples(res))
255 int ncols = PQnfields(res);
257 for(int i = 0; i < ncols; i++)
259 fl->push_back(GetValue(currentrow, i));
268 virtual SQLfieldMap* GetRowMapPtr()
270 SQLfieldMap* fm = new SQLfieldMap;
272 if(currentrow < PQntuples(res))
274 int ncols = PQnfields(res);
276 for(int i = 0; i < ncols; i++)
278 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
287 virtual void Free(SQLfieldMap* fm)
292 virtual void Free(SQLfieldList* fl)
298 /** SQLConn represents one SQL session.
300 class SQLConn : public EventHandler
303 SQLhost confhost; /* The <database> entry */
304 Module* us; /* Pointer to the SQL provider itself */
305 PGconn* sql; /* PgSQL database connection handle */
306 SQLstatus status; /* PgSQL database connection status */
307 bool qinprog; /* If there is currently a query in progress */
308 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
309 time_t idle; /* Time we last heard from the database */
312 SQLConn(Module* self, const SQLhost& hi)
313 : EventHandler(), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
315 idle = ServerInstance->Time();
318 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
328 virtual void HandleEvent(EventType et, int errornum)
351 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
354 if(PQstatus(sql) == CONNECTION_BAD)
357 if(PQsetnonblocking(sql, 1) == -1)
360 /* OK, we've initalised the connection, now to get it hooked into the socket engine
361 * and then start polling it.
363 this->fd = PQsocket(sql);
368 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
370 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
374 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
380 switch(PQconnectPoll(sql))
382 case PGRES_POLLING_WRITING:
383 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
386 case PGRES_POLLING_READING:
387 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
390 case PGRES_POLLING_FAILED:
392 case PGRES_POLLING_OK:
393 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
395 return DoConnectedPoll();
401 bool DoConnectedPoll()
403 if(!qinprog && queue.totalsize())
405 /* There's no query currently in progress, and there's queries in the queue. */
406 SQLrequest* query = queue.front();
410 if(PQconsumeInput(sql))
412 /* We just read stuff from the server, that counts as it being alive
413 * so update the idle-since time :p
415 idle = ServerInstance->Time();
419 /* Nothing happens here */
423 /* Grab the request we're processing */
424 SQLrequest* query = queue.front();
426 /* Get a pointer to the module we're about to return the result to */
427 Module* to = query->source;
429 /* Fetch the result.. */
430 PGresult* result = PQgetResult(sql);
432 /* PgSQL would allow a query string to be sent which has multiple
433 * queries in it, this isn't portable across database backends and
434 * we don't want modules doing it. But just in case we make sure we
435 * drain any results there are and just use the last one.
436 * If the module devs are behaving there will only be one result.
438 while (PGresult* temp = PQgetResult(sql))
446 /* ..and the result */
447 PgSQLresult reply(us, to, query->id, result);
449 /* Fix by brain, make sure the original query gets sent back in the reply */
450 reply.query = query->query.q;
452 switch(PQresultStatus(result))
454 case PGRES_EMPTY_QUERY:
455 case PGRES_BAD_RESPONSE:
456 case PGRES_FATAL_ERROR:
457 reply.error.Id(SQL_QREPLY_FAIL);
458 reply.error.Str(PQresultErrorMessage(result));
461 /* No action, other values are not errors */
466 /* PgSQLresult's destructor will free the PGresult */
470 /* If the client module is unloaded partway through a query then the provider will set
471 * the pointer to NULL. We cannot just cancel the query as the result will still come
472 * through at some point...and it could get messy if we play with invalid pointers...
484 /* I think we'll assume this means the server died...it might not,
485 * but I think that any error serious enough we actually get here
486 * deserves to reconnect [/excuse]
487 * Returning true so the core doesn't try and close the connection.
496 switch(PQresetPoll(sql))
498 case PGRES_POLLING_WRITING:
499 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
502 case PGRES_POLLING_READING:
503 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
506 case PGRES_POLLING_FAILED:
508 case PGRES_POLLING_OK:
509 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
511 return DoConnectedPoll();
519 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
525 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
534 void DelayReconnect();
540 if((status == CREAD) || (status == CWRITE))
544 else if((status == RREAD) || (status == RWRITE))
550 ret = DoConnectedPoll();
555 SQLerror DoQuery(SQLrequest &req)
557 if((status == WREAD) || (status == WWRITE))
561 /* Parse the command string and dispatch it */
563 /* Pointer to the buffer we screw around with substitution in */
565 /* Pointer to the current end of query, where we append new stuff */
568 /* Total length of the unescaped parameters */
569 unsigned long maxparamlen, paramcount;
571 /* The length of the longest parameter */
574 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
576 if (i->size() > maxparamlen)
577 maxparamlen = i->size();
580 /* How many params are there in the query? */
581 paramcount = count(req.query.q.c_str(), '?');
583 /* This stores copy of params to be inserted with using numbered params 1;3B*/
584 ParamL paramscopy(req.query.p);
586 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
587 * sizeofquery + (maxtotalparamlength*2) + 1
589 * The +1 is for null-terminating the string for PQsendQuery()
592 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
595 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
596 * the parameters into it...
599 for(unsigned int i = 0; i < req.query.q.length(); i++)
601 if(req.query.q[i] == '?')
603 /* We found a place to substitute..what fun.
604 * Use the PgSQL calls to escape and write the
605 * escaped string onto the end of our query buffer,
606 * then we "just" need to make sure queryend is
607 * pointing at the right place.
610 /* Is it numbered parameter?
616 /* Numbered parameter number :|
618 unsigned int paramnum;
621 /* Let's check if it's a numbered param. And also calculate it's number.
624 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
628 paramnum = paramnum * 10 + req.query.q[i] - '0';
631 if (paramnum > paramscopy.size() - 1)
633 /* index is out of range!
643 #ifdef PGSQL_HAS_ESCAPECONN
644 len = PQescapeStringConn(sql, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length(), &error);
646 len = PQescapeString (queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
650 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
653 /* Incremenet queryend to the end of the newly escaped parameter */
656 else if (req.query.p.size())
661 #ifdef PGSQL_HAS_ESCAPECONN
662 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
664 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
668 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
671 /* Incremenet queryend to the end of the newly escaped parameter */
674 /* Remove the parameter we just substituted in */
675 req.query.p.pop_front();
679 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
685 *queryend = req.query.q[i];
690 /* Null-terminate the query */
694 if(PQsendQuery(sql, query))
703 return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
707 return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
710 SQLerror Query(const SQLrequest &req)
712 queue.push(new SQLrequest(req));
714 if(!qinprog && queue.totalsize())
716 /* There's no query currently in progress, and there's queries in the queue. */
717 SQLrequest* query = queue.front();
718 return DoQuery(*query);
726 void OnUnloadModule(Module* mod)
728 queue.PurgeModule(mod);
731 const SQLhost GetConfHost()
738 if (!ServerInstance->SE->DelFd(this))
740 if (sql && PQstatus(sql) == CONNECTION_BAD)
742 ServerInstance->SE->DelFd(this, true);
746 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: PQsocket cant be removed from socket engine!");
759 class ModulePgSQL : public Module
763 unsigned long currid;
765 ReconnectTimer* retimer;
771 ServerInstance->Modules->UseInterface("SQLutils");
773 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
775 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
777 if (!ServerInstance->Modules->PublishFeature("SQL", this))
779 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
784 ServerInstance->Modules->PublishInterface("SQL", this);
785 Implementation eventlist[] = { I_OnUnloadModule, I_OnRehash };
786 ServerInstance->Modules->Attach(eventlist, this, 2);
789 virtual ~ModulePgSQL()
792 ServerInstance->Timers->DelTimer(retimer);
793 ClearAllConnections();
795 ServerInstance->Modules->UnpublishInterface("SQL", this);
796 ServerInstance->Modules->UnpublishFeature("SQL");
797 ServerInstance->Modules->DoneWithInterface("SQLutils");
801 virtual void OnRehash(User* user)
806 bool HasHost(const SQLhost &host)
808 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
810 if (host == iter->second->GetConfHost())
816 bool HostInConf(const SQLhost &h)
819 for(int i = 0; i < conf.Enumerate("database"); i++)
822 host.id = conf.ReadValue("database", "id", i);
823 host.host = conf.ReadValue("database", "hostname", i);
824 host.port = conf.ReadInteger("database", "port", i, true);
825 host.name = conf.ReadValue("database", "name", i);
826 host.user = conf.ReadValue("database", "username", i);
827 host.pass = conf.ReadValue("database", "password", i);
828 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
837 ClearOldConnections();
840 for(int i = 0; i < conf.Enumerate("database"); i++)
844 host.id = conf.ReadValue("database", "id", i);
845 host.host = conf.ReadValue("database", "hostname", i);
846 host.port = conf.ReadInteger("database", "port", i, true);
847 host.name = conf.ReadValue("database", "name", i);
848 host.user = conf.ReadValue("database", "username", i);
849 host.pass = conf.ReadValue("database", "password", i);
850 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
859 void ClearOldConnections()
861 ConnMap::iterator iter,safei;
862 for (iter = connections.begin(); iter != connections.end(); iter++)
864 if (!HostInConf(iter->second->GetConfHost()))
869 connections.erase(safei);
874 void ClearAllConnections()
877 while ((i = connections.begin()) != connections.end())
879 connections.erase(i);
884 void AddConn(const SQLhost& hi)
888 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: A pgsql connection with id: %s already exists. Aborting connection attempt.", hi.id.c_str());
894 newconn = new SQLConn(this, hi);
896 connections.insert(std::make_pair(hi.id, newconn));
899 void ReconnectConn(SQLConn* conn)
901 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
903 if (conn == iter->second)
906 connections.erase(iter);
910 retimer = new ReconnectTimer(this);
911 ServerInstance->Timers->AddTimer(retimer);
914 void OnRequest(Request& request)
916 if(strcmp(SQLREQID, request.id) == 0)
918 SQLrequest* req = (SQLrequest*)&request;
919 ConnMap::iterator iter;
920 if((iter = connections.find(req->dbid)) != connections.end())
924 req->error = iter->second->Query(*req);
928 req->error.Id(SQL_BAD_DBID);
933 virtual void OnUnloadModule(Module* mod)
935 /* When a module unloads we have to check all the pending queries for all our connections
936 * and set the Module* specifying where the query came from to NULL. If the query has already
937 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
939 * If the queries we find are not already being executed then we can simply remove them immediately.
941 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
943 iter->second->OnUnloadModule(mod);
947 unsigned long NewID()
955 virtual Version GetVersion()
957 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
961 void ReconnectTimer::Tick(time_t time)
963 ((ModulePgSQL*)mod)->ReadConf();
966 void SQLConn::DelayReconnect()
968 ((ModulePgSQL*)us)->ReconnectConn(this);
971 MODULE_INIT(ModulePgSQL)