]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlauth.cpp
This compiles, dont expect it to work yet
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlauth.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 <string>
19 #include <map>
20
21 #include "users.h"
22 #include "channels.h"
23 #include "modules.h"
24 #include "inspircd.h"
25 #include "helperfuncs.h"
26 #include "m_sqlv2.h"
27
28 /* $ModDesc: Allow/Deny connections based upon an arbitary SQL table */
29
30 typedef std::map<unsigned int, userrec*> QueryUserMap;
31
32 class ModuleSQLAuth : public Module
33 {
34         Server* Srv;
35
36         std::string usertable;
37         std::string userfield;
38         std::string passfield;
39         std::string encryption;
40         std::string killreason;
41         std::string allowpattern;
42         std::string databaseid;
43         
44         bool verbose;
45         
46         QueryUserMap qumap;
47         
48 public:
49         ModuleSQLAuth(Server* Me)
50         : Module::Module(Me)
51         {
52                 Srv = Me;
53                 OnRehash("");
54         }
55
56         void Implements(char* List)
57         {
58                 List[I_OnUserDisconnect] = List[I_OnCheckReady] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = 1;
59         }
60
61         virtual void OnRehash(const std::string &parameter)
62         {
63                 ConfigReader Conf;
64                 
65                 usertable       = Conf.ReadValue("sqlauth", "usertable", 0);    /* User table name */
66                 databaseid      = Conf.ReadValue("sqlauth", "dbid", 0);                 /* Database ID, given to the SQL service provider */
67                 userfield       = Conf.ReadValue("sqlauth", "userfield", 0);    /* Field name where username can be found */
68                 passfield       = Conf.ReadValue("sqlauth", "passfield", 0);    /* Field name where password can be found */
69                 killreason      = Conf.ReadValue("sqlauth", "killreason", 0);   /* Reason to give when access is denied to a user (put your reg details here) */
70                 allowpattern= Conf.ReadValue("sqlauth", "allowpattern",0 );     /* Allow nicks matching this pattern without requiring auth */
71                 encryption      = Conf.ReadValue("sqlauth", "encryption", 0);   /* Name of sql function used to encrypt password, e.g. "md5" or "passwd".
72                                                                                                                                          * define, but leave blank if no encryption is to be used.
73                                                                                                                                          */
74                 verbose         = Conf.ReadFlag("sqlauth", "verbose", 0);               /* Set to true if failed connects should be reported to operators */
75                 
76                 if (encryption.find("(") == std::string::npos)
77                 {
78                         encryption.append("(");
79                 }
80         }       
81
82         virtual void OnUserRegister(userrec* user)
83         {
84                 if ((allowpattern != "") && (Srv->MatchText(user->nick,allowpattern)))
85                         return;
86                 
87                 if (!CheckCredentials(user))
88                 {
89                         Srv->QuitUser(user,killreason);
90                 }
91         }
92
93         bool CheckCredentials(userrec* user)
94         {
95                 bool found;
96                 Module* target;
97                 
98                 found = false;
99                 target = Srv->FindFeature("SQL");
100                 
101                 if(target)
102                 {
103                         SQLrequest req = SQLreq(this, target, databaseid, "SELECT ? FROM ? WHERE ? = '?' AND ? = ?'?')", userfield, usertable, userfield, user->nick, passfield, encryption, user->password);
104                         
105                         if(req.Send())
106                         {
107                                 /* When we get the query response from the service provider we will be given an ID to play with,
108                                  * just an ID number which is unique to this query. We need a way of associating that ID with a userrec
109                                  * so we insert it into a map mapping the IDs to users.
110                                  * This isn't quite enough though, as if the user quit while the query was in progress then when the result
111                                  * came to be processed we'd get an invalid userrec* out of the map. Now we *could* solve this by watching
112                                  * OnUserDisconnect() and iterating the map every time someone quits to make sure they didn't have any queries
113                                  * in progress, but that would be relatively slow and inefficient. Instead (thanks to w00t ;p) we attach a list
114                                  * of query IDs associated with it to the userrec, so in OnUserDisconnect() we can remove it immediately.
115                                  */
116                                 log(DEBUG, "Sent query, got given ID %lu", req.id);
117                                 qumap.insert(std::make_pair(req.id, user));
118                                 
119                                 if(!user->Extend("sqlauth_queryid", new unsigned long(req.id)))
120                                 {
121                                         log(DEBUG, "BUG: user being sqlauth'd already extended with 'sqlauth_queryid' :/");
122                                 }
123                                 
124                                 return true;
125                         }
126                         else
127                         {
128                                 log(DEBUG, "SQLrequest failed: %s", req.error.Str());
129                                 
130                                 if (verbose)
131                                         WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, req.error.Str());
132                                 
133                                 return false;
134                         }
135                 }
136                 else
137                 {
138                         log(SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be allowed to connect until it comes back unless they match an exception");
139                         return false;
140                 }
141         }
142         
143         virtual char* OnRequest(Request* request)
144         {
145                 if(strcmp(SQLRESID, request->GetData()) == 0)
146                 {
147                         SQLresult* res;
148                         QueryUserMap::iterator iter;
149                 
150                         res = static_cast<SQLresult*>(request);
151                         
152                         log(DEBUG, "Got SQL result (%s) with ID %lu", res->GetData(), res->id);
153                         
154                         iter = qumap.find(res->id);
155                         
156                         if(iter != qumap.end())
157                         {
158                                 userrec* user;
159                                 unsigned long* id;
160                                 
161                                 user = iter->second;
162                                 
163                                 /* Remove our ID from the lookup table to keep it as small and neat as possible */
164                                 qumap.erase(iter);
165                                 
166                                 /* Cleanup the userrec, no point leaving this here */
167                                 if(user->GetExt("sqlauth_queryid", id))
168                                 {
169                                         user->Shrink("sqlauth_queryid");
170                                         delete id;
171                                 }
172                                 
173                                 if(res->error.Id() == NO_ERROR)
174                                 {                               
175                                         log(DEBUG, "Associated query ID %lu with user %s", res->id, user->nick);                        
176                                         log(DEBUG, "Got result with %d rows and %d columns", res->Rows(), res->Cols());
177                         
178                                         if(res->Rows())
179                                         {
180                                                 /* We got a row in the result, this is enough really */
181                                                 user->Extend("sqlauthed");
182                                         }
183                                         else if (verbose)
184                                         {
185                                                 /* No rows in result, this means there was no record matching the user */
186                                                 WriteOpers("Forbidden connection from %s!%s@%s (SQL query returned no matches)", user->nick, user->ident, user->host);
187                                                 user->Extend("sqlauth_failed");
188                                         }
189                                 }
190                                 else if (verbose)
191                                 {
192                                         log(DEBUG, "Query failed: %s", res->error.Str());
193                                         WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, res->error.Str());
194                                         user->Extend("sqlauth_failed");
195                                 }
196                         }
197                         else
198                         {
199                                 log(DEBUG, "Got query with unknown ID, this probably means the user quit while the query was in progress");
200                         }
201                 
202                         return SQLSUCCESS;
203                 }
204                 
205                 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
206                 
207                 return NULL;
208         }
209         
210         virtual void OnUserDisconnect(userrec* user)
211         {
212                 unsigned long* id;
213                 
214                 if(user->GetExt("sqlauth_queryid", id))
215                 {
216                         QueryUserMap::iterator iter;
217                         
218                         iter = qumap.find(*id);
219                         
220                         if(iter != qumap.end())
221                         {
222                                 if(iter->second == user)
223                                 {
224                                         qumap.erase(iter);
225                                         
226                                         log(DEBUG, "Erased query from map associated with quitting user %s", user->nick);
227                                 }
228                                 else
229                                 {
230                                         log(DEBUG, "BUG: ID associated with user %s doesn't have the same userrec* associated with it in the map");
231                                 }               
232                         }
233                         else
234                         {
235                                 log(DEBUG, "BUG: user %s was extended with sqlauth_queryid but there was nothing matching in the map", user->nick);
236                         }
237                         
238                         user->Shrink("sqlauth_queryid");
239                         delete id;
240                 }
241
242                 user->Shrink("sqlauthed");
243                 user->Shrink("sqlauth_failed");         
244         }
245         
246         virtual bool OnCheckReady(userrec* user)
247         {
248                 if(user->GetExt("sqlauth_failed"))
249                 {
250                         Srv->QuitUser(user,killreason);
251                         return false;
252                 }
253                 
254                 return user->GetExt("sqlauthed");
255         }
256
257         virtual ~ModuleSQLAuth()
258         {
259         }
260         
261         virtual Version GetVersion()
262         {
263                 return Version(1,0,1,0,VF_VENDOR);
264         }
265         
266 };
267
268 class ModuleSQLAuthFactory : public ModuleFactory
269 {
270  public:
271         ModuleSQLAuthFactory()
272         {
273         }
274         
275         ~ModuleSQLAuthFactory()
276         {
277         }
278         
279         virtual Module * CreateModule(Server* Me)
280         {
281                 return new ModuleSQLAuth(Me);
282         }
283         
284 };
285
286
287 extern "C" void * init_module( void )
288 {
289         return new ModuleSQLAuthFactory;
290 }