]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlauth.cpp
Fix mem leakage in reading in and connecting to databases and have destructor call...
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlauth.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include <string>
15
16 #include "users.h"
17 #include "channels.h"
18 #include "modules.h"
19 #include "inspircd.h"
20
21 #include "m_sqlv2.h"
22 #include "m_sqlutils.h"
23
24 /* $ModDesc: Allow/Deny connections based upon an arbitary SQL table */
25 /* $ModDep: m_sqlv2.h m_sqlutils.h */
26
27 class ModuleSQLAuth : public Module
28 {
29         InspIRCd* Srv;
30         Module* SQLutils;
31
32         std::string usertable;
33         std::string userfield;
34         std::string passfield;
35         std::string encryption;
36         std::string killreason;
37         std::string allowpattern;
38         std::string databaseid;
39         
40         bool verbose;
41         
42 public:
43         ModuleSQLAuth(InspIRCd* Me)
44         : Module::Module(Me), Srv(Me)
45         {
46                 SQLutils = Srv->FindFeature("SQLutils");
47                 
48                 if(SQLutils)
49                 {
50                         ServerInstance->Log(DEBUG, "Successfully got SQLutils pointer");
51                 }
52                 else
53                 {
54                         ServerInstance->Log(DEFAULT, "ERROR: This module requires a module offering the 'SQLutils' feature (usually m_sqlutils.so). Please load it and try again.");
55                         throw ModuleException("This module requires a module offering the 'SQLutils' feature (usually m_sqlutils.so). Please load it and try again.");
56                 }
57                                 
58                 OnRehash("");
59         }
60
61         void Implements(char* List)
62         {
63                 List[I_OnUserDisconnect] = List[I_OnCheckReady] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = 1;
64         }
65
66         virtual void OnRehash(const std::string &parameter)
67         {
68                 ConfigReader Conf(Srv);
69                 
70                 usertable       = Conf.ReadValue("sqlauth", "usertable", 0);    /* User table name */
71                 databaseid      = Conf.ReadValue("sqlauth", "dbid", 0);                 /* Database ID, given to the SQL service provider */
72                 userfield       = Conf.ReadValue("sqlauth", "userfield", 0);    /* Field name where username can be found */
73                 passfield       = Conf.ReadValue("sqlauth", "passfield", 0);    /* Field name where password can be found */
74                 killreason      = Conf.ReadValue("sqlauth", "killreason", 0);   /* Reason to give when access is denied to a user (put your reg details here) */
75                 allowpattern= Conf.ReadValue("sqlauth", "allowpattern",0 );     /* Allow nicks matching this pattern without requiring auth */
76                 encryption      = Conf.ReadValue("sqlauth", "encryption", 0);   /* Name of sql function used to encrypt password, e.g. "md5" or "passwd".
77                                                                                                                                          * define, but leave blank if no encryption is to be used.
78                                                                                                                                          */
79                 verbose         = Conf.ReadFlag("sqlauth", "verbose", 0);               /* Set to true if failed connects should be reported to operators */
80                 
81                 if (encryption.find("(") == std::string::npos)
82                 {
83                         encryption.append("(");
84                 }
85         }       
86
87         virtual int OnUserRegister(userrec* user)
88         {
89                 if ((allowpattern != "") && (Srv->MatchText(user->nick,allowpattern)))
90                 {
91                         user->Extend("sqlauthed");
92                         return 0;
93                 }
94                 
95                 if (!CheckCredentials(user))
96                 {
97                         userrec::QuitUser(Srv,user,killreason);
98                         return 1;
99                 }
100                 return 0;
101         }
102
103         bool CheckCredentials(userrec* user)
104         {
105                 Module* target;
106                 
107                 target = Srv->FindFeature("SQL");
108                 
109                 if(target)
110                 {
111                         SQLrequest req = SQLreq(this, target, databaseid, "SELECT ? FROM ? WHERE ? = '?' AND ? = ?'?')", userfield, usertable, userfield, user->nick, passfield, encryption, user->password);
112                         
113                         if(req.Send())
114                         {
115                                 /* When we get the query response from the service provider we will be given an ID to play with,
116                                  * just an ID number which is unique to this query. We need a way of associating that ID with a userrec
117                                  * so we insert it into a map mapping the IDs to users.
118                                  * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the
119                                  * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling
120                                  * us to discard the query.
121                                  */
122                                 ServerInstance->Log(DEBUG, "Sent query, got given ID %lu", req.id);
123                                 
124                                 AssociateUser(this, SQLutils, req.id, user).Send();
125                                         
126                                 return true;
127                         }
128                         else
129                         {
130                                 ServerInstance->Log(DEBUG, "SQLrequest failed: %s", req.error.Str());
131                         
132                                 if (verbose)
133                                         Srv->WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, req.error.Str());
134                         
135                                 return false;
136                         }
137                 }
138                 else
139                 {
140                         ServerInstance->Log(SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be allowed to connect until it comes back unless they match an exception");
141                         return false;
142                 }
143         }
144         
145         virtual char* OnRequest(Request* request)
146         {
147                 if(strcmp(SQLRESID, request->GetId()) == 0)
148                 {
149                         SQLresult* res;
150                 
151                         res = static_cast<SQLresult*>(request);
152                         
153                         ServerInstance->Log(DEBUG, "Got SQL result (%s) with ID %lu", res->GetId(), res->id);
154                         
155                         userrec* user = GetAssocUser(this, SQLutils, res->id).S().user;
156                         UnAssociate(this, SQLutils, res->id).S();
157                         
158                         if(user)
159                         {
160                                 if(res->error.Id() == NO_ERROR)
161                                 {                               
162                                         ServerInstance->Log(DEBUG, "Associated query ID %lu with user %s", res->id, user->nick);                        
163                                         ServerInstance->Log(DEBUG, "Got result with %d rows and %d columns", res->Rows(), res->Cols());
164                         
165                                         if(res->Rows())
166                                         {
167                                                 /* We got a row in the result, this is enough really */
168                                                 user->Extend("sqlauthed");
169                                         }
170                                         else if (verbose)
171                                         {
172                                                 /* No rows in result, this means there was no record matching the user */
173                                                 Srv->WriteOpers("Forbidden connection from %s!%s@%s (SQL query returned no matches)", user->nick, user->ident, user->host);
174                                                 user->Extend("sqlauth_failed");
175                                         }
176                                 }
177                                 else if (verbose)
178                                 {
179                                         ServerInstance->Log(DEBUG, "Query failed: %s", res->error.Str());
180                                         Srv->WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, res->error.Str());
181                                         user->Extend("sqlauth_failed");
182                                 }
183                         }
184                         else
185                         {
186                                 ServerInstance->Log(DEBUG, "Got query with unknown ID, this probably means the user quit while the query was in progress");
187                                 return NULL;
188                         }
189
190                         if (!user->GetExt("sqlauthed"))
191                         {
192                                 userrec::QuitUser(Srv,user,killreason);
193                         }
194                         return SQLSUCCESS;
195                 }
196                 
197                 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
198                 
199                 return NULL;
200         }
201         
202         virtual void OnUserDisconnect(userrec* user)
203         {
204                 user->Shrink("sqlauthed");
205                 user->Shrink("sqlauth_failed");         
206         }
207         
208         virtual bool OnCheckReady(userrec* user)
209         {
210                 return user->GetExt("sqlauthed");
211         }
212
213         virtual ~ModuleSQLAuth()
214         {
215         }
216         
217         virtual Version GetVersion()
218         {
219                 return Version(1,1,1,0,VF_VENDOR,API_VERSION);
220         }
221         
222 };
223
224 class ModuleSQLAuthFactory : public ModuleFactory
225 {
226  public:
227         ModuleSQLAuthFactory()
228         {
229         }
230         
231         ~ModuleSQLAuthFactory()
232         {
233         }
234         
235         virtual Module * CreateModule(InspIRCd* Me)
236         {
237                 return new ModuleSQLAuth(Me);
238         }
239         
240 };
241
242
243 extern "C" void * init_module( void )
244 {
245         return new ModuleSQLAuthFactory;
246 }