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 * ---------------------------------------------------
27 #include "helperfuncs.h"
29 #include "configreader.h"
33 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
34 /* $CompileFlags: -I`pg_config --includedir` */
35 /* $LinkerFlags: -L`pg_config --libdir` -lpq */
37 /* UGH, UGH, UGH, UGH, UGH, UGH
38 * I'm having trouble seeing how I
39 * can avoid this. The core-defined
40 * constructors for InspSocket just
41 * aren't suitable...and if I'm
42 * reimplementing them I need this so
43 * I can access the socket engine :\
45 extern InspIRCd* ServerInstance;
46 InspSocket* socket_ref[MAX_DESCRIPTORS];
48 /* Forward declare, so we can have the typedef neatly at the top */
51 typedef std::map<std::string, SQLConn*> ConnMap;
53 /* CREAD, Connecting and wants read event
54 * CWRITE, Connecting and wants write event
55 * WREAD, Connected/Working and wants read event
56 * WWRITE, Connected/Working and wants write event
58 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE };
60 /** QueryQueue, a queue of queries waiting to be executed.
61 * This maintains two queues internally, one for 'priority'
62 * queries and one for less important ones. Each queue has
63 * new queries appended to it and ones to execute are popped
64 * off the front. This keeps them flowing round nicely and no
65 * query should ever get 'stuck' for too long. If there are
66 * queries in the priority queue they will be executed first,
67 * 'unimportant' queries will only be executed when the
68 * priority queue is empty.
70 * We store lists of SQLrequest's here, by value as we want to avoid storing
71 * any data allocated inside the client module (in case that module is unloaded
72 * while the query is in progress).
74 * Because we want to work on the current SQLrequest in-situ, we need a way
75 * of accessing the request we are currently processing, QueryQueue::front(),
76 * but that call needs to always return the same request until that request
77 * is removed from the queue, this is what the 'which' variable is. New queries are
78 * always added to the back of one of the two queues, but if when front()
79 * is first called then the priority queue is empty then front() will return
80 * a query from the normal queue, but if a query is then added to the priority
81 * queue then front() must continue to return the front of the *normal* queue
82 * until pop() is called.
85 class QueryQueue : public classbase
88 std::deque<SQLrequest> priority; /* The priority queue */
89 std::deque<SQLrequest> normal; /* The 'normal' queue */
90 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
98 void push(const SQLrequest &q)
100 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.c_str());
103 priority.push_back(q);
110 if((which == PRI) && priority.size())
112 priority.pop_front();
114 else if((which == NOR) && normal.size())
122 /* Silently do nothing if there was no element to pop() */
130 return priority.front();
132 return normal.front();
137 return priority.front();
143 return normal.front();
146 /* This will probably result in a segfault,
147 * but the caller should have checked totalsize()
148 * first so..meh - moron :p
151 return priority.front();
155 std::pair<int, int> size()
157 return std::make_pair(priority.size(), normal.size());
162 return priority.size() + normal.size();
166 /** SQLConn represents one SQL session.
167 * Each session has its own persistent connection to the database.
168 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
169 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
173 class SQLConn : public InspSocket
176 Server* Srv; /* Server* for..uhm..something, maybe */
177 std::string dbhost; /* Database server hostname */
178 unsigned int dbport; /* Database server port */
179 std::string dbname; /* Database name */
180 std::string dbuser; /* Database username */
181 std::string dbpass; /* Database password */
182 bool ssl; /* If we should require SSL */
183 PGconn* sql; /* PgSQL database connection handle */
184 SQLstatus status; /* PgSQL database connection status */
185 bool qinprog;/* If there is currently a query in progress */
186 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
190 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
192 SQLConn(Server* srv, const std::string &h, unsigned int p, const std::string &d, const std::string &u, const std::string &pwd, bool s)
193 : InspSocket::InspSocket(), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE), qinprog(false)
195 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());
197 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
198 * just copied this over from the InspSocket constructor.
200 strlcpy(this->host, dbhost.c_str(), MAXBUF);
203 this->ClosePending = false;
205 if(!inet_aton(this->host, &this->addy))
207 /* Its not an ip, spawn the resolver.
208 * PgSQL doesn't do nonblocking DNS
209 * lookups, so we do it for it.
212 log(DEBUG,"Attempting to resolve %s", this->host);
214 this->dns.SetNS(Srv->GetConfig()->DNSServer);
215 this->dns.ForwardLookupWithFD(this->host, fd);
217 this->state = I_RESOLVING;
218 socket_ref[this->fd] = this;
224 log(DEBUG,"No need to resolve %s", this->host);
225 strlcpy(this->IP, this->host, MAXBUF);
227 if(!this->DoConnect())
229 throw ModuleException("Connect failed");
241 log(DEBUG, "Checking for DNS lookup result");
243 if(this->dns.HasResult())
245 std::string res_ip = dns.GetResultIP();
249 log(DEBUG, "Got result: %s", res_ip.c_str());
251 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
254 socket_ref[this->fd] = NULL;
256 return this->DoConnect();
260 log(DEBUG, "DNS lookup failed, dying horribly");
267 log(DEBUG, "No result for lookup yet!");
274 log(DEBUG, "SQLConn::DoConnect()");
276 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
278 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
283 if(PQstatus(sql) == CONNECTION_BAD)
285 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
292 if(PQsetnonblocking(sql, 1) == -1)
294 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
299 /* OK, we've initalised the connection, now to get it hooked into the socket engine
300 * and then start polling it.
303 log(DEBUG, "Old DNS socket: %d", this->fd);
304 this->fd = PQsocket(sql);
305 log(DEBUG, "New SQL socket: %d", this->fd);
309 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
314 this->state = I_CONNECTING;
315 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
316 socket_ref[this->fd] = this;
318 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
325 log(DEBUG,"SQLConn::Close");
328 socket_ref[this->fd] = NULL;
330 this->state = I_ERROR;
331 this->OnError(I_ERR_SOCKET);
332 this->ClosePending = true;
345 switch(PQconnectPoll(sql))
347 case PGRES_POLLING_WRITING:
348 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
352 case PGRES_POLLING_READING:
353 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
356 case PGRES_POLLING_FAILED:
357 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
359 case PGRES_POLLING_OK:
360 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
362 return DoConnectedPoll();
364 log(DEBUG, "PGconnectPoll: wtf?");
371 bool DoConnectedPoll()
373 if(!qinprog && queue.totalsize())
375 /* There's no query currently in progress, and there's queries in the queue. */
376 SQLrequest& query = queue.front();
380 if(PQconsumeInput(sql))
382 log(DEBUG, "PQconsumeInput succeeded");
386 log(DEBUG, "Still busy processing command though");
390 log(DEBUG, "Looks like we have a result to process!");
392 while(PGresult* result = PQgetResult(sql))
394 int cols = PQnfields(result);
396 log(DEBUG, "Got result! :D");
397 log(DEBUG, "%d rows, %d columns checking now what the column names are", PQntuples(result), cols);
399 for(int i = 0; i < cols; i++)
401 log(DEBUG, "Column name: %s (%d)", PQfname(result, i));
415 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
421 switch(PQstatus(sql))
423 case CONNECTION_STARTED:
424 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
427 case CONNECTION_MADE:
428 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
431 case CONNECTION_AWAITING_RESPONSE:
432 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
435 case CONNECTION_AUTH_OK:
436 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
439 case CONNECTION_SSL_STARTUP:
440 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
443 case CONNECTION_SETENV:
444 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
448 log(DEBUG, "PQstatus: ???");
452 virtual bool OnDataReady()
454 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
455 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
460 virtual bool OnWriteReady()
462 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
463 log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
468 virtual bool OnConnected()
470 log(DEBUG, "OnConnected(): status = %s", StatusStr());
479 if((status == CREAD) || (status == CWRITE))
485 ret = DoConnectedPoll();
491 log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
494 log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
497 log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
505 std::string MkInfoStr()
507 /* XXX - This needs nonblocking DNS lookups */
509 std::ostringstream conninfo("connect_timeout = '2'");
512 conninfo << " hostaddr = '" << dbhost << "'";
515 conninfo << " port = '" << dbport << "'";
518 conninfo << " dbname = '" << dbname << "'";
521 conninfo << " user = '" << dbuser << "'";
524 conninfo << " password = '" << dbpass << "'";
527 conninfo << " sslmode = 'require'";
529 return conninfo.str();
532 const char* StatusStr()
534 if(status == CREAD) return "CREAD";
535 if(status == CWRITE) return "CWRITE";
536 if(status == WREAD) return "WREAD";
537 if(status == WWRITE) return "WWRITE";
538 return "Err...what, erm..BUG!";
541 SQLerror DoQuery(const SQLrequest &req)
543 if((status == WREAD) || (status == WWRITE))
547 if(PQsendQuery(sql, req.query.c_str()))
549 log(DEBUG, "Dispatched query: %s", req.query.c_str());
555 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
556 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
561 log(DEBUG, "Can't query until connection is complete");
562 return SQLerror(BAD_CONN, "Can't query until connection is complete");
565 SQLerror Query(const SQLrequest &req)
569 if(!qinprog && queue.totalsize())
571 /* There's no query currently in progress, and there's queries in the queue. */
572 SQLrequest& query = queue.front();
573 return DoQuery(query);
582 class ModulePgSQL : public Module
589 ModulePgSQL(Server* Me)
590 : Module::Module(Me), Srv(Me)
592 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
593 log(DEBUG, "%s 'PgSQL' feature", Srv->PublishFeature("PgSQL", this) ? "Published" : "Couldn't publish");
598 void Implements(char* List)
600 List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
603 virtual void OnRehash(const std::string ¶meter)
607 /* Delete all the SQLConn objects in the connection lists,
608 * this will call their destructors where they can handle
609 * closing connections and such.
611 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
613 DELETE(iter->second);
616 /* Empty out our list of connections */
619 for(int i = 0; i < conf.Enumerate("database"); i++)
624 id = conf.ReadValue("database", "id", i);
625 newconn = new SQLConn(Srv, conf.ReadValue("database", "hostname", i),
626 conf.ReadInteger("database", "port", i, true),
627 conf.ReadValue("database", "name", i),
628 conf.ReadValue("database", "username", i),
629 conf.ReadValue("database", "password", i),
630 conf.ReadFlag("database", "ssl", i));
632 connections.insert(std::make_pair(id, newconn));
636 virtual char* OnRequest(Request* request)
638 if(strcmp(SQLREQID, request->GetData()) == 0)
640 SQLrequest* req = (SQLrequest*)request;
641 ConnMap::iterator iter;
643 log(DEBUG, "Got query: '%s' on id '%s'", req->query.c_str(), req->dbid.c_str());
645 if((iter = connections.find(req->dbid)) != connections.end())
648 req->error = iter->second->Query(*req);
654 req->error.Id(BAD_DBID);
659 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
664 virtual Version GetVersion()
666 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
669 virtual ~ModulePgSQL()
674 class ModulePgSQLFactory : public ModuleFactory
681 ~ModulePgSQLFactory()
685 virtual Module * CreateModule(Server* Me)
687 return new ModulePgSQL(Me);
692 extern "C" void * init_module( void )
694 return new ModulePgSQLFactory;