]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_pgsql.cpp
Fix SQL modules using "provider" in <database> instead of "module".
[user/henk/code/inspircd.git] / src / modules / extra / m_pgsql.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
10  *
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.
14  *
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
18  * details.
19  *
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/>.
22  */
23
24 /// $CompilerFlags: -Iexecute("pg_config --includedir" "POSTGRESQL_INCLUDE_DIR")
25 /// $LinkerFlags: -Lexecute("pg_config --libdir" "POSTGRESQL_LIBRARY_DIR") -lpq
26
27 /// $PackageInfo: require_system("centos") postgresql-devel
28 /// $PackageInfo: require_system("darwin") postgresql
29 /// $PackageInfo: require_system("debian") libpq-dev
30 /// $PackageInfo: require_system("ubuntu") libpq-dev
31
32
33 #include "inspircd.h"
34 #include <cstdlib>
35 #include <libpq-fe.h>
36 #include "modules/sql.h"
37
38 /* SQLConn rewritten by peavey to
39  * use EventHandler instead of
40  * BufferedSocket. This is much neater
41  * and gives total control of destroy
42  * and delete of resources.
43  */
44
45 /* Forward declare, so we can have the typedef neatly at the top */
46 class SQLConn;
47 class ModulePgSQL;
48
49 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
50
51 /* CREAD,       Connecting and wants read event
52  * CWRITE,      Connecting and wants write event
53  * WREAD,       Connected/Working and wants read event
54  * WWRITE,      Connected/Working and wants write event
55  * RREAD,       Resetting and wants read event
56  * RWRITE,      Resetting and wants write event
57  */
58 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
59
60 class ReconnectTimer : public Timer
61 {
62  private:
63         ModulePgSQL* mod;
64  public:
65         ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
66         {
67         }
68         bool Tick(time_t TIME) CXX11_OVERRIDE;
69 };
70
71 struct QueueItem
72 {
73         SQL::Query* c;
74         std::string q;
75         QueueItem(SQL::Query* C, const std::string& Q) : c(C), q(Q) {}
76 };
77
78 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
79  * All SQL providers must create their own subclass and define it's methods using that
80  * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
81  * of converting all data to a common format before it reaches the result structure. This way
82  * data is passes to the module nearly as directly as if it was using the API directly itself.
83  */
84
85 class PgSQLresult : public SQL::Result
86 {
87         PGresult* res;
88         int currentrow;
89         int rows;
90         std::vector<std::string> colnames;
91
92         void getColNames()
93         {
94                 colnames.resize(PQnfields(res));
95                 for(unsigned int i=0; i < colnames.size(); i++)
96                 {
97                         colnames[i] = PQfname(res, i);
98                 }
99         }
100  public:
101         PgSQLresult(PGresult* result) : res(result), currentrow(0)
102         {
103                 rows = PQntuples(res);
104                 if (!rows)
105                         rows = atoi(PQcmdTuples(res));
106         }
107
108         ~PgSQLresult()
109         {
110                 PQclear(res);
111         }
112
113         int Rows() CXX11_OVERRIDE
114         {
115                 return rows;
116         }
117
118         void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
119         {
120                 if (colnames.empty())
121                         getColNames();
122                 result = colnames;
123         }
124
125         bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
126         {
127                 if (colnames.empty())
128                         getColNames();
129
130                 for (size_t i = 0; i < colnames.size(); ++i)
131                 {
132                         if (colnames[i] == column)
133                         {
134                                 index = i;
135                                 return true;
136                         }
137                 }
138                 return false;
139         }
140
141         SQL::Field GetValue(int row, int column)
142         {
143                 char* v = PQgetvalue(res, row, column);
144                 if (!v || PQgetisnull(res, row, column))
145                         return SQL::Field();
146
147                 return SQL::Field(std::string(v, PQgetlength(res, row, column)));
148         }
149
150         bool GetRow(SQL::Row& result) CXX11_OVERRIDE
151         {
152                 if (currentrow >= PQntuples(res))
153                         return false;
154                 int ncols = PQnfields(res);
155
156                 for(int i = 0; i < ncols; i++)
157                 {
158                         result.push_back(GetValue(currentrow, i));
159                 }
160                 currentrow++;
161
162                 return true;
163         }
164 };
165
166 /** SQLConn represents one SQL session.
167  */
168 class SQLConn : public SQL::Provider, public EventHandler
169 {
170  public:
171         reference<ConfigTag> conf;      /* The <database> entry */
172         std::deque<QueueItem> queue;
173         PGconn*                 sql;            /* PgSQL database connection handle */
174         SQLstatus               status;         /* PgSQL database connection status */
175         QueueItem               qinprog;        /* If there is currently a query in progress */
176
177         SQLConn(Module* Creator, ConfigTag* tag)
178         : SQL::Provider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
179         {
180                 if (!DoConnect())
181                 {
182                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
183                         DelayReconnect();
184                 }
185         }
186
187         CullResult cull() CXX11_OVERRIDE
188         {
189                 this->SQL::Provider::cull();
190                 ServerInstance->Modules->DelService(*this);
191                 return this->EventHandler::cull();
192         }
193
194         ~SQLConn()
195         {
196                 SQL::Error err(SQL::BAD_DBID);
197                 if (qinprog.c)
198                 {
199                         qinprog.c->OnError(err);
200                         delete qinprog.c;
201                 }
202                 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
203                 {
204                         SQL::Query* q = i->c;
205                         q->OnError(err);
206                         delete q;
207                 }
208         }
209
210         void OnEventHandlerRead() CXX11_OVERRIDE
211         {
212                 DoEvent();
213         }
214
215         void OnEventHandlerWrite() CXX11_OVERRIDE
216         {
217                 DoEvent();
218         }
219
220         void OnEventHandlerError(int errornum) CXX11_OVERRIDE
221         {
222                 DelayReconnect();
223         }
224
225         std::string GetDSN()
226         {
227                 std::ostringstream conninfo("connect_timeout = '5'");
228                 std::string item;
229
230                 if (conf->readString("host", item))
231                         conninfo << " host = '" << item << "'";
232
233                 if (conf->readString("port", item))
234                         conninfo << " port = '" << item << "'";
235
236                 if (conf->readString("name", item))
237                         conninfo << " dbname = '" << item << "'";
238
239                 if (conf->readString("user", item))
240                         conninfo << " user = '" << item << "'";
241
242                 if (conf->readString("pass", item))
243                         conninfo << " password = '" << item << "'";
244
245                 if (conf->getBool("ssl"))
246                         conninfo << " sslmode = 'require'";
247                 else
248                         conninfo << " sslmode = 'disable'";
249
250                 return conninfo.str();
251         }
252
253         bool DoConnect()
254         {
255                 sql = PQconnectStart(GetDSN().c_str());
256                 if (!sql)
257                         return false;
258
259                 if(PQstatus(sql) == CONNECTION_BAD)
260                         return false;
261
262                 if(PQsetnonblocking(sql, 1) == -1)
263                         return false;
264
265                 /* OK, we've initalised the connection, now to get it hooked into the socket engine
266                 * and then start polling it.
267                 */
268                 this->fd = PQsocket(sql);
269
270                 if(this->fd <= -1)
271                         return false;
272
273                 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
274                 {
275                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
276                         return false;
277                 }
278
279                 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
280                 return DoPoll();
281         }
282
283         bool DoPoll()
284         {
285                 switch(PQconnectPoll(sql))
286                 {
287                         case PGRES_POLLING_WRITING:
288                                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
289                                 status = CWRITE;
290                                 return true;
291                         case PGRES_POLLING_READING:
292                                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
293                                 status = CREAD;
294                                 return true;
295                         case PGRES_POLLING_FAILED:
296                                 return false;
297                         case PGRES_POLLING_OK:
298                                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
299                                 status = WWRITE;
300                                 DoConnectedPoll();
301                         default:
302                                 return true;
303                 }
304         }
305
306         void DoConnectedPoll()
307         {
308 restart:
309                 while (qinprog.q.empty() && !queue.empty())
310                 {
311                         /* There's no query currently in progress, and there's queries in the queue. */
312                         DoQuery(queue.front());
313                         queue.pop_front();
314                 }
315
316                 if (PQconsumeInput(sql))
317                 {
318                         if (PQisBusy(sql))
319                         {
320                                 /* Nothing happens here */
321                         }
322                         else if (qinprog.c)
323                         {
324                                 /* Fetch the result.. */
325                                 PGresult* result = PQgetResult(sql);
326
327                                 /* PgSQL would allow a query string to be sent which has multiple
328                                  * queries in it, this isn't portable across database backends and
329                                  * we don't want modules doing it. But just in case we make sure we
330                                  * drain any results there are and just use the last one.
331                                  * If the module devs are behaving there will only be one result.
332                                  */
333                                 while (PGresult* temp = PQgetResult(sql))
334                                 {
335                                         PQclear(result);
336                                         result = temp;
337                                 }
338
339                                 /* ..and the result */
340                                 PgSQLresult reply(result);
341                                 switch(PQresultStatus(result))
342                                 {
343                                         case PGRES_EMPTY_QUERY:
344                                         case PGRES_BAD_RESPONSE:
345                                         case PGRES_FATAL_ERROR:
346                                         {
347                                                 SQL::Error err(SQL::QREPLY_FAIL, PQresultErrorMessage(result));
348                                                 qinprog.c->OnError(err);
349                                                 break;
350                                         }
351                                         default:
352                                                 /* Other values are not errors */
353                                                 qinprog.c->OnResult(reply);
354                                 }
355
356                                 delete qinprog.c;
357                                 qinprog = QueueItem(NULL, "");
358                                 goto restart;
359                         }
360                         else
361                         {
362                                 qinprog.q.clear();
363                         }
364                 }
365                 else
366                 {
367                         /* I think we'll assume this means the server died...it might not,
368                          * but I think that any error serious enough we actually get here
369                          * deserves to reconnect [/excuse]
370                          * Returning true so the core doesn't try and close the connection.
371                          */
372                         DelayReconnect();
373                 }
374         }
375
376         bool DoResetPoll()
377         {
378                 switch(PQresetPoll(sql))
379                 {
380                         case PGRES_POLLING_WRITING:
381                                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
382                                 status = CWRITE;
383                                 return DoPoll();
384                         case PGRES_POLLING_READING:
385                                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
386                                 status = CREAD;
387                                 return true;
388                         case PGRES_POLLING_FAILED:
389                                 return false;
390                         case PGRES_POLLING_OK:
391                                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
392                                 status = WWRITE;
393                                 DoConnectedPoll();
394                         default:
395                                 return true;
396                 }
397         }
398
399         void DelayReconnect();
400
401         void DoEvent()
402         {
403                 if((status == CREAD) || (status == CWRITE))
404                 {
405                         DoPoll();
406                 }
407                 else if((status == RREAD) || (status == RWRITE))
408                 {
409                         DoResetPoll();
410                 }
411                 else
412                 {
413                         DoConnectedPoll();
414                 }
415         }
416
417         void Submit(SQL::Query *req, const std::string& q) CXX11_OVERRIDE
418         {
419                 if (qinprog.q.empty())
420                 {
421                         DoQuery(QueueItem(req,q));
422                 }
423                 else
424                 {
425                         // wait your turn.
426                         queue.push_back(QueueItem(req,q));
427                 }
428         }
429
430         void Submit(SQL::Query *req, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
431         {
432                 std::string res;
433                 unsigned int param = 0;
434                 for(std::string::size_type i = 0; i < q.length(); i++)
435                 {
436                         if (q[i] != '?')
437                                 res.push_back(q[i]);
438                         else
439                         {
440                                 if (param < p.size())
441                                 {
442                                         std::string parm = p[param++];
443                                         std::vector<char> buffer(parm.length() * 2 + 1);
444                                         int error;
445                                         size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
446                                         if (error)
447                                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
448                                         res.append(&buffer[0], escapedsize);
449                                 }
450                         }
451                 }
452                 Submit(req, res);
453         }
454
455         void Submit(SQL::Query *req, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
456         {
457                 std::string res;
458                 for(std::string::size_type i = 0; i < q.length(); i++)
459                 {
460                         if (q[i] != '$')
461                                 res.push_back(q[i]);
462                         else
463                         {
464                                 std::string field;
465                                 i++;
466                                 while (i < q.length() && isalnum(q[i]))
467                                         field.push_back(q[i++]);
468                                 i--;
469
470                                 SQL::ParamMap::const_iterator it = p.find(field);
471                                 if (it != p.end())
472                                 {
473                                         std::string parm = it->second;
474                                         std::vector<char> buffer(parm.length() * 2 + 1);
475                                         int error;
476                                         size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
477                                         if (error)
478                                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
479                                         res.append(&buffer[0], escapedsize);
480                                 }
481                         }
482                 }
483                 Submit(req, res);
484         }
485
486         void DoQuery(const QueueItem& req)
487         {
488                 if (status != WREAD && status != WWRITE)
489                 {
490                         // whoops, not connected...
491                         SQL::Error err(SQL::BAD_CONN);
492                         req.c->OnError(err);
493                         delete req.c;
494                         return;
495                 }
496
497                 if(PQsendQuery(sql, req.q.c_str()))
498                 {
499                         qinprog = req;
500                 }
501                 else
502                 {
503                         SQL::Error err(SQL::QSEND_FAIL, PQerrorMessage(sql));
504                         req.c->OnError(err);
505                         delete req.c;
506                 }
507         }
508
509         void Close()
510         {
511                 SocketEngine::DelFd(this);
512
513                 if(sql)
514                 {
515                         PQfinish(sql);
516                         sql = NULL;
517                 }
518         }
519 };
520
521 class ModulePgSQL : public Module
522 {
523  public:
524         ConnMap connections;
525         ReconnectTimer* retimer;
526
527         ModulePgSQL()
528                 : retimer(NULL)
529         {
530         }
531
532         ~ModulePgSQL()
533         {
534                 delete retimer;
535                 ClearAllConnections();
536         }
537
538         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
539         {
540                 ReadConf();
541         }
542
543         void ReadConf()
544         {
545                 ConnMap conns;
546                 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
547                 for(ConfigIter i = tags.first; i != tags.second; i++)
548                 {
549                         if (!stdalgo::string::equalsci(i->second->getString("module"), "pgsql"))
550                                 continue;
551                         std::string id = i->second->getString("id");
552                         ConnMap::iterator curr = connections.find(id);
553                         if (curr == connections.end())
554                         {
555                                 SQLConn* conn = new SQLConn(this, i->second);
556                                 conns.insert(std::make_pair(id, conn));
557                                 ServerInstance->Modules->AddService(*conn);
558                         }
559                         else
560                         {
561                                 conns.insert(*curr);
562                                 connections.erase(curr);
563                         }
564                 }
565                 ClearAllConnections();
566                 conns.swap(connections);
567         }
568
569         void ClearAllConnections()
570         {
571                 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
572                 {
573                         i->second->cull();
574                         delete i->second;
575                 }
576                 connections.clear();
577         }
578
579         void OnUnloadModule(Module* mod) CXX11_OVERRIDE
580         {
581                 SQL::Error err(SQL::BAD_DBID);
582                 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
583                 {
584                         SQLConn* conn = i->second;
585                         if (conn->qinprog.c && conn->qinprog.c->creator == mod)
586                         {
587                                 conn->qinprog.c->OnError(err);
588                                 delete conn->qinprog.c;
589                                 conn->qinprog.c = NULL;
590                         }
591                         std::deque<QueueItem>::iterator j = conn->queue.begin();
592                         while (j != conn->queue.end())
593                         {
594                                 SQL::Query* q = j->c;
595                                 if (q->creator == mod)
596                                 {
597                                         q->OnError(err);
598                                         delete q;
599                                         j = conn->queue.erase(j);
600                                 }
601                                 else
602                                         j++;
603                         }
604                 }
605         }
606
607         Version GetVersion() CXX11_OVERRIDE
608         {
609                 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
610         }
611 };
612
613 bool ReconnectTimer::Tick(time_t time)
614 {
615         mod->retimer = NULL;
616         mod->ReadConf();
617         delete this;
618         return false;
619 }
620
621 void SQLConn::DelayReconnect()
622 {
623         ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
624         ConnMap::iterator it = mod->connections.find(conf->getString("id"));
625         if (it != mod->connections.end())
626         {
627                 mod->connections.erase(it);
628                 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
629                 if (!mod->retimer)
630                 {
631                         mod->retimer = new ReconnectTimer(mod);
632                         ServerInstance->Timers.AddTimer(mod->retimer);
633                 }
634         }
635 }
636
637 MODULE_INIT(ModulePgSQL)