]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqloper.cpp
Fix for bug #180, logging is not threadsafe, mutex it (ew, luckily we dont log much)
[user/henk/code/inspircd.git] / src / modules / extra / m_sqloper.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 #include "users.h"
16 #include "channels.h"
17 #include "modules.h"
18 #include "inspircd.h"
19 #include "configreader.h"
20
21 #include "m_sqlv2.h"
22 #include "m_sqlutils.h"
23 #include "commands/cmd_oper.h"
24
25 /* $ModDesc: Allows storage of oper credentials in an SQL table */
26 /* $ModDep: m_sqlv2.h m_sqlutils.h */
27
28 class ModuleSQLOper : public Module
29 {
30         InspIRCd* Srv;
31         Module* SQLutils;
32         std::string databaseid;
33
34 public:
35         ModuleSQLOper(InspIRCd* Me)
36         : Module::Module(Me), Srv(Me)
37         {
38                 SQLutils = Srv->FindFeature("SQLutils");
39                 
40                 if (SQLutils)
41                 {
42                         ServerInstance->Log(DEBUG, "Successfully got SQLutils pointer");
43                 }
44                 else
45                 {
46                         ServerInstance->Log(DEFAULT, "ERROR: This module requires a module offering the 'SQLutils' feature (usually m_sqlutils.so). Please load it and try again.");
47                         throw ModuleException("This module requires a module offering the 'SQLutils' feature (usually m_sqlutils.so). Please load it and try again.");
48                 }
49                 
50                 OnRehash("");
51         }
52
53         virtual void OnRehash(const std::string &parameter)
54         {
55                 ConfigReader Conf(Srv);
56                 
57                 databaseid = Conf.ReadValue("sqloper", "dbid", 0); /* Database ID of a database configured for the service provider module */
58         }
59
60         void Implements(char* List)
61         {
62                 List[I_OnRequest] = List[I_OnRehash] = List[I_OnPreCommand] = 1;
63         }
64
65         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
66         {
67                 if ((validated) && (command == "OPER"))
68                 {
69                         if (LookupOper(user, parameters[0], parameters[1]))
70                         {       
71                                 /* Returning true here just means the query is in progress, or on it's way to being
72                                  * in progress. Nothing about the /oper actually being successful..
73                                  * If the oper lookup fails later, we pass the command to the original handler
74                                  * for /oper by calling its Handle method directly.
75                                  */
76                                 return 1;
77                         }
78                 }
79                 return 0;
80         }
81
82         bool LookupOper(userrec* user, const std::string &username, const std::string &password)
83         {
84                 Module* target;
85                 
86                 target = Srv->FindFeature("SQL");
87
88                 if (target)
89                 {
90                         SQLrequest req = SQLreq(this, target, databaseid, "SELECT username, password, hostname, type FROM ircd_opers WHERE username = '?' AND password=md5('?')", username, password);
91                         
92                         if (req.Send())
93                         {
94                                 /* When we get the query response from the service provider we will be given an ID to play with,
95                                  * just an ID number which is unique to this query. We need a way of associating that ID with a userrec
96                                  * so we insert it into a map mapping the IDs to users.
97                                  * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the
98                                  * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling
99                                  * us to discard the query.
100                                  */
101                                 ServerInstance->Log(DEBUG, "Sent query, got given ID %lu", req.id);
102                                 
103                                 AssociateUser(this, SQLutils, req.id, user).Send();
104
105                                 user->Extend("oper_user", strdup(username.c_str()));
106                                 user->Extend("oper_pass", strdup(password.c_str()));
107                                         
108                                 return true;
109                         }
110                         else
111                         {
112                                 ServerInstance->Log(DEBUG, "SQLrequest failed: %s", req.error.Str());
113                         
114                                 return false;
115                         }
116                 }
117                 else
118                 {
119                         ServerInstance->Log(SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be able to oper up unless their o:line is statically configured");
120                         return false;
121                 }
122         }
123         
124         virtual char* OnRequest(Request* request)
125         {
126                 if (strcmp(SQLRESID, request->GetId()) == 0)
127                 {
128                         SQLresult* res;
129                 
130                         res = static_cast<SQLresult*>(request);
131                         
132                         ServerInstance->Log(DEBUG, "Got SQL result (%s) with ID %lu", res->GetId(), res->id);
133                         
134                         userrec* user = GetAssocUser(this, SQLutils, res->id).S().user;
135                         UnAssociate(this, SQLutils, res->id).S();
136
137                         char* tried_user = NULL;
138                         char* tried_pass = NULL;
139
140                         user->GetExt("oper_user", tried_user);
141                         user->GetExt("oper_pass", tried_pass);
142                         
143                         if (user)
144                         {
145                                 if (res->error.Id() == NO_ERROR)
146                                 {                               
147                                         ServerInstance->Log(DEBUG, "Associated query ID %lu with user %s", res->id, user->nick);                        
148                                         ServerInstance->Log(DEBUG, "Got result with %d rows and %d columns", res->Rows(), res->Cols());
149                         
150                                         if (res->Rows())
151                                         {
152                                                 /* We got a row in the result, this means there was a record for the oper..
153                                                  * now we just need to check if their host matches, and if it does then
154                                                  * oper them up.
155                                                  * 
156                                                  * We now (previous versions of the module didn't) support multiple SQL
157                                                  * rows per-oper in the same way the config file does, all rows will be tried
158                                                  * until one is found which matches. This is useful to define several different
159                                                  * hosts for a single oper.
160                                                  * 
161                                                  * The for() loop works as SQLresult::GetRowMap() returns an empty map when there
162                                                  * are no more rows to return.
163                                                  */
164                                                 
165                                                 for (SQLfieldMap& row = res->GetRowMap(); row.size(); row = res->GetRowMap())
166                                                 {
167                                                         ServerInstance->Log(DEBUG, "Trying to oper user %s with username = '%s', passhash = '%s', hostname = '%s', type = '%s'", user->nick, row["username"].d.c_str(), row["password"].d.c_str(), row["hostname"].d.c_str(), row["type"].d.c_str());
168                                                         
169                                                         if (OperUser(user, row["username"].d, row["password"].d, row["hostname"].d, row["type"].d))
170                                                         {
171                                                                 /* If/when one of the rows matches, stop checking and return */
172                                                                 return SQLSUCCESS;
173                                                         }
174                                                 }
175                                         }
176                                         else
177                                         {
178                                                 /* No rows in result, this means there was no oper line for the user,
179                                                  * we should have already checked the o:lines so now we need an
180                                                  * "insufficient awesomeness" (invalid credentials) error
181                                                  */
182                                                 if (tried_user && tried_pass)
183                                                 {
184                                                         LoginFail(user, tried_user, tried_pass);
185                                                         free(tried_user);
186                                                         free(tried_pass);
187                                                         user->Shrink("oper_user");
188                                                         user->Shrink("oper_pass");
189                                                 }
190                                         }
191                                 }
192                                 else
193                                 {
194                                         /* This one shouldn't happen, the query failed for some reason.
195                                          * We have to fail the /oper request and give them the same error
196                                          * as above.
197                                          */
198                                         ServerInstance->Log(DEBUG, "Query failed: %s", res->error.Str());
199
200                                         if (tried_user && tried_pass)
201                                         {
202                                                 LoginFail(user, tried_user, tried_pass);
203                                                 free(tried_user);
204                                                 free(tried_pass);
205                                                 user->Shrink("oper_user");
206                                                 user->Shrink("oper_pass");
207                                         }
208
209                                 }
210                         }
211                         else
212                         {
213                                 ServerInstance->Log(DEBUG, "Got query with unknown ID, this probably means the user quit while the query was in progress");
214                         }
215                 
216                         return SQLSUCCESS;
217                 }
218                 
219                 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
220
221                 return NULL;
222         }
223
224         void LoginFail(userrec* user, const std::string &username, const std::string &pass)
225         {
226                 command_t* oper_command = ServerInstance->Parser->GetHandler("OPER");
227
228                 if (oper_command)
229                 {
230                         const char* params[] = { username.c_str(), pass.c_str() };
231                         oper_command->Handle(params, 2, user);
232                 }
233                 else
234                 {
235                         ServerInstance->Log(DEBUG, "WHAT?! Why do we have no OPER command?!");
236                 }
237         }
238
239         bool OperUser(userrec* user, const std::string &username, const std::string &password, const std::string &pattern, const std::string &type)
240         {
241                 ConfigReader Conf(Srv);
242                 
243                 for (int j = 0; j < Conf.Enumerate("type"); j++)
244                 {
245                         std::string tname = Conf.ReadValue("type","name",j);
246                         
247                         ServerInstance->Log(DEBUG, "Scanning opertype: %s", tname.c_str());
248                         
249                         std::string hostname(user->ident);
250                         hostname.append("@").append(user->host);
251                                                         
252                         if ((tname == type) && OneOfMatches(hostname.c_str(), user->GetIPString(), pattern.c_str()))
253                         {
254                                 /* Opertype and host match, looks like this is it. */
255                                 ServerInstance->Log(DEBUG, "Host (%s matched %s OR %s) and type (%s)", pattern.c_str(), hostname.c_str(), user->GetIPString(), type.c_str());
256                                 
257                                 std::string operhost = Conf.ReadValue("type", "host", j);
258                                                         
259                                 if (operhost.size())
260                                         user->ChangeDisplayedHost(operhost.c_str());
261                                                                 
262                                 Srv->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s", user->nick, user->ident, user->host, type.c_str());
263                                 user->WriteServ("381 %s :You are now an IRC operator of type %s", user->nick, type.c_str());
264                                 
265                                 if (!user->modes[UM_OPERATOR])
266                                         user->Oper(type);
267                                                                 
268                                 return true;
269                         }
270                 }
271                 
272                 return false;
273         }
274
275         virtual ~ModuleSQLOper()
276         {
277         }
278         
279         virtual Version GetVersion()
280         {
281                 return Version(1,1,1,0,VF_VENDOR,API_VERSION);
282         }
283         
284 };
285
286 class ModuleSQLOperFactory : public ModuleFactory
287 {
288  public:
289         ModuleSQLOperFactory()
290         {
291         }
292         
293         ~ModuleSQLOperFactory()
294         {
295         }
296         
297         virtual Module * CreateModule(InspIRCd* Me)
298         {
299                 return new ModuleSQLOper(Me);
300         }
301         
302 };
303
304
305 extern "C" void * init_module( void )
306 {
307         return new ModuleSQLOperFactory;
308 }
309