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