+SQLConn::SQLConn(InspIRCd* SI, ModulePgSQL* self, const SQLhost& hi)
+: InspSocket::InspSocket(SI), us(self), dbhost(hi.host), dbport(hi.port), dbname(hi.name), dbuser(hi.user), dbpass(hi.pass), ssl(hi.ssl), sql(NULL), status(CWRITE), qinprog(false)
+{
+ 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());
+
+ /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
+ * just copied this over from the InspSocket constructor.
+ */
+ strlcpy(this->host, dbhost.c_str(), MAXBUF);
+ strlcpy(this->IP, dbhost.c_str(), MAXBUF);
+ this->port = dbport;
+ idle = TIME;
+
+ this->ClosePending = false;
+
+ log(DEBUG,"No need to resolve %s", this->host);
+
+
+ if(!this->DoConnect())
+ {
+ throw ModuleException("Connect failed");
+ }
+}
+
+SQLConn::~SQLConn()
+{
+ Close();
+}
+
+bool SQLConn::DoConnect()
+{
+ log(DEBUG, "SQLConn::DoConnect()");
+
+ if(!(sql = PQconnectStart(MkInfoStr().c_str())))
+ {
+ log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
+ Close();
+ return false;
+ }
+
+ if(PQstatus(sql) == CONNECTION_BAD)
+ {
+ log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
+ Close();
+ return false;
+ }
+
+ ShowStatus();
+
+ if(PQsetnonblocking(sql, 1) == -1)
+ {
+ log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
+ Close();
+ return false;
+ }
+
+ /* OK, we've initalised the connection, now to get it hooked into the socket engine
+ * and then start polling it.
+ */
+
+ log(DEBUG, "Old DNS socket: %d", this->fd);
+ this->fd = PQsocket(sql);
+ log(DEBUG, "New SQL socket: %d", this->fd);
+
+ if(this->fd <= -1)
+ {
+ log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
+ Close();
+ return false;
+ }
+
+ this->state = I_CONNECTING;
+ if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
+ {
+ log(DEBUG, "A PQsocket cant be added to the socket engine!");
+ Close();
+ return false;
+ }
+ this->Instance->socket_ref[this->fd] = this;
+
+ /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
+
+ return DoPoll();
+}
+
+void SQLConn::Close()
+{
+ log(DEBUG,"SQLConn::Close");
+
+ if(this->fd > 01)
+ Instance->socket_ref[this->fd] = NULL;
+ this->fd = -1;
+ this->state = I_ERROR;
+ this->OnError(I_ERR_SOCKET);
+ this->ClosePending = true;
+
+ if(sql)
+ {
+ PQfinish(sql);
+ sql = NULL;
+ }
+
+ return;
+}
+
+bool SQLConn::DoPoll()
+{
+ switch(PQconnectPoll(sql))
+ {
+ case PGRES_POLLING_WRITING:
+ log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
+ WantWrite();
+ status = CWRITE;
+ return DoPoll();
+ case PGRES_POLLING_READING:
+ log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
+ status = CREAD;
+ return true;
+ case PGRES_POLLING_FAILED:
+ log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
+ return false;
+ case PGRES_POLLING_OK:
+ log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
+ status = WWRITE;
+ return DoConnectedPoll();
+ default:
+ log(DEBUG, "PGconnectPoll: wtf?");
+ return true;
+ }
+}
+
+bool SQLConn::DoConnectedPoll()
+{
+ if(!qinprog && queue.totalsize())
+ {
+ /* There's no query currently in progress, and there's queries in the queue. */
+ SQLrequest& query = queue.front();
+ DoQuery(query);
+ }
+
+ if(PQconsumeInput(sql))
+ {
+ log(DEBUG, "PQconsumeInput succeeded");
+
+ /* We just read stuff from the server, that counts as it being alive
+ * so update the idle-since time :p
+ */
+ idle = TIME;
+
+ if(PQisBusy(sql))
+ {
+ log(DEBUG, "Still busy processing command though");
+ }
+ else if(qinprog)
+ {
+ log(DEBUG, "Looks like we have a result to process!");
+
+ /* Grab the request we're processing */
+ SQLrequest& query = queue.front();
+
+ log(DEBUG, "ID is %lu", query.id);
+
+ /* Get a pointer to the module we're about to return the result to */
+ Module* to = query.GetSource();
+
+ /* Fetch the result.. */
+ PGresult* result = PQgetResult(sql);
+
+ /* PgSQL would allow a query string to be sent which has multiple
+ * queries in it, this isn't portable across database backends and
+ * we don't want modules doing it. But just in case we make sure we
+ * drain any results there are and just use the last one.
+ * If the module devs are behaving there will only be one result.
+ */
+ while (PGresult* temp = PQgetResult(sql))
+ {
+ PQclear(result);
+ result = temp;
+ }
+
+ if(to)
+ {
+ /* ..and the result */
+ PgSQLresult reply(us, to, query.id, result);
+
+ log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
+
+ switch(PQresultStatus(result))
+ {
+ case PGRES_EMPTY_QUERY:
+ case PGRES_BAD_RESPONSE:
+ case PGRES_FATAL_ERROR:
+ reply.error.Id(QREPLY_FAIL);
+ reply.error.Str(PQresultErrorMessage(result));
+ default:;
+ /* No action, other values are not errors */
+ }
+
+ reply.Send();
+
+ /* PgSQLresult's destructor will free the PGresult */
+ }
+ else
+ {
+ /* If the client module is unloaded partway through a query then the provider will set
+ * the pointer to NULL. We cannot just cancel the query as the result will still come
+ * through at some point...and it could get messy if we play with invalid pointers...
+ */
+ log(DEBUG, "Looks like we're handling a zombie query from a module which unloaded before it got a result..fun. ID: %lu", query.id);
+ PQclear(result);
+ }
+
+ qinprog = false;
+ queue.pop();
+ DoConnectedPoll();
+ }
+ else
+ {
+ log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
+ }
+
+ return true;
+ }
+ else
+ {
+ /* I think we'll assume this means the server died...it might not,
+ * but I think that any error serious enough we actually get here
+ * deserves to reconnect [/excuse]
+ * Returning true so the core doesn't try and close the connection.
+ */
+ log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
+ Reconnect();
+ return true;
+ }
+}
+
+bool SQLConn::DoResetPoll()
+{
+ switch(PQresetPoll(sql))
+ {
+ case PGRES_POLLING_WRITING:
+ log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
+ WantWrite();
+ status = CWRITE;
+ return DoPoll();
+ case PGRES_POLLING_READING:
+ log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
+ status = CREAD;
+ return true;
+ case PGRES_POLLING_FAILED:
+ log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
+ return false;
+ case PGRES_POLLING_OK:
+ log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
+ status = WWRITE;
+ return DoConnectedPoll();
+ default:
+ log(DEBUG, "PGresetPoll: wtf?");
+ return true;
+ }
+}
+
+void SQLConn::ShowStatus()
+{
+ switch(PQstatus(sql))
+ {
+ case CONNECTION_STARTED:
+ log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
+ break;
+
+ case CONNECTION_MADE:
+ log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
+ break;
+
+ case CONNECTION_AWAITING_RESPONSE:
+ log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
+ break;
+
+ case CONNECTION_AUTH_OK:
+ log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
+ break;
+
+ case CONNECTION_SSL_STARTUP:
+ log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
+ break;
+
+ case CONNECTION_SETENV:
+ log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
+ break;
+
+ default:
+ log(DEBUG, "PQstatus: ???");
+ }
+}
+
+bool SQLConn::OnDataReady()
+{
+ /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
+ log(DEBUG, "OnDataReady(): status = %s", StatusStr());
+
+ return DoEvent();
+}
+
+bool SQLConn::OnWriteReady()
+{
+ /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
+ log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
+
+ return DoEvent();
+}
+
+bool SQLConn::OnConnected()
+{
+ log(DEBUG, "OnConnected(): status = %s", StatusStr());
+
+ return DoEvent();
+}
+
+bool SQLConn::Reconnect()
+{
+ log(DEBUG, "Initiating reconnect");
+
+ if(PQresetStart(sql))
+ {
+ /* Successfully initiatied database reconnect,
+ * set flags so PQresetPoll() will be called appropriately
+ */
+ status = RWRITE;
+ qinprog = false;
+ return true;
+ }
+ else
+ {
+ log(DEBUG, "Failed to initiate reconnect...fun");
+ return false;
+ }
+}
+
+bool SQLConn::DoEvent()
+{
+ bool ret;
+
+ if((status == CREAD) || (status == CWRITE))
+ {
+ ret = DoPoll();
+ }
+ else if((status == RREAD) || (status == RWRITE))
+ {
+ ret = DoResetPoll();
+ }
+ else
+ {
+ ret = DoConnectedPoll();
+ }
+
+ switch(PQflush(sql))
+ {
+ case -1:
+ log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
+ break;
+ case 0:
+ log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
+ break;
+ case 1:
+ log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
+ WantWrite();
+ break;
+ }
+
+ return ret;
+}
+
+std::string SQLConn::MkInfoStr()
+{
+ std::ostringstream conninfo("connect_timeout = '2'");
+
+ if(dbhost.length())
+ conninfo << " hostaddr = '" << dbhost << "'";
+
+ if(dbport)
+ conninfo << " port = '" << dbport << "'";
+
+ if(dbname.length())
+ conninfo << " dbname = '" << dbname << "'";
+
+ if(dbuser.length())
+ conninfo << " user = '" << dbuser << "'";
+
+ if(dbpass.length())
+ conninfo << " password = '" << dbpass << "'";
+
+ if(ssl)
+ conninfo << " sslmode = 'require'";
+
+ return conninfo.str();
+}
+
+const char* SQLConn::StatusStr()
+{
+ if(status == CREAD) return "CREAD";
+ if(status == CWRITE) return "CWRITE";
+ if(status == WREAD) return "WREAD";
+ if(status == WWRITE) return "WWRITE";
+ return "Err...what, erm..BUG!";
+}
+
+SQLerror SQLConn::DoQuery(SQLrequest &req)
+{
+ if((status == WREAD) || (status == WWRITE))
+ {
+ if(!qinprog)
+ {
+ /* Parse the command string and dispatch it */
+
+ /* Pointer to the buffer we screw around with substitution in */
+ char* query;
+ /* Pointer to the current end of query, where we append new stuff */
+ char* queryend;
+ /* Total length of the unescaped parameters */
+ unsigned int paramlen;
+
+ paramlen = 0;
+
+ for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
+ {
+ paramlen += i->size();
+ }
+
+ /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
+ * sizeofquery + (totalparamlength*2) + 1
+ *
+ * The +1 is for null-terminating the string for PQsendQuery()
+ */
+
+ query = new char[req.query.q.length() + (paramlen*2)];
+ queryend = query;
+
+ /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
+ * the parameters into it...
+ */
+
+ for(unsigned int i = 0; i < req.query.q.length(); i++)
+ {
+ if(req.query.q[i] == '?')
+ {
+ /* We found a place to substitute..what fun.
+ * Use the PgSQL calls to escape and write the
+ * escaped string onto the end of our query buffer,
+ * then we "just" need to make sure queryend is
+ * pointing at the right place.
+ */
+
+ if(req.query.p.size())
+ {
+ int error = 0;
+ size_t len = 0;
+
+#ifdef PGSQL_HAS_ESCAPECONN
+ len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
+#else
+ len = PQescapeStringConn(queryend, req.query.p.front().c_str(), req.query.p.front().length());
+ error = 0;
+#endif
+ if(error)
+ {
+ log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
+ }
+
+ log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
+
+ /* Incremenet queryend to the end of the newly escaped parameter */
+ queryend += len;
+
+ /* Remove the parameter we just substituted in */
+ req.query.p.pop_front();
+ }
+ else
+ {
+ log(DEBUG, "Found a substitution location but no parameter to substitute :|");
+ break;
+ }
+ }
+ else
+ {
+ *queryend = req.query.q[i];
+ queryend++;
+ }
+ }
+
+ /* Null-terminate the query */
+ *queryend = 0;
+
+ log(DEBUG, "Attempting to dispatch query: %s", query);
+
+ req.query.q = query;
+
+ if(PQsendQuery(sql, query))
+ {
+ log(DEBUG, "Dispatched query successfully");
+ qinprog = true;
+ DELETE(query);
+ return SQLerror();
+ }
+ else
+ {
+ log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
+ DELETE(query);
+ return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
+ }
+ }
+ }
+
+ log(DEBUG, "Can't query until connection is complete");
+ return SQLerror(BAD_CONN, "Can't query until connection is complete");
+}
+
+SQLerror SQLConn::Query(const SQLrequest &req)
+{
+ queue.push(req);
+
+ if(!qinprog && queue.totalsize())
+ {
+ /* There's no query currently in progress, and there's queries in the queue. */
+ SQLrequest& query = queue.front();
+ return DoQuery(query);
+ }
+ else
+ {
+ return SQLerror();
+ }
+}
+
+void SQLConn::OnUnloadModule(Module* mod)
+{
+ queue.PurgeModule(mod);
+}
+
+void SQLresolver::OnLookupComplete(const std::string &result)
+{
+ host.host = result;
+ mod->AddConn(host);
+}
+