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("ubuntu") libpq-dev
35 #include "modules/sql.h"
37 /* SQLConn rewritten by peavey to
38 * use EventHandler instead of
39 * BufferedSocket. This is much neater
40 * and gives total control of destroy
41 * and delete of resources.
44 /* Forward declare, so we can have the typedef neatly at the top */
48 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
50 /* CREAD, Connecting and wants read event
51 * CWRITE, Connecting and wants write event
52 * WREAD, Connected/Working and wants read event
53 * WWRITE, Connected/Working and wants write event
54 * RREAD, Resetting and wants read event
55 * RWRITE, Resetting and wants write event
57 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
59 class ReconnectTimer : public Timer
64 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
67 bool Tick(time_t TIME);
74 QueueItem(SQLQuery* C, const std::string& Q) : c(C), q(Q) {}
77 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
78 * All SQL providers must create their own subclass and define it's methods using that
79 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
80 * of converting all data to a common format before it reaches the result structure. This way
81 * data is passes to the module nearly as directly as if it was using the API directly itself.
84 class PgSQLresult : public SQLResult
90 PgSQLresult(PGresult* result) : res(result), currentrow(0)
92 rows = PQntuples(res);
94 rows = atoi(PQcmdTuples(res));
107 void GetCols(std::vector<std::string>& result)
109 result.resize(PQnfields(res));
110 for(unsigned int i=0; i < result.size(); i++)
112 result[i] = PQfname(res, i);
116 SQLEntry GetValue(int row, int column)
118 char* v = PQgetvalue(res, row, column);
119 if (!v || PQgetisnull(res, row, column))
122 return SQLEntry(std::string(v, PQgetlength(res, row, column)));
125 bool GetRow(SQLEntries& result)
127 if (currentrow >= PQntuples(res))
129 int ncols = PQnfields(res);
131 for(int i = 0; i < ncols; i++)
133 result.push_back(GetValue(currentrow, i));
141 /** SQLConn represents one SQL session.
143 class SQLConn : public SQLProvider, public EventHandler
146 reference<ConfigTag> conf; /* The <database> entry */
147 std::deque<QueueItem> queue;
148 PGconn* sql; /* PgSQL database connection handle */
149 SQLstatus status; /* PgSQL database connection status */
150 QueueItem qinprog; /* If there is currently a query in progress */
152 SQLConn(Module* Creator, ConfigTag* tag)
153 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
157 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
164 this->SQLProvider::cull();
165 ServerInstance->Modules->DelService(*this);
166 return this->EventHandler::cull();
171 SQLerror err(SQL_BAD_DBID);
174 qinprog.c->OnError(err);
177 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
185 void OnEventHandlerRead() CXX11_OVERRIDE
190 void OnEventHandlerWrite() CXX11_OVERRIDE
195 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
202 std::ostringstream conninfo("connect_timeout = '5'");
205 if (conf->readString("host", item))
206 conninfo << " host = '" << item << "'";
208 if (conf->readString("port", item))
209 conninfo << " port = '" << item << "'";
211 if (conf->readString("name", item))
212 conninfo << " dbname = '" << item << "'";
214 if (conf->readString("user", item))
215 conninfo << " user = '" << item << "'";
217 if (conf->readString("pass", item))
218 conninfo << " password = '" << item << "'";
220 if (conf->getBool("ssl"))
221 conninfo << " sslmode = 'require'";
223 conninfo << " sslmode = 'disable'";
225 return conninfo.str();
230 sql = PQconnectStart(GetDSN().c_str());
234 if(PQstatus(sql) == CONNECTION_BAD)
237 if(PQsetnonblocking(sql, 1) == -1)
240 /* OK, we've initalised the connection, now to get it hooked into the socket engine
241 * and then start polling it.
243 this->fd = PQsocket(sql);
248 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
250 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
254 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
260 switch(PQconnectPoll(sql))
262 case PGRES_POLLING_WRITING:
263 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
266 case PGRES_POLLING_READING:
267 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
270 case PGRES_POLLING_FAILED:
272 case PGRES_POLLING_OK:
273 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
281 void DoConnectedPoll()
284 while (qinprog.q.empty() && !queue.empty())
286 /* There's no query currently in progress, and there's queries in the queue. */
287 DoQuery(queue.front());
291 if (PQconsumeInput(sql))
295 /* Nothing happens here */
299 /* Fetch the result.. */
300 PGresult* result = PQgetResult(sql);
302 /* PgSQL would allow a query string to be sent which has multiple
303 * queries in it, this isn't portable across database backends and
304 * we don't want modules doing it. But just in case we make sure we
305 * drain any results there are and just use the last one.
306 * If the module devs are behaving there will only be one result.
308 while (PGresult* temp = PQgetResult(sql))
314 /* ..and the result */
315 PgSQLresult reply(result);
316 switch(PQresultStatus(result))
318 case PGRES_EMPTY_QUERY:
319 case PGRES_BAD_RESPONSE:
320 case PGRES_FATAL_ERROR:
322 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
323 qinprog.c->OnError(err);
327 /* Other values are not errors */
328 qinprog.c->OnResult(reply);
332 qinprog = QueueItem(NULL, "");
342 /* I think we'll assume this means the server died...it might not,
343 * but I think that any error serious enough we actually get here
344 * deserves to reconnect [/excuse]
345 * Returning true so the core doesn't try and close the connection.
353 switch(PQresetPoll(sql))
355 case PGRES_POLLING_WRITING:
356 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
359 case PGRES_POLLING_READING:
360 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
363 case PGRES_POLLING_FAILED:
365 case PGRES_POLLING_OK:
366 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
374 void DelayReconnect();
378 if((status == CREAD) || (status == CWRITE))
382 else if((status == RREAD) || (status == RWRITE))
392 void submit(SQLQuery *req, const std::string& q)
394 if (qinprog.q.empty())
396 DoQuery(QueueItem(req,q));
401 queue.push_back(QueueItem(req,q));
405 void submit(SQLQuery *req, const std::string& q, const ParamL& p)
408 unsigned int param = 0;
409 for(std::string::size_type i = 0; i < q.length(); i++)
415 if (param < p.size())
417 std::string parm = p[param++];
418 std::vector<char> buffer(parm.length() * 2 + 1);
420 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
422 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
423 res.append(&buffer[0], escapedsize);
430 void submit(SQLQuery *req, const std::string& q, const ParamM& p)
433 for(std::string::size_type i = 0; i < q.length(); i++)
441 while (i < q.length() && isalnum(q[i]))
442 field.push_back(q[i++]);
445 ParamM::const_iterator it = p.find(field);
448 std::string parm = it->second;
449 std::vector<char> buffer(parm.length() * 2 + 1);
451 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
453 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
454 res.append(&buffer[0], escapedsize);
461 void DoQuery(const QueueItem& req)
463 if (status != WREAD && status != WWRITE)
465 // whoops, not connected...
466 SQLerror err(SQL_BAD_CONN);
472 if(PQsendQuery(sql, req.q.c_str()))
478 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
486 SocketEngine::DelFd(this);
496 class ModulePgSQL : public Module
500 ReconnectTimer* retimer;
510 ClearAllConnections();
513 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
521 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
522 for(ConfigIter i = tags.first; i != tags.second; i++)
524 if (i->second->getString("module", "pgsql") != "pgsql")
526 std::string id = i->second->getString("id");
527 ConnMap::iterator curr = connections.find(id);
528 if (curr == connections.end())
530 SQLConn* conn = new SQLConn(this, i->second);
531 conns.insert(std::make_pair(id, conn));
532 ServerInstance->Modules->AddService(*conn);
537 connections.erase(curr);
540 ClearAllConnections();
541 conns.swap(connections);
544 void ClearAllConnections()
546 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
554 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
556 SQLerror err(SQL_BAD_DBID);
557 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
559 SQLConn* conn = i->second;
560 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
562 conn->qinprog.c->OnError(err);
563 delete conn->qinprog.c;
564 conn->qinprog.c = NULL;
566 std::deque<QueueItem>::iterator j = conn->queue.begin();
567 while (j != conn->queue.end())
570 if (q->creator == mod)
574 j = conn->queue.erase(j);
582 Version GetVersion() CXX11_OVERRIDE
584 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
588 bool ReconnectTimer::Tick(time_t time)
596 void SQLConn::DelayReconnect()
598 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
599 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
600 if (it != mod->connections.end())
602 mod->connections.erase(it);
603 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
606 mod->retimer = new ReconnectTimer(mod);
607 ServerInstance->Timers.AddTimer(mod->retimer);
612 MODULE_INIT(ModulePgSQL)