2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2016 Adam <Adam@anope.org>
5 * Copyright (C) 2015 Daniel Vassdal <shutter@canternet.org>
6 * Copyright (C) 2013, 2016-2020 Sadie Powell <sadie@witchery.services>
7 * Copyright (C) 2012-2015 Attila Molnar <attilamolnar@hush.com>
8 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
9 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
10 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
11 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
12 * Copyright (C) 2007, 2009-2010 Craig Edwards <brain@inspircd.org>
13 * Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
14 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
15 * Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
17 * This file is part of InspIRCd. InspIRCd is free software: you can
18 * redistribute it and/or modify it under the terms of the GNU General Public
19 * License as published by the Free Software Foundation, version 2.
21 * This program is distributed in the hope that it will be useful, but WITHOUT
22 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
23 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 /// $CompilerFlags: -Iexecute("pg_config --includedir" "POSTGRESQL_INCLUDE_DIR")
31 /// $LinkerFlags: -Lexecute("pg_config --libdir" "POSTGRESQL_LIBRARY_DIR") -lpq
33 /// $PackageInfo: require_system("arch") postgresql-libs
34 /// $PackageInfo: require_system("centos") postgresql-devel
35 /// $PackageInfo: require_system("darwin") postgresql
36 /// $PackageInfo: require_system("debian") libpq-dev
37 /// $PackageInfo: require_system("ubuntu") libpq-dev
43 #include "modules/sql.h"
45 /* SQLConn rewritten by peavey to
46 * use EventHandler instead of
47 * BufferedSocket. This is much neater
48 * and gives total control of destroy
49 * and delete of resources.
52 /* Forward declare, so we can have the typedef neatly at the top */
56 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
60 // The connection has died.
63 // Connecting and wants read event.
66 // Connecting and wants write event.
69 // Connected/working and wants read event.
72 // Connected/working and wants write event.
76 class ReconnectTimer : public Timer
81 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
84 bool Tick(time_t TIME) CXX11_OVERRIDE;
91 QueueItem(SQL::Query* C, const std::string& Q) : c(C), q(Q) {}
94 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
95 * All SQL providers must create their own subclass and define it's methods using that
96 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
97 * of converting all data to a common format before it reaches the result structure. This way
98 * data is passes to the module nearly as directly as if it was using the API directly itself.
101 class PgSQLresult : public SQL::Result
106 std::vector<std::string> colnames;
110 colnames.resize(PQnfields(res));
111 for(unsigned int i=0; i < colnames.size(); i++)
113 colnames[i] = PQfname(res, i);
117 PgSQLresult(PGresult* result) : res(result), currentrow(0)
119 rows = PQntuples(res);
121 rows = ConvToNum<int>(PQcmdTuples(res));
129 int Rows() CXX11_OVERRIDE
134 void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
136 if (colnames.empty())
141 bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
143 if (colnames.empty())
146 for (size_t i = 0; i < colnames.size(); ++i)
148 if (colnames[i] == column)
157 SQL::Field GetValue(int row, int column)
159 char* v = PQgetvalue(res, row, column);
160 if (!v || PQgetisnull(res, row, column))
163 return SQL::Field(std::string(v, PQgetlength(res, row, column)));
166 bool GetRow(SQL::Row& result) CXX11_OVERRIDE
168 if (currentrow >= PQntuples(res))
170 int ncols = PQnfields(res);
172 for(int i = 0; i < ncols; i++)
174 result.push_back(GetValue(currentrow, i));
182 /** SQLConn represents one SQL session.
184 class SQLConn : public SQL::Provider, public EventHandler
187 reference<ConfigTag> conf; /* The <database> entry */
188 std::deque<QueueItem> queue;
189 PGconn* sql; /* PgSQL database connection handle */
190 SQLstatus status; /* PgSQL database connection status */
191 QueueItem qinprog; /* If there is currently a query in progress */
193 SQLConn(Module* Creator, ConfigTag* tag)
194 : SQL::Provider(Creator, tag->getString("id"))
204 CullResult cull() CXX11_OVERRIDE
206 this->SQL::Provider::cull();
207 ServerInstance->Modules->DelService(*this);
208 return this->EventHandler::cull();
213 SQL::Error err(SQL::BAD_DBID);
216 qinprog.c->OnError(err);
219 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
221 SQL::Query* q = i->c;
228 void OnEventHandlerRead() CXX11_OVERRIDE
233 void OnEventHandlerWrite() CXX11_OVERRIDE
238 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
245 std::ostringstream conninfo("connect_timeout = '5'");
248 if (conf->readString("host", item))
249 conninfo << " host = '" << item << "'";
251 if (conf->readString("port", item))
252 conninfo << " port = '" << item << "'";
254 if (conf->readString("name", item))
255 conninfo << " dbname = '" << item << "'";
257 if (conf->readString("user", item))
258 conninfo << " user = '" << item << "'";
260 if (conf->readString("pass", item))
261 conninfo << " password = '" << item << "'";
263 if (conf->getBool("ssl"))
264 conninfo << " sslmode = 'require'";
266 conninfo << " sslmode = 'disable'";
268 return conninfo.str();
271 bool HandleConnectError(const char* reason)
273 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Could not connect to the \"%s\" database: %s",
274 GetId().c_str(), reason);
280 sql = PQconnectStart(GetDSN().c_str());
282 return HandleConnectError("PQconnectStart returned NULL");
284 if(PQstatus(sql) == CONNECTION_BAD)
285 return HandleConnectError("connection status is bad");
287 if(PQsetnonblocking(sql, 1) == -1)
288 return HandleConnectError("unable to mark fd as non-blocking");
290 /* OK, we've initialised the connection, now to get it hooked into the socket engine
291 * and then start polling it.
293 SetFd(PQsocket(sql));
295 return HandleConnectError("PQsocket returned an invalid fd");
297 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
298 return HandleConnectError("could not add the pgsql socket to the socket engine");
300 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
302 return HandleConnectError("could not poll the connection state");
309 switch(PQconnectPoll(sql))
311 case PGRES_POLLING_WRITING:
312 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
315 case PGRES_POLLING_READING:
316 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
319 case PGRES_POLLING_FAILED:
320 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
323 case PGRES_POLLING_OK:
324 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
333 void DoConnectedPoll()
336 while (qinprog.q.empty() && !queue.empty())
338 /* There's no query currently in progress, and there's queries in the queue. */
339 DoQuery(queue.front());
343 if (PQconsumeInput(sql))
347 /* Nothing happens here */
351 /* Fetch the result.. */
352 PGresult* result = PQgetResult(sql);
354 /* PgSQL would allow a query string to be sent which has multiple
355 * queries in it, this isn't portable across database backends and
356 * we don't want modules doing it. But just in case we make sure we
357 * drain any results there are and just use the last one.
358 * If the module devs are behaving there will only be one result.
360 while (PGresult* temp = PQgetResult(sql))
366 /* ..and the result */
367 PgSQLresult reply(result);
368 switch(PQresultStatus(result))
370 case PGRES_EMPTY_QUERY:
371 case PGRES_BAD_RESPONSE:
372 case PGRES_FATAL_ERROR:
374 SQL::Error err(SQL::QREPLY_FAIL, PQresultErrorMessage(result));
375 qinprog.c->OnError(err);
379 /* Other values are not errors */
380 qinprog.c->OnResult(reply);
384 qinprog = QueueItem(NULL, "");
394 /* I think we'll assume this means the server died...it might not,
395 * but I think that any error serious enough we actually get here
396 * deserves to reconnect [/excuse]
397 * Returning true so the core doesn't try and close the connection.
403 void DelayReconnect();
407 if((status == CREAD) || (status == CWRITE))
411 else if (status == WREAD || status == WWRITE)
417 void Submit(SQL::Query *req, const std::string& q) CXX11_OVERRIDE
419 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing PostgreSQL query: " + q);
420 if (qinprog.q.empty())
422 DoQuery(QueueItem(req,q));
427 queue.push_back(QueueItem(req,q));
431 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
434 unsigned int param = 0;
435 for(std::string::size_type i = 0; i < q.length(); i++)
441 if (param < p.size())
443 std::string parm = p[param++];
444 std::vector<char> buffer(parm.length() * 2 + 1);
446 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
448 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
449 res.append(&buffer[0], escapedsize);
456 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
459 for(std::string::size_type i = 0; i < q.length(); i++)
467 while (i < q.length() && isalnum(q[i]))
468 field.push_back(q[i++]);
471 SQL::ParamMap::const_iterator it = p.find(field);
474 std::string parm = it->second;
475 std::vector<char> buffer(parm.length() * 2 + 1);
477 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
479 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
480 res.append(&buffer[0], escapedsize);
487 void DoQuery(const QueueItem& req)
489 if (status != WREAD && status != WWRITE)
491 // whoops, not connected...
492 SQL::Error err(SQL::BAD_CONN);
498 if(PQsendQuery(sql, req.q.c_str()))
504 SQL::Error err(SQL::QSEND_FAIL, PQerrorMessage(sql));
514 if (HasFd() && SocketEngine::HasFd(GetFd()))
515 SocketEngine::DelFd(this);
525 class ModulePgSQL : public Module
529 ReconnectTimer* retimer;
539 ClearAllConnections();
542 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
550 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
551 for(ConfigIter i = tags.first; i != tags.second; i++)
553 if (!stdalgo::string::equalsci(i->second->getString("module"), "pgsql"))
555 std::string id = i->second->getString("id");
556 ConnMap::iterator curr = connections.find(id);
557 if (curr == connections.end())
559 SQLConn* conn = new SQLConn(this, i->second);
560 if (conn->status != DEAD)
562 conns.insert(std::make_pair(id, conn));
563 ServerInstance->Modules->AddService(*conn);
565 // If the connection is dead it has already been queued for culling
566 // at the end of the main loop so we don't need to delete it here.
571 connections.erase(curr);
574 ClearAllConnections();
575 conns.swap(connections);
578 void ClearAllConnections()
580 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
588 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
590 SQL::Error err(SQL::BAD_DBID);
591 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
593 SQLConn* conn = i->second;
594 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
596 conn->qinprog.c->OnError(err);
597 delete conn->qinprog.c;
598 conn->qinprog.c = NULL;
600 std::deque<QueueItem>::iterator j = conn->queue.begin();
601 while (j != conn->queue.end())
603 SQL::Query* q = j->c;
604 if (q->creator == mod)
608 j = conn->queue.erase(j);
616 Version GetVersion() CXX11_OVERRIDE
618 return Version("Provides the ability for SQL modules to query a PostgreSQL database.", VF_VENDOR);
622 bool ReconnectTimer::Tick(time_t time)
630 void SQLConn::DelayReconnect()
633 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
635 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
636 if (it != mod->connections.end())
637 mod->connections.erase(it);
638 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
641 mod->retimer = new ReconnectTimer(mod);
642 ServerInstance->Timers.AddTimer(mod->retimer);
646 MODULE_INIT(ModulePgSQL)