1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
26 #include "configreader.h"
30 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
31 /* $CompileFlags: -I`pg_config --includedir` `perl extra/pgsql_config.pl` */
32 /* $LinkerFlags: -L`pg_config --libdir` -lpq */
33 /* $ModDep: m_sqlv2.h */
35 /* UGH, UGH, UGH, UGH, UGH, UGH
36 * I'm having trouble seeing how I
37 * can avoid this. The core-defined
38 * constructors for InspSocket just
39 * aren't suitable...and if I'm
40 * reimplementing them I need this so
41 * I can access the socket engine :\
44 /* Forward declare, so we can have the typedef neatly at the top */
47 typedef std::map<std::string, SQLConn*> ConnMap;
49 /* CREAD, Connecting and wants read event
50 * CWRITE, Connecting and wants write event
51 * WREAD, Connected/Working and wants read event
52 * WWRITE, Connected/Working and wants write event
53 * RREAD, Resetting and wants read event
54 * RWRITE, Resetting and wants write event
56 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
58 /** SQLhost, simple structure to store information about a SQL-connection-to-be
59 * We use this struct simply to make it neater passing around host information
60 * when we're creating connections and resolving hosts.
61 * Rather than giving SQLresolver a parameter for every field here so it can in
62 * turn call SQLConn's constructor with them all, both can simply use a SQLhost.
67 std::string id; /* Database handle id */
68 std::string host; /* Database server hostname */
69 unsigned int port; /* Database server port */
70 std::string name; /* Database name */
71 std::string user; /* Database username */
72 std::string pass; /* Database password */
73 bool ssl; /* If we should require SSL */
79 SQLhost(const std::string& i, const std::string& h, unsigned int p, const std::string& n, const std::string& u, const std::string& pa, bool s)
80 : id(i), host(h), port(p), name(n), user(u), pass(pa), ssl(s)
85 /** Used to resolve sql server hostnames
87 class SQLresolver : public Resolver
93 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi)
94 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, (Module*)m), host(hi), mod(m)
98 virtual void OnLookupComplete(const std::string &result);
100 virtual void OnError(ResolverError e, const std::string &errormessage)
102 ServerInstance->Log(DEBUG, "DNS lookup failed (%s), dying horribly", errormessage.c_str());
107 /** QueryQueue, a queue of queries waiting to be executed.
108 * This maintains two queues internally, one for 'priority'
109 * queries and one for less important ones. Each queue has
110 * new queries appended to it and ones to execute are popped
111 * off the front. This keeps them flowing round nicely and no
112 * query should ever get 'stuck' for too long. If there are
113 * queries in the priority queue they will be executed first,
114 * 'unimportant' queries will only be executed when the
115 * priority queue is empty.
117 * We store lists of SQLrequest's here, by value as we want to avoid storing
118 * any data allocated inside the client module (in case that module is unloaded
119 * while the query is in progress).
121 * Because we want to work on the current SQLrequest in-situ, we need a way
122 * of accessing the request we are currently processing, QueryQueue::front(),
123 * but that call needs to always return the same request until that request
124 * is removed from the queue, this is what the 'which' variable is. New queries are
125 * always added to the back of one of the two queues, but if when front()
126 * is first called then the priority queue is empty then front() will return
127 * a query from the normal queue, but if a query is then added to the priority
128 * queue then front() must continue to return the front of the *normal* queue
129 * until pop() is called.
132 class QueryQueue : public classbase
135 typedef std::deque<SQLrequest> ReqDeque;
137 ReqDeque priority; /* The priority queue */
138 ReqDeque normal; /* The 'normal' queue */
139 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
147 void push(const SQLrequest &q)
149 //ServerInstance->Log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
152 priority.push_back(q);
159 if((which == PRI) && priority.size())
161 priority.pop_front();
163 else if((which == NOR) && normal.size())
171 /* Silently do nothing if there was no element to pop() */
179 return priority.front();
181 return normal.front();
186 return priority.front();
192 return normal.front();
195 /* This will probably result in a segfault,
196 * but the caller should have checked totalsize()
197 * first so..meh - moron :p
200 return priority.front();
204 std::pair<int, int> size()
206 return std::make_pair(priority.size(), normal.size());
211 return priority.size() + normal.size();
214 void PurgeModule(Module* mod)
216 DoPurgeModule(mod, priority);
217 DoPurgeModule(mod, normal);
221 void DoPurgeModule(Module* mod, ReqDeque& q)
223 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
225 if(iter->GetSource() == mod)
227 if(iter->id == front().id)
229 /* It's the currently active query.. :x */
230 iter->SetSource(NULL);
234 /* It hasn't been executed yet..just remove it */
235 iter = q.erase(iter);
242 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
243 * All SQL providers must create their own subclass and define it's methods using that
244 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
245 * of converting all data to a common format before it reaches the result structure. This way
246 * data is passes to the module nearly as directly as if it was using the API directly itself.
249 class PgSQLresult : public SQLresult
256 SQLfieldList* fieldlist;
257 SQLfieldMap* fieldmap;
259 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
260 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
262 rows = PQntuples(res);
263 cols = PQnfields(res);
265 //ServerInstance->Log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
270 /* If we allocated these, free them... */
284 return atoi(PQcmdTuples(res));
294 return PQnfields(res);
297 virtual std::string ColName(int column)
299 char* name = PQfname(res, column);
301 return (name) ? name : "";
304 virtual int ColNum(const std::string &column)
306 int n = PQfnumber(res, column.c_str());
310 throw SQLbadColName();
318 virtual SQLfield GetValue(int row, int column)
320 char* v = PQgetvalue(res, row, column);
324 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
328 //ServerInstance->Log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
329 throw SQLbadColName();
333 virtual SQLfieldList& GetRow()
335 /* In an effort to reduce overhead we don't actually allocate the list
336 * until the first time it's needed...so...
344 fieldlist = new SQLfieldList;
347 if(currentrow < PQntuples(res))
349 int cols = PQnfields(res);
351 for(int i = 0; i < cols; i++)
353 fieldlist->push_back(GetValue(currentrow, i));
362 virtual SQLfieldMap& GetRowMap()
364 /* In an effort to reduce overhead we don't actually allocate the map
365 * until the first time it's needed...so...
373 fieldmap = new SQLfieldMap;
376 if(currentrow < PQntuples(res))
378 int cols = PQnfields(res);
380 for(int i = 0; i < cols; i++)
382 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
391 virtual SQLfieldList* GetRowPtr()
393 SQLfieldList* fl = new SQLfieldList;
395 if(currentrow < PQntuples(res))
397 int cols = PQnfields(res);
399 for(int i = 0; i < cols; i++)
401 fl->push_back(GetValue(currentrow, i));
410 virtual SQLfieldMap* GetRowMapPtr()
412 SQLfieldMap* fm = new SQLfieldMap;
414 if(currentrow < PQntuples(res))
416 int cols = PQnfields(res);
418 for(int i = 0; i < cols; i++)
420 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
429 virtual void Free(SQLfieldMap* fm)
434 virtual void Free(SQLfieldList* fl)
440 /** SQLConn represents one SQL session.
441 * Each session has its own persistent connection to the database.
442 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
443 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
447 class SQLConn : public InspSocket
450 Module* us; /* Pointer to the SQL provider itself */
451 std::string dbhost; /* Database server hostname */
452 unsigned int dbport; /* Database server port */
453 std::string dbname; /* Database name */
454 std::string dbuser; /* Database username */
455 std::string dbpass; /* Database password */
456 bool ssl; /* If we should require SSL */
457 PGconn* sql; /* PgSQL database connection handle */
458 SQLstatus status; /* PgSQL database connection status */
459 bool qinprog;/* If there is currently a query in progress */
460 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
461 time_t idle; /* Time we last heard from the database */
465 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
467 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hostinfo);
473 virtual void Close();
477 bool DoConnectedPoll();
483 virtual bool OnDataReady();
485 virtual bool OnWriteReady();
487 virtual bool OnConnected();
493 std::string MkInfoStr();
495 const char* StatusStr();
497 SQLerror DoQuery(SQLrequest &req);
499 SQLerror Query(const SQLrequest &req);
501 void OnUnloadModule(Module* mod);
504 SQLConn::SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
505 : InspSocket::InspSocket(SI), us(self), dbhost(hi.host), dbport(hi.port), dbname(hi.name), dbuser(hi.user), dbpass(hi.pass), ssl(hi.ssl), sql(NULL), status(CWRITE), qinprog(false)
507 //ServerInstance->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());
509 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
510 * just copied this over from the InspSocket constructor.
512 strlcpy(this->host, dbhost.c_str(), MAXBUF);
513 strlcpy(this->IP, dbhost.c_str(), MAXBUF);
515 idle = this->Instance->Time();
517 this->ClosePending = false;
519 Instance->Log(DEBUG,"No need to resolve %s", this->host);
521 if(!this->DoConnect())
523 throw ModuleException("Connect failed");
532 bool SQLConn::DoConnect()
534 //ServerInstance->Log(DEBUG, "SQLConn::DoConnect()");
536 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
538 Instance->Log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
543 if(PQstatus(sql) == CONNECTION_BAD)
545 Instance->Log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
552 if(PQsetnonblocking(sql, 1) == -1)
554 Instance->Log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
559 /* OK, we've initalised the connection, now to get it hooked into the socket engine
560 * and then start polling it.
563 //ServerInstance->Log(DEBUG, "Old DNS socket: %d", this->fd);
564 this->fd = PQsocket(sql);
565 Instance->Log(DEBUG, "New SQL socket: %d", this->fd);
569 Instance->Log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
574 this->state = I_CONNECTING;
575 if (!this->Instance->SE->AddFd(this))
577 Instance->Log(DEBUG, "A PQsocket cant be added to the socket engine!");
582 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
587 void SQLConn::Close()
589 Instance->Log(DEBUG,"SQLConn::Close");
591 if (!this->Instance->SE->DelFd(this))
593 Instance->Log(DEBUG, "PQsocket cant be removed from the socket engine!");
596 this->state = I_ERROR;
597 this->OnError(I_ERR_SOCKET);
598 this->ClosePending = true;
607 bool SQLConn::DoPoll()
609 switch(PQconnectPoll(sql))
611 case PGRES_POLLING_WRITING:
612 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
616 case PGRES_POLLING_READING:
617 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
620 case PGRES_POLLING_FAILED:
621 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
623 case PGRES_POLLING_OK:
624 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
626 return DoConnectedPoll();
628 //ServerInstance->Log(DEBUG, "PGconnectPoll: wtf?");
633 bool SQLConn::DoConnectedPoll()
635 if(!qinprog && queue.totalsize())
637 /* There's no query currently in progress, and there's queries in the queue. */
638 SQLrequest& query = queue.front();
642 if(PQconsumeInput(sql))
644 Instance->Log(DEBUG, "PQconsumeInput succeeded");
646 /* We just read stuff from the server, that counts as it being alive
647 * so update the idle-since time :p
649 idle = this->Instance->Time();
653 //ServerInstance->Log(DEBUG, "Still busy processing command though");
657 //ServerInstance->Log(DEBUG, "Looks like we have a result to process!");
659 /* Grab the request we're processing */
660 SQLrequest& query = queue.front();
662 Instance->Log(DEBUG, "ID is %lu", query.id);
664 /* Get a pointer to the module we're about to return the result to */
665 Module* to = query.GetSource();
667 /* Fetch the result.. */
668 PGresult* result = PQgetResult(sql);
670 /* PgSQL would allow a query string to be sent which has multiple
671 * queries in it, this isn't portable across database backends and
672 * we don't want modules doing it. But just in case we make sure we
673 * drain any results there are and just use the last one.
674 * If the module devs are behaving there will only be one result.
676 while (PGresult* temp = PQgetResult(sql))
684 /* ..and the result */
685 PgSQLresult reply(us, to, query.id, result);
687 /* Fix by brain, make sure the original query gets sent back in the reply */
688 reply.query = query.query.q;
690 Instance->Log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
692 switch(PQresultStatus(result))
694 case PGRES_EMPTY_QUERY:
695 case PGRES_BAD_RESPONSE:
696 case PGRES_FATAL_ERROR:
697 reply.error.Id(QREPLY_FAIL);
698 reply.error.Str(PQresultErrorMessage(result));
700 /* No action, other values are not errors */
705 /* PgSQLresult's destructor will free the PGresult */
709 /* If the client module is unloaded partway through a query then the provider will set
710 * the pointer to NULL. We cannot just cancel the query as the result will still come
711 * through at some point...and it could get messy if we play with invalid pointers...
713 Instance->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);
723 Instance->Log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
730 /* I think we'll assume this means the server died...it might not,
731 * but I think that any error serious enough we actually get here
732 * deserves to reconnect [/excuse]
733 * Returning true so the core doesn't try and close the connection.
735 Instance->Log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
741 bool SQLConn::DoResetPoll()
743 switch(PQresetPoll(sql))
745 case PGRES_POLLING_WRITING:
746 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
750 case PGRES_POLLING_READING:
751 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
754 case PGRES_POLLING_FAILED:
755 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
757 case PGRES_POLLING_OK:
758 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
760 return DoConnectedPoll();
762 //ServerInstance->Log(DEBUG, "PGresetPoll: wtf?");
767 void SQLConn::ShowStatus()
769 switch(PQstatus(sql))
771 case CONNECTION_STARTED:
772 Instance->Log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
775 case CONNECTION_MADE:
776 Instance->Log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
779 case CONNECTION_AWAITING_RESPONSE:
780 Instance->Log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
783 case CONNECTION_AUTH_OK:
784 Instance->Log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
787 case CONNECTION_SSL_STARTUP:
788 Instance->Log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
791 case CONNECTION_SETENV:
792 Instance->Log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
796 Instance->Log(DEBUG, "PQstatus: ???");
800 bool SQLConn::OnDataReady()
802 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
803 Instance->Log(DEBUG, "OnDataReady(): status = %s", StatusStr());
808 bool SQLConn::OnWriteReady()
810 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
811 Instance->Log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
816 bool SQLConn::OnConnected()
818 Instance->Log(DEBUG, "OnConnected(): status = %s", StatusStr());
823 bool SQLConn::Reconnect()
825 Instance->Log(DEBUG, "Initiating reconnect");
827 if(PQresetStart(sql))
829 /* Successfully initiatied database reconnect,
830 * set flags so PQresetPoll() will be called appropriately
838 Instance->Log(DEBUG, "Failed to initiate reconnect...fun");
843 bool SQLConn::DoEvent()
847 if((status == CREAD) || (status == CWRITE))
851 else if((status == RREAD) || (status == RWRITE))
857 ret = DoConnectedPoll();
863 Instance->Log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
866 Instance->Log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
869 Instance->Log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
877 std::string SQLConn::MkInfoStr()
879 std::ostringstream conninfo("connect_timeout = '2'");
882 conninfo << " hostaddr = '" << dbhost << "'";
885 conninfo << " port = '" << dbport << "'";
888 conninfo << " dbname = '" << dbname << "'";
891 conninfo << " user = '" << dbuser << "'";
894 conninfo << " password = '" << dbpass << "'";
897 conninfo << " sslmode = 'require'";
899 return conninfo.str();
902 const char* SQLConn::StatusStr()
904 if(status == CREAD) return "CREAD";
905 if(status == CWRITE) return "CWRITE";
906 if(status == WREAD) return "WREAD";
907 if(status == WWRITE) return "WWRITE";
908 return "Err...what, erm..BUG!";
911 SQLerror SQLConn::DoQuery(SQLrequest &req)
913 if((status == WREAD) || (status == WWRITE))
917 /* Parse the command string and dispatch it */
919 /* Pointer to the buffer we screw around with substitution in */
921 /* Pointer to the current end of query, where we append new stuff */
923 /* Total length of the unescaped parameters */
924 unsigned int paramlen;
928 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
930 paramlen += i->size();
933 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
934 * sizeofquery + (totalparamlength*2) + 1
936 * The +1 is for null-terminating the string for PQsendQuery()
939 query = new char[req.query.q.length() + (paramlen*2) + 1];
942 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
943 * the parameters into it...
946 for(unsigned int i = 0; i < req.query.q.length(); i++)
948 if(req.query.q[i] == '?')
950 /* We found a place to substitute..what fun.
951 * Use the PgSQL calls to escape and write the
952 * escaped string onto the end of our query buffer,
953 * then we "just" need to make sure queryend is
954 * pointing at the right place.
957 if(req.query.p.size())
962 #ifdef PGSQL_HAS_ESCAPECONN
963 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
965 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
969 Instance->Log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
972 Instance->Log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
974 /* Incremenet queryend to the end of the newly escaped parameter */
977 /* Remove the parameter we just substituted in */
978 req.query.p.pop_front();
982 Instance->Log(DEBUG, "Found a substitution location but no parameter to substitute :|");
988 *queryend = req.query.q[i];
993 /* Null-terminate the query */
996 Instance->Log(DEBUG, "Attempting to dispatch query: %s", query);
1000 if(PQsendQuery(sql, query))
1002 Instance->Log(DEBUG, "Dispatched query successfully");
1009 Instance->Log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
1011 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
1016 Instance->Log(DEBUG, "Can't query until connection is complete");
1017 return SQLerror(BAD_CONN, "Can't query until connection is complete");
1020 SQLerror SQLConn::Query(const SQLrequest &req)
1024 if(!qinprog && queue.totalsize())
1026 /* There's no query currently in progress, and there's queries in the queue. */
1027 SQLrequest& query = queue.front();
1028 return DoQuery(query);
1036 void SQLConn::OnUnloadModule(Module* mod)
1038 queue.PurgeModule(mod);
1041 class ModulePgSQL : public Module
1045 ConnMap connections;
1046 unsigned long currid;
1051 ModulePgSQL(InspIRCd* Me)
1052 : Module::Module(Me), currid(0), modloading(true)
1054 ServerInstance->UseInterface("SQLutils");
1056 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
1058 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS)+1);
1060 if (!ServerInstance->PublishFeature("SQL", this))
1062 throw ModuleException("m_pgsql: Unable to publish feature 'SQL'");
1067 ServerInstance->PublishInterface("SQL", this);
1070 virtual ~ModulePgSQL()
1074 ServerInstance->UnpublishInterface("SQL", this);
1075 ServerInstance->UnpublishFeature("SQL");
1076 ServerInstance->DoneWithInterface("SQLutils");
1079 void Implements(char* List)
1081 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
1084 virtual void OnRehash(const std::string ¶meter)
1097 ConfigReader conf(ServerInstance);
1100 for(int i = 0; i < conf.Enumerate("database"); i++)
1104 insp_inaddr blargle;
1106 host.id = conf.ReadValue("database", "id", i);
1107 host.host = conf.ReadValue("database", "hostname", i);
1108 host.port = conf.ReadInteger("database", "port", i, true);
1109 host.name = conf.ReadValue("database", "name", i);
1110 host.user = conf.ReadValue("database", "username", i);
1111 host.pass = conf.ReadValue("database", "password", i);
1112 host.ssl = conf.ReadFlag("database", "ssl", i);
1114 ipvalid = insp_aton(host.host.c_str(), &blargle);
1118 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1119 this->AddConn(host);
1121 else if(ipvalid == 0)
1123 /* Conversion failed, assume it's a host */
1124 SQLresolver* resolver;
1128 resolver = new SQLresolver(this, ServerInstance, host);
1130 ServerInstance->AddResolver(resolver);
1134 ServerInstance->Log(DEBUG, "Couldn't make a SQLresolver..this connection is gonna diiiiiie...actually we just won't create it");
1139 /* Invalid address family, die horribly. */
1140 ServerInstance->Log(DEBUG, "insp_aton failed returning -1, oh noes.");
1145 void ClearConnections()
1147 ConnMap::iterator iter;
1148 while ((iter = connections.begin()) != connections.end())
1150 connections.erase(iter);
1151 DELETE(iter->second);
1155 void AddConn(const SQLhost& hi)
1159 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1160 newconn = new SQLConn(ServerInstance, this, hi);
1162 connections.insert(std::make_pair(hi.id, newconn));
1165 virtual char* OnRequest(Request* request)
1167 if(strcmp(SQLREQID, request->GetId()) == 0)
1169 SQLrequest* req = (SQLrequest*)request;
1170 ConnMap::iterator iter;
1172 ServerInstance->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());
1174 if((iter = connections.find(req->dbid)) != connections.end())
1178 req->error = iter->second->Query(*req);
1180 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
1184 req->error.Id(BAD_DBID);
1189 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
1194 virtual void OnUnloadModule(Module* mod, const std::string& name)
1196 /* When a module unloads we have to check all the pending queries for all our connections
1197 * and set the Module* specifying where the query came from to NULL. If the query has already
1198 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1200 * If the queries we find are not already being executed then we can simply remove them immediately.
1202 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1204 iter->second->OnUnloadModule(mod);
1208 unsigned long NewID()
1216 virtual Version GetVersion()
1218 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1222 /* move this here to use AddConn, rather that than having the whole
1223 * module above SQLConn, since this is buggin me right now :/
1225 void SQLresolver::OnLookupComplete(const std::string &result)
1228 ((ModulePgSQL*)mod)->AddConn(host);
1231 class ModulePgSQLFactory : public ModuleFactory
1234 ModulePgSQLFactory()
1238 ~ModulePgSQLFactory()
1242 virtual Module * CreateModule(InspIRCd* Me)
1244 return new ModulePgSQL(Me);
1249 extern "C" void * init_module( void )
1251 return new ModulePgSQLFactory;