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