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-2019 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;
58 /* CREAD, Connecting and wants read event
59 * CWRITE, Connecting and wants write event
60 * WREAD, Connected/Working and wants read event
61 * WWRITE, Connected/Working and wants write event
62 * RREAD, Resetting and wants read event
63 * RWRITE, Resetting and wants write event
65 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
67 class ReconnectTimer : public Timer
72 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
75 bool Tick(time_t TIME) CXX11_OVERRIDE;
82 QueueItem(SQL::Query* C, const std::string& Q) : c(C), q(Q) {}
85 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
86 * All SQL providers must create their own subclass and define it's methods using that
87 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
88 * of converting all data to a common format before it reaches the result structure. This way
89 * data is passes to the module nearly as directly as if it was using the API directly itself.
92 class PgSQLresult : public SQL::Result
97 std::vector<std::string> colnames;
101 colnames.resize(PQnfields(res));
102 for(unsigned int i=0; i < colnames.size(); i++)
104 colnames[i] = PQfname(res, i);
108 PgSQLresult(PGresult* result) : res(result), currentrow(0)
110 rows = PQntuples(res);
112 rows = ConvToNum<int>(PQcmdTuples(res));
120 int Rows() CXX11_OVERRIDE
125 void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
127 if (colnames.empty())
132 bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
134 if (colnames.empty())
137 for (size_t i = 0; i < colnames.size(); ++i)
139 if (colnames[i] == column)
148 SQL::Field GetValue(int row, int column)
150 char* v = PQgetvalue(res, row, column);
151 if (!v || PQgetisnull(res, row, column))
154 return SQL::Field(std::string(v, PQgetlength(res, row, column)));
157 bool GetRow(SQL::Row& result) CXX11_OVERRIDE
159 if (currentrow >= PQntuples(res))
161 int ncols = PQnfields(res);
163 for(int i = 0; i < ncols; i++)
165 result.push_back(GetValue(currentrow, i));
173 /** SQLConn represents one SQL session.
175 class SQLConn : public SQL::Provider, public EventHandler
178 reference<ConfigTag> conf; /* The <database> entry */
179 std::deque<QueueItem> queue;
180 PGconn* sql; /* PgSQL database connection handle */
181 SQLstatus status; /* PgSQL database connection status */
182 QueueItem qinprog; /* If there is currently a query in progress */
184 SQLConn(Module* Creator, ConfigTag* tag)
185 : SQL::Provider(Creator, tag->getString("id"))
193 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
198 CullResult cull() CXX11_OVERRIDE
200 this->SQL::Provider::cull();
201 ServerInstance->Modules->DelService(*this);
202 return this->EventHandler::cull();
207 SQL::Error err(SQL::BAD_DBID);
210 qinprog.c->OnError(err);
213 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
215 SQL::Query* q = i->c;
221 void OnEventHandlerRead() CXX11_OVERRIDE
226 void OnEventHandlerWrite() CXX11_OVERRIDE
231 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
238 std::ostringstream conninfo("connect_timeout = '5'");
241 if (conf->readString("host", item))
242 conninfo << " host = '" << item << "'";
244 if (conf->readString("port", item))
245 conninfo << " port = '" << item << "'";
247 if (conf->readString("name", item))
248 conninfo << " dbname = '" << item << "'";
250 if (conf->readString("user", item))
251 conninfo << " user = '" << item << "'";
253 if (conf->readString("pass", item))
254 conninfo << " password = '" << item << "'";
256 if (conf->getBool("ssl"))
257 conninfo << " sslmode = 'require'";
259 conninfo << " sslmode = 'disable'";
261 return conninfo.str();
266 sql = PQconnectStart(GetDSN().c_str());
270 if(PQstatus(sql) == CONNECTION_BAD)
273 if(PQsetnonblocking(sql, 1) == -1)
276 /* OK, we've initalised the connection, now to get it hooked into the socket engine
277 * and then start polling it.
279 this->fd = PQsocket(sql);
284 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
286 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
290 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
296 switch(PQconnectPoll(sql))
298 case PGRES_POLLING_WRITING:
299 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
302 case PGRES_POLLING_READING:
303 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
306 case PGRES_POLLING_FAILED:
308 case PGRES_POLLING_OK:
309 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
318 void DoConnectedPoll()
321 while (qinprog.q.empty() && !queue.empty())
323 /* There's no query currently in progress, and there's queries in the queue. */
324 DoQuery(queue.front());
328 if (PQconsumeInput(sql))
332 /* Nothing happens here */
336 /* Fetch the result.. */
337 PGresult* result = PQgetResult(sql);
339 /* PgSQL would allow a query string to be sent which has multiple
340 * queries in it, this isn't portable across database backends and
341 * we don't want modules doing it. But just in case we make sure we
342 * drain any results there are and just use the last one.
343 * If the module devs are behaving there will only be one result.
345 while (PGresult* temp = PQgetResult(sql))
351 /* ..and the result */
352 PgSQLresult reply(result);
353 switch(PQresultStatus(result))
355 case PGRES_EMPTY_QUERY:
356 case PGRES_BAD_RESPONSE:
357 case PGRES_FATAL_ERROR:
359 SQL::Error err(SQL::QREPLY_FAIL, PQresultErrorMessage(result));
360 qinprog.c->OnError(err);
364 /* Other values are not errors */
365 qinprog.c->OnResult(reply);
369 qinprog = QueueItem(NULL, "");
379 /* I think we'll assume this means the server died...it might not,
380 * but I think that any error serious enough we actually get here
381 * deserves to reconnect [/excuse]
382 * Returning true so the core doesn't try and close the connection.
390 switch(PQresetPoll(sql))
392 case PGRES_POLLING_WRITING:
393 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
396 case PGRES_POLLING_READING:
397 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
400 case PGRES_POLLING_FAILED:
402 case PGRES_POLLING_OK:
403 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
412 void DelayReconnect();
416 if((status == CREAD) || (status == CWRITE))
420 else if((status == RREAD) || (status == RWRITE))
430 void Submit(SQL::Query *req, const std::string& q) CXX11_OVERRIDE
432 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing PostgreSQL query: " + q);
433 if (qinprog.q.empty())
435 DoQuery(QueueItem(req,q));
440 queue.push_back(QueueItem(req,q));
444 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
447 unsigned int param = 0;
448 for(std::string::size_type i = 0; i < q.length(); i++)
454 if (param < p.size())
456 std::string parm = p[param++];
457 std::vector<char> buffer(parm.length() * 2 + 1);
459 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
461 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
462 res.append(&buffer[0], escapedsize);
469 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
472 for(std::string::size_type i = 0; i < q.length(); i++)
480 while (i < q.length() && isalnum(q[i]))
481 field.push_back(q[i++]);
484 SQL::ParamMap::const_iterator it = p.find(field);
487 std::string parm = it->second;
488 std::vector<char> buffer(parm.length() * 2 + 1);
490 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
492 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
493 res.append(&buffer[0], escapedsize);
500 void DoQuery(const QueueItem& req)
502 if (status != WREAD && status != WWRITE)
504 // whoops, not connected...
505 SQL::Error err(SQL::BAD_CONN);
511 if(PQsendQuery(sql, req.q.c_str()))
517 SQL::Error err(SQL::QSEND_FAIL, PQerrorMessage(sql));
525 SocketEngine::DelFd(this);
535 class ModulePgSQL : public Module
539 ReconnectTimer* retimer;
549 ClearAllConnections();
552 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
560 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
561 for(ConfigIter i = tags.first; i != tags.second; i++)
563 if (!stdalgo::string::equalsci(i->second->getString("module"), "pgsql"))
565 std::string id = i->second->getString("id");
566 ConnMap::iterator curr = connections.find(id);
567 if (curr == connections.end())
569 SQLConn* conn = new SQLConn(this, i->second);
570 conns.insert(std::make_pair(id, conn));
571 ServerInstance->Modules->AddService(*conn);
576 connections.erase(curr);
579 ClearAllConnections();
580 conns.swap(connections);
583 void ClearAllConnections()
585 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
593 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
595 SQL::Error err(SQL::BAD_DBID);
596 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
598 SQLConn* conn = i->second;
599 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
601 conn->qinprog.c->OnError(err);
602 delete conn->qinprog.c;
603 conn->qinprog.c = NULL;
605 std::deque<QueueItem>::iterator j = conn->queue.begin();
606 while (j != conn->queue.end())
608 SQL::Query* q = j->c;
609 if (q->creator == mod)
613 j = conn->queue.erase(j);
621 Version GetVersion() CXX11_OVERRIDE
623 return Version("Provides PostgreSQL support to modules", VF_VENDOR);
627 bool ReconnectTimer::Tick(time_t time)
635 void SQLConn::DelayReconnect()
637 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
638 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
639 if (it != mod->connections.end())
641 mod->connections.erase(it);
642 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
645 mod->retimer = new ReconnectTimer(mod);
646 ServerInstance->Timers.AddTimer(mod->retimer);
651 MODULE_INIT(ModulePgSQL)