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 */
50 /* Also needs forward declaration, as it's used inside SQLconn */
53 typedef std::map<std::string, SQLConn*> ConnMap;
55 /* CREAD, Connecting and wants read event
56 * CWRITE, Connecting and wants write event
57 * WREAD, Connected/Working and wants read event
58 * WWRITE, Connected/Working and wants write event
60 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE };
62 /** QueryQueue, a queue of queries waiting to be executed.
63 * This maintains two queues internally, one for 'priority'
64 * queries and one for less important ones. Each queue has
65 * new queries appended to it and ones to execute are popped
66 * off the front. This keeps them flowing round nicely and no
67 * query should ever get 'stuck' for too long. If there are
68 * queries in the priority queue they will be executed first,
69 * 'unimportant' queries will only be executed when the
70 * priority queue is empty.
72 * We store lists of SQLrequest's here, by value as we want to avoid storing
73 * any data allocated inside the client module (in case that module is unloaded
74 * while the query is in progress).
76 * Because we want to work on the current SQLrequest in-situ, we need a way
77 * of accessing the request we are currently processing, QueryQueue::front(),
78 * but that call needs to always return the same request until that request
79 * is removed from the queue, this is what the 'which' variable is. New queries are
80 * always added to the back of one of the two queues, but if when front()
81 * is first called then the priority queue is empty then front() will return
82 * a query from the normal queue, but if a query is then added to the priority
83 * queue then front() must continue to return the front of the *normal* queue
84 * until pop() is called.
87 class QueryQueue : public classbase
90 std::deque<SQLrequest> priority; /* The priority queue */
91 std::deque<SQLrequest> normal; /* The 'normal' queue */
92 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
100 void push(const SQLrequest &q)
102 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.c_str());
105 priority.push_back(q);
112 if((which == PRI) && priority.size())
114 priority.pop_front();
116 else if((which == NOR) && normal.size())
124 /* Silently do nothing if there was no element to pop() */
132 return priority.front();
134 return normal.front();
139 return priority.front();
145 return normal.front();
148 /* This will probably result in a segfault,
149 * but the caller should have checked totalsize()
150 * first so..meh - moron :p
153 return priority.front();
157 std::pair<int, int> size()
159 return std::make_pair(priority.size(), normal.size());
164 return priority.size() + normal.size();
168 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
169 * All SQL providers must create their own subclass and define it's methods using that
170 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
171 * of converting all data to a common format before it reaches the result structure. This way
172 * data is passes to the module nearly as directly as if it was using the API directly itself.
175 class PgSQLresult : public SQLresult
180 SQLfieldList* fieldlist;
181 SQLfieldMap* fieldmap;
183 PgSQLresult(Module* self, Module* to, PGresult* result)
184 : SQLresult(self, to), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
186 int rows = PQntuples(res);
187 int cols = PQnfields(res);
189 log(DEBUG, "Created new PgSQL result; %d rows, %d columns", rows, cols);
199 return PQntuples(res);
204 return PQnfields(res);
207 virtual std::string ColName(int column)
209 char* name = PQfname(res, column);
211 return (name) ? name : "";
214 virtual int ColNum(const std::string &column)
216 int n = PQfnumber(res, column.c_str());
220 throw SQLbadColName();
228 virtual SQLfield GetValue(int row, int column)
230 char* v = PQgetvalue(res, row, column);
234 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
238 log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
239 throw SQLbadColName();
243 virtual SQLfieldList& GetRow()
245 /* In an effort to reduce overhead we don't actually allocate the list
246 * until the first time it's needed...so...
254 fieldlist = new SQLfieldList;
257 if(currentrow < PQntuples(res))
259 int cols = PQnfields(res);
261 for(int i = 0; i < cols; i++)
263 fieldlist->push_back(GetValue(currentrow, i));
272 virtual SQLfieldMap& GetRowMap()
274 /* In an effort to reduce overhead we don't actually allocate the map
275 * until the first time it's needed...so...
283 fieldmap = new SQLfieldMap;
286 if(currentrow < PQntuples(res))
288 int cols = PQnfields(res);
290 for(int i = 0; i < cols; i++)
292 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
301 virtual SQLfieldList* GetRowPtr()
303 SQLfieldList* fl = new SQLfieldList;
305 if(currentrow < PQntuples(res))
307 int cols = PQnfields(res);
309 for(int i = 0; i < cols; i++)
311 fl->push_back(GetValue(currentrow, i));
320 virtual SQLfieldMap* GetRowMapPtr()
322 SQLfieldMap* fm = new SQLfieldMap;
324 if(currentrow < PQntuples(res))
326 int cols = PQnfields(res);
328 for(int i = 0; i < cols; i++)
330 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
339 virtual void Free(SQLfieldMap* fm)
344 virtual void Free(SQLfieldList* fl)
350 /** SQLConn represents one SQL session.
351 * Each session has its own persistent connection to the database.
352 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
353 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
357 class SQLConn : public InspSocket
360 ModulePgSQL* us; /* Pointer to the SQL provider itself */
361 Server* Srv; /* Server* for..uhm..something, maybe */
362 std::string dbhost; /* Database server hostname */
363 unsigned int dbport; /* Database server port */
364 std::string dbname; /* Database name */
365 std::string dbuser; /* Database username */
366 std::string dbpass; /* Database password */
367 bool ssl; /* If we should require SSL */
368 PGconn* sql; /* PgSQL database connection handle */
369 SQLstatus status; /* PgSQL database connection status */
370 bool qinprog;/* If there is currently a query in progress */
371 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
375 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
377 SQLConn(ModulePgSQL* self, Server* srv, const std::string &h, unsigned int p, const std::string &d, const std::string &u, const std::string &pwd, bool s);
385 virtual void Close();
389 bool DoConnectedPoll();
393 virtual bool OnDataReady();
395 virtual bool OnWriteReady();
397 virtual bool OnConnected();
401 std::string MkInfoStr();
403 const char* StatusStr();
405 SQLerror DoQuery(const SQLrequest &req);
407 SQLerror Query(const SQLrequest &req);
410 class ModulePgSQL : public Module
415 unsigned long currid;
419 ModulePgSQL(Server* Me)
420 : Module::Module(Me), Srv(Me), currid(0)
422 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
423 log(DEBUG, "%s 'PgSQL' feature", Srv->PublishFeature("PgSQL", this) ? "Published" : "Couldn't publish");
425 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
427 strcpy(sqlsuccess, SQLSUCCESS);
432 void Implements(char* List)
434 List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
437 virtual void OnRehash(const std::string ¶meter)
441 /* Delete all the SQLConn objects in the connection lists,
442 * this will call their destructors where they can handle
443 * closing connections and such.
445 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
447 DELETE(iter->second);
450 /* Empty out our list of connections */
453 for(int i = 0; i < conf.Enumerate("database"); i++)
458 id = conf.ReadValue("database", "id", i);
459 newconn = new SQLConn(this, Srv,
460 conf.ReadValue("database", "hostname", i),
461 conf.ReadInteger("database", "port", i, true),
462 conf.ReadValue("database", "name", i),
463 conf.ReadValue("database", "username", i),
464 conf.ReadValue("database", "password", i),
465 conf.ReadFlag("database", "ssl", i));
467 connections.insert(std::make_pair(id, newconn));
471 virtual char* OnRequest(Request* request)
473 if(strcmp(SQLREQID, request->GetData()) == 0)
475 SQLrequest* req = (SQLrequest*)request;
476 ConnMap::iterator iter;
478 log(DEBUG, "Got query: '%s' on id '%s'", req->query.c_str(), req->dbid.c_str());
480 if((iter = connections.find(req->dbid)) != connections.end())
483 req->error = iter->second->Query(*req);
486 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
490 req->error.Id(BAD_DBID);
495 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
500 unsigned long NewID()
508 virtual Version GetVersion()
510 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
513 virtual ~ModulePgSQL()
519 SQLConn::SQLConn(ModulePgSQL* self, Server* srv, const std::string &h, unsigned int p, const std::string &d, const std::string &u, const std::string &pwd, bool s)
520 : InspSocket::InspSocket(), us(self), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE), qinprog(false)
522 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());
524 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
525 * just copied this over from the InspSocket constructor.
527 strlcpy(this->host, dbhost.c_str(), MAXBUF);
530 this->ClosePending = false;
532 if(!inet_aton(this->host, &this->addy))
534 /* Its not an ip, spawn the resolver.
535 * PgSQL doesn't do nonblocking DNS
536 * lookups, so we do it for it.
539 log(DEBUG,"Attempting to resolve %s", this->host);
541 this->dns.SetNS(Srv->GetConfig()->DNSServer);
542 this->dns.ForwardLookupWithFD(this->host, fd);
544 this->state = I_RESOLVING;
545 socket_ref[this->fd] = this;
551 log(DEBUG,"No need to resolve %s", this->host);
552 strlcpy(this->IP, this->host, MAXBUF);
554 if(!this->DoConnect())
556 throw ModuleException("Connect failed");
566 bool SQLConn::DoResolve()
568 log(DEBUG, "Checking for DNS lookup result");
570 if(this->dns.HasResult())
572 std::string res_ip = dns.GetResultIP();
576 log(DEBUG, "Got result: %s", res_ip.c_str());
578 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
581 socket_ref[this->fd] = NULL;
583 return this->DoConnect();
587 log(DEBUG, "DNS lookup failed, dying horribly");
594 log(DEBUG, "No result for lookup yet!");
599 bool SQLConn::DoConnect()
601 log(DEBUG, "SQLConn::DoConnect()");
603 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
605 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
610 if(PQstatus(sql) == CONNECTION_BAD)
612 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
619 if(PQsetnonblocking(sql, 1) == -1)
621 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
626 /* OK, we've initalised the connection, now to get it hooked into the socket engine
627 * and then start polling it.
630 log(DEBUG, "Old DNS socket: %d", this->fd);
631 this->fd = PQsocket(sql);
632 log(DEBUG, "New SQL socket: %d", this->fd);
636 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
641 this->state = I_CONNECTING;
642 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
643 socket_ref[this->fd] = this;
645 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
650 void SQLConn::Close()
652 log(DEBUG,"SQLConn::Close");
655 socket_ref[this->fd] = NULL;
657 this->state = I_ERROR;
658 this->OnError(I_ERR_SOCKET);
659 this->ClosePending = true;
670 bool SQLConn::DoPoll()
672 switch(PQconnectPoll(sql))
674 case PGRES_POLLING_WRITING:
675 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
679 case PGRES_POLLING_READING:
680 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
683 case PGRES_POLLING_FAILED:
684 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
686 case PGRES_POLLING_OK:
687 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
689 return DoConnectedPoll();
691 log(DEBUG, "PGconnectPoll: wtf?");
698 bool SQLConn::DoConnectedPoll()
700 if(!qinprog && queue.totalsize())
702 /* There's no query currently in progress, and there's queries in the queue. */
703 SQLrequest& query = queue.front();
707 if(PQconsumeInput(sql))
709 log(DEBUG, "PQconsumeInput succeeded");
713 log(DEBUG, "Still busy processing command though");
717 log(DEBUG, "Looks like we have a result to process!");
719 /* Grab the request we're processing */
720 SQLrequest& query = queue.front();
722 /* Get a pointer to the module we're about to return the result to */
723 Module* to = query.GetSource();
725 /* Fetch the result.. */
726 PGresult* result = PQgetResult(sql);
728 /* PgSQL would allow a query string to be sent which has multiple
729 * queries in it, this isn't portable across database backends and
730 * we don't want modules doing it. But just in case we make sure we
731 * drain any results there are and just use the last one.
732 * If the module devs are behaving there will only be one result.
734 while (PGresult* temp = PQgetResult(sql))
742 /* ..and the result */
743 log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
745 PgSQLresult reply(us, to, result);
749 /* PgSQLresult's destructor will free the PGresult */
753 /* If the client module is unloaded partway through a query then the provider will set
754 * the pointer to NULL. We cannot just cancel the query as the result will still come
755 * through at some point...and it could get messy if we play with invalid pointers...
757 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);
769 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
773 void SQLConn::ShowStatus()
775 switch(PQstatus(sql))
777 case CONNECTION_STARTED:
778 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
781 case CONNECTION_MADE:
782 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
785 case CONNECTION_AWAITING_RESPONSE:
786 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
789 case CONNECTION_AUTH_OK:
790 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
793 case CONNECTION_SSL_STARTUP:
794 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
797 case CONNECTION_SETENV:
798 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
802 log(DEBUG, "PQstatus: ???");
806 bool SQLConn::OnDataReady()
808 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
809 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
814 bool SQLConn::OnWriteReady()
816 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
817 log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
822 bool SQLConn::OnConnected()
824 log(DEBUG, "OnConnected(): status = %s", StatusStr());
829 bool SQLConn::DoEvent()
833 if((status == CREAD) || (status == CWRITE))
839 ret = DoConnectedPoll();
845 log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
848 log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
851 log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
859 std::string SQLConn::MkInfoStr()
861 std::ostringstream conninfo("connect_timeout = '2'");
864 conninfo << " hostaddr = '" << dbhost << "'";
867 conninfo << " port = '" << dbport << "'";
870 conninfo << " dbname = '" << dbname << "'";
873 conninfo << " user = '" << dbuser << "'";
876 conninfo << " password = '" << dbpass << "'";
879 conninfo << " sslmode = 'require'";
881 return conninfo.str();
884 const char* SQLConn::StatusStr()
886 if(status == CREAD) return "CREAD";
887 if(status == CWRITE) return "CWRITE";
888 if(status == WREAD) return "WREAD";
889 if(status == WWRITE) return "WWRITE";
890 return "Err...what, erm..BUG!";
893 SQLerror SQLConn::DoQuery(const SQLrequest &req)
895 if((status == WREAD) || (status == WWRITE))
899 if(PQsendQuery(sql, req.query.c_str()))
901 log(DEBUG, "Dispatched query: %s", req.query.c_str());
907 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
908 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
913 log(DEBUG, "Can't query until connection is complete");
914 return SQLerror(BAD_CONN, "Can't query until connection is complete");
917 SQLerror SQLConn::Query(const SQLrequest &req)
921 if(!qinprog && queue.totalsize())
923 /* There's no query currently in progress, and there's queries in the queue. */
924 SQLrequest& query = queue.front();
925 return DoQuery(query);
933 class ModulePgSQLFactory : public ModuleFactory
940 ~ModulePgSQLFactory()
944 virtual Module * CreateModule(Server* Me)
946 return new ModulePgSQL(Me);
951 extern "C" void * init_module( void )
953 return new ModulePgSQLFactory;