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;
60 // Connecting and wants read event.
63 // Connecting and wants write event.
66 // Connected/working and wants read event.
69 // Connected/working and wants write event.
73 class ReconnectTimer : public Timer
78 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
81 bool Tick(time_t TIME) CXX11_OVERRIDE;
88 QueueItem(SQL::Query* C, const std::string& Q) : c(C), q(Q) {}
91 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
92 * All SQL providers must create their own subclass and define it's methods using that
93 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
94 * of converting all data to a common format before it reaches the result structure. This way
95 * data is passes to the module nearly as directly as if it was using the API directly itself.
98 class PgSQLresult : public SQL::Result
103 std::vector<std::string> colnames;
107 colnames.resize(PQnfields(res));
108 for(unsigned int i=0; i < colnames.size(); i++)
110 colnames[i] = PQfname(res, i);
114 PgSQLresult(PGresult* result) : res(result), currentrow(0)
116 rows = PQntuples(res);
118 rows = ConvToNum<int>(PQcmdTuples(res));
126 int Rows() CXX11_OVERRIDE
131 void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
133 if (colnames.empty())
138 bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
140 if (colnames.empty())
143 for (size_t i = 0; i < colnames.size(); ++i)
145 if (colnames[i] == column)
154 SQL::Field GetValue(int row, int column)
156 char* v = PQgetvalue(res, row, column);
157 if (!v || PQgetisnull(res, row, column))
160 return SQL::Field(std::string(v, PQgetlength(res, row, column)));
163 bool GetRow(SQL::Row& result) CXX11_OVERRIDE
165 if (currentrow >= PQntuples(res))
167 int ncols = PQnfields(res);
169 for(int i = 0; i < ncols; i++)
171 result.push_back(GetValue(currentrow, i));
179 /** SQLConn represents one SQL session.
181 class SQLConn : public SQL::Provider, public EventHandler
184 reference<ConfigTag> conf; /* The <database> entry */
185 std::deque<QueueItem> queue;
186 PGconn* sql; /* PgSQL database connection handle */
187 SQLstatus status; /* PgSQL database connection status */
188 QueueItem qinprog; /* If there is currently a query in progress */
190 SQLConn(Module* Creator, ConfigTag* tag)
191 : SQL::Provider(Creator, tag->getString("id"))
199 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + 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;
227 void OnEventHandlerRead() CXX11_OVERRIDE
232 void OnEventHandlerWrite() CXX11_OVERRIDE
237 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
244 std::ostringstream conninfo("connect_timeout = '5'");
247 if (conf->readString("host", item))
248 conninfo << " host = '" << item << "'";
250 if (conf->readString("port", item))
251 conninfo << " port = '" << item << "'";
253 if (conf->readString("name", item))
254 conninfo << " dbname = '" << item << "'";
256 if (conf->readString("user", item))
257 conninfo << " user = '" << item << "'";
259 if (conf->readString("pass", item))
260 conninfo << " password = '" << item << "'";
262 if (conf->getBool("ssl"))
263 conninfo << " sslmode = 'require'";
265 conninfo << " sslmode = 'disable'";
267 return conninfo.str();
272 sql = PQconnectStart(GetDSN().c_str());
276 if(PQstatus(sql) == CONNECTION_BAD)
279 if(PQsetnonblocking(sql, 1) == -1)
282 /* OK, we've initialised the connection, now to get it hooked into the socket engine
283 * and then start polling it.
285 this->fd = PQsocket(sql);
290 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
292 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
296 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
302 switch(PQconnectPoll(sql))
304 case PGRES_POLLING_WRITING:
305 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
308 case PGRES_POLLING_READING:
309 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
312 case PGRES_POLLING_FAILED:
314 case PGRES_POLLING_OK:
315 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
324 void DoConnectedPoll()
327 while (qinprog.q.empty() && !queue.empty())
329 /* There's no query currently in progress, and there's queries in the queue. */
330 DoQuery(queue.front());
334 if (PQconsumeInput(sql))
338 /* Nothing happens here */
342 /* Fetch the result.. */
343 PGresult* result = PQgetResult(sql);
345 /* PgSQL would allow a query string to be sent which has multiple
346 * queries in it, this isn't portable across database backends and
347 * we don't want modules doing it. But just in case we make sure we
348 * drain any results there are and just use the last one.
349 * If the module devs are behaving there will only be one result.
351 while (PGresult* temp = PQgetResult(sql))
357 /* ..and the result */
358 PgSQLresult reply(result);
359 switch(PQresultStatus(result))
361 case PGRES_EMPTY_QUERY:
362 case PGRES_BAD_RESPONSE:
363 case PGRES_FATAL_ERROR:
365 SQL::Error err(SQL::QREPLY_FAIL, PQresultErrorMessage(result));
366 qinprog.c->OnError(err);
370 /* Other values are not errors */
371 qinprog.c->OnResult(reply);
375 qinprog = QueueItem(NULL, "");
385 /* I think we'll assume this means the server died...it might not,
386 * but I think that any error serious enough we actually get here
387 * deserves to reconnect [/excuse]
388 * Returning true so the core doesn't try and close the connection.
394 void DelayReconnect();
398 if((status == CREAD) || (status == CWRITE))
408 void Submit(SQL::Query *req, const std::string& q) CXX11_OVERRIDE
410 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing PostgreSQL query: " + q);
411 if (qinprog.q.empty())
413 DoQuery(QueueItem(req,q));
418 queue.push_back(QueueItem(req,q));
422 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
425 unsigned int param = 0;
426 for(std::string::size_type i = 0; i < q.length(); i++)
432 if (param < p.size())
434 std::string parm = p[param++];
435 std::vector<char> buffer(parm.length() * 2 + 1);
437 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
439 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
440 res.append(&buffer[0], escapedsize);
447 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
450 for(std::string::size_type i = 0; i < q.length(); i++)
458 while (i < q.length() && isalnum(q[i]))
459 field.push_back(q[i++]);
462 SQL::ParamMap::const_iterator it = p.find(field);
465 std::string parm = it->second;
466 std::vector<char> buffer(parm.length() * 2 + 1);
468 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
470 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
471 res.append(&buffer[0], escapedsize);
478 void DoQuery(const QueueItem& req)
480 if (status != WREAD && status != WWRITE)
482 // whoops, not connected...
483 SQL::Error err(SQL::BAD_CONN);
489 if(PQsendQuery(sql, req.q.c_str()))
495 SQL::Error err(SQL::QSEND_FAIL, PQerrorMessage(sql));
503 SocketEngine::DelFd(this);
513 class ModulePgSQL : public Module
517 ReconnectTimer* retimer;
527 ClearAllConnections();
530 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
538 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
539 for(ConfigIter i = tags.first; i != tags.second; i++)
541 if (!stdalgo::string::equalsci(i->second->getString("module"), "pgsql"))
543 std::string id = i->second->getString("id");
544 ConnMap::iterator curr = connections.find(id);
545 if (curr == connections.end())
547 SQLConn* conn = new SQLConn(this, i->second);
548 conns.insert(std::make_pair(id, conn));
549 ServerInstance->Modules->AddService(*conn);
554 connections.erase(curr);
557 ClearAllConnections();
558 conns.swap(connections);
561 void ClearAllConnections()
563 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
571 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
573 SQL::Error err(SQL::BAD_DBID);
574 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
576 SQLConn* conn = i->second;
577 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
579 conn->qinprog.c->OnError(err);
580 delete conn->qinprog.c;
581 conn->qinprog.c = NULL;
583 std::deque<QueueItem>::iterator j = conn->queue.begin();
584 while (j != conn->queue.end())
586 SQL::Query* q = j->c;
587 if (q->creator == mod)
591 j = conn->queue.erase(j);
599 Version GetVersion() CXX11_OVERRIDE
601 return Version("Provides the ability for SQL modules to query a PostgreSQL database.", VF_VENDOR);
605 bool ReconnectTimer::Tick(time_t time)
613 void SQLConn::DelayReconnect()
615 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
616 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
617 if (it != mod->connections.end())
619 mod->connections.erase(it);
620 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
623 mod->retimer = new ReconnectTimer(mod);
624 ServerInstance->Timers.AddTimer(mod->retimer);
629 MODULE_INIT(ModulePgSQL)