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