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