1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
20 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
21 /* $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));") */
22 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
23 /* $ModDep: m_sqlv2.h */
26 /* SQLConn rewritten by peavey to
27 * use EventHandler instead of
28 * BufferedSocket. This is much neater
29 * and gives total control of destroy
30 * and delete of resources.
33 /* Forward declare, so we can have the typedef neatly at the top */
36 typedef std::map<std::string, SQLConn*> ConnMap;
38 /* CREAD, Connecting and wants read event
39 * CWRITE, Connecting and wants write event
40 * WREAD, Connected/Working and wants read event
41 * WWRITE, Connected/Working and wants write event
42 * RREAD, Resetting and wants read event
43 * RWRITE, Resetting and wants write event
45 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
47 unsigned long count(const char * const str, char a)
50 for (const char *p = reinterpret_cast<const char *>(str); *p; ++p)
58 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
60 std::string SQLhost::GetDSN()
62 std::ostringstream conninfo("connect_timeout = '5'");
65 conninfo << " host = '" << host << "'";
68 conninfo << " port = '" << port << "'";
71 conninfo << " dbname = '" << name << "'";
74 conninfo << " user = '" << user << "'";
77 conninfo << " password = '" << pass << "'";
81 conninfo << " sslmode = 'require'";
85 conninfo << " sslmode = 'disable'";
88 return conninfo.str();
91 class ReconnectTimer : public Timer
96 ReconnectTimer(InspIRCd* SI, Module* m)
97 : Timer(5, SI->Time(), false), mod(m)
100 virtual void Tick(time_t TIME);
104 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
105 * All SQL providers must create their own subclass and define it's methods using that
106 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
107 * of converting all data to a common format before it reaches the result structure. This way
108 * data is passes to the module nearly as directly as if it was using the API directly itself.
111 class PgSQLresult : public SQLresult
118 SQLfieldList* fieldlist;
119 SQLfieldMap* fieldmap;
121 PgSQLresult(Module* self, Module* to, unsigned long rid, PGresult* result)
122 : SQLresult(self, to, rid), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
124 rows = PQntuples(res);
125 cols = PQnfields(res);
130 /* If we allocated these, free them... */
144 return atoi(PQcmdTuples(res));
154 return PQnfields(res);
157 virtual std::string ColName(int column)
159 char* name = PQfname(res, column);
161 return (name) ? name : "";
164 virtual int ColNum(const std::string &column)
166 int n = PQfnumber(res, column.c_str());
170 throw SQLbadColName();
178 virtual SQLfield GetValue(int row, int column)
180 char* v = PQgetvalue(res, row, column);
184 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
188 throw SQLbadColName();
192 virtual SQLfieldList& GetRow()
194 /* In an effort to reduce overhead we don't actually allocate the list
195 * until the first time it's needed...so...
203 fieldlist = new SQLfieldList;
206 if(currentrow < PQntuples(res))
208 int ncols = PQnfields(res);
210 for(int i = 0; i < ncols; i++)
212 fieldlist->push_back(GetValue(currentrow, i));
221 virtual SQLfieldMap& GetRowMap()
223 /* In an effort to reduce overhead we don't actually allocate the map
224 * until the first time it's needed...so...
232 fieldmap = new SQLfieldMap;
235 if(currentrow < PQntuples(res))
237 int ncols = PQnfields(res);
239 for(int i = 0; i < ncols; i++)
241 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
250 virtual SQLfieldList* GetRowPtr()
252 SQLfieldList* fl = new SQLfieldList;
254 if(currentrow < PQntuples(res))
256 int ncols = PQnfields(res);
258 for(int i = 0; i < ncols; i++)
260 fl->push_back(GetValue(currentrow, i));
269 virtual SQLfieldMap* GetRowMapPtr()
271 SQLfieldMap* fm = new SQLfieldMap;
273 if(currentrow < PQntuples(res))
275 int ncols = PQnfields(res);
277 for(int i = 0; i < ncols; i++)
279 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
288 virtual void Free(SQLfieldMap* fm)
293 virtual void Free(SQLfieldList* fl)
299 /** SQLConn represents one SQL session.
301 class SQLConn : public EventHandler
304 InspIRCd* ServerInstance;
305 SQLhost confhost; /* The <database> entry */
306 Module* us; /* Pointer to the SQL provider itself */
307 PGconn* sql; /* PgSQL database connection handle */
308 SQLstatus status; /* PgSQL database connection status */
309 bool qinprog; /* If there is currently a query in progress */
310 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
311 time_t idle; /* Time we last heard from the database */
314 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
315 : EventHandler(), ServerInstance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
317 idle = this->ServerInstance->Time();
320 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
330 virtual void HandleEvent(EventType et, int errornum)
353 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
356 if(PQstatus(sql) == CONNECTION_BAD)
359 if(PQsetnonblocking(sql, 1) == -1)
362 /* OK, we've initalised the connection, now to get it hooked into the socket engine
363 * and then start polling it.
365 this->fd = PQsocket(sql);
370 if (!this->ServerInstance->SE->AddFd(this))
372 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
376 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
382 switch(PQconnectPoll(sql))
384 case PGRES_POLLING_WRITING:
385 ServerInstance->SE->WantWrite(this);
388 case PGRES_POLLING_READING:
391 case PGRES_POLLING_FAILED:
393 case PGRES_POLLING_OK:
395 return DoConnectedPoll();
401 bool DoConnectedPoll()
403 if(!qinprog && queue.totalsize())
405 /* There's no query currently in progress, and there's queries in the queue. */
406 SQLrequest& query = queue.front();
410 if(PQconsumeInput(sql))
412 /* We just read stuff from the server, that counts as it being alive
413 * so update the idle-since time :p
415 idle = this->ServerInstance->Time();
419 /* Nothing happens here */
423 /* Grab the request we're processing */
424 SQLrequest& query = queue.front();
426 /* Get a pointer to the module we're about to return the result to */
427 Module* to = query.GetSource();
429 /* Fetch the result.. */
430 PGresult* result = PQgetResult(sql);
432 /* PgSQL would allow a query string to be sent which has multiple
433 * queries in it, this isn't portable across database backends and
434 * we don't want modules doing it. But just in case we make sure we
435 * drain any results there are and just use the last one.
436 * If the module devs are behaving there will only be one result.
438 while (PGresult* temp = PQgetResult(sql))
446 /* ..and the result */
447 PgSQLresult reply(us, to, query.id, result);
449 /* Fix by brain, make sure the original query gets sent back in the reply */
450 reply.query = query.query.q;
452 switch(PQresultStatus(result))
454 case PGRES_EMPTY_QUERY:
455 case PGRES_BAD_RESPONSE:
456 case PGRES_FATAL_ERROR:
457 reply.error.Id(SQL_QREPLY_FAIL);
458 reply.error.Str(PQresultErrorMessage(result));
461 /* No action, other values are not errors */
466 /* PgSQLresult's destructor will free the PGresult */
470 /* If the client module is unloaded partway through a query then the provider will set
471 * the pointer to NULL. We cannot just cancel the query as the result will still come
472 * through at some point...and it could get messy if we play with invalid pointers...
484 /* I think we'll assume this means the server died...it might not,
485 * but I think that any error serious enough we actually get here
486 * deserves to reconnect [/excuse]
487 * Returning true so the core doesn't try and close the connection.
496 switch(PQresetPoll(sql))
498 case PGRES_POLLING_WRITING:
499 ServerInstance->SE->WantWrite(this);
502 case PGRES_POLLING_READING:
505 case PGRES_POLLING_FAILED:
507 case PGRES_POLLING_OK:
509 return DoConnectedPoll();
517 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
523 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
532 void DelayReconnect();
538 if((status == CREAD) || (status == CWRITE))
542 else if((status == RREAD) || (status == RWRITE))
548 ret = DoConnectedPoll();
553 SQLerror DoQuery(SQLrequest &req)
555 if((status == WREAD) || (status == WWRITE))
559 /* Parse the command string and dispatch it */
561 /* Pointer to the buffer we screw around with substitution in */
563 /* Pointer to the current end of query, where we append new stuff */
566 /* Total length of the unescaped parameters */
567 unsigned long maxparamlen, paramcount;
569 /* The length of the longest parameter */
572 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
574 if (i->size() > maxparamlen)
575 maxparamlen = i->size();
578 /* How many params are there in the query? */
579 paramcount = count(req.query.q.c_str(), '?');
581 /* This stores copy of params to be inserted with using numbered params 1;3B*/
582 ParamL paramscopy(req.query.p);
584 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
585 * sizeofquery + (maxtotalparamlength*2) + 1
587 * The +1 is for null-terminating the string for PQsendQuery()
590 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
593 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
594 * the parameters into it...
597 for(unsigned int i = 0; i < req.query.q.length(); i++)
599 if(req.query.q[i] == '?')
601 /* We found a place to substitute..what fun.
602 * Use the PgSQL calls to escape and write the
603 * escaped string onto the end of our query buffer,
604 * then we "just" need to make sure queryend is
605 * pointing at the right place.
608 /* Is it numbered parameter?
614 /* Numbered parameter number :|
616 unsigned int paramnum;
619 /* Let's check if it's a numbered param. And also calculate it's number.
622 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
626 paramnum = paramnum * 10 + req.query.q[i] - '0';
629 if (paramnum > paramscopy.size() - 1)
631 /* index is out of range!
641 #ifdef PGSQL_HAS_ESCAPECONN
642 len = PQescapeStringConn(sql, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length(), &error);
644 len = PQescapeString (queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
648 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
651 /* Incremenet queryend to the end of the newly escaped parameter */
654 else if (req.query.p.size())
659 #ifdef PGSQL_HAS_ESCAPECONN
660 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
662 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
666 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
669 /* Incremenet queryend to the end of the newly escaped parameter */
672 /* Remove the parameter we just substituted in */
673 req.query.p.pop_front();
677 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
683 *queryend = req.query.q[i];
688 /* Null-terminate the query */
692 if(PQsendQuery(sql, query))
701 return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
705 return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
708 SQLerror Query(const SQLrequest &req)
712 if(!qinprog && queue.totalsize())
714 /* There's no query currently in progress, and there's queries in the queue. */
715 SQLrequest& query = queue.front();
716 return DoQuery(query);
724 void OnUnloadModule(Module* mod)
726 queue.PurgeModule(mod);
729 const SQLhost GetConfHost()
736 if (!this->ServerInstance->SE->DelFd(this))
738 if (sql && PQstatus(sql) == CONNECTION_BAD)
740 this->ServerInstance->SE->DelFd(this, true);
744 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: PQsocket cant be removed from socket engine!");
757 class ModulePgSQL : public Module
761 unsigned long currid;
763 ReconnectTimer* retimer;
766 ModulePgSQL(InspIRCd* Me)
767 : Module(Me), currid(0)
769 ServerInstance->Modules->UseInterface("SQLutils");
771 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
773 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
775 if (!ServerInstance->Modules->PublishFeature("SQL", this))
777 throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
782 ServerInstance->Modules->PublishInterface("SQL", this);
783 Implementation eventlist[] = { I_OnUnloadModule, I_OnRequest, I_OnRehash };
784 ServerInstance->Modules->Attach(eventlist, this, 3);
787 virtual ~ModulePgSQL()
790 ServerInstance->Timers->DelTimer(retimer);
791 ClearAllConnections();
793 ServerInstance->Modules->UnpublishInterface("SQL", this);
794 ServerInstance->Modules->UnpublishFeature("SQL");
795 ServerInstance->Modules->DoneWithInterface("SQLutils");
799 virtual void OnRehash(User* user, const std::string ¶meter)
804 bool HasHost(const SQLhost &host)
806 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
808 if (host == iter->second->GetConfHost())
814 bool HostInConf(const SQLhost &h)
816 ConfigReader conf(ServerInstance);
817 for(int i = 0; i < conf.Enumerate("database"); i++)
820 host.id = conf.ReadValue("database", "id", i);
821 host.host = conf.ReadValue("database", "hostname", i);
822 host.port = conf.ReadInteger("database", "port", i, true);
823 host.name = conf.ReadValue("database", "name", i);
824 host.user = conf.ReadValue("database", "username", i);
825 host.pass = conf.ReadValue("database", "password", i);
826 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
835 ClearOldConnections();
837 ConfigReader conf(ServerInstance);
838 for(int i = 0; i < conf.Enumerate("database"); i++)
842 host.id = conf.ReadValue("database", "id", i);
843 host.host = conf.ReadValue("database", "hostname", i);
844 host.port = conf.ReadInteger("database", "port", i, true);
845 host.name = conf.ReadValue("database", "name", i);
846 host.user = conf.ReadValue("database", "username", i);
847 host.pass = conf.ReadValue("database", "password", i);
848 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
857 void ClearOldConnections()
859 ConnMap::iterator iter,safei;
860 for (iter = connections.begin(); iter != connections.end(); iter++)
862 if (!HostInConf(iter->second->GetConfHost()))
867 connections.erase(safei);
872 void ClearAllConnections()
875 while ((i = connections.begin()) != connections.end())
877 connections.erase(i);
882 void AddConn(const SQLhost& hi)
886 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: A pgsql connection with id: %s already exists. Aborting connection attempt.", hi.id.c_str());
892 newconn = new SQLConn(ServerInstance, this, hi);
894 connections.insert(std::make_pair(hi.id, newconn));
897 void ReconnectConn(SQLConn* conn)
899 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
901 if (conn == iter->second)
904 connections.erase(iter);
908 retimer = new ReconnectTimer(ServerInstance, this);
909 ServerInstance->Timers->AddTimer(retimer);
912 virtual const char* OnRequest(Request* request)
914 if(strcmp(SQLREQID, request->GetId()) == 0)
916 SQLrequest* req = (SQLrequest*)request;
917 ConnMap::iterator iter;
918 if((iter = connections.find(req->dbid)) != connections.end())
922 req->error = iter->second->Query(*req);
924 return (req->error.Id() == SQL_NO_ERROR) ? sqlsuccess : NULL;
928 req->error.Id(SQL_BAD_DBID);
935 virtual void OnUnloadModule(Module* mod, const std::string& name)
937 /* When a module unloads we have to check all the pending queries for all our connections
938 * and set the Module* specifying where the query came from to NULL. If the query has already
939 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
941 * If the queries we find are not already being executed then we can simply remove them immediately.
943 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
945 iter->second->OnUnloadModule(mod);
949 unsigned long NewID()
957 virtual Version GetVersion()
959 return Version("$Id$", VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
963 void ReconnectTimer::Tick(time_t time)
965 ((ModulePgSQL*)mod)->ReadConf();
968 void SQLConn::DelayReconnect()
970 ((ModulePgSQL*)us)->ReconnectConn(this);
973 MODULE_INIT(ModulePgSQL)