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/>.
24 /// $CompilerFlags: -Iexecute("pg_config --includedir" "POSTGRESQL_INCLUDE_DIR")
25 /// $LinkerFlags: -Lexecute("pg_config --libdir" "POSTGRESQL_LIBRARY_DIR") -lpq
27 /// $PackageInfo: require_system("centos") postgresql-devel
28 /// $PackageInfo: require_system("darwin") postgresql
29 /// $PackageInfo: require_system("debian") libpq-dev
30 /// $PackageInfo: require_system("ubuntu") libpq-dev
36 #include "modules/sql.h"
38 /* SQLConn rewritten by peavey to
39 * use EventHandler instead of
40 * BufferedSocket. This is much neater
41 * and gives total control of destroy
42 * and delete of resources.
45 /* Forward declare, so we can have the typedef neatly at the top */
49 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
51 /* CREAD, Connecting and wants read event
52 * CWRITE, Connecting and wants write event
53 * WREAD, Connected/Working and wants read event
54 * WWRITE, Connected/Working and wants write event
55 * RREAD, Resetting and wants read event
56 * RWRITE, Resetting and wants write event
58 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
60 class ReconnectTimer : public Timer
65 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
68 bool Tick(time_t TIME);
75 QueueItem(SQLQuery* C, const std::string& Q) : c(C), q(Q) {}
78 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
79 * All SQL providers must create their own subclass and define it's methods using that
80 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
81 * of converting all data to a common format before it reaches the result structure. This way
82 * data is passes to the module nearly as directly as if it was using the API directly itself.
85 class PgSQLresult : public SQLResult
91 PgSQLresult(PGresult* result) : res(result), currentrow(0)
93 rows = PQntuples(res);
95 rows = atoi(PQcmdTuples(res));
108 void GetCols(std::vector<std::string>& result)
110 result.resize(PQnfields(res));
111 for(unsigned int i=0; i < result.size(); i++)
113 result[i] = PQfname(res, i);
117 SQLEntry GetValue(int row, int column)
119 char* v = PQgetvalue(res, row, column);
120 if (!v || PQgetisnull(res, row, column))
123 return SQLEntry(std::string(v, PQgetlength(res, row, column)));
126 bool GetRow(SQLEntries& result)
128 if (currentrow >= PQntuples(res))
130 int ncols = PQnfields(res);
132 for(int i = 0; i < ncols; i++)
134 result.push_back(GetValue(currentrow, i));
142 /** SQLConn represents one SQL session.
144 class SQLConn : public SQLProvider, public EventHandler
147 reference<ConfigTag> conf; /* The <database> entry */
148 std::deque<QueueItem> queue;
149 PGconn* sql; /* PgSQL database connection handle */
150 SQLstatus status; /* PgSQL database connection status */
151 QueueItem qinprog; /* If there is currently a query in progress */
153 SQLConn(Module* Creator, ConfigTag* tag)
154 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
158 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
163 CullResult cull() CXX11_OVERRIDE
165 this->SQLProvider::cull();
166 ServerInstance->Modules->DelService(*this);
167 return this->EventHandler::cull();
172 SQLerror err(SQL_BAD_DBID);
175 qinprog.c->OnError(err);
178 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
186 void OnEventHandlerRead() CXX11_OVERRIDE
191 void OnEventHandlerWrite() CXX11_OVERRIDE
196 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
203 std::ostringstream conninfo("connect_timeout = '5'");
206 if (conf->readString("host", item))
207 conninfo << " host = '" << item << "'";
209 if (conf->readString("port", item))
210 conninfo << " port = '" << item << "'";
212 if (conf->readString("name", item))
213 conninfo << " dbname = '" << item << "'";
215 if (conf->readString("user", item))
216 conninfo << " user = '" << item << "'";
218 if (conf->readString("pass", item))
219 conninfo << " password = '" << item << "'";
221 if (conf->getBool("ssl"))
222 conninfo << " sslmode = 'require'";
224 conninfo << " sslmode = 'disable'";
226 return conninfo.str();
231 sql = PQconnectStart(GetDSN().c_str());
235 if(PQstatus(sql) == CONNECTION_BAD)
238 if(PQsetnonblocking(sql, 1) == -1)
241 /* OK, we've initalised the connection, now to get it hooked into the socket engine
242 * and then start polling it.
244 this->fd = PQsocket(sql);
249 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
251 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
255 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
261 switch(PQconnectPoll(sql))
263 case PGRES_POLLING_WRITING:
264 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
267 case PGRES_POLLING_READING:
268 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
271 case PGRES_POLLING_FAILED:
273 case PGRES_POLLING_OK:
274 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
282 void DoConnectedPoll()
285 while (qinprog.q.empty() && !queue.empty())
287 /* There's no query currently in progress, and there's queries in the queue. */
288 DoQuery(queue.front());
292 if (PQconsumeInput(sql))
296 /* Nothing happens here */
300 /* Fetch the result.. */
301 PGresult* result = PQgetResult(sql);
303 /* PgSQL would allow a query string to be sent which has multiple
304 * queries in it, this isn't portable across database backends and
305 * we don't want modules doing it. But just in case we make sure we
306 * drain any results there are and just use the last one.
307 * If the module devs are behaving there will only be one result.
309 while (PGresult* temp = PQgetResult(sql))
315 /* ..and the result */
316 PgSQLresult reply(result);
317 switch(PQresultStatus(result))
319 case PGRES_EMPTY_QUERY:
320 case PGRES_BAD_RESPONSE:
321 case PGRES_FATAL_ERROR:
323 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
324 qinprog.c->OnError(err);
328 /* Other values are not errors */
329 qinprog.c->OnResult(reply);
333 qinprog = QueueItem(NULL, "");
343 /* I think we'll assume this means the server died...it might not,
344 * but I think that any error serious enough we actually get here
345 * deserves to reconnect [/excuse]
346 * Returning true so the core doesn't try and close the connection.
354 switch(PQresetPoll(sql))
356 case PGRES_POLLING_WRITING:
357 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
360 case PGRES_POLLING_READING:
361 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
364 case PGRES_POLLING_FAILED:
366 case PGRES_POLLING_OK:
367 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
375 void DelayReconnect();
379 if((status == CREAD) || (status == CWRITE))
383 else if((status == RREAD) || (status == RWRITE))
393 void submit(SQLQuery *req, const std::string& q) CXX11_OVERRIDE
395 if (qinprog.q.empty())
397 DoQuery(QueueItem(req,q));
402 queue.push_back(QueueItem(req,q));
406 void submit(SQLQuery *req, const std::string& q, const ParamL& p) CXX11_OVERRIDE
409 unsigned int param = 0;
410 for(std::string::size_type i = 0; i < q.length(); i++)
416 if (param < p.size())
418 std::string parm = p[param++];
419 std::vector<char> buffer(parm.length() * 2 + 1);
421 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
423 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
424 res.append(&buffer[0], escapedsize);
431 void submit(SQLQuery *req, const std::string& q, const ParamM& p) CXX11_OVERRIDE
434 for(std::string::size_type i = 0; i < q.length(); i++)
442 while (i < q.length() && isalnum(q[i]))
443 field.push_back(q[i++]);
446 ParamM::const_iterator it = p.find(field);
449 std::string parm = it->second;
450 std::vector<char> buffer(parm.length() * 2 + 1);
452 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
454 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
455 res.append(&buffer[0], escapedsize);
462 void DoQuery(const QueueItem& req)
464 if (status != WREAD && status != WWRITE)
466 // whoops, not connected...
467 SQLerror err(SQL_BAD_CONN);
473 if(PQsendQuery(sql, req.q.c_str()))
479 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
487 SocketEngine::DelFd(this);
497 class ModulePgSQL : public Module
501 ReconnectTimer* retimer;
511 ClearAllConnections();
514 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
522 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
523 for(ConfigIter i = tags.first; i != tags.second; i++)
525 if (i->second->getString("module", "pgsql") != "pgsql")
527 std::string id = i->second->getString("id");
528 ConnMap::iterator curr = connections.find(id);
529 if (curr == connections.end())
531 SQLConn* conn = new SQLConn(this, i->second);
532 conns.insert(std::make_pair(id, conn));
533 ServerInstance->Modules->AddService(*conn);
538 connections.erase(curr);
541 ClearAllConnections();
542 conns.swap(connections);
545 void ClearAllConnections()
547 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
555 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
557 SQLerror err(SQL_BAD_DBID);
558 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
560 SQLConn* conn = i->second;
561 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
563 conn->qinprog.c->OnError(err);
564 delete conn->qinprog.c;
565 conn->qinprog.c = NULL;
567 std::deque<QueueItem>::iterator j = conn->queue.begin();
568 while (j != conn->queue.end())
571 if (q->creator == mod)
575 j = conn->queue.erase(j);
583 Version GetVersion() CXX11_OVERRIDE
585 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
589 bool ReconnectTimer::Tick(time_t time)
597 void SQLConn::DelayReconnect()
599 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
600 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
601 if (it != mod->connections.end())
603 mod->connections.erase(it);
604 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
607 mod->retimer = new ReconnectTimer(mod);
608 ServerInstance->Timers.AddTimer(mod->retimer);
613 MODULE_INIT(ModulePgSQL)