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 typedef std::deque<SQLrequest> ReqDeque;
92 ReqDeque priority; /* The priority queue */
93 ReqDeque normal; /* The 'normal' queue */
94 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
102 void push(const SQLrequest &q)
104 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.c_str());
107 priority.push_back(q);
114 if((which == PRI) && priority.size())
116 priority.pop_front();
118 else if((which == NOR) && normal.size())
126 /* Silently do nothing if there was no element to pop() */
134 return priority.front();
136 return normal.front();
141 return priority.front();
147 return normal.front();
150 /* This will probably result in a segfault,
151 * but the caller should have checked totalsize()
152 * first so..meh - moron :p
155 return priority.front();
159 std::pair<int, int> size()
161 return std::make_pair(priority.size(), normal.size());
166 return priority.size() + normal.size();
169 void PurgeModule(Module* mod)
171 DoPurgeModule(mod, priority);
172 DoPurgeModule(mod, normal);
176 void DoPurgeModule(Module* mod, ReqDeque& q)
178 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
180 if(iter->GetSource() == mod)
182 if(iter->id == front().id)
184 /* It's the currently active query.. :x */
185 iter->SetSource(NULL);
189 /* It hasn't been executed yet..just remove it */
190 iter = q.erase(iter);
197 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
198 * All SQL providers must create their own subclass and define it's methods using that
199 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
200 * of converting all data to a common format before it reaches the result structure. This way
201 * data is passes to the module nearly as directly as if it was using the API directly itself.
204 class PgSQLresult : public SQLresult
209 SQLfieldList* fieldlist;
210 SQLfieldMap* fieldmap;
212 PgSQLresult(Module* self, Module* to, PGresult* result)
213 : SQLresult(self, to), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
215 int rows = PQntuples(res);
216 int cols = PQnfields(res);
218 log(DEBUG, "Created new PgSQL result; %d rows, %d columns", rows, cols);
228 return PQntuples(res);
233 return PQnfields(res);
236 virtual std::string ColName(int column)
238 char* name = PQfname(res, column);
240 return (name) ? name : "";
243 virtual int ColNum(const std::string &column)
245 int n = PQfnumber(res, column.c_str());
249 throw SQLbadColName();
257 virtual SQLfield GetValue(int row, int column)
259 char* v = PQgetvalue(res, row, column);
263 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
267 log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
268 throw SQLbadColName();
272 virtual SQLfieldList& GetRow()
274 /* In an effort to reduce overhead we don't actually allocate the list
275 * until the first time it's needed...so...
283 fieldlist = new SQLfieldList;
286 if(currentrow < PQntuples(res))
288 int cols = PQnfields(res);
290 for(int i = 0; i < cols; i++)
292 fieldlist->push_back(GetValue(currentrow, i));
301 virtual SQLfieldMap& GetRowMap()
303 /* In an effort to reduce overhead we don't actually allocate the map
304 * until the first time it's needed...so...
312 fieldmap = new SQLfieldMap;
315 if(currentrow < PQntuples(res))
317 int cols = PQnfields(res);
319 for(int i = 0; i < cols; i++)
321 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
330 virtual SQLfieldList* GetRowPtr()
332 SQLfieldList* fl = new SQLfieldList;
334 if(currentrow < PQntuples(res))
336 int cols = PQnfields(res);
338 for(int i = 0; i < cols; i++)
340 fl->push_back(GetValue(currentrow, i));
349 virtual SQLfieldMap* GetRowMapPtr()
351 SQLfieldMap* fm = new SQLfieldMap;
353 if(currentrow < PQntuples(res))
355 int cols = PQnfields(res);
357 for(int i = 0; i < cols; i++)
359 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
368 virtual void Free(SQLfieldMap* fm)
373 virtual void Free(SQLfieldList* fl)
379 /** SQLConn represents one SQL session.
380 * Each session has its own persistent connection to the database.
381 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
382 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
386 class SQLConn : public InspSocket
389 ModulePgSQL* us; /* Pointer to the SQL provider itself */
390 Server* Srv; /* Server* for..uhm..something, maybe */
391 std::string dbhost; /* Database server hostname */
392 unsigned int dbport; /* Database server port */
393 std::string dbname; /* Database name */
394 std::string dbuser; /* Database username */
395 std::string dbpass; /* Database password */
396 bool ssl; /* If we should require SSL */
397 PGconn* sql; /* PgSQL database connection handle */
398 SQLstatus status; /* PgSQL database connection status */
399 bool qinprog;/* If there is currently a query in progress */
400 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
404 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
406 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);
414 virtual void Close();
418 bool DoConnectedPoll();
422 virtual bool OnDataReady();
424 virtual bool OnWriteReady();
426 virtual bool OnConnected();
430 std::string MkInfoStr();
432 const char* StatusStr();
434 SQLerror DoQuery(const SQLrequest &req);
436 SQLerror Query(const SQLrequest &req);
438 void OnUnloadModule(Module* mod);
441 class ModulePgSQL : public Module
446 unsigned long currid;
450 ModulePgSQL(Server* Me)
451 : Module::Module(Me), Srv(Me), currid(0)
453 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
454 log(DEBUG, "%s 'PgSQL' feature", Srv->PublishFeature("PgSQL", this) ? "Published" : "Couldn't publish");
456 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
458 strcpy(sqlsuccess, SQLSUCCESS);
463 void Implements(char* List)
465 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
468 virtual void OnRehash(const std::string ¶meter)
472 /* Delete all the SQLConn objects in the connection lists,
473 * this will call their destructors where they can handle
474 * closing connections and such.
476 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
478 DELETE(iter->second);
481 /* Empty out our list of connections */
484 for(int i = 0; i < conf.Enumerate("database"); i++)
489 id = conf.ReadValue("database", "id", i);
490 newconn = new SQLConn(this, Srv,
491 conf.ReadValue("database", "hostname", i),
492 conf.ReadInteger("database", "port", i, true),
493 conf.ReadValue("database", "name", i),
494 conf.ReadValue("database", "username", i),
495 conf.ReadValue("database", "password", i),
496 conf.ReadFlag("database", "ssl", i));
498 connections.insert(std::make_pair(id, newconn));
502 virtual char* OnRequest(Request* request)
504 if(strcmp(SQLREQID, request->GetData()) == 0)
506 SQLrequest* req = (SQLrequest*)request;
507 ConnMap::iterator iter;
509 log(DEBUG, "Got query: '%s' on id '%s'", req->query.c_str(), req->dbid.c_str());
511 if((iter = connections.find(req->dbid)) != connections.end())
514 req->error = iter->second->Query(*req);
517 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
521 req->error.Id(BAD_DBID);
526 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
531 virtual void OnUnloadModule(Module* mod, const std::string& name)
533 /* When a module unloads we have to check all the pending queries for all our connections
534 * and set the Module* specifying where the query came from to NULL. If the query has already
535 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
537 * If the queries we find are not already being executed then we can simply remove them immediately.
539 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
545 unsigned long NewID()
553 virtual Version GetVersion()
555 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
558 virtual ~ModulePgSQL()
564 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)
565 : InspSocket::InspSocket(), us(self), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE), qinprog(false)
567 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());
569 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
570 * just copied this over from the InspSocket constructor.
572 strlcpy(this->host, dbhost.c_str(), MAXBUF);
575 this->ClosePending = false;
577 if(!inet_aton(this->host, &this->addy))
579 /* Its not an ip, spawn the resolver.
580 * PgSQL doesn't do nonblocking DNS
581 * lookups, so we do it for it.
584 log(DEBUG,"Attempting to resolve %s", this->host);
586 this->dns.SetNS(Srv->GetConfig()->DNSServer);
587 this->dns.ForwardLookupWithFD(this->host, fd);
589 this->state = I_RESOLVING;
590 socket_ref[this->fd] = this;
596 log(DEBUG,"No need to resolve %s", this->host);
597 strlcpy(this->IP, this->host, MAXBUF);
599 if(!this->DoConnect())
601 throw ModuleException("Connect failed");
611 bool SQLConn::DoResolve()
613 log(DEBUG, "Checking for DNS lookup result");
615 if(this->dns.HasResult())
617 std::string res_ip = dns.GetResultIP();
621 log(DEBUG, "Got result: %s", res_ip.c_str());
623 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
626 socket_ref[this->fd] = NULL;
628 return this->DoConnect();
632 log(DEBUG, "DNS lookup failed, dying horribly");
639 log(DEBUG, "No result for lookup yet!");
644 bool SQLConn::DoConnect()
646 log(DEBUG, "SQLConn::DoConnect()");
648 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
650 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
655 if(PQstatus(sql) == CONNECTION_BAD)
657 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
664 if(PQsetnonblocking(sql, 1) == -1)
666 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
671 /* OK, we've initalised the connection, now to get it hooked into the socket engine
672 * and then start polling it.
675 log(DEBUG, "Old DNS socket: %d", this->fd);
676 this->fd = PQsocket(sql);
677 log(DEBUG, "New SQL socket: %d", this->fd);
681 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
686 this->state = I_CONNECTING;
687 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
688 socket_ref[this->fd] = this;
690 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
695 void SQLConn::Close()
697 log(DEBUG,"SQLConn::Close");
700 socket_ref[this->fd] = NULL;
702 this->state = I_ERROR;
703 this->OnError(I_ERR_SOCKET);
704 this->ClosePending = true;
715 bool SQLConn::DoPoll()
717 switch(PQconnectPoll(sql))
719 case PGRES_POLLING_WRITING:
720 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
724 case PGRES_POLLING_READING:
725 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
728 case PGRES_POLLING_FAILED:
729 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
731 case PGRES_POLLING_OK:
732 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
734 return DoConnectedPoll();
736 log(DEBUG, "PGconnectPoll: wtf?");
743 bool SQLConn::DoConnectedPoll()
745 if(!qinprog && queue.totalsize())
747 /* There's no query currently in progress, and there's queries in the queue. */
748 SQLrequest& query = queue.front();
752 if(PQconsumeInput(sql))
754 log(DEBUG, "PQconsumeInput succeeded");
758 log(DEBUG, "Still busy processing command though");
762 log(DEBUG, "Looks like we have a result to process!");
764 /* Grab the request we're processing */
765 SQLrequest& query = queue.front();
767 /* Get a pointer to the module we're about to return the result to */
768 Module* to = query.GetSource();
770 /* Fetch the result.. */
771 PGresult* result = PQgetResult(sql);
773 /* PgSQL would allow a query string to be sent which has multiple
774 * queries in it, this isn't portable across database backends and
775 * we don't want modules doing it. But just in case we make sure we
776 * drain any results there are and just use the last one.
777 * If the module devs are behaving there will only be one result.
779 while (PGresult* temp = PQgetResult(sql))
787 /* ..and the result */
788 log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
790 PgSQLresult reply(us, to, result);
794 /* PgSQLresult's destructor will free the PGresult */
798 /* If the client module is unloaded partway through a query then the provider will set
799 * the pointer to NULL. We cannot just cancel the query as the result will still come
800 * through at some point...and it could get messy if we play with invalid pointers...
802 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);
814 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
818 void SQLConn::ShowStatus()
820 switch(PQstatus(sql))
822 case CONNECTION_STARTED:
823 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
826 case CONNECTION_MADE:
827 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
830 case CONNECTION_AWAITING_RESPONSE:
831 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
834 case CONNECTION_AUTH_OK:
835 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
838 case CONNECTION_SSL_STARTUP:
839 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
842 case CONNECTION_SETENV:
843 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
847 log(DEBUG, "PQstatus: ???");
851 bool SQLConn::OnDataReady()
853 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
854 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
859 bool SQLConn::OnWriteReady()
861 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
862 log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
867 bool SQLConn::OnConnected()
869 log(DEBUG, "OnConnected(): status = %s", StatusStr());
874 bool SQLConn::DoEvent()
878 if((status == CREAD) || (status == CWRITE))
884 ret = DoConnectedPoll();
890 log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
893 log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
896 log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
904 std::string SQLConn::MkInfoStr()
906 std::ostringstream conninfo("connect_timeout = '2'");
909 conninfo << " hostaddr = '" << dbhost << "'";
912 conninfo << " port = '" << dbport << "'";
915 conninfo << " dbname = '" << dbname << "'";
918 conninfo << " user = '" << dbuser << "'";
921 conninfo << " password = '" << dbpass << "'";
924 conninfo << " sslmode = 'require'";
926 return conninfo.str();
929 const char* SQLConn::StatusStr()
931 if(status == CREAD) return "CREAD";
932 if(status == CWRITE) return "CWRITE";
933 if(status == WREAD) return "WREAD";
934 if(status == WWRITE) return "WWRITE";
935 return "Err...what, erm..BUG!";
938 SQLerror SQLConn::DoQuery(const SQLrequest &req)
940 if((status == WREAD) || (status == WWRITE))
944 if(PQsendQuery(sql, req.query.c_str()))
946 log(DEBUG, "Dispatched query: %s", req.query.c_str());
952 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
953 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
958 log(DEBUG, "Can't query until connection is complete");
959 return SQLerror(BAD_CONN, "Can't query until connection is complete");
962 SQLerror SQLConn::Query(const SQLrequest &req)
966 if(!qinprog && queue.totalsize())
968 /* There's no query currently in progress, and there's queries in the queue. */
969 SQLrequest& query = queue.front();
970 return DoQuery(query);
978 void SQLConn::OnUnloadModule(Module* mod)
980 queue.PurgeModule(mod);
983 class ModulePgSQLFactory : public ModuleFactory
990 ~ModulePgSQLFactory()
994 virtual Module * CreateModule(Server* Me)
996 return new ModulePgSQL(Me);
1001 extern "C" void * init_module( void )
1003 return new ModulePgSQLFactory;