1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
11 * Written by Craig Edwards, Craig McLure, and others.
12 * This program is free but copyrighted software; see
13 * the file COPYING for details.
15 * ---------------------------------------------------
26 #include "helperfuncs.h"
28 #include "configreader.h"
32 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
33 /* $CompileFlags: -I`pg_config --includedir` */
34 /* $LinkerFlags: -L`pg_config --libdir` -lpq */
36 /* UGH, UGH, UGH, UGH, UGH, UGH
37 * I'm having trouble seeing how I
38 * can avoid this. The core-defined
39 * constructors for InspSocket just
40 * aren't suitable...and if I'm
41 * reimplementing them I need this so
42 * I can access the socket engine :\
44 extern InspIRCd* ServerInstance;
45 InspSocket* socket_ref[MAX_DESCRIPTORS];
47 /* Forward declare, so we can have the typedef neatly at the top */
50 typedef std::map<std::string, SQLConn*> ConnMap;
52 /* CREAD, Connecting and wants read event
53 * CWRITE, Connecting and wants write event
54 * WREAD, Connected/Working and wants read event
55 * WWRITE, Connected/Working and wants write event
57 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE };
64 SQLerror(const std::string &s)
70 /** SQLConn represents one SQL session.
71 * Each session has its own persistent connection to the database.
72 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
73 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
77 class SQLConn : public InspSocket
80 Server* Srv; /* Server* for..uhm..something, maybe */
81 std::string dbhost; /* Database server hostname */
82 unsigned int dbport; /* Database server port */
83 std::string dbname; /* Database name */
84 std::string dbuser; /* Database username */
85 std::string dbpass; /* Database password */
86 bool ssl; /* If we should require SSL */
87 PGconn* sql; /* PgSQL database connection handle */
88 SQLstatus status; /* PgSQL database connection status */
92 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
94 SQLConn(Server* srv, const std::string &h, unsigned int p, const std::string &d, const std::string &u, const std::string &pwd, bool s)
95 : InspSocket::InspSocket(), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE)
97 log(DEBUG, "Creating new PgSQL connection to database %s on %s:%u (%s/%s)", dbname.c_str(), dbhost.c_str(), dbport, dbuser.c_str(), dbpass.c_str());
99 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
100 * just copied this over from the InspSocket constructor.
102 strlcpy(this->host, dbhost.c_str(), MAXBUF);
105 this->ClosePending = false;
107 if(!inet_aton(this->host, &this->addy))
109 /* Its not an ip, spawn the resolver.
110 * PgSQL doesn't do nonblocking DNS
111 * lookups, so we do it for it.
114 log(DEBUG,"Attempting to resolve %s", this->host);
116 this->dns.SetNS(Srv->GetConfig()->DNSServer);
117 this->dns.ForwardLookupWithFD(this->host, fd);
119 this->state = I_RESOLVING;
120 socket_ref[this->fd] = this;
126 log(DEBUG,"No need to resolve %s", this->host);
127 strlcpy(this->IP, this->host, MAXBUF);
129 if(!this->DoConnect())
131 throw ModuleException("Connect failed");
140 log(DEBUG, "Checking for DNS lookup result");
142 if(this->dns.HasResult())
144 std::string res_ip = dns.GetResultIP();
148 log(DEBUG, "Got result: %s", res_ip.c_str());
150 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
153 socket_ref[this->fd] = NULL;
155 return this->DoConnect();
159 log(DEBUG, "DNS lookup failed, dying horribly");
166 log(DEBUG, "No result for lookup yet!");
175 log(DEBUG, "SQLConn::DoConnect()");
177 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
179 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
184 if(PQstatus(sql) == CONNECTION_BAD)
186 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
193 if(PQsetnonblocking(sql, 1) == -1)
195 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
200 /* OK, we've initalised the connection, now to get it hooked into the socket engine
201 * and then start polling it.
204 log(DEBUG, "Old DNS socket: %d", this->fd);
205 this->fd = PQsocket(sql);
206 log(DEBUG, "New SQL socket: %d", this->fd);
210 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
215 this->state = I_CONNECTING;
216 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
217 socket_ref[this->fd] = this;
219 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
227 this->state = I_ERROR;
228 this->OnError(I_ERR_SOCKET);
229 this->ClosePending = true;
230 log(DEBUG,"SQLConn::DoError");
243 switch(PQconnectPoll(sql))
245 case PGRES_POLLING_WRITING:
246 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
250 case PGRES_POLLING_READING:
251 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
254 case PGRES_POLLING_FAILED:
255 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
258 case PGRES_POLLING_OK:
259 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
261 Query("SELECT * FROM rawr");
264 log(DEBUG, "PGconnectPoll: wtf?");
273 switch(PQstatus(sql))
275 case CONNECTION_STARTED:
276 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
279 case CONNECTION_MADE:
280 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
283 case CONNECTION_AWAITING_RESPONSE:
284 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
287 case CONNECTION_AUTH_OK:
288 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
291 case CONNECTION_SSL_STARTUP:
292 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
295 case CONNECTION_SETENV:
296 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
300 log(DEBUG, "PQstatus: ???");
304 virtual void OnTimeout()
306 /* Unused, I think */
309 virtual bool OnDataReady()
311 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
312 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
317 virtual bool OnConnected()
319 log(DEBUG, "OnConnected(): status = %s", StatusStr());
326 if((status == CREAD) || (status == CWRITE))
332 if(PQconsumeInput(sql))
334 log(DEBUG, "PQconsumeInput succeeded");
338 log(DEBUG, "Still busy processing command though");
342 log(DEBUG, "Looks like we have a result to process!");
344 while(PGresult* result = PQgetResult(sql))
346 int cols = PQnfields(result);
348 log(DEBUG, "Got result! :D");
349 log(DEBUG, "%d rows, %d columns checking now what the column names are", PQntuples(result), cols);
351 for(int i = 0; i < cols; i++)
353 log(DEBUG, "Column name: %s (%d)", PQfname(result, i));
362 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
369 virtual void OnClose()
371 /* Close PgSQL connection */
374 virtual void OnError(InspSocketError e)
376 /* Unsure if we need this, we should be reading/writing via the PgSQL API rather than the insp one... */
379 std::string MkInfoStr()
381 /* XXX - This needs nonblocking DNS lookups */
383 std::ostringstream conninfo("connect_timeout = '2'");
386 conninfo << " hostaddr = '" << dbhost << "'";
389 conninfo << " port = '" << dbport << "'";
392 conninfo << " dbname = '" << dbname << "'";
395 conninfo << " user = '" << dbuser << "'";
398 conninfo << " password = '" << dbpass << "'";
401 conninfo << " sslmode = 'require'";
403 return conninfo.str();
406 const char* StatusStr()
408 if(status == CREAD) return "CREAD";
409 if(status == CWRITE) return "CWRITE";
410 if(status == WREAD) return "WREAD";
411 if(status == WWRITE) return "WWRITE";
414 bool Query(const std::string &query)
416 if((status == WREAD) || (status == WWRITE))
418 if(PQsendQuery(sql, query.c_str()))
420 log(DEBUG, "Dispatched query: %s", query.c_str());
425 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
431 log(DEBUG, "Can't query until connection is complete");
437 class ModulePgSQL : public Module
444 ModulePgSQL(Server* Me)
445 : Module::Module(Me), Srv(Me)
450 void Implements(char* List)
452 List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
455 virtual void OnRehash(const std::string ¶meter)
459 /* Delete all the SQLConn objects in the connection lists,
460 * this will call their destructors where they can handle
461 * closing connections and such.
463 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
465 DELETE(iter->second);
468 /* Empty out our list of connections */
471 for(int i = 0; i < conf.Enumerate("database"); i++)
476 id = conf.ReadValue("database", "id", i);
477 newconn = new SQLConn(Srv, conf.ReadValue("database", "hostname", i),
478 conf.ReadInteger("database", "port", i, true),
479 conf.ReadValue("database", "name", i),
480 conf.ReadValue("database", "username", i),
481 conf.ReadValue("database", "password", i),
482 conf.ReadFlag("database", "ssl", i));
484 connections.insert(std::make_pair(id, newconn));
488 virtual Version GetVersion()
490 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
493 virtual ~ModulePgSQL()
498 class ModulePgSQLFactory : public ModuleFactory
505 ~ModulePgSQLFactory()
509 virtual Module * CreateModule(Server* Me)
511 return new ModulePgSQL(Me);
516 extern "C" void * init_module( void )
518 return new ModulePgSQLFactory;