2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2007, 2009 Dennis Friis <peavey@inspircd.org>
6 * Copyright (C) 2006-2007, 2009 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
8 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include "modules/sql.h"
30 /* $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));") */
31 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
33 /* SQLConn rewritten by peavey to
34 * use EventHandler instead of
35 * BufferedSocket. This is much neater
36 * and gives total control of destroy
37 * and delete of resources.
40 /* Forward declare, so we can have the typedef neatly at the top */
44 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
46 /* CREAD, Connecting and wants read event
47 * CWRITE, Connecting and wants write event
48 * WREAD, Connected/Working and wants read event
49 * WWRITE, Connected/Working and wants write event
50 * RREAD, Resetting and wants read event
51 * RWRITE, Resetting and wants write event
53 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
55 class ReconnectTimer : public Timer
60 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
63 bool Tick(time_t TIME);
70 QueueItem(SQLQuery* C, const std::string& Q) : c(C), q(Q) {}
73 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
74 * All SQL providers must create their own subclass and define it's methods using that
75 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
76 * of converting all data to a common format before it reaches the result structure. This way
77 * data is passes to the module nearly as directly as if it was using the API directly itself.
80 class PgSQLresult : public SQLResult
86 PgSQLresult(PGresult* result) : res(result), currentrow(0)
88 rows = PQntuples(res);
90 rows = atoi(PQcmdTuples(res));
103 void GetCols(std::vector<std::string>& result)
105 result.resize(PQnfields(res));
106 for(unsigned int i=0; i < result.size(); i++)
108 result[i] = PQfname(res, i);
112 SQLEntry GetValue(int row, int column)
114 char* v = PQgetvalue(res, row, column);
115 if (!v || PQgetisnull(res, row, column))
118 return SQLEntry(std::string(v, PQgetlength(res, row, column)));
121 bool GetRow(SQLEntries& result)
123 if (currentrow >= PQntuples(res))
125 int ncols = PQnfields(res);
127 for(int i = 0; i < ncols; i++)
129 result.push_back(GetValue(currentrow, i));
137 /** SQLConn represents one SQL session.
139 class SQLConn : public SQLProvider, public EventHandler
142 reference<ConfigTag> conf; /* The <database> entry */
143 std::deque<QueueItem> queue;
144 PGconn* sql; /* PgSQL database connection handle */
145 SQLstatus status; /* PgSQL database connection status */
146 QueueItem qinprog; /* If there is currently a query in progress */
148 SQLConn(Module* Creator, ConfigTag* tag)
149 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
153 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
160 this->SQLProvider::cull();
161 ServerInstance->Modules->DelService(*this);
162 return this->EventHandler::cull();
167 SQLerror err(SQL_BAD_DBID);
170 qinprog.c->OnError(err);
173 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
181 void HandleEvent(EventType et, int errornum)
197 std::ostringstream conninfo("connect_timeout = '5'");
200 if (conf->readString("host", item))
201 conninfo << " host = '" << item << "'";
203 if (conf->readString("port", item))
204 conninfo << " port = '" << item << "'";
206 if (conf->readString("name", item))
207 conninfo << " dbname = '" << item << "'";
209 if (conf->readString("user", item))
210 conninfo << " user = '" << item << "'";
212 if (conf->readString("pass", item))
213 conninfo << " password = '" << item << "'";
215 if (conf->getBool("ssl"))
216 conninfo << " sslmode = 'require'";
218 conninfo << " sslmode = 'disable'";
220 return conninfo.str();
225 sql = PQconnectStart(GetDSN().c_str());
229 if(PQstatus(sql) == CONNECTION_BAD)
232 if(PQsetnonblocking(sql, 1) == -1)
235 /* OK, we've initalised the connection, now to get it hooked into the socket engine
236 * and then start polling it.
238 this->fd = PQsocket(sql);
243 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
245 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
249 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
255 switch(PQconnectPoll(sql))
257 case PGRES_POLLING_WRITING:
258 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
261 case PGRES_POLLING_READING:
262 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
265 case PGRES_POLLING_FAILED:
267 case PGRES_POLLING_OK:
268 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
276 void DoConnectedPoll()
279 while (qinprog.q.empty() && !queue.empty())
281 /* There's no query currently in progress, and there's queries in the queue. */
282 DoQuery(queue.front());
286 if (PQconsumeInput(sql))
290 /* Nothing happens here */
294 /* Fetch the result.. */
295 PGresult* result = PQgetResult(sql);
297 /* PgSQL would allow a query string to be sent which has multiple
298 * queries in it, this isn't portable across database backends and
299 * we don't want modules doing it. But just in case we make sure we
300 * drain any results there are and just use the last one.
301 * If the module devs are behaving there will only be one result.
303 while (PGresult* temp = PQgetResult(sql))
309 /* ..and the result */
310 PgSQLresult reply(result);
311 switch(PQresultStatus(result))
313 case PGRES_EMPTY_QUERY:
314 case PGRES_BAD_RESPONSE:
315 case PGRES_FATAL_ERROR:
317 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
318 qinprog.c->OnError(err);
322 /* Other values are not errors */
323 qinprog.c->OnResult(reply);
327 qinprog = QueueItem(NULL, "");
337 /* I think we'll assume this means the server died...it might not,
338 * but I think that any error serious enough we actually get here
339 * deserves to reconnect [/excuse]
340 * Returning true so the core doesn't try and close the connection.
348 switch(PQresetPoll(sql))
350 case PGRES_POLLING_WRITING:
351 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
354 case PGRES_POLLING_READING:
355 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
358 case PGRES_POLLING_FAILED:
360 case PGRES_POLLING_OK:
361 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
369 void DelayReconnect();
373 if((status == CREAD) || (status == CWRITE))
377 else if((status == RREAD) || (status == RWRITE))
387 void submit(SQLQuery *req, const std::string& q)
389 if (qinprog.q.empty())
391 DoQuery(QueueItem(req,q));
396 queue.push_back(QueueItem(req,q));
400 void submit(SQLQuery *req, const std::string& q, const ParamL& p)
403 unsigned int param = 0;
404 for(std::string::size_type i = 0; i < q.length(); i++)
410 if (param < p.size())
412 std::string parm = p[param++];
413 std::vector<char> buffer(parm.length() * 2 + 1);
414 #ifdef PGSQL_HAS_ESCAPECONN
416 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
418 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
420 size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length());
422 res.append(&buffer[0], escapedsize);
429 void submit(SQLQuery *req, const std::string& q, const ParamM& p)
432 for(std::string::size_type i = 0; i < q.length(); i++)
440 while (i < q.length() && isalnum(q[i]))
441 field.push_back(q[i++]);
444 ParamM::const_iterator it = p.find(field);
447 std::string parm = it->second;
448 std::vector<char> buffer(parm.length() * 2 + 1);
449 #ifdef PGSQL_HAS_ESCAPECONN
451 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
453 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
455 size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length());
457 res.append(&buffer[0], escapedsize);
464 void DoQuery(const QueueItem& req)
466 if (status != WREAD && status != WWRITE)
468 // whoops, not connected...
469 SQLerror err(SQL_BAD_CONN);
475 if(PQsendQuery(sql, req.q.c_str()))
481 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
489 SocketEngine::DelFd(this);
499 class ModulePgSQL : public Module
503 ReconnectTimer* retimer;
513 ClearAllConnections();
516 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
524 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
525 for(ConfigIter i = tags.first; i != tags.second; i++)
527 if (i->second->getString("module", "pgsql") != "pgsql")
529 std::string id = i->second->getString("id");
530 ConnMap::iterator curr = connections.find(id);
531 if (curr == connections.end())
533 SQLConn* conn = new SQLConn(this, i->second);
534 conns.insert(std::make_pair(id, conn));
535 ServerInstance->Modules->AddService(*conn);
540 connections.erase(curr);
543 ClearAllConnections();
544 conns.swap(connections);
547 void ClearAllConnections()
549 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
557 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
559 SQLerror err(SQL_BAD_DBID);
560 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
562 SQLConn* conn = i->second;
563 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
565 conn->qinprog.c->OnError(err);
566 delete conn->qinprog.c;
567 conn->qinprog.c = NULL;
569 std::deque<QueueItem>::iterator j = conn->queue.begin();
570 while (j != conn->queue.end())
573 if (q->creator == mod)
577 j = conn->queue.erase(j);
585 Version GetVersion() CXX11_OVERRIDE
587 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
591 bool ReconnectTimer::Tick(time_t time)
599 void SQLConn::DelayReconnect()
601 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
602 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
603 if (it != mod->connections.end())
605 mod->connections.erase(it);
606 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
609 mod->retimer = new ReconnectTimer(mod);
610 ServerInstance->Timers.AddTimer(mod->retimer);
615 MODULE_INIT(ModulePgSQL)