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::GetDSN() - Overload to return correct DSN for PostgreSQL
60 std::string SQLhost::GetDSN()
62 std::ostringstream conninfo("connect_timeout = '2'");
65 conninfo << " hostaddr = '" << ip << "'";
68 conninfo << " port = '" << port << "'";
71 conninfo << " dbname = '" << name << "'";
74 conninfo << " user = '" << user << "'";
77 conninfo << " password = '" << pass << "'";
80 conninfo << " sslmode = 'require'";
82 return conninfo.str();
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());
106 /** QueryQueue, a queue of queries waiting to be executed.
107 * This maintains two queues internally, one for 'priority'
108 * queries and one for less important ones. Each queue has
109 * new queries appended to it and ones to execute are popped
110 * off the front. This keeps them flowing round nicely and no
111 * query should ever get 'stuck' for too long. If there are
112 * queries in the priority queue they will be executed first,
113 * 'unimportant' queries will only be executed when the
114 * priority queue is empty.
116 * We store lists of SQLrequest's here, by value as we want to avoid storing
117 * any data allocated inside the client module (in case that module is unloaded
118 * while the query is in progress).
120 * Because we want to work on the current SQLrequest in-situ, we need a way
121 * of accessing the request we are currently processing, QueryQueue::front(),
122 * but that call needs to always return the same request until that request
123 * is removed from the queue, this is what the 'which' variable is. New queries are
124 * always added to the back of one of the two queues, but if when front()
125 * is first called then the priority queue is empty then front() will return
126 * a query from the normal queue, but if a query is then added to the priority
127 * queue then front() must continue to return the front of the *normal* queue
128 * until pop() is called.
131 class QueryQueue : public classbase
134 typedef std::deque<SQLrequest> ReqDeque;
136 ReqDeque priority; /* The priority queue */
137 ReqDeque normal; /* The 'normal' queue */
138 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
146 void push(const SQLrequest &q)
148 //ServerInstance->Log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
151 priority.push_back(q);
158 if((which == PRI) && priority.size())
160 priority.pop_front();
162 else if((which == NOR) && normal.size())
170 /* Silently do nothing if there was no element to pop() */
178 return priority.front();
180 return normal.front();
185 return priority.front();
191 return normal.front();
194 /* This will probably result in a segfault,
195 * but the caller should have checked totalsize()
196 * first so..meh - moron :p
199 return priority.front();
203 std::pair<int, int> size()
205 return std::make_pair(priority.size(), normal.size());
210 return priority.size() + normal.size();
213 void PurgeModule(Module* mod)
215 DoPurgeModule(mod, priority);
216 DoPurgeModule(mod, normal);
220 void DoPurgeModule(Module* mod, ReqDeque& q)
222 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
224 if(iter->GetSource() == mod)
226 if(iter->id == front().id)
228 /* It's the currently active query.. :x */
229 iter->SetSource(NULL);
233 /* It hasn't been executed yet..just remove it */
234 iter = q.erase(iter);
241 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
242 * All SQL providers must create their own subclass and define it's methods using that
243 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
244 * of converting all data to a common format before it reaches the result structure. This way
245 * data is passes to the module nearly as directly as if it was using the API directly itself.
248 class PgSQLresult : public SQLresult
255 SQLfieldList* fieldlist;
256 SQLfieldMap* fieldmap;
258 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
259 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
261 rows = PQntuples(res);
262 cols = PQnfields(res);
264 //ServerInstance->Log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
269 /* If we allocated these, free them... */
283 return atoi(PQcmdTuples(res));
293 return PQnfields(res);
296 virtual std::string ColName(int column)
298 char* name = PQfname(res, column);
300 return (name) ? name : "";
303 virtual int ColNum(const std::string &column)
305 int n = PQfnumber(res, column.c_str());
309 throw SQLbadColName();
317 virtual SQLfield GetValue(int row, int column)
319 char* v = PQgetvalue(res, row, column);
323 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
327 //ServerInstance->Log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
328 throw SQLbadColName();
332 virtual SQLfieldList& GetRow()
334 /* In an effort to reduce overhead we don't actually allocate the list
335 * until the first time it's needed...so...
343 fieldlist = new SQLfieldList;
346 if(currentrow < PQntuples(res))
348 int cols = PQnfields(res);
350 for(int i = 0; i < cols; i++)
352 fieldlist->push_back(GetValue(currentrow, i));
361 virtual SQLfieldMap& GetRowMap()
363 /* In an effort to reduce overhead we don't actually allocate the map
364 * until the first time it's needed...so...
372 fieldmap = new SQLfieldMap;
375 if(currentrow < PQntuples(res))
377 int cols = PQnfields(res);
379 for(int i = 0; i < cols; i++)
381 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
390 virtual SQLfieldList* GetRowPtr()
392 SQLfieldList* fl = new SQLfieldList;
394 if(currentrow < PQntuples(res))
396 int cols = PQnfields(res);
398 for(int i = 0; i < cols; i++)
400 fl->push_back(GetValue(currentrow, i));
409 virtual SQLfieldMap* GetRowMapPtr()
411 SQLfieldMap* fm = new SQLfieldMap;
413 if(currentrow < PQntuples(res))
415 int cols = PQnfields(res);
417 for(int i = 0; i < cols; i++)
419 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
428 virtual void Free(SQLfieldMap* fm)
433 virtual void Free(SQLfieldList* fl)
439 /** SQLConn represents one SQL session.
440 * Each session has its own persistent connection to the database.
441 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
442 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
446 class SQLConn : public InspSocket
449 SQLhost confhost; /* The <database> entry */
450 Module* us; /* Pointer to the SQL provider itself */
451 PGconn* sql; /* PgSQL database connection handle */
452 SQLstatus status; /* PgSQL database connection status */
453 bool qinprog; /* If there is currently a query in progress */
454 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
455 time_t idle; /* Time we last heard from the database */
458 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
460 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hostinfo);
466 virtual void Close();
472 bool DoConnectedPoll();
478 virtual bool OnDataReady();
480 virtual bool OnWriteReady();
482 virtual bool OnConnected();
488 const char* StatusStr();
490 SQLerror DoQuery(SQLrequest &req);
492 SQLerror Query(const SQLrequest &req);
494 void OnUnloadModule(Module* mod);
496 const SQLhost GetConfHost();
499 SQLConn::SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
500 : InspSocket::InspSocket(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
502 idle = this->Instance->Time();
503 this->ClosePending = false;
505 if(!this->DoConnect())
507 Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
516 bool SQLConn::DoConnect()
518 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
520 Instance->Log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
525 if(PQstatus(sql) == CONNECTION_BAD)
527 Instance->Log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
534 if(PQsetnonblocking(sql, 1) == -1)
536 Instance->Log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
541 /* OK, we've initalised the connection, now to get it hooked into the socket engine
542 * and then start polling it.
545 //ServerInstance->Log(DEBUG, "Old DNS socket: %d", this->fd);
546 this->fd = PQsocket(sql);
547 Instance->Log(DEBUG, "New SQL socket: %d", this->fd);
551 Instance->Log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
556 this->state = I_CONNECTING;
557 if (!this->Instance->SE->AddFd(this))
559 Instance->Log(DEBUG, "A PQsocket cant be added to the socket engine!");
564 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
569 void SQLConn::Close() {
573 bool SQLConn::DoPoll()
575 switch(PQconnectPoll(sql))
577 case PGRES_POLLING_WRITING:
578 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
582 case PGRES_POLLING_READING:
583 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
586 case PGRES_POLLING_FAILED:
587 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
589 case PGRES_POLLING_OK:
590 //ServerInstance->Log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
592 return DoConnectedPoll();
594 //ServerInstance->Log(DEBUG, "PGconnectPoll: wtf?");
599 bool SQLConn::DoConnectedPoll()
601 if(!qinprog && queue.totalsize())
603 /* There's no query currently in progress, and there's queries in the queue. */
604 SQLrequest& query = queue.front();
608 if(PQconsumeInput(sql))
610 Instance->Log(DEBUG, "PQconsumeInput succeeded");
612 /* We just read stuff from the server, that counts as it being alive
613 * so update the idle-since time :p
615 idle = this->Instance->Time();
619 //ServerInstance->Log(DEBUG, "Still busy processing command though");
623 //ServerInstance->Log(DEBUG, "Looks like we have a result to process!");
625 /* Grab the request we're processing */
626 SQLrequest& query = queue.front();
628 Instance->Log(DEBUG, "ID is %lu", query.id);
630 /* Get a pointer to the module we're about to return the result to */
631 Module* to = query.GetSource();
633 /* Fetch the result.. */
634 PGresult* result = PQgetResult(sql);
636 /* PgSQL would allow a query string to be sent which has multiple
637 * queries in it, this isn't portable across database backends and
638 * we don't want modules doing it. But just in case we make sure we
639 * drain any results there are and just use the last one.
640 * If the module devs are behaving there will only be one result.
642 while (PGresult* temp = PQgetResult(sql))
650 /* ..and the result */
651 PgSQLresult reply(us, to, query.id, result);
653 /* Fix by brain, make sure the original query gets sent back in the reply */
654 reply.query = query.query.q;
656 Instance->Log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
658 switch(PQresultStatus(result))
660 case PGRES_EMPTY_QUERY:
661 case PGRES_BAD_RESPONSE:
662 case PGRES_FATAL_ERROR:
663 reply.error.Id(QREPLY_FAIL);
664 reply.error.Str(PQresultErrorMessage(result));
666 /* No action, other values are not errors */
671 /* PgSQLresult's destructor will free the PGresult */
675 /* If the client module is unloaded partway through a query then the provider will set
676 * the pointer to NULL. We cannot just cancel the query as the result will still come
677 * through at some point...and it could get messy if we play with invalid pointers...
679 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);
689 Instance->Log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
696 /* I think we'll assume this means the server died...it might not,
697 * but I think that any error serious enough we actually get here
698 * deserves to reconnect [/excuse]
699 * Returning true so the core doesn't try and close the connection.
701 Instance->Log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
707 bool SQLConn::DoResetPoll()
709 switch(PQresetPoll(sql))
711 case PGRES_POLLING_WRITING:
712 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
716 case PGRES_POLLING_READING:
717 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
720 case PGRES_POLLING_FAILED:
721 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
723 case PGRES_POLLING_OK:
724 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
726 return DoConnectedPoll();
728 //ServerInstance->Log(DEBUG, "PGresetPoll: wtf?");
733 void SQLConn::ShowStatus()
735 switch(PQstatus(sql))
737 case CONNECTION_STARTED:
738 Instance->Log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
741 case CONNECTION_MADE:
742 Instance->Log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
745 case CONNECTION_AWAITING_RESPONSE:
746 Instance->Log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
749 case CONNECTION_AUTH_OK:
750 Instance->Log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
753 case CONNECTION_SSL_STARTUP:
754 Instance->Log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
757 case CONNECTION_SETENV:
758 Instance->Log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
762 Instance->Log(DEBUG, "PQstatus: ???");
766 bool SQLConn::OnDataReady()
768 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
769 Instance->Log(DEBUG, "OnDataReady(): status = %s", StatusStr());
774 bool SQLConn::OnWriteReady()
776 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
777 Instance->Log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
782 bool SQLConn::OnConnected()
784 Instance->Log(DEBUG, "OnConnected(): status = %s", StatusStr());
789 bool SQLConn::Reconnect()
791 Instance->Log(DEBUG, "Initiating reconnect");
793 if(PQresetStart(sql))
795 /* Successfully initiatied database reconnect,
796 * set flags so PQresetPoll() will be called appropriately
804 Instance->Log(DEBUG, "Failed to initiate reconnect...fun");
809 bool SQLConn::DoEvent()
813 if((status == CREAD) || (status == CWRITE))
817 else if((status == RREAD) || (status == RWRITE))
823 ret = DoConnectedPoll();
829 Instance->Log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
832 Instance->Log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
835 Instance->Log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
843 const char* SQLConn::StatusStr()
845 if(status == CREAD) return "CREAD";
846 if(status == CWRITE) return "CWRITE";
847 if(status == WREAD) return "WREAD";
848 if(status == WWRITE) return "WWRITE";
849 return "Err...what, erm..BUG!";
852 SQLerror SQLConn::DoQuery(SQLrequest &req)
854 if((status == WREAD) || (status == WWRITE))
858 /* Parse the command string and dispatch it */
860 /* Pointer to the buffer we screw around with substitution in */
862 /* Pointer to the current end of query, where we append new stuff */
864 /* Total length of the unescaped parameters */
865 unsigned int paramlen;
869 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
871 paramlen += i->size();
874 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
875 * sizeofquery + (totalparamlength*2) + 1
877 * The +1 is for null-terminating the string for PQsendQuery()
880 query = new char[req.query.q.length() + (paramlen*2) + 1];
883 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
884 * the parameters into it...
887 for(unsigned int i = 0; i < req.query.q.length(); i++)
889 if(req.query.q[i] == '?')
891 /* We found a place to substitute..what fun.
892 * Use the PgSQL calls to escape and write the
893 * escaped string onto the end of our query buffer,
894 * then we "just" need to make sure queryend is
895 * pointing at the right place.
898 if(req.query.p.size())
903 #ifdef PGSQL_HAS_ESCAPECONN
904 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
906 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
910 Instance->Log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
913 Instance->Log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
915 /* Incremenet queryend to the end of the newly escaped parameter */
918 /* Remove the parameter we just substituted in */
919 req.query.p.pop_front();
923 Instance->Log(DEBUG, "Found a substitution location but no parameter to substitute :|");
929 *queryend = req.query.q[i];
934 /* Null-terminate the query */
937 Instance->Log(DEBUG, "Attempting to dispatch query: %s", query);
941 if(PQsendQuery(sql, query))
943 Instance->Log(DEBUG, "Dispatched query successfully");
950 Instance->Log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
952 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
957 return SQLerror(BAD_CONN, "Can't query until connection is complete");
960 SQLerror SQLConn::Query(const SQLrequest &req)
964 if(!qinprog && queue.totalsize())
966 /* There's no query currently in progress, and there's queries in the queue. */
967 SQLrequest& query = queue.front();
968 return DoQuery(query);
976 void SQLConn::OnUnloadModule(Module* mod)
978 queue.PurgeModule(mod);
981 const SQLhost SQLConn::GetConfHost()
986 class ModulePgSQL : public Module
991 ConnMap deadconnections;
992 unsigned long currid;
996 ModulePgSQL(InspIRCd* Me)
997 : Module::Module(Me), currid(0)
999 ServerInstance->UseInterface("SQLutils");
1001 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
1003 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
1005 if (!ServerInstance->PublishFeature("SQL", this))
1007 throw ModuleException("m_pgsql: Unable to publish feature 'SQL'");
1012 ServerInstance->PublishInterface("SQL", this);
1015 virtual ~ModulePgSQL()
1017 ClearAllConnections();
1018 delete[] sqlsuccess;
1019 ServerInstance->UnpublishInterface("SQL", this);
1020 ServerInstance->UnpublishFeature("SQL");
1021 ServerInstance->DoneWithInterface("SQLutils");
1024 void Implements(char* List)
1026 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
1029 virtual void OnRehash(userrec* user, const std::string ¶meter)
1034 bool HasHost(const SQLhost &host)
1036 ClearDeadConnections();
1037 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1039 if (host == iter->second->GetConfHost())
1045 bool HostInConf(const SQLhost &h)
1047 ClearDeadConnections();
1048 ConfigReader conf(ServerInstance);
1049 for(int i = 0; i < conf.Enumerate("database"); i++)
1052 host.id = conf.ReadValue("database", "id", i);
1053 host.host = conf.ReadValue("database", "hostname", i);
1054 host.port = conf.ReadInteger("database", "port", i, true);
1055 host.name = conf.ReadValue("database", "name", i);
1056 host.user = conf.ReadValue("database", "username", i);
1057 host.pass = conf.ReadValue("database", "password", i);
1058 host.ssl = conf.ReadFlag("database", "ssl", i);
1067 ClearDeadConnections();
1068 ConfigReader conf(ServerInstance);
1070 for(int i = 0; i < conf.Enumerate("database"); i++)
1074 insp_inaddr blargle;
1076 host.id = conf.ReadValue("database", "id", i);
1077 host.host = conf.ReadValue("database", "hostname", i);
1078 host.port = conf.ReadInteger("database", "port", i, true);
1079 host.name = conf.ReadValue("database", "name", i);
1080 host.user = conf.ReadValue("database", "username", i);
1081 host.pass = conf.ReadValue("database", "password", i);
1082 host.ssl = conf.ReadFlag("database", "ssl", i);
1087 ipvalid = insp_aton(host.host.c_str(), &blargle);
1091 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1092 host.ip = host.host;
1093 this->AddConn(host);
1095 else if(ipvalid == 0)
1097 /* Conversion failed, assume it's a host */
1098 SQLresolver* resolver;
1102 resolver = new SQLresolver(this, ServerInstance, host);
1104 ServerInstance->AddResolver(resolver);
1108 /* THE WORLD IS COMING TO AN END! */
1109 ServerInstance->Log(DEBUG, "Couldn't make a SQLresolver..this connection is gonna diiiiiie...actually we just won't create it");
1114 /* Invalid address family, die horribly. */
1115 ServerInstance->Log(DEBUG, "insp_aton failed returning -1, oh noes.");
1118 ClearOldConnections();
1121 void ClearOldConnections()
1123 ClearDeadConnections();
1124 ConnMap::iterator iter,safei;
1125 for (iter = connections.begin(); iter != connections.end(); iter++)
1127 if (!HostInConf(iter->second->GetConfHost()))
1129 delete iter->second;
1132 connections.erase(safei);
1137 void ClearAllConnections()
1139 ClearDeadConnections();
1140 ConnMap::iterator iter;
1141 while ((iter = connections.begin()) != connections.end())
1143 connections.erase(iter);
1144 delete iter->second;
1148 void ClearDeadConnections()
1150 ConnMap::iterator di;
1151 while ((di = deadconnections.begin()) != deadconnections.end())
1153 ConnMap::iterator iter = connections.find(di->first);
1154 if (iter != connections.end())
1156 connections.erase(iter);
1158 deadconnections.erase(di);
1162 void AddDeadConn(std::string id, SQLConn* conn)
1164 deadconnections[id] = conn;
1167 void AddConn(const SQLhost& hi)
1171 ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
1177 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1178 newconn = new SQLConn(ServerInstance, this, hi);
1180 connections.insert(std::make_pair(hi.id, newconn));
1183 virtual char* OnRequest(Request* request)
1185 if(strcmp(SQLREQID, request->GetId()) == 0)
1187 SQLrequest* req = (SQLrequest*)request;
1188 ConnMap::iterator iter;
1190 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());
1192 if((iter = connections.find(req->dbid)) != connections.end())
1196 req->error = iter->second->Query(*req);
1198 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
1202 req->error.Id(BAD_DBID);
1207 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
1212 virtual void OnUnloadModule(Module* mod, const std::string& name)
1214 /* When a module unloads we have to check all the pending queries for all our connections
1215 * and set the Module* specifying where the query came from to NULL. If the query has already
1216 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1218 * If the queries we find are not already being executed then we can simply remove them immediately.
1220 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1222 iter->second->OnUnloadModule(mod);
1226 unsigned long NewID()
1234 virtual Version GetVersion()
1236 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1240 /* move this here to use AddConn, rather that than having the whole
1241 * module above SQLConn, since this is buggin me right now :/
1243 void SQLresolver::OnLookupComplete(const std::string &result)
1246 ((ModulePgSQL*)mod)->AddConn(host);
1247 ((ModulePgSQL*)mod)->ClearOldConnections();
1250 /* move this here too, to use AddDeadConn */
1251 void SQLConn::DoClose()
1253 Instance->Log(DEBUG,"SQLConn::Close");
1255 if (!this->Instance->SE->DelFd(this))
1257 Instance->Log(DEBUG, "PQsocket cant be removed from the socket engine!");
1260 this->state = I_ERROR;
1261 this->OnError(I_ERR_SOCKET);
1262 this->ClosePending = true;
1270 ((ModulePgSQL*)us)->AddDeadConn(confhost.id, this);
1273 class ModulePgSQLFactory : public ModuleFactory
1276 ModulePgSQLFactory()
1280 ~ModulePgSQLFactory()
1284 virtual Module * CreateModule(InspIRCd* Me)
1286 return new ModulePgSQL(Me);
1291 extern "C" void * init_module( void )
1293 // PQregisterThreadLock(pgthreadlock_t(1));
1294 return new ModulePgSQLFactory;