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 OnEventHandlerRead() CXX11_OVERRIDE
186 void OnEventHandlerWrite() CXX11_OVERRIDE
191 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
198 std::ostringstream conninfo("connect_timeout = '5'");
201 if (conf->readString("host", item))
202 conninfo << " host = '" << item << "'";
204 if (conf->readString("port", item))
205 conninfo << " port = '" << item << "'";
207 if (conf->readString("name", item))
208 conninfo << " dbname = '" << item << "'";
210 if (conf->readString("user", item))
211 conninfo << " user = '" << item << "'";
213 if (conf->readString("pass", item))
214 conninfo << " password = '" << item << "'";
216 if (conf->getBool("ssl"))
217 conninfo << " sslmode = 'require'";
219 conninfo << " sslmode = 'disable'";
221 return conninfo.str();
226 sql = PQconnectStart(GetDSN().c_str());
230 if(PQstatus(sql) == CONNECTION_BAD)
233 if(PQsetnonblocking(sql, 1) == -1)
236 /* OK, we've initalised the connection, now to get it hooked into the socket engine
237 * and then start polling it.
239 this->fd = PQsocket(sql);
244 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
246 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
250 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
256 switch(PQconnectPoll(sql))
258 case PGRES_POLLING_WRITING:
259 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
262 case PGRES_POLLING_READING:
263 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
266 case PGRES_POLLING_FAILED:
268 case PGRES_POLLING_OK:
269 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
277 void DoConnectedPoll()
280 while (qinprog.q.empty() && !queue.empty())
282 /* There's no query currently in progress, and there's queries in the queue. */
283 DoQuery(queue.front());
287 if (PQconsumeInput(sql))
291 /* Nothing happens here */
295 /* Fetch the result.. */
296 PGresult* result = PQgetResult(sql);
298 /* PgSQL would allow a query string to be sent which has multiple
299 * queries in it, this isn't portable across database backends and
300 * we don't want modules doing it. But just in case we make sure we
301 * drain any results there are and just use the last one.
302 * If the module devs are behaving there will only be one result.
304 while (PGresult* temp = PQgetResult(sql))
310 /* ..and the result */
311 PgSQLresult reply(result);
312 switch(PQresultStatus(result))
314 case PGRES_EMPTY_QUERY:
315 case PGRES_BAD_RESPONSE:
316 case PGRES_FATAL_ERROR:
318 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
319 qinprog.c->OnError(err);
323 /* Other values are not errors */
324 qinprog.c->OnResult(reply);
328 qinprog = QueueItem(NULL, "");
338 /* I think we'll assume this means the server died...it might not,
339 * but I think that any error serious enough we actually get here
340 * deserves to reconnect [/excuse]
341 * Returning true so the core doesn't try and close the connection.
349 switch(PQresetPoll(sql))
351 case PGRES_POLLING_WRITING:
352 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
355 case PGRES_POLLING_READING:
356 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
359 case PGRES_POLLING_FAILED:
361 case PGRES_POLLING_OK:
362 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
370 void DelayReconnect();
374 if((status == CREAD) || (status == CWRITE))
378 else if((status == RREAD) || (status == RWRITE))
388 void submit(SQLQuery *req, const std::string& q)
390 if (qinprog.q.empty())
392 DoQuery(QueueItem(req,q));
397 queue.push_back(QueueItem(req,q));
401 void submit(SQLQuery *req, const std::string& q, const ParamL& p)
404 unsigned int param = 0;
405 for(std::string::size_type i = 0; i < q.length(); i++)
411 if (param < p.size())
413 std::string parm = p[param++];
414 std::vector<char> buffer(parm.length() * 2 + 1);
415 #ifdef PGSQL_HAS_ESCAPECONN
417 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
419 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
421 size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length());
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);
450 #ifdef PGSQL_HAS_ESCAPECONN
452 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
454 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
456 size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length());
458 res.append(&buffer[0], escapedsize);
465 void DoQuery(const QueueItem& req)
467 if (status != WREAD && status != WWRITE)
469 // whoops, not connected...
470 SQLerror err(SQL_BAD_CONN);
476 if(PQsendQuery(sql, req.q.c_str()))
482 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
490 SocketEngine::DelFd(this);
500 class ModulePgSQL : public Module
504 ReconnectTimer* retimer;
514 ClearAllConnections();
517 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
525 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
526 for(ConfigIter i = tags.first; i != tags.second; i++)
528 if (i->second->getString("module", "pgsql") != "pgsql")
530 std::string id = i->second->getString("id");
531 ConnMap::iterator curr = connections.find(id);
532 if (curr == connections.end())
534 SQLConn* conn = new SQLConn(this, i->second);
535 conns.insert(std::make_pair(id, conn));
536 ServerInstance->Modules->AddService(*conn);
541 connections.erase(curr);
544 ClearAllConnections();
545 conns.swap(connections);
548 void ClearAllConnections()
550 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
558 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
560 SQLerror err(SQL_BAD_DBID);
561 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
563 SQLConn* conn = i->second;
564 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
566 conn->qinprog.c->OnError(err);
567 delete conn->qinprog.c;
568 conn->qinprog.c = NULL;
570 std::deque<QueueItem>::iterator j = conn->queue.begin();
571 while (j != conn->queue.end())
574 if (q->creator == mod)
578 j = conn->queue.erase(j);
586 Version GetVersion() CXX11_OVERRIDE
588 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
592 bool ReconnectTimer::Tick(time_t time)
600 void SQLConn::DelayReconnect()
602 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
603 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
604 if (it != mod->connections.end())
606 mod->connections.erase(it);
607 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
610 mod->retimer = new ReconnectTimer(mod);
611 ServerInstance->Timers.AddTimer(mod->retimer);
616 MODULE_INIT(ModulePgSQL)