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");
145 log(DEBUG, "Checking for DNS lookup result");
147 if(this->dns.HasResult())
149 std::string res_ip = dns.GetResultIP();
153 log(DEBUG, "Got result: %s", res_ip.c_str());
155 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
158 socket_ref[this->fd] = NULL;
160 return this->DoConnect();
164 log(DEBUG, "DNS lookup failed, dying horribly");
171 log(DEBUG, "No result for lookup yet!");
180 log(DEBUG, "SQLConn::DoConnect()");
182 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
184 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
189 if(PQstatus(sql) == CONNECTION_BAD)
191 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
198 if(PQsetnonblocking(sql, 1) == -1)
200 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
205 /* OK, we've initalised the connection, now to get it hooked into the socket engine
206 * and then start polling it.
209 log(DEBUG, "Old DNS socket: %d", this->fd);
210 this->fd = PQsocket(sql);
211 log(DEBUG, "New SQL socket: %d", this->fd);
215 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
220 this->state = I_CONNECTING;
221 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
222 socket_ref[this->fd] = this;
224 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
232 this->state = I_ERROR;
233 this->OnError(I_ERR_SOCKET);
234 this->ClosePending = true;
235 log(DEBUG,"SQLConn::Close");
248 switch(PQconnectPoll(sql))
250 case PGRES_POLLING_WRITING:
251 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
255 case PGRES_POLLING_READING:
256 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
259 case PGRES_POLLING_FAILED:
260 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
263 case PGRES_POLLING_OK:
264 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
266 Query("SELECT * FROM rawr");
269 log(DEBUG, "PGconnectPoll: wtf?");
278 switch(PQstatus(sql))
280 case CONNECTION_STARTED:
281 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
284 case CONNECTION_MADE:
285 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
288 case CONNECTION_AWAITING_RESPONSE:
289 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
292 case CONNECTION_AUTH_OK:
293 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
296 case CONNECTION_SSL_STARTUP:
297 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
300 case CONNECTION_SETENV:
301 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
305 log(DEBUG, "PQstatus: ???");
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 std::string MkInfoStr()
371 /* XXX - This needs nonblocking DNS lookups */
373 std::ostringstream conninfo("connect_timeout = '2'");
376 conninfo << " hostaddr = '" << dbhost << "'";
379 conninfo << " port = '" << dbport << "'";
382 conninfo << " dbname = '" << dbname << "'";
385 conninfo << " user = '" << dbuser << "'";
388 conninfo << " password = '" << dbpass << "'";
391 conninfo << " sslmode = 'require'";
393 return conninfo.str();
396 const char* StatusStr()
398 if(status == CREAD) return "CREAD";
399 if(status == CWRITE) return "CWRITE";
400 if(status == WREAD) return "WREAD";
401 if(status == WWRITE) return "WWRITE";
402 return "Err...what, erm..BUG!";
405 bool Query(const std::string &query)
407 if((status == WREAD) || (status == WWRITE))
409 if(PQsendQuery(sql, query.c_str()))
411 log(DEBUG, "Dispatched query: %s", query.c_str());
416 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
421 log(DEBUG, "Can't query until connection is complete");
425 virtual void OnClose()
427 /* Close PgSQL connection */
430 virtual void OnError(InspSocketError e)
432 /* Unsure if we need this, we should be reading/writing via the PgSQL API rather than the insp one... */
435 virtual void OnTimeout()
437 /* Unused, I think */
442 class ModulePgSQL : public Module
449 ModulePgSQL(Server* Me)
450 : Module::Module(Me), Srv(Me)
452 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
453 log(DEBUG, "%s 'PgSQL' feature", Srv->PublishFeature("PgSQL", this) ? "Published" : "Couldn't publish");
458 void Implements(char* List)
460 List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
463 virtual void OnRehash(const std::string ¶meter)
467 /* Delete all the SQLConn objects in the connection lists,
468 * this will call their destructors where they can handle
469 * closing connections and such.
471 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
473 DELETE(iter->second);
476 /* Empty out our list of connections */
479 for(int i = 0; i < conf.Enumerate("database"); i++)
484 id = conf.ReadValue("database", "id", i);
485 newconn = new SQLConn(Srv, conf.ReadValue("database", "hostname", i),
486 conf.ReadInteger("database", "port", i, true),
487 conf.ReadValue("database", "name", i),
488 conf.ReadValue("database", "username", i),
489 conf.ReadValue("database", "password", i),
490 conf.ReadFlag("database", "ssl", i));
492 connections.insert(std::make_pair(id, newconn));
496 virtual Version GetVersion()
498 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
501 virtual ~ModulePgSQL()
506 class ModulePgSQLFactory : public ModuleFactory
513 ~ModulePgSQLFactory()
517 virtual Module * CreateModule(Server* Me)
519 return new ModulePgSQL(Me);
524 extern "C" void * init_module( void )
526 return new ModulePgSQLFactory;