]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlite3.cpp
86b2cb3789d1c1997ba86a3954aea9084f22ed96
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlite3.cpp
1 /*               +------------------------------------+
2  *               | Inspire Internet Relay Chat Daemon |
3  *               +------------------------------------+
4  *
5  *      InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *                        the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <sqlite3.h>
16 #include "m_sqlv2.h"
17
18 /* $ModDesc: sqlite3 provider */
19 /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
20 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
21 /* $ModDep: m_sqlv2.h */
22 /* $NoPedantic */
23
24 class SQLConn;
25 class SQLite3Result;
26 class ResultNotifier;
27 class SQLiteListener;
28 class ModuleSQLite3;
29
30 typedef std::map<std::string, SQLConn*> ConnMap;
31 typedef std::deque<classbase*> paramlist;
32 typedef std::deque<SQLite3Result*> ResultQueue;
33
34 unsigned long count(const char * const str, char a)
35 {
36         unsigned long n = 0;
37         for (const char *p = str; *p; ++p)
38         {
39                 if (*p == '?')
40                         ++n;
41         }
42         return n;
43 }
44
45 ResultNotifier* notifier = NULL;
46 SQLiteListener* listener = NULL;
47 int QueueFD = -1;
48
49 class ResultNotifier : public BufferedSocket
50 {
51         ModuleSQLite3* mod;
52
53  public:
54         ResultNotifier(ModuleSQLite3* m, InspIRCd* SI, int newfd, char* ip) : BufferedSocket(SI, newfd, ip), mod(m)
55         {
56         }
57
58         virtual bool OnDataReady()
59         {
60                 char data = 0;
61                 if (ServerInstance->SE->Recv(this, &data, 1, 0) > 0)
62                 {
63                         Dispatch();
64                         return true;
65                 }
66                 return false;
67         }
68
69         void Dispatch();
70 };
71
72 class SQLiteListener : public ListenSocketBase
73 {
74         ModuleSQLite3* Parent;
75         irc::sockets::insp_sockaddr sock_us;
76         socklen_t uslen;
77         FileReader* index;
78
79  public:
80         SQLiteListener(ModuleSQLite3* P, InspIRCd* Instance, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr), Parent(P)
81         {
82                 uslen = sizeof(sock_us);
83                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
84                 {
85                         throw ModuleException("Could not getsockname() to find out port number for ITC port");
86                 }
87         }
88
89         virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
90         {
91                 new ResultNotifier(this->Parent, this->ServerInstance, nfd, (char *)ipconnectedto.c_str()); // XXX unsafe casts suck
92         }
93
94         /* Using getsockname and ntohs, we can determine which port number we were allocated */
95         int GetPort()
96         {
97 #ifdef IPV6
98                 return ntohs(sock_us.sin6_port);
99 #else
100                 return ntohs(sock_us.sin_port);
101 #endif
102         }
103 };
104
105 class SQLite3Result : public SQLresult
106 {
107  private:
108         int currentrow;
109         int rows;
110         int cols;
111
112         std::vector<std::string> colnames;
113         std::vector<SQLfieldList> fieldlists;
114         SQLfieldList emptyfieldlist;
115
116         SQLfieldList* fieldlist;
117         SQLfieldMap* fieldmap;
118
119  public:
120         SQLite3Result(Module* self, Module* to, unsigned int rid)
121         : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
122         {
123         }
124
125         ~SQLite3Result()
126         {
127         }
128
129         void AddRow(int colsnum, char **dat, char **colname)
130         {
131                 colnames.clear();
132                 cols = colsnum;
133                 for (int i = 0; i < colsnum; i++)
134                 {
135                         fieldlists.resize(fieldlists.size()+1);
136                         colnames.push_back(colname[i]);
137                         SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
138                         fieldlists[rows].push_back(sf);
139                 }
140                 rows++;
141         }
142
143         void UpdateAffectedCount()
144         {
145                 rows++;
146         }
147
148         virtual int Rows()
149         {
150                 return rows;
151         }
152
153         virtual int Cols()
154         {
155                 return cols;
156         }
157
158         virtual std::string ColName(int column)
159         {
160                 if (column < (int)colnames.size())
161                 {
162                         return colnames[column];
163                 }
164                 else
165                 {
166                         throw SQLbadColName();
167                 }
168                 return "";
169         }
170
171         virtual int ColNum(const std::string &column)
172         {
173                 for (unsigned int i = 0; i < colnames.size(); i++)
174                 {
175                         if (column == colnames[i])
176                                 return i;
177                 }
178                 throw SQLbadColName();
179                 return 0;
180         }
181
182         virtual SQLfield GetValue(int row, int column)
183         {
184                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
185                 {
186                         return fieldlists[row][column];
187                 }
188
189                 throw SQLbadColName();
190
191                 /* XXX: We never actually get here because of the throw */
192                 return SQLfield("",true);
193         }
194
195         virtual SQLfieldList& GetRow()
196         {
197                 if (currentrow < rows)
198                         return fieldlists[currentrow];
199                 else
200                         return emptyfieldlist;
201         }
202
203         virtual SQLfieldMap& GetRowMap()
204         {
205                 /* In an effort to reduce overhead we don't actually allocate the map
206                  * until the first time it's needed...so...
207                  */
208                 if(fieldmap)
209                 {
210                         fieldmap->clear();
211                 }
212                 else
213                 {
214                         fieldmap = new SQLfieldMap;
215                 }
216
217                 if (currentrow < rows)
218                 {
219                         for (int i = 0; i < Cols(); i++)
220                         {
221                                 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
222                         }
223                         currentrow++;
224                 }
225
226                 return *fieldmap;
227         }
228
229         virtual SQLfieldList* GetRowPtr()
230         {
231                 fieldlist = new SQLfieldList();
232
233                 if (currentrow < rows)
234                 {
235                         for (int i = 0; i < Rows(); i++)
236                         {
237                                 fieldlist->push_back(fieldlists[currentrow][i]);
238                         }
239                         currentrow++;
240                 }
241                 return fieldlist;
242         }
243
244         virtual SQLfieldMap* GetRowMapPtr()
245         {
246                 fieldmap = new SQLfieldMap();
247
248                 if (currentrow < rows)
249                 {
250                         for (int i = 0; i < Cols(); i++)
251                         {
252                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
253                         }
254                         currentrow++;
255                 }
256
257                 return fieldmap;
258         }
259
260         virtual void Free(SQLfieldMap* fm)
261         {
262                 delete fm;
263         }
264
265         virtual void Free(SQLfieldList* fl)
266         {
267                 delete fl;
268         }
269
270
271 };
272
273 class SQLConn : public classbase
274 {
275  private:
276         ResultQueue results;
277         InspIRCd* ServerInstance;
278         Module* mod;
279         SQLhost host;
280         sqlite3* conn;
281
282  public:
283         SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
284         : ServerInstance(SI), mod(m), host(hi)
285         {
286                 if (OpenDB() != SQLITE_OK)
287                 {
288                         ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
289                         CloseDB();
290                 }
291         }
292
293         ~SQLConn()
294         {
295                 CloseDB();
296         }
297
298         SQLerror Query(SQLrequest &req)
299         {
300                 /* Pointer to the buffer we screw around with substitution in */
301                 char* query;
302
303                 /* Pointer to the current end of query, where we append new stuff */
304                 char* queryend;
305
306                 /* Total length of the unescaped parameters */
307                 unsigned long maxparamlen, paramcount;
308
309                 /* The length of the longest parameter */
310                 maxparamlen = 0;
311
312                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
313                 {
314                         if (i->size() > maxparamlen)
315                                 maxparamlen = i->size();
316                 }
317
318                 /* How many params are there in the query? */
319                 paramcount = count(req.query.q.c_str(), '?');
320
321                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
322                 ParamL paramscopy(req.query.p);
323
324                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
325                  * sizeofquery + (maxtotalparamlength*2) + 1
326                  *
327                  * The +1 is for null-terminating the string
328                  */
329
330                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
331                 queryend = query;
332
333                 for(unsigned long i = 0; i < req.query.q.length(); i++)
334                 {
335                         if(req.query.q[i] == '?')
336                         {
337                                 /* We found a place to substitute..what fun.
338                                  * use sqlite calls to escape and write the
339                                  * escaped string onto the end of our query buffer,
340                                  * then we "just" need to make sure queryend is
341                                  * pointing at the right place.
342                                  */
343
344                                 /* Is it numbered parameter?
345                                  */
346
347                                 bool numbered;
348                                 numbered = false;
349
350                                 /* Numbered parameter number :|
351                                  */
352                                 unsigned int paramnum;
353                                 paramnum = 0;
354
355                                 /* Let's check if it's a numbered param. And also calculate it's number.
356                                  */
357
358                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
359                                 {
360                                         numbered = true;
361                                         ++i;
362                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
363                                 }
364
365                                 if (paramnum > paramscopy.size() - 1)
366                                 {
367                                         /* index is out of range!
368                                          */
369                                         numbered = false;
370                                 }
371
372
373                                 if (numbered)
374                                 {
375                                         char* escaped;
376                                         escaped = sqlite3_mprintf("%q", paramscopy[paramnum].c_str());
377                                         for (char* n = escaped; *n; n++)
378                                         {
379                                                 *queryend = *n;
380                                                 queryend++;
381                                         }
382                                         sqlite3_free(escaped);
383                                 }
384                                 else if (req.query.p.size())
385                                 {
386                                         char* escaped;
387                                         escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
388                                         for (char* n = escaped; *n; n++)
389                                         {
390                                                 *queryend = *n;
391                                                 queryend++;
392                                         }
393                                         sqlite3_free(escaped);
394                                         req.query.p.pop_front();
395                                 }
396                                 else
397                                         break;
398                         }
399                         else
400                         {
401                                 *queryend = req.query.q[i];
402                                 queryend++;
403                         }
404                 }
405                 *queryend = 0;
406                 req.query.q = query;
407
408                 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
409                 res->dbid = host.id;
410                 res->query = req.query.q;
411                 paramlist params;
412                 params.push_back(this);
413                 params.push_back(res);
414
415                 char *errmsg = 0;
416                 sqlite3_update_hook(conn, QueryUpdateHook, &params);
417                 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, &params, &errmsg) != SQLITE_OK)
418                 {
419                         std::string error(errmsg);
420                         sqlite3_free(errmsg);
421                         delete[] query;
422                         delete res;
423                         return SQLerror(SQL_QSEND_FAIL, error);
424                 }
425                 delete[] query;
426
427                 results.push_back(res);
428                 SendNotify();
429                 return SQLerror();
430         }
431
432         static int QueryResult(void *params, int argc, char **argv, char **azColName)
433         {
434                 paramlist* p = (paramlist*)params;
435                 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
436                 return 0;
437         }
438
439         static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
440         {
441                 paramlist* p = (paramlist*)params;
442                 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
443         }
444
445         void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
446         {
447                 res->AddRow(cols, data, colnames);
448         }
449
450         void AffectedReady(SQLite3Result *res)
451         {
452                 res->UpdateAffectedCount();
453         }
454
455         int OpenDB()
456         {
457                 return sqlite3_open_v2(host.host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0);
458         }
459
460         void CloseDB()
461         {
462                 sqlite3_interrupt(conn);
463                 sqlite3_close(conn);
464         }
465
466         SQLhost GetConfHost()
467         {
468                 return host;
469         }
470
471         void SendResults()
472         {
473                 while (results.size())
474                 {
475                         SQLite3Result* res = results[0];
476                         if (res->GetDest())
477                         {
478                                 res->Send();
479                         }
480                         else
481                         {
482                                 /* If the client module is unloaded partway through a query then the provider will set
483                                  * the pointer to NULL. We cannot just cancel the query as the result will still come
484                                  * through at some point...and it could get messy if we play with invalid pointers...
485                                  */
486                                 delete res;
487                         }
488                         results.pop_front();
489                 }
490         }
491
492         void ClearResults()
493         {
494                 while (results.size())
495                 {
496                         SQLite3Result* res = results[0];
497                         delete res;
498                         results.pop_front();
499                 }
500         }
501
502         void SendNotify()
503         {
504                 if (QueueFD < 0)
505                 {
506                         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
507                         {
508                                 /* crap, we're out of sockets... */
509                                 return;
510                         }
511
512                         irc::sockets::insp_sockaddr addr;
513
514 #ifdef IPV6
515                         irc::sockets::insp_aton("::1", &addr.sin6_addr);
516                         addr.sin6_family = AF_FAMILY;
517                         addr.sin6_port = htons(listener->GetPort());
518 #else
519                         irc::sockets::insp_inaddr ia;
520                         irc::sockets::insp_aton("127.0.0.1", &ia);
521                         addr.sin_family = AF_FAMILY;
522                         addr.sin_addr = ia;
523                         addr.sin_port = htons(listener->GetPort());
524 #endif
525
526                         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
527                         {
528                                 /* wtf, we cant connect to it, but we just created it! */
529                                 return;
530                         }
531                 }
532                 char id = 0;
533                 send(QueueFD, &id, 1, 0);
534         }
535
536 };
537
538
539 class ModuleSQLite3 : public Module
540 {
541  private:
542         ConnMap connections;
543         unsigned long currid;
544
545  public:
546         ModuleSQLite3(InspIRCd* Me)
547         : Module(Me), currid(0)
548         {
549                 ServerInstance->Modules->UseInterface("SQLutils");
550
551                 if (!ServerInstance->Modules->PublishFeature("SQL", this))
552                 {
553                         throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
554                 }
555
556                 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
557 #ifdef IPV6
558                 listener = new SQLiteListener(this, ServerInstance, 0, "::1");
559 #else
560                 listener = new SQLiteListener(this, ServerInstance, 0, "127.0.0.1");
561 #endif
562
563                 if (listener->GetFd() == -1)
564                 {
565                         ServerInstance->Modules->DoneWithInterface("SQLutils");
566                         throw ModuleException("m_sqlite3: unable to create ITC pipe");
567                 }
568                 else
569                 {
570                         ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
571                 }
572
573                 ReadConf();
574
575                 ServerInstance->Modules->PublishInterface("SQL", this);
576                 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
577                 ServerInstance->Modules->Attach(eventlist, this, 2);
578         }
579
580         virtual ~ModuleSQLite3()
581         {
582                 ClearQueue();
583                 ClearAllConnections();
584
585                 ServerInstance->SE->DelFd(listener);
586                 ServerInstance->BufferedSocketCull();
587
588                 if (QueueFD >= 0)
589                 {
590                         shutdown(QueueFD, 2);
591                         close(QueueFD);
592                 }
593
594                 if (notifier)
595                 {
596                         ServerInstance->SE->DelFd(notifier);
597                         notifier->Close();
598                         ServerInstance->BufferedSocketCull();
599                 }
600
601                 ServerInstance->Modules->UnpublishInterface("SQL", this);
602                 ServerInstance->Modules->UnpublishFeature("SQL");
603                 ServerInstance->Modules->DoneWithInterface("SQLutils");
604         }
605
606
607         void SendQueue()
608         {
609                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
610                 {
611                         iter->second->SendResults();
612                 }
613         }
614
615         void ClearQueue()
616         {
617                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
618                 {
619                         iter->second->ClearResults();
620                 }
621         }
622
623         bool HasHost(const SQLhost &host)
624         {
625                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
626                 {
627                         if (host == iter->second->GetConfHost())
628                                 return true;
629                 }
630                 return false;
631         }
632
633         bool HostInConf(const SQLhost &h)
634         {
635                 ConfigReader conf(ServerInstance);
636                 for(int i = 0; i < conf.Enumerate("database"); i++)
637                 {
638                         SQLhost host;
639                         host.id         = conf.ReadValue("database", "id", i);
640                         host.host       = conf.ReadValue("database", "hostname", i);
641                         host.port       = conf.ReadInteger("database", "port", i, true);
642                         host.name       = conf.ReadValue("database", "name", i);
643                         host.user       = conf.ReadValue("database", "username", i);
644                         host.pass       = conf.ReadValue("database", "password", i);
645                         if (h == host)
646                                 return true;
647                 }
648                 return false;
649         }
650
651         void ReadConf()
652         {
653                 ClearOldConnections();
654
655                 ConfigReader conf(ServerInstance);
656                 for(int i = 0; i < conf.Enumerate("database"); i++)
657                 {
658                         SQLhost host;
659
660                         host.id         = conf.ReadValue("database", "id", i);
661                         host.host       = conf.ReadValue("database", "hostname", i);
662                         host.port       = conf.ReadInteger("database", "port", i, true);
663                         host.name       = conf.ReadValue("database", "name", i);
664                         host.user       = conf.ReadValue("database", "username", i);
665                         host.pass       = conf.ReadValue("database", "password", i);
666
667                         if (HasHost(host))
668                                 continue;
669
670                         this->AddConn(host);
671                 }
672         }
673
674         void AddConn(const SQLhost& hi)
675         {
676                 if (HasHost(hi))
677                 {
678                         ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
679                         return;
680                 }
681
682                 SQLConn* newconn;
683
684                 newconn = new SQLConn(ServerInstance, this, hi);
685
686                 connections.insert(std::make_pair(hi.id, newconn));
687         }
688
689         void ClearOldConnections()
690         {
691                 ConnMap::iterator iter,safei;
692                 for (iter = connections.begin(); iter != connections.end(); iter++)
693                 {
694                         if (!HostInConf(iter->second->GetConfHost()))
695                         {
696                                 delete iter->second;
697                                 safei = iter;
698                                 --iter;
699                                 connections.erase(safei);
700                         }
701                 }
702         }
703
704         void ClearAllConnections()
705         {
706                 ConnMap::iterator i;
707                 while ((i = connections.begin()) != connections.end())
708                 {
709                         connections.erase(i);
710                         delete i->second;
711                 }
712         }
713
714         virtual void OnRehash(User* user)
715         {
716                 ReadConf();
717         }
718
719         virtual const char* OnRequest(Request* request)
720         {
721                 if(strcmp(SQLREQID, request->GetId()) == 0)
722                 {
723                         SQLrequest* req = (SQLrequest*)request;
724                         ConnMap::iterator iter;
725                         if((iter = connections.find(req->dbid)) != connections.end())
726                         {
727                                 req->id = NewID();
728                                 req->error = iter->second->Query(*req);
729                                 return SQLSUCCESS;
730                         }
731                         else
732                         {
733                                 req->error.Id(SQL_BAD_DBID);
734                                 return NULL;
735                         }
736                 }
737                 return NULL;
738         }
739
740         unsigned long NewID()
741         {
742                 if (currid+1 == 0)
743                         currid++;
744
745                 return ++currid;
746         }
747
748         virtual Version GetVersion()
749         {
750                 return Version("sqlite3 provider", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
751         }
752
753 };
754
755 void ResultNotifier::Dispatch()
756 {
757         mod->SendQueue();
758 }
759
760 MODULE_INIT(ModuleSQLite3)