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 bool operator== (const SQLhost& l, const SQLhost& r)
87 return (l.id == r.id && l.host == r.host && l.port == r.port && l.name == r.name && l.user == l.user && l.pass == r.pass && l.ssl == r.ssl);
90 /** Used to resolve sql server hostnames
92 class SQLresolver : public Resolver
99 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, const SQLhost& ci)
100 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, (Module*)m), host(hi), confhost(ci), mod(m)
104 virtual void OnLookupComplete(const std::string &result);
106 virtual void OnError(ResolverError e, const std::string &errormessage)
108 ServerInstance->Log(DEBUG, "DNS lookup failed (%s), dying horribly", errormessage.c_str());
112 /** QueryQueue, a queue of queries waiting to be executed.
113 * This maintains two queues internally, one for 'priority'
114 * queries and one for less important ones. Each queue has
115 * new queries appended to it and ones to execute are popped
116 * off the front. This keeps them flowing round nicely and no
117 * query should ever get 'stuck' for too long. If there are
118 * queries in the priority queue they will be executed first,
119 * 'unimportant' queries will only be executed when the
120 * priority queue is empty.
122 * We store lists of SQLrequest's here, by value as we want to avoid storing
123 * any data allocated inside the client module (in case that module is unloaded
124 * while the query is in progress).
126 * Because we want to work on the current SQLrequest in-situ, we need a way
127 * of accessing the request we are currently processing, QueryQueue::front(),
128 * but that call needs to always return the same request until that request
129 * is removed from the queue, this is what the 'which' variable is. New queries are
130 * always added to the back of one of the two queues, but if when front()
131 * is first called then the priority queue is empty then front() will return
132 * a query from the normal queue, but if a query is then added to the priority
133 * queue then front() must continue to return the front of the *normal* queue
134 * until pop() is called.
137 class QueryQueue : public classbase
140 typedef std::deque<SQLrequest> ReqDeque;
142 ReqDeque priority; /* The priority queue */
143 ReqDeque normal; /* The 'normal' queue */
144 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
152 void push(const SQLrequest &q)
154 //ServerInstance->Log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
157 priority.push_back(q);
164 if((which == PRI) && priority.size())
166 priority.pop_front();
168 else if((which == NOR) && normal.size())
176 /* Silently do nothing if there was no element to pop() */
184 return priority.front();
186 return normal.front();
191 return priority.front();
197 return normal.front();
200 /* This will probably result in a segfault,
201 * but the caller should have checked totalsize()
202 * first so..meh - moron :p
205 return priority.front();
209 std::pair<int, int> size()
211 return std::make_pair(priority.size(), normal.size());
216 return priority.size() + normal.size();
219 void PurgeModule(Module* mod)
221 DoPurgeModule(mod, priority);
222 DoPurgeModule(mod, normal);
226 void DoPurgeModule(Module* mod, ReqDeque& q)
228 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
230 if(iter->GetSource() == mod)
232 if(iter->id == front().id)
234 /* It's the currently active query.. :x */
235 iter->SetSource(NULL);
239 /* It hasn't been executed yet..just remove it */
240 iter = q.erase(iter);
247 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
248 * All SQL providers must create their own subclass and define it's methods using that
249 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
250 * of converting all data to a common format before it reaches the result structure. This way
251 * data is passes to the module nearly as directly as if it was using the API directly itself.
254 class PgSQLresult : public SQLresult
261 SQLfieldList* fieldlist;
262 SQLfieldMap* fieldmap;
264 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
265 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
267 rows = PQntuples(res);
268 cols = PQnfields(res);
270 //ServerInstance->Log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
275 /* If we allocated these, free them... */
289 return atoi(PQcmdTuples(res));
299 return PQnfields(res);
302 virtual std::string ColName(int column)
304 char* name = PQfname(res, column);
306 return (name) ? name : "";
309 virtual int ColNum(const std::string &column)
311 int n = PQfnumber(res, column.c_str());
315 throw SQLbadColName();
323 virtual SQLfield GetValue(int row, int column)
325 char* v = PQgetvalue(res, row, column);
329 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
333 //ServerInstance->Log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
334 throw SQLbadColName();
338 virtual SQLfieldList& GetRow()
340 /* In an effort to reduce overhead we don't actually allocate the list
341 * until the first time it's needed...so...
349 fieldlist = new SQLfieldList;
352 if(currentrow < PQntuples(res))
354 int cols = PQnfields(res);
356 for(int i = 0; i < cols; i++)
358 fieldlist->push_back(GetValue(currentrow, i));
367 virtual SQLfieldMap& GetRowMap()
369 /* In an effort to reduce overhead we don't actually allocate the map
370 * until the first time it's needed...so...
378 fieldmap = new SQLfieldMap;
381 if(currentrow < PQntuples(res))
383 int cols = PQnfields(res);
385 for(int i = 0; i < cols; i++)
387 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
396 virtual SQLfieldList* GetRowPtr()
398 SQLfieldList* fl = new SQLfieldList;
400 if(currentrow < PQntuples(res))
402 int cols = PQnfields(res);
404 for(int i = 0; i < cols; i++)
406 fl->push_back(GetValue(currentrow, i));
415 virtual SQLfieldMap* GetRowMapPtr()
417 SQLfieldMap* fm = new SQLfieldMap;
419 if(currentrow < PQntuples(res))
421 int cols = PQnfields(res);
423 for(int i = 0; i < cols; i++)
425 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
434 virtual void Free(SQLfieldMap* fm)
439 virtual void Free(SQLfieldList* fl)
445 /** SQLConn represents one SQL session.
446 * Each session has its own persistent connection to the database.
447 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
448 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
452 class SQLConn : public InspSocket
455 Module* us; /* Pointer to the SQL provider itself */
456 std::string dbhost; /* Database server hostname */
457 unsigned int dbport; /* Database server port */
458 std::string dbname; /* Database name */
459 std::string dbuser; /* Database username */
460 std::string dbpass; /* Database password */
461 bool ssl; /* If we should require SSL */
462 PGconn* sql; /* PgSQL database connection handle */
463 SQLstatus status; /* PgSQL database connection status */
464 bool qinprog; /* If there is currently a query in progress */
465 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
466 time_t idle; /* Time we last heard from the database */
467 SQLhost confhost; /* A copy of the config <database> entry for conf checks */
470 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
472 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hostinfo, const SQLhost& confinfo);
478 virtual void Close();
482 bool DoConnectedPoll();
488 virtual bool OnDataReady();
490 virtual bool OnWriteReady();
492 virtual bool OnConnected();
498 std::string MkInfoStr();
500 const char* StatusStr();
502 SQLerror DoQuery(SQLrequest &req);
504 SQLerror Query(const SQLrequest &req);
506 void OnUnloadModule(Module* mod);
508 const SQLhost GetConfHost();
511 SQLConn::SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi, const SQLhost& ci)
512 : 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)
514 //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());
516 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
517 * just copied this over from the InspSocket constructor.
520 strlcpy(this->host, dbhost.c_str(), MAXBUF);
521 strlcpy(this->IP, dbhost.c_str(), MAXBUF);
523 idle = this->Instance->Time();
525 this->ClosePending = false;
527 Instance->Log(DEBUG,"No need to resolve %s", this->host);
529 if(!this->DoConnect())
531 throw ModuleException("Connect failed");
540 bool SQLConn::DoConnect()
542 //ServerInstance->Log(DEBUG, "SQLConn::DoConnect()");
544 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
546 Instance->Log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
551 if(PQstatus(sql) == CONNECTION_BAD)
553 Instance->Log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
560 if(PQsetnonblocking(sql, 1) == -1)
562 Instance->Log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
567 /* OK, we've initalised the connection, now to get it hooked into the socket engine
568 * and then start polling it.
571 //ServerInstance->Log(DEBUG, "Old DNS socket: %d", this->fd);
572 this->fd = PQsocket(sql);
573 Instance->Log(DEBUG, "New SQL socket: %d", this->fd);
577 Instance->Log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
582 this->state = I_CONNECTING;
583 if (!this->Instance->SE->AddFd(this))
585 Instance->Log(DEBUG, "A PQsocket cant be added to the socket engine!");
590 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
595 void SQLConn::Close()
597 Instance->Log(DEBUG,"SQLConn::Close");
599 if (!this->Instance->SE->DelFd(this))
601 Instance->Log(DEBUG, "PQsocket cant be removed from the socket engine!");
604 this->state = I_ERROR;
605 this->OnError(I_ERR_SOCKET);
606 this->ClosePending = true;
615 bool SQLConn::DoPoll()
617 switch(PQconnectPoll(sql))
619 case PGRES_POLLING_WRITING:
620 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
624 case PGRES_POLLING_READING:
625 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
628 case PGRES_POLLING_FAILED:
629 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
631 case PGRES_POLLING_OK:
632 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
634 return DoConnectedPoll();
636 //ServerInstance->Log(DEBUG, "PGconnectPoll: wtf?");
641 bool SQLConn::DoConnectedPoll()
643 if(!qinprog && queue.totalsize())
645 /* There's no query currently in progress, and there's queries in the queue. */
646 SQLrequest& query = queue.front();
650 if(PQconsumeInput(sql))
652 Instance->Log(DEBUG, "PQconsumeInput succeeded");
654 /* We just read stuff from the server, that counts as it being alive
655 * so update the idle-since time :p
657 idle = this->Instance->Time();
661 //ServerInstance->Log(DEBUG, "Still busy processing command though");
665 //ServerInstance->Log(DEBUG, "Looks like we have a result to process!");
667 /* Grab the request we're processing */
668 SQLrequest& query = queue.front();
670 Instance->Log(DEBUG, "ID is %lu", query.id);
672 /* Get a pointer to the module we're about to return the result to */
673 Module* to = query.GetSource();
675 /* Fetch the result.. */
676 PGresult* result = PQgetResult(sql);
678 /* PgSQL would allow a query string to be sent which has multiple
679 * queries in it, this isn't portable across database backends and
680 * we don't want modules doing it. But just in case we make sure we
681 * drain any results there are and just use the last one.
682 * If the module devs are behaving there will only be one result.
684 while (PGresult* temp = PQgetResult(sql))
692 /* ..and the result */
693 PgSQLresult reply(us, to, query.id, result);
695 /* Fix by brain, make sure the original query gets sent back in the reply */
696 reply.query = query.query.q;
698 Instance->Log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
700 switch(PQresultStatus(result))
702 case PGRES_EMPTY_QUERY:
703 case PGRES_BAD_RESPONSE:
704 case PGRES_FATAL_ERROR:
705 reply.error.Id(QREPLY_FAIL);
706 reply.error.Str(PQresultErrorMessage(result));
708 /* No action, other values are not errors */
713 /* PgSQLresult's destructor will free the PGresult */
717 /* If the client module is unloaded partway through a query then the provider will set
718 * the pointer to NULL. We cannot just cancel the query as the result will still come
719 * through at some point...and it could get messy if we play with invalid pointers...
721 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);
731 Instance->Log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
738 /* I think we'll assume this means the server died...it might not,
739 * but I think that any error serious enough we actually get here
740 * deserves to reconnect [/excuse]
741 * Returning true so the core doesn't try and close the connection.
743 Instance->Log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
749 bool SQLConn::DoResetPoll()
751 switch(PQresetPoll(sql))
753 case PGRES_POLLING_WRITING:
754 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
758 case PGRES_POLLING_READING:
759 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
762 case PGRES_POLLING_FAILED:
763 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
765 case PGRES_POLLING_OK:
766 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
768 return DoConnectedPoll();
770 //ServerInstance->Log(DEBUG, "PGresetPoll: wtf?");
775 void SQLConn::ShowStatus()
777 switch(PQstatus(sql))
779 case CONNECTION_STARTED:
780 Instance->Log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
783 case CONNECTION_MADE:
784 Instance->Log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
787 case CONNECTION_AWAITING_RESPONSE:
788 Instance->Log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
791 case CONNECTION_AUTH_OK:
792 Instance->Log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
795 case CONNECTION_SSL_STARTUP:
796 Instance->Log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
799 case CONNECTION_SETENV:
800 Instance->Log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
804 Instance->Log(DEBUG, "PQstatus: ???");
808 bool SQLConn::OnDataReady()
810 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
811 Instance->Log(DEBUG, "OnDataReady(): status = %s", StatusStr());
816 bool SQLConn::OnWriteReady()
818 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
819 Instance->Log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
824 bool SQLConn::OnConnected()
826 Instance->Log(DEBUG, "OnConnected(): status = %s", StatusStr());
831 bool SQLConn::Reconnect()
833 Instance->Log(DEBUG, "Initiating reconnect");
835 if(PQresetStart(sql))
837 /* Successfully initiatied database reconnect,
838 * set flags so PQresetPoll() will be called appropriately
846 Instance->Log(DEBUG, "Failed to initiate reconnect...fun");
851 bool SQLConn::DoEvent()
855 if((status == CREAD) || (status == CWRITE))
859 else if((status == RREAD) || (status == RWRITE))
865 ret = DoConnectedPoll();
871 Instance->Log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
874 Instance->Log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
877 Instance->Log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
885 std::string SQLConn::MkInfoStr()
887 std::ostringstream conninfo("connect_timeout = '2'");
890 conninfo << " hostaddr = '" << dbhost << "'";
893 conninfo << " port = '" << dbport << "'";
896 conninfo << " dbname = '" << dbname << "'";
899 conninfo << " user = '" << dbuser << "'";
902 conninfo << " password = '" << dbpass << "'";
905 conninfo << " sslmode = 'require'";
907 return conninfo.str();
910 const char* SQLConn::StatusStr()
912 if(status == CREAD) return "CREAD";
913 if(status == CWRITE) return "CWRITE";
914 if(status == WREAD) return "WREAD";
915 if(status == WWRITE) return "WWRITE";
916 return "Err...what, erm..BUG!";
919 SQLerror SQLConn::DoQuery(SQLrequest &req)
921 if((status == WREAD) || (status == WWRITE))
925 /* Parse the command string and dispatch it */
927 /* Pointer to the buffer we screw around with substitution in */
929 /* Pointer to the current end of query, where we append new stuff */
931 /* Total length of the unescaped parameters */
932 unsigned int paramlen;
936 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
938 paramlen += i->size();
941 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
942 * sizeofquery + (totalparamlength*2) + 1
944 * The +1 is for null-terminating the string for PQsendQuery()
947 query = new char[req.query.q.length() + (paramlen*2) + 1];
950 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
951 * the parameters into it...
954 for(unsigned int i = 0; i < req.query.q.length(); i++)
956 if(req.query.q[i] == '?')
958 /* We found a place to substitute..what fun.
959 * Use the PgSQL calls to escape and write the
960 * escaped string onto the end of our query buffer,
961 * then we "just" need to make sure queryend is
962 * pointing at the right place.
965 if(req.query.p.size())
970 #ifdef PGSQL_HAS_ESCAPECONN
971 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
973 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
977 Instance->Log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
980 Instance->Log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
982 /* Incremenet queryend to the end of the newly escaped parameter */
985 /* Remove the parameter we just substituted in */
986 req.query.p.pop_front();
990 Instance->Log(DEBUG, "Found a substitution location but no parameter to substitute :|");
996 *queryend = req.query.q[i];
1001 /* Null-terminate the query */
1004 Instance->Log(DEBUG, "Attempting to dispatch query: %s", query);
1006 req.query.q = query;
1008 if(PQsendQuery(sql, query))
1010 Instance->Log(DEBUG, "Dispatched query successfully");
1017 Instance->Log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
1019 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
1024 return SQLerror(BAD_CONN, "Can't query until connection is complete");
1027 SQLerror SQLConn::Query(const SQLrequest &req)
1031 if(!qinprog && queue.totalsize())
1033 /* There's no query currently in progress, and there's queries in the queue. */
1034 SQLrequest& query = queue.front();
1035 return DoQuery(query);
1043 void SQLConn::OnUnloadModule(Module* mod)
1045 queue.PurgeModule(mod);
1048 const SQLhost SQLConn::GetConfHost()
1053 class ModulePgSQL : public Module
1057 ConnMap connections;
1058 unsigned long currid;
1062 ModulePgSQL(InspIRCd* Me)
1063 : Module::Module(Me), currid(0)
1065 ServerInstance->UseInterface("SQLutils");
1067 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
1069 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS)+1);
1071 if (!ServerInstance->PublishFeature("SQL", this))
1073 throw ModuleException("m_pgsql: Unable to publish feature 'SQL'");
1078 ServerInstance->PublishInterface("SQL", this);
1081 virtual ~ModulePgSQL()
1083 ClearAllConnections();
1085 ServerInstance->UnpublishInterface("SQL", this);
1086 ServerInstance->UnpublishFeature("SQL");
1087 ServerInstance->DoneWithInterface("SQLutils");
1090 void Implements(char* List)
1092 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
1095 virtual void OnRehash(const std::string ¶meter)
1100 bool HasHost(const SQLhost &host)
1102 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1104 if (host == iter->second->GetConfHost())
1110 bool HostInConf(const SQLhost &h)
1112 ConfigReader conf(ServerInstance);
1113 for(int i = 0; i < conf.Enumerate("database"); i++)
1116 host.id = conf.ReadValue("database", "id", i);
1117 host.host = conf.ReadValue("database", "hostname", i);
1118 host.port = conf.ReadInteger("database", "port", i, true);
1119 host.name = conf.ReadValue("database", "name", i);
1120 host.user = conf.ReadValue("database", "username", i);
1121 host.pass = conf.ReadValue("database", "password", i);
1122 host.ssl = conf.ReadFlag("database", "ssl", i);
1131 ConfigReader conf(ServerInstance);
1133 for(int i = 0; i < conf.Enumerate("database"); i++)
1137 insp_inaddr blargle;
1139 host.id = conf.ReadValue("database", "id", i);
1140 host.host = conf.ReadValue("database", "hostname", i);
1141 host.port = conf.ReadInteger("database", "port", i, true);
1142 host.name = conf.ReadValue("database", "name", i);
1143 host.user = conf.ReadValue("database", "username", i);
1144 host.pass = conf.ReadValue("database", "password", i);
1145 host.ssl = conf.ReadFlag("database", "ssl", i);
1150 ipvalid = insp_aton(host.host.c_str(), &blargle);
1154 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1155 this->AddConn(host, host);
1157 else if(ipvalid == 0)
1159 /* Conversion failed, assume it's a host */
1160 SQLresolver* resolver;
1164 resolver = new SQLresolver(this, ServerInstance, host, host);
1166 ServerInstance->AddResolver(resolver);
1170 /* THE WORLD IS COMING TO AN END! */
1171 ServerInstance->Log(DEBUG, "Couldn't make a SQLresolver..this connection is gonna diiiiiie...actually we just won't create it");
1176 /* Invalid address family, die horribly. */
1177 ServerInstance->Log(DEBUG, "insp_aton failed returning -1, oh noes.");
1180 ClearOldConnections();
1183 void ClearOldConnections()
1185 ConnMap::iterator iter,safei;
1186 for (iter = connections.begin(); iter != connections.end(); iter++)
1188 if (!HostInConf(iter->second->GetConfHost()))
1190 DELETE(iter->second);
1193 connections.erase(safei);
1198 void ClearAllConnections()
1200 ConnMap::iterator iter;
1201 while ((iter = connections.begin()) != connections.end())
1203 connections.erase(iter);
1204 DELETE(iter->second);
1208 void AddConn(const SQLhost& hi, const SQLhost& ci)
1212 ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
1218 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1219 newconn = new SQLConn(ServerInstance, this, hi, ci);
1221 connections.insert(std::make_pair(hi.id, newconn));
1224 virtual char* OnRequest(Request* request)
1226 if(strcmp(SQLREQID, request->GetId()) == 0)
1228 SQLrequest* req = (SQLrequest*)request;
1229 ConnMap::iterator iter;
1231 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());
1233 if((iter = connections.find(req->dbid)) != connections.end())
1237 req->error = iter->second->Query(*req);
1239 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
1243 req->error.Id(BAD_DBID);
1248 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
1253 virtual void OnUnloadModule(Module* mod, const std::string& name)
1255 /* When a module unloads we have to check all the pending queries for all our connections
1256 * and set the Module* specifying where the query came from to NULL. If the query has already
1257 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1259 * If the queries we find are not already being executed then we can simply remove them immediately.
1261 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1263 iter->second->OnUnloadModule(mod);
1267 unsigned long NewID()
1275 virtual Version GetVersion()
1277 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1281 /* move this here to use AddConn, rather that than having the whole
1282 * module above SQLConn, since this is buggin me right now :/
1284 void SQLresolver::OnLookupComplete(const std::string &result)
1287 ((ModulePgSQL*)mod)->AddConn(host, confhost);
1288 ((ModulePgSQL*)mod)->ClearOldConnections();
1291 class ModulePgSQLFactory : public ModuleFactory
1294 ModulePgSQLFactory()
1298 ~ModulePgSQLFactory()
1302 virtual Module * CreateModule(InspIRCd* Me)
1304 return new ModulePgSQL(Me);
1309 extern "C" void * init_module( void )
1311 // PQregisterThreadLock(pgthreadlock_t(1));
1312 return new ModulePgSQLFactory;