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));
226 /* If we allocated these, free them... */
240 return atoi(PQcmdTuples(res));
250 return PQnfields(res);
253 virtual std::string ColName(int column)
255 char* name = PQfname(res, column);
257 return (name) ? name : "";
260 virtual int ColNum(const std::string &column)
262 int n = PQfnumber(res, column.c_str());
266 throw SQLbadColName();
274 virtual SQLfield GetValue(int row, int column)
276 char* v = PQgetvalue(res, row, column);
280 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
284 log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
285 throw SQLbadColName();
289 virtual SQLfieldList& GetRow()
291 /* In an effort to reduce overhead we don't actually allocate the list
292 * until the first time it's needed...so...
300 fieldlist = new SQLfieldList;
303 if(currentrow < PQntuples(res))
305 int cols = PQnfields(res);
307 for(int i = 0; i < cols; i++)
309 fieldlist->push_back(GetValue(currentrow, i));
318 virtual SQLfieldMap& GetRowMap()
320 /* In an effort to reduce overhead we don't actually allocate the map
321 * until the first time it's needed...so...
329 fieldmap = new SQLfieldMap;
332 if(currentrow < PQntuples(res))
334 int cols = PQnfields(res);
336 for(int i = 0; i < cols; i++)
338 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
347 virtual SQLfieldList* GetRowPtr()
349 SQLfieldList* fl = new SQLfieldList;
351 if(currentrow < PQntuples(res))
353 int cols = PQnfields(res);
355 for(int i = 0; i < cols; i++)
357 fl->push_back(GetValue(currentrow, i));
366 virtual SQLfieldMap* GetRowMapPtr()
368 SQLfieldMap* fm = new SQLfieldMap;
370 if(currentrow < PQntuples(res))
372 int cols = PQnfields(res);
374 for(int i = 0; i < cols; i++)
376 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
385 virtual void Free(SQLfieldMap* fm)
390 virtual void Free(SQLfieldList* fl)
396 /** SQLConn represents one SQL session.
397 * Each session has its own persistent connection to the database.
398 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
399 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
403 class SQLConn : public InspSocket
406 ModulePgSQL* us; /* Pointer to the SQL provider itself */
407 Server* Srv; /* Server* for..uhm..something, maybe */
408 std::string dbhost; /* Database server hostname */
409 unsigned int dbport; /* Database server port */
410 std::string dbname; /* Database name */
411 std::string dbuser; /* Database username */
412 std::string dbpass; /* Database password */
413 bool ssl; /* If we should require SSL */
414 PGconn* sql; /* PgSQL database connection handle */
415 SQLstatus status; /* PgSQL database connection status */
416 bool qinprog;/* If there is currently a query in progress */
417 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
421 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
423 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);
431 virtual void Close();
435 bool DoConnectedPoll();
439 virtual bool OnDataReady();
441 virtual bool OnWriteReady();
443 virtual bool OnConnected();
447 std::string MkInfoStr();
449 const char* StatusStr();
451 SQLerror DoQuery(SQLrequest &req);
453 SQLerror Query(const SQLrequest &req);
455 void OnUnloadModule(Module* mod);
458 class ModulePgSQL : public Module
463 unsigned long currid;
467 ModulePgSQL(Server* Me)
468 : Module::Module(Me), Srv(Me), currid(0)
470 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
472 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
474 strcpy(sqlsuccess, SQLSUCCESS);
479 void Implements(char* List)
481 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
484 virtual void OnRehash(const std::string ¶meter)
488 /* Delete all the SQLConn objects in the connection lists,
489 * this will call their destructors where they can handle
490 * closing connections and such.
492 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
494 DELETE(iter->second);
497 /* Empty out our list of connections */
500 for(int i = 0; i < conf.Enumerate("database"); i++)
505 id = conf.ReadValue("database", "id", i);
506 newconn = new SQLConn(this, Srv,
507 conf.ReadValue("database", "hostname", i),
508 conf.ReadInteger("database", "port", i, true),
509 conf.ReadValue("database", "name", i),
510 conf.ReadValue("database", "username", i),
511 conf.ReadValue("database", "password", i),
512 conf.ReadFlag("database", "ssl", i));
514 connections.insert(std::make_pair(id, newconn));
518 virtual char* OnRequest(Request* request)
520 if(strcmp(SQLREQID, request->GetData()) == 0)
522 SQLrequest* req = (SQLrequest*)request;
523 ConnMap::iterator iter;
525 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());
527 if((iter = connections.find(req->dbid)) != connections.end())
531 req->error = iter->second->Query(*req);
533 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
537 req->error.Id(BAD_DBID);
542 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
547 virtual void OnUnloadModule(Module* mod, const std::string& name)
549 /* When a module unloads we have to check all the pending queries for all our connections
550 * and set the Module* specifying where the query came from to NULL. If the query has already
551 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
553 * If the queries we find are not already being executed then we can simply remove them immediately.
555 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
557 iter->second->OnUnloadModule(mod);
561 unsigned long NewID()
569 virtual Version GetVersion()
571 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
574 virtual ~ModulePgSQL()
580 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)
581 : InspSocket::InspSocket(), us(self), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE), qinprog(false)
583 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());
585 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
586 * just copied this over from the InspSocket constructor.
588 strlcpy(this->host, dbhost.c_str(), MAXBUF);
591 this->ClosePending = false;
593 if(!inet_aton(this->host, &this->addy))
595 /* Its not an ip, spawn the resolver.
596 * PgSQL doesn't do nonblocking DNS
597 * lookups, so we do it for it.
600 log(DEBUG,"Attempting to resolve %s", this->host);
602 this->dns.SetNS(Srv->GetConfig()->DNSServer);
603 this->dns.ForwardLookupWithFD(this->host, fd);
605 this->state = I_RESOLVING;
606 socket_ref[this->fd] = this;
612 log(DEBUG,"No need to resolve %s", this->host);
613 strlcpy(this->IP, this->host, MAXBUF);
615 if(!this->DoConnect())
617 throw ModuleException("Connect failed");
627 bool SQLConn::DoResolve()
629 log(DEBUG, "Checking for DNS lookup result");
631 if(this->dns.HasResult())
633 std::string res_ip = dns.GetResultIP();
637 log(DEBUG, "Got result: %s", res_ip.c_str());
639 strlcpy(this->IP, res_ip.c_str(), MAXBUF);
642 socket_ref[this->fd] = NULL;
644 return this->DoConnect();
648 log(DEBUG, "DNS lookup failed, dying horribly");
655 log(DEBUG, "No result for lookup yet!");
660 bool SQLConn::DoConnect()
662 log(DEBUG, "SQLConn::DoConnect()");
664 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
666 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
671 if(PQstatus(sql) == CONNECTION_BAD)
673 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
680 if(PQsetnonblocking(sql, 1) == -1)
682 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
687 /* OK, we've initalised the connection, now to get it hooked into the socket engine
688 * and then start polling it.
691 log(DEBUG, "Old DNS socket: %d", this->fd);
692 this->fd = PQsocket(sql);
693 log(DEBUG, "New SQL socket: %d", this->fd);
697 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
702 this->state = I_CONNECTING;
703 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
704 socket_ref[this->fd] = this;
706 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
711 void SQLConn::Close()
713 log(DEBUG,"SQLConn::Close");
716 socket_ref[this->fd] = NULL;
718 this->state = I_ERROR;
719 this->OnError(I_ERR_SOCKET);
720 this->ClosePending = true;
731 bool SQLConn::DoPoll()
733 switch(PQconnectPoll(sql))
735 case PGRES_POLLING_WRITING:
736 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
740 case PGRES_POLLING_READING:
741 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
744 case PGRES_POLLING_FAILED:
745 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
747 case PGRES_POLLING_OK:
748 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
750 return DoConnectedPoll();
752 log(DEBUG, "PGconnectPoll: wtf?");
759 bool SQLConn::DoConnectedPoll()
761 if(!qinprog && queue.totalsize())
763 /* There's no query currently in progress, and there's queries in the queue. */
764 SQLrequest& query = queue.front();
768 if(PQconsumeInput(sql))
770 log(DEBUG, "PQconsumeInput succeeded");
774 log(DEBUG, "Still busy processing command though");
778 log(DEBUG, "Looks like we have a result to process!");
780 /* Grab the request we're processing */
781 SQLrequest& query = queue.front();
783 log(DEBUG, "ID is %lu", query.id);
785 /* Get a pointer to the module we're about to return the result to */
786 Module* to = query.GetSource();
788 /* Fetch the result.. */
789 PGresult* result = PQgetResult(sql);
791 /* PgSQL would allow a query string to be sent which has multiple
792 * queries in it, this isn't portable across database backends and
793 * we don't want modules doing it. But just in case we make sure we
794 * drain any results there are and just use the last one.
795 * If the module devs are behaving there will only be one result.
797 while (PGresult* temp = PQgetResult(sql))
805 /* ..and the result */
806 PgSQLresult reply(us, to, query.id, result);
808 log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
810 switch(PQresultStatus(result))
812 case PGRES_EMPTY_QUERY:
813 case PGRES_BAD_RESPONSE:
814 case PGRES_FATAL_ERROR:
815 reply.error.Id(QREPLY_FAIL);
816 reply.error.Str(PQresultErrorMessage(result));
818 /* No action, other values are not errors */
823 /* PgSQLresult's destructor will free the PGresult */
827 /* If the client module is unloaded partway through a query then the provider will set
828 * the pointer to NULL. We cannot just cancel the query as the result will still come
829 * through at some point...and it could get messy if we play with invalid pointers...
831 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);
843 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
847 void SQLConn::ShowStatus()
849 switch(PQstatus(sql))
851 case CONNECTION_STARTED:
852 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
855 case CONNECTION_MADE:
856 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
859 case CONNECTION_AWAITING_RESPONSE:
860 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
863 case CONNECTION_AUTH_OK:
864 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
867 case CONNECTION_SSL_STARTUP:
868 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
871 case CONNECTION_SETENV:
872 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
876 log(DEBUG, "PQstatus: ???");
880 bool SQLConn::OnDataReady()
882 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
883 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
888 bool SQLConn::OnWriteReady()
890 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
891 log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
896 bool SQLConn::OnConnected()
898 log(DEBUG, "OnConnected(): status = %s", StatusStr());
903 bool SQLConn::DoEvent()
907 if((status == CREAD) || (status == CWRITE))
913 ret = DoConnectedPoll();
919 log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
922 log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
925 log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
933 std::string SQLConn::MkInfoStr()
935 std::ostringstream conninfo("connect_timeout = '2'");
938 conninfo << " hostaddr = '" << dbhost << "'";
941 conninfo << " port = '" << dbport << "'";
944 conninfo << " dbname = '" << dbname << "'";
947 conninfo << " user = '" << dbuser << "'";
950 conninfo << " password = '" << dbpass << "'";
953 conninfo << " sslmode = 'require'";
955 return conninfo.str();
958 const char* SQLConn::StatusStr()
960 if(status == CREAD) return "CREAD";
961 if(status == CWRITE) return "CWRITE";
962 if(status == WREAD) return "WREAD";
963 if(status == WWRITE) return "WWRITE";
964 return "Err...what, erm..BUG!";
967 SQLerror SQLConn::DoQuery(SQLrequest &req)
969 if((status == WREAD) || (status == WWRITE))
973 /* Parse the command string and dispatch it */
975 /* Pointer to the buffer we screw around with substitution in */
977 /* Pointer to the current end of query, where we append new stuff */
979 /* Total length of the unescaped parameters */
980 unsigned int paramlen;
984 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
986 paramlen += i->size();
989 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
990 * sizeofquery + (totalparamlength*2) + 1
992 * The +1 is for null-terminating the string for PQsendQuery()
995 query = new char[req.query.q.length() + (paramlen*2)];
998 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
999 * the parameters into it...
1002 for(unsigned int i = 0; i < req.query.q.length(); i++)
1004 if(req.query.q[i] == '?')
1006 /* We found a place to substitute..what fun.
1007 * Use the PgSQL calls to escape and write the
1008 * escaped string onto the end of our query buffer,
1009 * then we "just" need to make sure queryend is
1010 * pointing at the right place.
1013 if(req.query.p.size())
1018 #ifdef PGSQL_HAS_ESCAPECONN
1019 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
1021 len = PQescapeStringConn(queryend, req.query.p.front().c_str(), req.query.p.front().length());
1027 log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
1030 log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
1032 /* Incremenet queryend to the end of the newly escaped parameter */
1035 /* Remove the parameter we just substituted in */
1036 req.query.p.pop_front();
1040 log(DEBUG, "Found a substitution location but no parameter to substitute :|");
1046 *queryend = req.query.q[i];
1051 /* Null-terminate the query */
1054 log(DEBUG, "Attempting to dispatch query: %s", query);
1056 req.query.q = query;
1058 if(PQsendQuery(sql, query))
1060 log(DEBUG, "Dispatched query successfully");
1067 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
1069 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
1074 log(DEBUG, "Can't query until connection is complete");
1075 return SQLerror(BAD_CONN, "Can't query until connection is complete");
1078 SQLerror SQLConn::Query(const SQLrequest &req)
1082 if(!qinprog && queue.totalsize())
1084 /* There's no query currently in progress, and there's queries in the queue. */
1085 SQLrequest& query = queue.front();
1086 return DoQuery(query);
1094 void SQLConn::OnUnloadModule(Module* mod)
1096 queue.PurgeModule(mod);
1099 class ModulePgSQLFactory : public ModuleFactory
1102 ModulePgSQLFactory()
1106 ~ModulePgSQLFactory()
1110 virtual Module * CreateModule(Server* Me)
1112 return new ModulePgSQL(Me);
1117 extern "C" void * init_module( void )
1119 return new ModulePgSQLFactory;