]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlite3.cpp
Remove InspIRCd* parameters and fields
[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, 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, int port, const std::string &addr) : ListenSocketBase(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         Module* mod;
278         SQLhost host;
279         sqlite3* conn;
280
281  public:
282         SQLConn(Module* m, const SQLhost& hi)
283         : mod(m), host(hi)
284         {
285                 if (OpenDB() != SQLITE_OK)
286                 {
287                         ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
288                         CloseDB();
289                 }
290         }
291
292         ~SQLConn()
293         {
294                 CloseDB();
295         }
296
297         SQLerror Query(SQLrequest &req)
298         {
299                 /* Pointer to the buffer we screw around with substitution in */
300                 char* query;
301
302                 /* Pointer to the current end of query, where we append new stuff */
303                 char* queryend;
304
305                 /* Total length of the unescaped parameters */
306                 unsigned long maxparamlen, paramcount;
307
308                 /* The length of the longest parameter */
309                 maxparamlen = 0;
310
311                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
312                 {
313                         if (i->size() > maxparamlen)
314                                 maxparamlen = i->size();
315                 }
316
317                 /* How many params are there in the query? */
318                 paramcount = count(req.query.q.c_str(), '?');
319
320                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
321                 ParamL paramscopy(req.query.p);
322
323                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
324                  * sizeofquery + (maxtotalparamlength*2) + 1
325                  *
326                  * The +1 is for null-terminating the string
327                  */
328
329                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
330                 queryend = query;
331
332                 for(unsigned long i = 0; i < req.query.q.length(); i++)
333                 {
334                         if(req.query.q[i] == '?')
335                         {
336                                 /* We found a place to substitute..what fun.
337                                  * use sqlite calls to escape and write the
338                                  * escaped string onto the end of our query buffer,
339                                  * then we "just" need to make sure queryend is
340                                  * pointing at the right place.
341                                  */
342
343                                 /* Is it numbered parameter?
344                                  */
345
346                                 bool numbered;
347                                 numbered = false;
348
349                                 /* Numbered parameter number :|
350                                  */
351                                 unsigned int paramnum;
352                                 paramnum = 0;
353
354                                 /* Let's check if it's a numbered param. And also calculate it's number.
355                                  */
356
357                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
358                                 {
359                                         numbered = true;
360                                         ++i;
361                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
362                                 }
363
364                                 if (paramnum > paramscopy.size() - 1)
365                                 {
366                                         /* index is out of range!
367                                          */
368                                         numbered = false;
369                                 }
370
371
372                                 if (numbered)
373                                 {
374                                         char* escaped;
375                                         escaped = sqlite3_mprintf("%q", paramscopy[paramnum].c_str());
376                                         for (char* n = escaped; *n; n++)
377                                         {
378                                                 *queryend = *n;
379                                                 queryend++;
380                                         }
381                                         sqlite3_free(escaped);
382                                 }
383                                 else if (req.query.p.size())
384                                 {
385                                         char* escaped;
386                                         escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
387                                         for (char* n = escaped; *n; n++)
388                                         {
389                                                 *queryend = *n;
390                                                 queryend++;
391                                         }
392                                         sqlite3_free(escaped);
393                                         req.query.p.pop_front();
394                                 }
395                                 else
396                                         break;
397                         }
398                         else
399                         {
400                                 *queryend = req.query.q[i];
401                                 queryend++;
402                         }
403                 }
404                 *queryend = 0;
405                 req.query.q = query;
406
407                 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
408                 res->dbid = host.id;
409                 res->query = req.query.q;
410                 paramlist params;
411                 params.push_back(this);
412                 params.push_back(res);
413
414                 char *errmsg = 0;
415                 sqlite3_update_hook(conn, QueryUpdateHook, &params);
416                 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, &params, &errmsg) != SQLITE_OK)
417                 {
418                         std::string error(errmsg);
419                         sqlite3_free(errmsg);
420                         delete[] query;
421                         delete res;
422                         return SQLerror(SQL_QSEND_FAIL, error);
423                 }
424                 delete[] query;
425
426                 results.push_back(res);
427                 SendNotify();
428                 return SQLerror();
429         }
430
431         static int QueryResult(void *params, int argc, char **argv, char **azColName)
432         {
433                 paramlist* p = (paramlist*)params;
434                 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
435                 return 0;
436         }
437
438         static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
439         {
440                 paramlist* p = (paramlist*)params;
441                 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
442         }
443
444         void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
445         {
446                 res->AddRow(cols, data, colnames);
447         }
448
449         void AffectedReady(SQLite3Result *res)
450         {
451                 res->UpdateAffectedCount();
452         }
453
454         int OpenDB()
455         {
456                 return sqlite3_open_v2(host.host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0);
457         }
458
459         void CloseDB()
460         {
461                 sqlite3_interrupt(conn);
462                 sqlite3_close(conn);
463         }
464
465         SQLhost GetConfHost()
466         {
467                 return host;
468         }
469
470         void SendResults()
471         {
472                 while (results.size())
473                 {
474                         SQLite3Result* res = results[0];
475                         if (res->GetDest())
476                         {
477                                 res->Send();
478                         }
479                         else
480                         {
481                                 /* If the client module is unloaded partway through a query then the provider will set
482                                  * the pointer to NULL. We cannot just cancel the query as the result will still come
483                                  * through at some point...and it could get messy if we play with invalid pointers...
484                                  */
485                                 delete res;
486                         }
487                         results.pop_front();
488                 }
489         }
490
491         void ClearResults()
492         {
493                 while (results.size())
494                 {
495                         SQLite3Result* res = results[0];
496                         delete res;
497                         results.pop_front();
498                 }
499         }
500
501         void SendNotify()
502         {
503                 if (QueueFD < 0)
504                 {
505                         if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
506                         {
507                                 /* crap, we're out of sockets... */
508                                 return;
509                         }
510
511                         irc::sockets::insp_sockaddr addr;
512
513 #ifdef IPV6
514                         irc::sockets::insp_aton("::1", &addr.sin6_addr);
515                         addr.sin6_family = AF_FAMILY;
516                         addr.sin6_port = htons(listener->GetPort());
517 #else
518                         irc::sockets::insp_inaddr ia;
519                         irc::sockets::insp_aton("127.0.0.1", &ia);
520                         addr.sin_family = AF_FAMILY;
521                         addr.sin_addr = ia;
522                         addr.sin_port = htons(listener->GetPort());
523 #endif
524
525                         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
526                         {
527                                 /* wtf, we cant connect to it, but we just created it! */
528                                 return;
529                         }
530                 }
531                 char id = 0;
532                 send(QueueFD, &id, 1, 0);
533         }
534
535 };
536
537
538 class ModuleSQLite3 : public Module
539 {
540  private:
541         ConnMap connections;
542         unsigned long currid;
543
544  public:
545         ModuleSQLite3()
546         : currid(0)
547         {
548                 ServerInstance->Modules->UseInterface("SQLutils");
549
550                 if (!ServerInstance->Modules->PublishFeature("SQL", this))
551                 {
552                         throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'");
553                 }
554
555                 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
556 #ifdef IPV6
557                 listener = new SQLiteListener(this, ServerInstance, 0, "::1");
558 #else
559                 listener = new SQLiteListener(this, ServerInstance, 0, "127.0.0.1");
560 #endif
561
562                 if (listener->GetFd() == -1)
563                 {
564                         ServerInstance->Modules->DoneWithInterface("SQLutils");
565                         throw ModuleException("m_sqlite3: unable to create ITC pipe");
566                 }
567                 else
568                 {
569                         ServerInstance->Logs->Log("m_sqlite3", DEBUG, "SQLite: Interthread comms port is %d", listener->GetPort());
570                 }
571
572                 ReadConf();
573
574                 ServerInstance->Modules->PublishInterface("SQL", this);
575                 Implementation eventlist[] = { I_OnRequest, I_OnRehash };
576                 ServerInstance->Modules->Attach(eventlist, this, 2);
577         }
578
579         virtual ~ModuleSQLite3()
580         {
581                 ClearQueue();
582                 ClearAllConnections();
583
584                 ServerInstance->SE->DelFd(listener);
585                 ServerInstance->BufferedSocketCull();
586
587                 if (QueueFD >= 0)
588                 {
589                         shutdown(QueueFD, 2);
590                         close(QueueFD);
591                 }
592
593                 if (notifier)
594                 {
595                         ServerInstance->SE->DelFd(notifier);
596                         notifier->Close();
597                         ServerInstance->BufferedSocketCull();
598                 }
599
600                 ServerInstance->Modules->UnpublishInterface("SQL", this);
601                 ServerInstance->Modules->UnpublishFeature("SQL");
602                 ServerInstance->Modules->DoneWithInterface("SQLutils");
603         }
604
605
606         void SendQueue()
607         {
608                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
609                 {
610                         iter->second->SendResults();
611                 }
612         }
613
614         void ClearQueue()
615         {
616                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
617                 {
618                         iter->second->ClearResults();
619                 }
620         }
621
622         bool HasHost(const SQLhost &host)
623         {
624                 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
625                 {
626                         if (host == iter->second->GetConfHost())
627                                 return true;
628                 }
629                 return false;
630         }
631
632         bool HostInConf(const SQLhost &h)
633         {
634                 ConfigReader conf;
635                 for(int i = 0; i < conf.Enumerate("database"); i++)
636                 {
637                         SQLhost host;
638                         host.id         = conf.ReadValue("database", "id", i);
639                         host.host       = conf.ReadValue("database", "hostname", i);
640                         host.port       = conf.ReadInteger("database", "port", i, true);
641                         host.name       = conf.ReadValue("database", "name", i);
642                         host.user       = conf.ReadValue("database", "username", i);
643                         host.pass       = conf.ReadValue("database", "password", i);
644                         if (h == host)
645                                 return true;
646                 }
647                 return false;
648         }
649
650         void ReadConf()
651         {
652                 ClearOldConnections();
653
654                 ConfigReader conf;
655                 for(int i = 0; i < conf.Enumerate("database"); i++)
656                 {
657                         SQLhost host;
658
659                         host.id         = conf.ReadValue("database", "id", i);
660                         host.host       = conf.ReadValue("database", "hostname", i);
661                         host.port       = conf.ReadInteger("database", "port", i, true);
662                         host.name       = conf.ReadValue("database", "name", i);
663                         host.user       = conf.ReadValue("database", "username", i);
664                         host.pass       = conf.ReadValue("database", "password", i);
665
666                         if (HasHost(host))
667                                 continue;
668
669                         this->AddConn(host);
670                 }
671         }
672
673         void AddConn(const SQLhost& hi)
674         {
675                 if (HasHost(hi))
676                 {
677                         ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
678                         return;
679                 }
680
681                 SQLConn* newconn;
682
683                 newconn = new SQLConn(this, hi);
684
685                 connections.insert(std::make_pair(hi.id, newconn));
686         }
687
688         void ClearOldConnections()
689         {
690                 ConnMap::iterator iter,safei;
691                 for (iter = connections.begin(); iter != connections.end(); iter++)
692                 {
693                         if (!HostInConf(iter->second->GetConfHost()))
694                         {
695                                 delete iter->second;
696                                 safei = iter;
697                                 --iter;
698                                 connections.erase(safei);
699                         }
700                 }
701         }
702
703         void ClearAllConnections()
704         {
705                 ConnMap::iterator i;
706                 while ((i = connections.begin()) != connections.end())
707                 {
708                         connections.erase(i);
709                         delete i->second;
710                 }
711         }
712
713         virtual void OnRehash(User* user)
714         {
715                 ReadConf();
716         }
717
718         virtual const char* OnRequest(Request* request)
719         {
720                 if(strcmp(SQLREQID, request->GetId()) == 0)
721                 {
722                         SQLrequest* req = (SQLrequest*)request;
723                         ConnMap::iterator iter;
724                         if((iter = connections.find(req->dbid)) != connections.end())
725                         {
726                                 req->id = NewID();
727                                 req->error = iter->second->Query(*req);
728                                 return SQLSUCCESS;
729                         }
730                         else
731                         {
732                                 req->error.Id(SQL_BAD_DBID);
733                                 return NULL;
734                         }
735                 }
736                 return NULL;
737         }
738
739         unsigned long NewID()
740         {
741                 if (currid+1 == 0)
742                         currid++;
743
744                 return ++currid;
745         }
746
747         virtual Version GetVersion()
748         {
749                 return Version("sqlite3 provider", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
750         }
751
752 };
753
754 void ResultNotifier::Dispatch()
755 {
756         mod->SendQueue();
757 }
758
759 MODULE_INIT(ModuleSQLite3)