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