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 * ---------------------------------------------------
28 #include "helperfuncs.h"
30 #include "configreader.h"
34 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
35 /* $CompileFlags: -I`pg_config --includedir` `perl extra/pgsql_config.pl` */
36 /* $LinkerFlags: -L`pg_config --libdir` -lpq */
38 /* UGH, UGH, UGH, UGH, UGH, UGH
39 * I'm having trouble seeing how I
40 * can avoid this. The core-defined
41 * constructors for InspSocket just
42 * aren't suitable...and if I'm
43 * reimplementing them I need this so
44 * I can access the socket engine :\
46 extern InspIRCd* ServerInstance;
47 InspSocket* socket_ref[MAX_DESCRIPTORS];
49 /* Forward declare, so we can have the typedef neatly at the top */
51 /* Also needs forward declaration, as it's used inside SQLconn */
54 typedef std::map<std::string, SQLConn*> ConnMap;
56 /* CREAD, Connecting and wants read event
57 * CWRITE, Connecting and wants write event
58 * WREAD, Connected/Working and wants read event
59 * WWRITE, Connected/Working and wants write event
61 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE };
63 /** QueryQueue, a queue of queries waiting to be executed.
64 * This maintains two queues internally, one for 'priority'
65 * queries and one for less important ones. Each queue has
66 * new queries appended to it and ones to execute are popped
67 * off the front. This keeps them flowing round nicely and no
68 * query should ever get 'stuck' for too long. If there are
69 * queries in the priority queue they will be executed first,
70 * 'unimportant' queries will only be executed when the
71 * priority queue is empty.
73 * We store lists of SQLrequest's here, by value as we want to avoid storing
74 * any data allocated inside the client module (in case that module is unloaded
75 * while the query is in progress).
77 * Because we want to work on the current SQLrequest in-situ, we need a way
78 * of accessing the request we are currently processing, QueryQueue::front(),
79 * but that call needs to always return the same request until that request
80 * is removed from the queue, this is what the 'which' variable is. New queries are
81 * always added to the back of one of the two queues, but if when front()
82 * is first called then the priority queue is empty then front() will return
83 * a query from the normal queue, but if a query is then added to the priority
84 * queue then front() must continue to return the front of the *normal* queue
85 * until pop() is called.
88 class QueryQueue : public classbase
91 typedef std::deque<SQLrequest> ReqDeque;
93 ReqDeque priority; /* The priority queue */
94 ReqDeque normal; /* The 'normal' queue */
95 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
103 void push(const SQLrequest &q)
105 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
108 priority.push_back(q);
115 if((which == PRI) && priority.size())
117 priority.pop_front();
119 else if((which == NOR) && normal.size())
127 /* Silently do nothing if there was no element to pop() */
135 return priority.front();
137 return normal.front();
142 return priority.front();
148 return normal.front();
151 /* This will probably result in a segfault,
152 * but the caller should have checked totalsize()
153 * first so..meh - moron :p
156 return priority.front();
160 std::pair<int, int> size()
162 return std::make_pair(priority.size(), normal.size());
167 return priority.size() + normal.size();
170 void PurgeModule(Module* mod)
172 DoPurgeModule(mod, priority);
173 DoPurgeModule(mod, normal);
177 void DoPurgeModule(Module* mod, ReqDeque& q)
179 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
181 if(iter->GetSource() == mod)
183 if(iter->id == front().id)
185 /* It's the currently active query.. :x */
186 iter->SetSource(NULL);
190 /* It hasn't been executed yet..just remove it */
191 iter = q.erase(iter);
198 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
199 * All SQL providers must create their own subclass and define it's methods using that
200 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
201 * of converting all data to a common format before it reaches the result structure. This way
202 * data is passes to the module nearly as directly as if it was using the API directly itself.
205 class PgSQLresult : public SQLresult
212 SQLfieldList* fieldlist;
213 SQLfieldMap* fieldmap;
215 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
216 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
218 rows = PQntuples(res);
219 cols = PQnfields(res);
221 log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
233 return atoi(PQcmdTuples(res));
243 return PQnfields(res);
246 virtual std::string ColName(int column)
248 char* name = PQfname(res, column);
250 return (name) ? name : "";
253 virtual int ColNum(const std::string &column)
255 int n = PQfnumber(res, column.c_str());
259 throw SQLbadColName();
267 virtual SQLfield GetValue(int row, int column)
269 char* v = PQgetvalue(res, row, column);
273 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
277 log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
278 throw SQLbadColName();
282 virtual SQLfieldList& GetRow()
284 /* In an effort to reduce overhead we don't actually allocate the list
285 * until the first time it's needed...so...
293 fieldlist = new SQLfieldList;
296 if(currentrow < PQntuples(res))
298 int cols = PQnfields(res);
300 for(int i = 0; i < cols; i++)
302 fieldlist->push_back(GetValue(currentrow, i));
311 virtual SQLfieldMap& GetRowMap()
313 /* In an effort to reduce overhead we don't actually allocate the map
314 * until the first time it's needed...so...
322 fieldmap = new SQLfieldMap;
325 if(currentrow < PQntuples(res))
327 int cols = PQnfields(res);
329 for(int i = 0; i < cols; i++)
331 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
340 virtual SQLfieldList* GetRowPtr()
342 SQLfieldList* fl = new SQLfieldList;
344 if(currentrow < PQntuples(res))
346 int cols = PQnfields(res);
348 for(int i = 0; i < cols; i++)
350 fl->push_back(GetValue(currentrow, i));
359 virtual SQLfieldMap* GetRowMapPtr()
361 SQLfieldMap* fm = new SQLfieldMap;
363 if(currentrow < PQntuples(res))
365 int cols = PQnfields(res);
367 for(int i = 0; i < cols; i++)
369 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
378 virtual void Free(SQLfieldMap* fm)
383 virtual void Free(SQLfieldList* fl)
389 /** SQLConn represents one SQL session.
390 * Each session has its own persistent connection to the database.
391 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
392 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
396 class SQLConn : public InspSocket
399 ModulePgSQL* us; /* Pointer to the SQL provider itself */
400 Server* Srv; /* Server* for..uhm..something, maybe */
401 std::string dbhost; /* Database server hostname */
402 unsigned int dbport; /* Database server port */
403 std::string dbname; /* Database name */
404 std::string dbuser; /* Database username */
405 std::string dbpass; /* Database password */
406 bool ssl; /* If we should require SSL */
407 PGconn* sql; /* PgSQL database connection handle */
408 SQLstatus status; /* PgSQL database connection status */
409 bool qinprog;/* If there is currently a query in progress */
410 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
414 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
416 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);
424 virtual void Close();
428 bool DoConnectedPoll();
432 virtual bool OnDataReady();
434 virtual bool OnWriteReady();
436 virtual bool OnConnected();
440 std::string MkInfoStr();
442 const char* StatusStr();
444 SQLerror DoQuery(SQLrequest &req);
446 SQLerror Query(const SQLrequest &req);
448 void OnUnloadModule(Module* mod);
451 class ModulePgSQL : public Module
456 unsigned long currid;
460 ModulePgSQL(Server* Me)
461 : Module::Module(Me), Srv(Me), currid(0)
463 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
465 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
467 strcpy(sqlsuccess, SQLSUCCESS);
472 void Implements(char* List)
474 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
477 virtual void OnRehash(const std::string ¶meter)
481 /* Delete all the SQLConn objects in the connection lists,
482 * this will call their destructors where they can handle
483 * closing connections and such.
485 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
487 DELETE(iter->second);
490 /* Empty out our list of connections */
493 for(int i = 0; i < conf.Enumerate("database"); i++)
498 id = conf.ReadValue("database", "id", i);
499 newconn = new SQLConn(this, Srv,
500 conf.ReadValue("database", "hostname", i),
501 conf.ReadInteger("database", "port", i, true),
502 conf.ReadValue("database", "name", i),
503 conf.ReadValue("database", "username", i),
504 conf.ReadValue("database", "password", i),
505 conf.ReadFlag("database", "ssl", i));
507 connections.insert(std::make_pair(id, newconn));
511 virtual char* OnRequest(Request* request)
513 if(strcmp(SQLREQID, request->GetData()) == 0)
515 SQLrequest* req = (SQLrequest*)request;
516 ConnMap::iterator iter;
518 log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
520 if((iter = connections.find(req->dbid)) != connections.end())
524 req->error = iter->second->Query(*req);
526 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
530 req->error.Id(BAD_DBID);
535 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
540 virtual void OnUnloadModule(Module* mod, const std::string& name)
542 /* When a module unloads we have to check all the pending queries for all our connections
543 * and set the Module* specifying where the query came from to NULL. If the query has already
544 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
546 * If the queries we find are not already being executed then we can simply remove them immediately.
548 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
550 iter->second->OnUnloadModule(mod);
554 unsigned long NewID()
562 virtual Version GetVersion()
564 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
567 virtual ~ModulePgSQL()
573 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)
574 : InspSocket::InspSocket(), us(self), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE), qinprog(false)
576 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());
578 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
579 * just copied this over from the InspSocket constructor.
581 strlcpy(this->host, dbhost.c_str(), MAXBUF);
584 this->ClosePending = false;
586 if(!inet_aton(this->host, &this->addy))
588 /* Its not an ip, spawn the resolver.
589 * PgSQL doesn't do nonblocking DNS
590 * lookups, so we do it for it.
593 log(DEBUG,"Attempting to resolve %s", this->host);
595 this->dns.SetNS(Srv->GetConfig()->DNSServer);
596 this->dns.ForwardLookupWithFD(this->host, fd);
598 this->state = I_RESOLVING;
599 socket_ref[this->fd] = this;
605 log(DEBUG,"No need to resolve %s", this->host);
606 strlcpy(this->IP, this->host, MAXBUF);
608 if(!this->DoConnect())
610 throw ModuleException("Connect failed");
620 bool SQLConn::DoResolve()
622 log(DEBUG, "Checking for DNS lookup result");
624 if(this->dns.HasResult())
626 std::string res_ip = dns.GetResultIP();
630 log(DEBUG, "Got result: %s", res_ip.c_str());
632 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
635 socket_ref[this->fd] = NULL;
637 return this->DoConnect();
641 log(DEBUG, "DNS lookup failed, dying horribly");
648 log(DEBUG, "No result for lookup yet!");
653 bool SQLConn::DoConnect()
655 log(DEBUG, "SQLConn::DoConnect()");
657 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
659 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
664 if(PQstatus(sql) == CONNECTION_BAD)
666 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
673 if(PQsetnonblocking(sql, 1) == -1)
675 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
680 /* OK, we've initalised the connection, now to get it hooked into the socket engine
681 * and then start polling it.
684 log(DEBUG, "Old DNS socket: %d", this->fd);
685 this->fd = PQsocket(sql);
686 log(DEBUG, "New SQL socket: %d", this->fd);
690 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
695 this->state = I_CONNECTING;
696 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
697 socket_ref[this->fd] = this;
699 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
704 void SQLConn::Close()
706 log(DEBUG,"SQLConn::Close");
709 socket_ref[this->fd] = NULL;
711 this->state = I_ERROR;
712 this->OnError(I_ERR_SOCKET);
713 this->ClosePending = true;
724 bool SQLConn::DoPoll()
726 switch(PQconnectPoll(sql))
728 case PGRES_POLLING_WRITING:
729 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
733 case PGRES_POLLING_READING:
734 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
737 case PGRES_POLLING_FAILED:
738 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
740 case PGRES_POLLING_OK:
741 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
743 return DoConnectedPoll();
745 log(DEBUG, "PGconnectPoll: wtf?");
752 bool SQLConn::DoConnectedPoll()
754 if(!qinprog && queue.totalsize())
756 /* There's no query currently in progress, and there's queries in the queue. */
757 SQLrequest& query = queue.front();
761 if(PQconsumeInput(sql))
763 log(DEBUG, "PQconsumeInput succeeded");
767 log(DEBUG, "Still busy processing command though");
771 log(DEBUG, "Looks like we have a result to process!");
773 /* Grab the request we're processing */
774 SQLrequest& query = queue.front();
776 log(DEBUG, "ID is %lu", query.id);
778 /* Get a pointer to the module we're about to return the result to */
779 Module* to = query.GetSource();
781 /* Fetch the result.. */
782 PGresult* result = PQgetResult(sql);
784 /* PgSQL would allow a query string to be sent which has multiple
785 * queries in it, this isn't portable across database backends and
786 * we don't want modules doing it. But just in case we make sure we
787 * drain any results there are and just use the last one.
788 * If the module devs are behaving there will only be one result.
790 while (PGresult* temp = PQgetResult(sql))
798 /* ..and the result */
799 PgSQLresult reply(us, to, query.id, result);
801 log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
803 switch(PQresultStatus(result))
805 case PGRES_EMPTY_QUERY:
806 case PGRES_BAD_RESPONSE:
807 case PGRES_FATAL_ERROR:
808 reply.error.Id(QREPLY_FAIL);
809 reply.error.Str(PQresultErrorMessage(result));
811 /* No action, other values are not errors */
816 /* PgSQLresult's destructor will free the PGresult */
820 /* If the client module is unloaded partway through a query then the provider will set
821 * the pointer to NULL. We cannot just cancel the query as the result will still come
822 * through at some point...and it could get messy if we play with invalid pointers...
824 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);
836 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
840 void SQLConn::ShowStatus()
842 switch(PQstatus(sql))
844 case CONNECTION_STARTED:
845 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
848 case CONNECTION_MADE:
849 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
852 case CONNECTION_AWAITING_RESPONSE:
853 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
856 case CONNECTION_AUTH_OK:
857 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
860 case CONNECTION_SSL_STARTUP:
861 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
864 case CONNECTION_SETENV:
865 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
869 log(DEBUG, "PQstatus: ???");
873 bool SQLConn::OnDataReady()
875 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
876 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
881 bool SQLConn::OnWriteReady()
883 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
884 log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
889 bool SQLConn::OnConnected()
891 log(DEBUG, "OnConnected(): status = %s", StatusStr());
896 bool SQLConn::DoEvent()
900 if((status == CREAD) || (status == CWRITE))
906 ret = DoConnectedPoll();
912 log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
915 log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
918 log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
926 std::string SQLConn::MkInfoStr()
928 std::ostringstream conninfo("connect_timeout = '2'");
931 conninfo << " hostaddr = '" << dbhost << "'";
934 conninfo << " port = '" << dbport << "'";
937 conninfo << " dbname = '" << dbname << "'";
940 conninfo << " user = '" << dbuser << "'";
943 conninfo << " password = '" << dbpass << "'";
946 conninfo << " sslmode = 'require'";
948 return conninfo.str();
951 const char* SQLConn::StatusStr()
953 if(status == CREAD) return "CREAD";
954 if(status == CWRITE) return "CWRITE";
955 if(status == WREAD) return "WREAD";
956 if(status == WWRITE) return "WWRITE";
957 return "Err...what, erm..BUG!";
960 SQLerror SQLConn::DoQuery(SQLrequest &req)
962 if((status == WREAD) || (status == WWRITE))
966 /* Parse the command string and dispatch it */
968 /* Pointer to the buffer we screw around with substitution in */
970 /* Pointer to the current end of query, where we append new stuff */
972 /* Total length of the unescaped parameters */
973 unsigned int paramlen;
977 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
979 paramlen += i->size();
982 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
983 * sizeofquery + (totalparamlength*2) + 1
985 * The +1 is for null-terminating the string for PQsendQuery()
988 query = new char[req.query.q.length() + (paramlen*2)];
991 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
992 * the parameters into it...
995 for(unsigned int i = 0; i < req.query.q.length(); i++)
997 if(req.query.q[i] == '?')
999 /* We found a place to substitute..what fun.
1000 * Use the PgSQL calls to escape and write the
1001 * escaped string onto the end of our query buffer,
1002 * then we "just" need to make sure queryend is
1003 * pointing at the right place.
1006 if(req.query.p.size())
1011 #ifdef PGSQL_HAS_ESCAPECONN
1012 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
1014 len = PQescapeStringConn(queryend, req.query.p.front().c_str(), req.query.p.front().length());
1020 log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
1023 log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
1025 /* Incremenet queryend to the end of the newly escaped parameter */
1028 /* Remove the parameter we just substituted in */
1029 req.query.p.pop_front();
1033 log(DEBUG, "Found a substitution location but no parameter to substitute :|");
1039 *queryend = req.query.q[i];
1044 /* Null-terminate the query */
1047 log(DEBUG, "Attempting to dispatch query: %s", query);
1049 req.query.q = query;
1051 if(PQsendQuery(sql, query))
1053 log(DEBUG, "Dispatched query successfully");
1060 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
1062 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
1067 log(DEBUG, "Can't query until connection is complete");
1068 return SQLerror(BAD_CONN, "Can't query until connection is complete");
1071 SQLerror SQLConn::Query(const SQLrequest &req)
1075 if(!qinprog && queue.totalsize())
1077 /* There's no query currently in progress, and there's queries in the queue. */
1078 SQLrequest& query = queue.front();
1079 return DoQuery(query);
1087 void SQLConn::OnUnloadModule(Module* mod)
1089 queue.PurgeModule(mod);
1092 class ModulePgSQLFactory : public ModuleFactory
1095 ModulePgSQLFactory()
1099 ~ModulePgSQLFactory()
1103 virtual Module * CreateModule(Server* Me)
1105 return new ModulePgSQL(Me);
1110 extern "C" void * init_module( void )
1112 return new ModulePgSQLFactory;