]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_pgsql.cpp
Mass comment removal.
[user/henk/code/inspircd.git] / src / modules / extra / m_pgsql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include <cstdlib>
15 #include <sstream>
16 #include <string>
17 #include <deque>
18 #include <map>
19 #include <libpq-fe.h>
20
21 #include "users.h"
22 #include "channels.h"
23 #include "modules.h"
24
25 #include "inspircd.h"
26 #include "configreader.h"
27
28 #include "m_sqlv2.h"
29
30 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
31 /* $CompileFlags: -Iexec("pg_config --includedir") eval("my $s = `pg_config --version`;$s =~ /^.*?(\d+)\.(\d+)\.(\d+).*?$/;my $v = hex(sprintf("0x%02x%02x%02x", $1, $2, $3));print "-DPGSQL_HAS_ESCAPECONN" if(($v >= 0x080104) or (($v >= 0x07030F) and ($v < 0x080000)));") */
32 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
33 /* $ModDep: m_sqlv2.h */
34
35
36 /* SQLConn rewritten by peavey to
37  * use EventHandler instead of
38  * InspSocket. This is much neater
39  * and gives total control of destroy
40  * and delete of resources.
41  */
42
43 /* Forward declare, so we can have the typedef neatly at the top */
44 class SQLConn;
45
46 typedef std::map<std::string, SQLConn*> ConnMap;
47
48 /* CREAD,       Connecting and wants read event
49  * CWRITE,      Connecting and wants write event
50  * WREAD,       Connected/Working and wants read event
51  * WWRITE,      Connected/Working and wants write event
52  * RREAD,       Resetting and wants read event
53  * RWRITE,      Resetting and wants write event
54  */
55 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
56
57 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
58  */
59 std::string SQLhost::GetDSN()
60 {
61         std::ostringstream conninfo("connect_timeout = '2'");
62
63         if (ip.length())
64                 conninfo << " hostaddr = '" << ip << "'";
65
66         if (port)
67                 conninfo << " port = '" << port << "'";
68
69         if (name.length())
70                 conninfo << " dbname = '" << name << "'";
71
72         if (user.length())
73                 conninfo << " user = '" << user << "'";
74
75         if (pass.length())
76                 conninfo << " password = '" << pass << "'";
77
78         if (ssl)
79         {
80                 conninfo << " sslmode = 'require'";
81         }
82         else
83         {
84                 conninfo << " sslmode = 'disable'";
85         }
86
87         return conninfo.str();
88 }
89
90 class ReconnectTimer : public InspTimer
91 {
92   private:
93         Module* mod;
94   public:
95         ReconnectTimer(InspIRCd* SI, Module* m)
96         : InspTimer(5, SI->Time(), false), mod(m)
97         {
98         }
99         virtual void Tick(time_t TIME);
100 };
101
102
103 /** Used to resolve sql server hostnames
104  */
105 class SQLresolver : public Resolver
106 {
107  private:
108         SQLhost host;
109         Module* mod;
110  public:
111         SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
112         : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
113         {
114         }
115
116         virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached);
117
118         virtual void OnError(ResolverError e, const std::string &errormessage)
119         {
120                 ServerInstance->Log(DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str());
121         }
122 };
123
124 /** QueryQueue, a queue of queries waiting to be executed.
125  * This maintains two queues internally, one for 'priority'
126  * queries and one for less important ones. Each queue has
127  * new queries appended to it and ones to execute are popped
128  * off the front. This keeps them flowing round nicely and no
129  * query should ever get 'stuck' for too long. If there are
130  * queries in the priority queue they will be executed first,
131  * 'unimportant' queries will only be executed when the
132  * priority queue is empty.
133  *
134  * We store lists of SQLrequest's here, by value as we want to avoid storing
135  * any data allocated inside the client module (in case that module is unloaded
136  * while the query is in progress).
137  *
138  * Because we want to work on the current SQLrequest in-situ, we need a way
139  * of accessing the request we are currently processing, QueryQueue::front(),
140  * but that call needs to always return the same request until that request
141  * is removed from the queue, this is what the 'which' variable is. New queries are
142  * always added to the back of one of the two queues, but if when front()
143  * is first called then the priority queue is empty then front() will return
144  * a query from the normal queue, but if a query is then added to the priority
145  * queue then front() must continue to return the front of the *normal* queue
146  * until pop() is called.
147  */
148
149 class QueryQueue : public classbase
150 {
151 private:
152         typedef std::deque<SQLrequest> ReqDeque;
153
154         ReqDeque priority;      /* The priority queue */
155         ReqDeque normal;        /* The 'normal' queue */
156         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
157
158 public:
159         QueryQueue()
160         : which(NON)
161         {
162         }
163
164         void push(const SQLrequest &q)
165         {
166                 if(q.pri)
167                         priority.push_back(q);
168                 else
169                         normal.push_back(q);
170         }
171
172         void pop()
173         {
174                 if((which == PRI) && priority.size())
175                 {
176                         priority.pop_front();
177                 }
178                 else if((which == NOR) && normal.size())
179                 {
180                         normal.pop_front();
181                 }
182
183                 /* Reset this */
184                 which = NON;
185
186                 /* Silently do nothing if there was no element to pop() */
187         }
188
189         SQLrequest& front()
190         {
191                 switch(which)
192                 {
193                         case PRI:
194                                 return priority.front();
195                         case NOR:
196                                 return normal.front();
197                         default:
198                                 if(priority.size())
199                                 {
200                                         which = PRI;
201                                         return priority.front();
202                                 }
203
204                                 if(normal.size())
205                                 {
206                                         which = NOR;
207                                         return normal.front();
208                                 }
209
210                                 /* This will probably result in a segfault,
211                                  * but the caller should have checked totalsize()
212                                  * first so..meh - moron :p
213                                  */
214
215                                 return priority.front();
216                 }
217         }
218
219         std::pair<int, int> size()
220         {
221                 return std::make_pair(priority.size(), normal.size());
222         }
223
224         int totalsize()
225         {
226                 return priority.size() + normal.size();
227         }
228
229         void PurgeModule(Module* mod)
230         {
231                 DoPurgeModule(mod, priority);
232                 DoPurgeModule(mod, normal);
233         }
234
235 private:
236         void DoPurgeModule(Module* mod, ReqDeque& q)
237         {
238                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
239                 {
240                         if(iter->GetSource() == mod)
241                         {
242                                 if(iter->id == front().id)
243                                 {
244                                         /* It's the currently active query.. :x */
245                                         iter->SetSource(NULL);
246                                 }
247                                 else
248                                 {
249                                         /* It hasn't been executed yet..just remove it */
250                                         iter = q.erase(iter);
251                                 }
252                         }
253                 }
254         }
255 };
256
257 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
258  * All SQL providers must create their own subclass and define it's methods using that
259  * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
260  * of converting all data to a common format before it reaches the result structure. This way
261  * data is passes to the module nearly as directly as if it was using the API directly itself.
262  */
263
264 class PgSQLresult : public SQLresult
265 {
266         PGresult* res;
267         int currentrow;
268         int rows;
269         int cols;
270
271         SQLfieldList* fieldlist;
272         SQLfieldMap* fieldmap;
273 public:
274         PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
275         : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
276         {
277                 rows = PQntuples(res);
278                 cols = PQnfields(res);
279         }
280
281         ~PgSQLresult()
282         {
283                 /* If we allocated these, free them... */
284                 if(fieldlist)
285                         DELETE(fieldlist);
286
287                 if(fieldmap)
288                         DELETE(fieldmap);
289
290                 PQclear(res);
291         }
292
293         virtual int Rows()
294         {
295                 if(!cols && !rows)
296                 {
297                         return atoi(PQcmdTuples(res));
298                 }
299                 else
300                 {
301                         return rows;
302                 }
303         }
304
305         virtual int Cols()
306         {
307                 return PQnfields(res);
308         }
309
310         virtual std::string ColName(int column)
311         {
312                 char* name = PQfname(res, column);
313
314                 return (name) ? name : "";
315         }
316
317         virtual int ColNum(const std::string &column)
318         {
319                 int n = PQfnumber(res, column.c_str());
320
321                 if(n == -1)
322                 {
323                         throw SQLbadColName();
324                 }
325                 else
326                 {
327                         return n;
328                 }
329         }
330
331         virtual SQLfield GetValue(int row, int column)
332         {
333                 char* v = PQgetvalue(res, row, column);
334
335                 if(v)
336                 {
337                         return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
338                 }
339                 else
340                 {
341                         throw SQLbadColName();
342                 }
343         }
344
345         virtual SQLfieldList& GetRow()
346         {
347                 /* In an effort to reduce overhead we don't actually allocate the list
348                  * until the first time it's needed...so...
349                  */
350                 if(fieldlist)
351                 {
352                         fieldlist->clear();
353                 }
354                 else
355                 {
356                         fieldlist = new SQLfieldList;
357                 }
358
359                 if(currentrow < PQntuples(res))
360                 {
361                         int cols = PQnfields(res);
362
363                         for(int i = 0; i < cols; i++)
364                         {
365                                 fieldlist->push_back(GetValue(currentrow, i));
366                         }
367
368                         currentrow++;
369                 }
370
371                 return *fieldlist;
372         }
373
374         virtual SQLfieldMap& GetRowMap()
375         {
376                 /* In an effort to reduce overhead we don't actually allocate the map
377                  * until the first time it's needed...so...
378                  */
379                 if(fieldmap)
380                 {
381                         fieldmap->clear();
382                 }
383                 else
384                 {
385                         fieldmap = new SQLfieldMap;
386                 }
387
388                 if(currentrow < PQntuples(res))
389                 {
390                         int cols = PQnfields(res);
391
392                         for(int i = 0; i < cols; i++)
393                         {
394                                 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
395                         }
396
397                         currentrow++;
398                 }
399
400                 return *fieldmap;
401         }
402
403         virtual SQLfieldList* GetRowPtr()
404         {
405                 SQLfieldList* fl = new SQLfieldList;
406
407                 if(currentrow < PQntuples(res))
408                 {
409                         int cols = PQnfields(res);
410
411                         for(int i = 0; i < cols; i++)
412                         {
413                                 fl->push_back(GetValue(currentrow, i));
414                         }
415
416                         currentrow++;
417                 }
418
419                 return fl;
420         }
421
422         virtual SQLfieldMap* GetRowMapPtr()
423         {
424                 SQLfieldMap* fm = new SQLfieldMap;
425
426                 if(currentrow < PQntuples(res))
427                 {
428                         int cols = PQnfields(res);
429
430                         for(int i = 0; i < cols; i++)
431                         {
432                                 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
433                         }
434
435                         currentrow++;
436                 }
437
438                 return fm;
439         }
440
441         virtual void Free(SQLfieldMap* fm)
442         {
443                 DELETE(fm);
444         }
445
446         virtual void Free(SQLfieldList* fl)
447         {
448                 DELETE(fl);
449         }
450 };
451
452 /** SQLConn represents one SQL session.
453  */
454 class SQLConn : public EventHandler
455 {
456   private:
457         InspIRCd*               Instance;
458         SQLhost                 confhost;       /* The <database> entry */
459         Module*                 us;                     /* Pointer to the SQL provider itself */
460         PGconn*                 sql;            /* PgSQL database connection handle */
461         SQLstatus               status;         /* PgSQL database connection status */
462         bool                    qinprog;        /* If there is currently a query in progress */
463         QueryQueue              queue;          /* Queue of queries waiting to be executed on this connection */
464         time_t                  idle;           /* Time we last heard from the database */
465
466   public:
467         SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
468         : EventHandler(), Instance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
469         {
470                 idle = this->Instance->Time();
471                 if(!DoConnect())
472                 {
473                         Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
474                         DelayReconnect();
475                 }
476         }
477
478         ~SQLConn()
479         {
480                 Close();
481         }
482
483         virtual void HandleEvent(EventType et, int errornum)
484         {
485                 switch (et)
486                 {
487                         case EVENT_READ:
488                                 OnDataReady();
489                         break;
490
491                         case EVENT_WRITE:
492                                 OnWriteReady();
493                         break;
494
495                         case EVENT_ERROR:
496                                 DelayReconnect();
497                         break;
498
499                         default:
500                         break;
501                 }
502         }
503
504         bool DoConnect()
505         {
506                 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
507                         return false;
508
509                 if(PQstatus(sql) == CONNECTION_BAD)
510                         return false;
511
512                 if(PQsetnonblocking(sql, 1) == -1)
513                         return false;
514
515                 /* OK, we've initalised the connection, now to get it hooked into the socket engine
516                 * and then start polling it.
517                 */
518                 this->fd = PQsocket(sql);
519
520                 if(this->fd <= -1)
521                         return false;
522
523                 if (!this->Instance->SE->AddFd(this))
524                 {
525                         Instance->Log(DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
526                         return false;
527                 }
528
529                 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
530                 return DoPoll();
531         }
532
533         bool DoPoll()
534         {
535                 switch(PQconnectPoll(sql))
536                 {
537                         case PGRES_POLLING_WRITING:
538                                 Instance->SE->WantWrite(this);
539                                 status = CWRITE;
540                                 return true;
541                         case PGRES_POLLING_READING:
542                                 status = CREAD;
543                                 return true;
544                         case PGRES_POLLING_FAILED:
545                                 return false;
546                         case PGRES_POLLING_OK:
547                                 status = WWRITE;
548                                 return DoConnectedPoll();
549                         default:
550                                 return true;
551                 }
552         }
553
554         bool DoConnectedPoll()
555         {
556                 if(!qinprog && queue.totalsize())
557                 {
558                         /* There's no query currently in progress, and there's queries in the queue. */
559                         SQLrequest& query = queue.front();
560                         DoQuery(query);
561                 }
562
563                 if(PQconsumeInput(sql))
564                 {
565                         /* We just read stuff from the server, that counts as it being alive
566                          * so update the idle-since time :p
567                          */
568                         idle = this->Instance->Time();
569
570                         if (PQisBusy(sql))
571                         {
572                                 /* Nothing happens here */
573                         }
574                         else if (qinprog)
575                         {
576                                 /* Grab the request we're processing */
577                                 SQLrequest& query = queue.front();
578
579                                 /* Get a pointer to the module we're about to return the result to */
580                                 Module* to = query.GetSource();
581
582                                 /* Fetch the result.. */
583                                 PGresult* result = PQgetResult(sql);
584
585                                 /* PgSQL would allow a query string to be sent which has multiple
586                                  * queries in it, this isn't portable across database backends and
587                                  * we don't want modules doing it. But just in case we make sure we
588                                  * drain any results there are and just use the last one.
589                                  * If the module devs are behaving there will only be one result.
590                                  */
591                                 while (PGresult* temp = PQgetResult(sql))
592                                 {
593                                         PQclear(result);
594                                         result = temp;
595                                 }
596
597                                 if(to)
598                                 {
599                                         /* ..and the result */
600                                         PgSQLresult reply(us, to, query.id, result);
601
602                                         /* Fix by brain, make sure the original query gets sent back in the reply */
603                                         reply.query = query.query.q;
604
605                                         switch(PQresultStatus(result))
606                                         {
607                                                 case PGRES_EMPTY_QUERY:
608                                                 case PGRES_BAD_RESPONSE:
609                                                 case PGRES_FATAL_ERROR:
610                                                         reply.error.Id(QREPLY_FAIL);
611                                                         reply.error.Str(PQresultErrorMessage(result));
612                                                 default:;
613                                                         /* No action, other values are not errors */
614                                         }
615
616                                         reply.Send();
617
618                                         /* PgSQLresult's destructor will free the PGresult */
619                                 }
620                                 else
621                                 {
622                                         /* If the client module is unloaded partway through a query then the provider will set
623                                          * the pointer to NULL. We cannot just cancel the query as the result will still come
624                                          * through at some point...and it could get messy if we play with invalid pointers...
625                                          */
626                                         PQclear(result);
627                                 }
628                                 qinprog = false;
629                                 queue.pop();
630                                 DoConnectedPoll();
631                         }
632                         return true;
633                 }
634                 else
635                 {
636                         /* I think we'll assume this means the server died...it might not,
637                          * but I think that any error serious enough we actually get here
638                          * deserves to reconnect [/excuse]
639                          * Returning true so the core doesn't try and close the connection.
640                          */
641                         DelayReconnect();
642                         return true;
643                 }
644         }
645
646         bool DoResetPoll()
647         {
648                 switch(PQresetPoll(sql))
649                 {
650                         case PGRES_POLLING_WRITING:
651                                 Instance->SE->WantWrite(this);
652                                 status = CWRITE;
653                                 return DoPoll();
654                         case PGRES_POLLING_READING:
655                                 status = CREAD;
656                                 return true;
657                         case PGRES_POLLING_FAILED:
658                                 return false;
659                         case PGRES_POLLING_OK:
660                                 status = WWRITE;
661                                 return DoConnectedPoll();
662                         default:
663                                 return true;
664                 }
665         }
666
667         bool OnDataReady()
668         {
669                 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
670                 return DoEvent();
671         }
672
673         bool OnWriteReady()
674         {
675                 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
676                 return DoEvent();
677         }
678
679         bool OnConnected()
680         {
681                 return DoEvent();
682         }
683
684         void DelayReconnect();
685
686         bool DoEvent()
687         {
688                 bool ret;
689
690                 if((status == CREAD) || (status == CWRITE))
691                 {
692                         ret = DoPoll();
693                 }
694                 else if((status == RREAD) || (status == RWRITE))
695                 {
696                         ret = DoResetPoll();
697                 }
698                 else
699                 {
700                         ret = DoConnectedPoll();
701                 }
702                 return ret;
703         }
704
705         SQLerror DoQuery(SQLrequest &req)
706         {
707                 if((status == WREAD) || (status == WWRITE))
708                 {
709                         if(!qinprog)
710                         {
711                                 /* Parse the command string and dispatch it */
712
713                                 /* Pointer to the buffer we screw around with substitution in */
714                                 char* query;
715                                 /* Pointer to the current end of query, where we append new stuff */
716                                 char* queryend;
717                                 /* Total length of the unescaped parameters */
718                                 unsigned int paramlen;
719
720                                 paramlen = 0;
721
722                                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
723                                 {
724                                         paramlen += i->size();
725                                 }
726
727                                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
728                                  * sizeofquery + (totalparamlength*2) + 1
729                                  *
730                                  * The +1 is for null-terminating the string for PQsendQuery()
731                                  */
732
733                                 query = new char[req.query.q.length() + (paramlen*2) + 1];
734                                 queryend = query;
735
736                                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
737                                  * the parameters into it...
738                                  */
739
740                                 for(unsigned int i = 0; i < req.query.q.length(); i++)
741                                 {
742                                         if(req.query.q[i] == '?')
743                                         {
744                                                 /* We found a place to substitute..what fun.
745                                                  * Use the PgSQL calls to escape and write the
746                                                  * escaped string onto the end of our query buffer,
747                                                  * then we "just" need to make sure queryend is
748                                                  * pointing at the right place.
749                                                  */
750
751                                                 if(req.query.p.size())
752                                                 {
753                                                         int error = 0;
754                                                         size_t len = 0;
755
756 #ifdef PGSQL_HAS_ESCAPECONN
757                                                         len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
758 #else
759                                                         len = PQescapeString         (queryend, req.query.p.front().c_str(), req.query.p.front().length());
760 #endif
761                                                         if(error)
762                                                         {
763                                                                 Instance->Log(DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
764                                                         }
765
766                                                         /* Incremenet queryend to the end of the newly escaped parameter */
767                                                         queryend += len;
768
769                                                         /* Remove the parameter we just substituted in */
770                                                         req.query.p.pop_front();
771                                                 }
772                                                 else
773                                                 {
774                                                         Instance->Log(DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
775                                                         break;
776                                                 }
777                                         }
778                                         else
779                                         {
780                                                 *queryend = req.query.q[i];
781                                                 queryend++;
782                                         }
783                                 }
784
785                                 /* Null-terminate the query */
786                                 *queryend = 0;
787                                 req.query.q = query;
788
789                                 if(PQsendQuery(sql, query))
790                                 {
791                                         qinprog = true;
792                                         delete[] query;
793                                         return SQLerror();
794                                 }
795                                 else
796                                 {
797                                         delete[] query;
798                                         return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
799                                 }
800                         }
801                 }
802                 return SQLerror(BAD_CONN, "Can't query until connection is complete");
803         }
804
805         SQLerror Query(const SQLrequest &req)
806         {
807                 queue.push(req);
808
809                 if(!qinprog && queue.totalsize())
810                 {
811                         /* There's no query currently in progress, and there's queries in the queue. */
812                         SQLrequest& query = queue.front();
813                         return DoQuery(query);
814                 }
815                 else
816                 {
817                         return SQLerror();
818                 }
819         }
820
821         void OnUnloadModule(Module* mod)
822         {
823                 queue.PurgeModule(mod);
824         }
825
826         const SQLhost GetConfHost()
827         {
828                 return confhost;
829         }
830
831         void Close() {
832                 if (!this->Instance->SE->DelFd(this))
833                 {
834                         if (sql && PQstatus(sql) == CONNECTION_BAD)
835                         {
836                                 this->Instance->SE->DelFd(this, true);
837                         }
838                         else
839                         {
840                                 Instance->Log(DEBUG, "BUG: PQsocket cant be removed from socket engine!");
841                         }
842                 }
843
844                 if(sql)
845                 {
846                         PQfinish(sql);
847                         sql = NULL;
848                 }
849         }
850
851 };
852
853 class ModulePgSQL : public Module
854 {
855   private:
856         ConnMap connections;
857         unsigned long currid;
858         char* sqlsuccess;
859         ReconnectTimer* retimer;
860
861   public:
862         ModulePgSQL(InspIRCd* Me)
863         : Module::Module(Me), currid(0)
864         {
865                 ServerInstance->UseInterface("SQLutils");
866
867                 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
868
869                 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
870
871                 if (!ServerInstance->PublishFeature("SQL", this))
872                 {
873                         throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'");
874                 }
875
876                 ReadConf();
877
878                 ServerInstance->PublishInterface("SQL", this);
879         }
880
881         virtual ~ModulePgSQL()
882         {
883                 if (retimer)
884                         ServerInstance->Timers->DelTimer(retimer);
885                 ClearAllConnections();
886                 delete[] sqlsuccess;
887                 ServerInstance->UnpublishInterface("SQL", this);
888                 ServerInstance->UnpublishFeature("SQL");
889                 ServerInstance->DoneWithInterface("SQLutils");
890         }
891
892         void Implements(char* List)
893         {
894                 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
895         }
896
897         virtual void OnRehash(userrec* user, const std::string &parameter)
898         {
899                 ReadConf();
900         }
901
902         bool HasHost(const SQLhost &host)
903         {
904                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
905                 {
906                         if (host == iter->second->GetConfHost())
907                                 return true;
908                 }
909                 return false;
910         }
911
912         bool HostInConf(const SQLhost &h)
913         {
914                 ConfigReader conf(ServerInstance);
915                 for(int i = 0; i < conf.Enumerate("database"); i++)
916                 {
917                         SQLhost host;
918                         host.id         = conf.ReadValue("database", "id", i);
919                         host.host       = conf.ReadValue("database", "hostname", i);
920                         host.port       = conf.ReadInteger("database", "port", i, true);
921                         host.name       = conf.ReadValue("database", "name", i);
922                         host.user       = conf.ReadValue("database", "username", i);
923                         host.pass       = conf.ReadValue("database", "password", i);
924                         host.ssl        = conf.ReadFlag("database", "ssl", "0", i);
925                         if (h == host)
926                                 return true;
927                 }
928                 return false;
929         }
930
931         void ReadConf()
932         {
933                 ClearOldConnections();
934
935                 ConfigReader conf(ServerInstance);
936                 for(int i = 0; i < conf.Enumerate("database"); i++)
937                 {
938                         SQLhost host;
939                         int ipvalid;
940                         insp_inaddr blargle;
941
942                         host.id         = conf.ReadValue("database", "id", i);
943                         host.host       = conf.ReadValue("database", "hostname", i);
944                         host.port       = conf.ReadInteger("database", "port", i, true);
945                         host.name       = conf.ReadValue("database", "name", i);
946                         host.user       = conf.ReadValue("database", "username", i);
947                         host.pass       = conf.ReadValue("database", "password", i);
948                         host.ssl        = conf.ReadFlag("database", "ssl", "0", i);
949
950                         if (HasHost(host))
951                                 continue;
952
953                         ipvalid = insp_aton(host.host.c_str(), &blargle);
954
955                         if(ipvalid > 0)
956                         {
957                                 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
958                                 host.ip = host.host;
959                                 this->AddConn(host);
960                         }
961                         else if(ipvalid == 0)
962                         {
963                                 /* Conversion failed, assume it's a host */
964                                 SQLresolver* resolver;
965
966                                 try
967                                 {
968                                         bool cached;
969                                         resolver = new SQLresolver(this, ServerInstance, host, cached);
970                                         ServerInstance->AddResolver(resolver, cached);
971                                 }
972                                 catch(...)
973                                 {
974                                         /* THE WORLD IS COMING TO AN END! */
975                                 }
976                         }
977                         else
978                         {
979                                 /* Invalid address family, die horribly. */
980                                 ServerInstance->Log(DEBUG, "BUG: insp_aton failed returning -1, oh noes.");
981                         }
982                 }
983         }
984
985         void ClearOldConnections()
986         {
987                 ConnMap::iterator iter,safei;
988                 for (iter = connections.begin(); iter != connections.end(); iter++)
989                 {
990                         if (!HostInConf(iter->second->GetConfHost()))
991                         {
992                                 DELETE(iter->second);
993                                 safei = iter;
994                                 --iter;
995                                 connections.erase(safei);
996                         }
997                 }
998         }
999
1000         void ClearAllConnections()
1001         {
1002                 ConnMap::iterator i;
1003                 while ((i = connections.begin()) != connections.end())
1004                 {
1005                         connections.erase(i);
1006                         DELETE(i->second);
1007                 }
1008         }
1009
1010         void AddConn(const SQLhost& hi)
1011         {
1012                 if (HasHost(hi))
1013                 {
1014                         ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
1015                         return;
1016                 }
1017
1018                 SQLConn* newconn;
1019
1020                 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1021                 newconn = new SQLConn(ServerInstance, this, hi);
1022
1023                 connections.insert(std::make_pair(hi.id, newconn));
1024         }
1025
1026         void ReconnectConn(SQLConn* conn)
1027         {
1028                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1029                 {
1030                         if (conn == iter->second)
1031                         {
1032                                 DELETE(iter->second);
1033                                 connections.erase(iter);
1034                                 break;
1035                         }
1036                 }
1037                 retimer = new ReconnectTimer(ServerInstance, this);
1038                 ServerInstance->Timers->AddTimer(retimer);
1039         }
1040
1041         virtual char* OnRequest(Request* request)
1042         {
1043                 if(strcmp(SQLREQID, request->GetId()) == 0)
1044                 {
1045                         SQLrequest* req = (SQLrequest*)request;
1046                         ConnMap::iterator iter;
1047                         if((iter = connections.find(req->dbid)) != connections.end())
1048                         {
1049                                 /* Execute query */
1050                                 req->id = NewID();
1051                                 req->error = iter->second->Query(*req);
1052
1053                                 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
1054                         }
1055                         else
1056                         {
1057                                 req->error.Id(BAD_DBID);
1058                                 return NULL;
1059                         }
1060                 }
1061                 return NULL;
1062         }
1063
1064         virtual void OnUnloadModule(Module* mod, const std::string&     name)
1065         {
1066                 /* When a module unloads we have to check all the pending queries for all our connections
1067                  * and set the Module* specifying where the query came from to NULL. If the query has already
1068                  * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1069                  *
1070                  * If the queries we find are not already being executed then we can simply remove them immediately.
1071                  */
1072                 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1073                 {
1074                         iter->second->OnUnloadModule(mod);
1075                 }
1076         }
1077
1078         unsigned long NewID()
1079         {
1080                 if (currid+1 == 0)
1081                         currid++;
1082
1083                 return ++currid;
1084         }
1085
1086         virtual Version GetVersion()
1087         {
1088                 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1089         }
1090 };
1091
1092 /* move this here to use AddConn, rather that than having the whole
1093  * module above SQLConn, since this is buggin me right now :/
1094  */
1095 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
1096 {
1097         host.ip = result;
1098         ((ModulePgSQL*)mod)->AddConn(host);
1099         ((ModulePgSQL*)mod)->ClearOldConnections();
1100 }
1101
1102 void ReconnectTimer::Tick(time_t time)
1103 {
1104         ((ModulePgSQL*)mod)->ReadConf();
1105 }
1106
1107 void SQLConn::DelayReconnect()
1108 {
1109         ((ModulePgSQL*)us)->ReconnectConn(this);
1110 }
1111
1112
1113 class ModulePgSQLFactory : public ModuleFactory
1114 {
1115  public:
1116         ModulePgSQLFactory()
1117         {
1118         }
1119
1120         ~ModulePgSQLFactory()
1121         {
1122         }
1123
1124         virtual Module * CreateModule(InspIRCd* Me)
1125         {
1126                 return new ModulePgSQL(Me);
1127         }
1128 };
1129
1130
1131 extern "C" void * init_module( void )
1132 {
1133         return new ModulePgSQLFactory;
1134 }