]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Add Module::init() for correct exception handling during hook registration
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 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 "xline.h"
16 #include "socketengine.h"
17 #include "socket.h"
18 #include "command_parse.h"
19 #include "exitcodes.h"
20
21 /* Directory Searching for Unix-Only */
22 #ifndef WIN32
23 #include <dirent.h>
24 #include <dlfcn.h>
25 #endif
26
27 int InspIRCd::PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype)
28 {
29         ModResult res;
30         FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
31
32         /* Module matched */
33         if (res == MOD_RES_ALLOW)
34                 return 0;
35
36         /* Module explicitly didnt match */
37         if (res == MOD_RES_DENY)
38                 return 1;
39
40         /* We dont handle any hash types except for plaintext - Thanks tra26 */
41         if (hashtype != "" && hashtype != "plaintext")
42                 /* See below. 1 because they dont match */
43                 return 1;
44
45         return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
46 }
47
48 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
49  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
50  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
51  * the channel names and their keys as follows:
52  * JOIN #chan1,#chan2,#chan3 key1,,key3
53  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
54  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
55  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
56  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
57  */
58 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, int extra, bool usemax)
59 {
60         if (splithere >= parameters.size())
61                 return 0;
62
63         if (extra >= (signed)parameters.size())
64                 extra = -1;
65
66         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
67          * which called us just carries on as it was.
68          */
69         if (parameters[splithere].find(',') == std::string::npos)
70                 return 0;
71
72         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
73          * By using std::set (thanks for the idea w00t) we can cut this down a ton.
74          * ...VOOODOOOO!
75          */
76         std::set<irc::string> dupes;
77
78         /* Create two lists, one for channel names, one for keys
79          */
80         irc::commasepstream items1(parameters[splithere]);
81         irc::commasepstream items2(extra >= 0 ? parameters[extra] : "");
82         std::string extrastuff;
83         std::string item;
84         unsigned int max = 0;
85
86         /* Attempt to iterate these lists and call the command objech
87          * which called us, for every parameter pair until there are
88          * no more left to parse.
89          */
90         while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
91         {
92                 if (dupes.find(item.c_str()) == dupes.end())
93                 {
94                         std::vector<std::string> new_parameters(parameters);
95
96                         if (!items2.GetToken(extrastuff))
97                                 extrastuff = "";
98
99                         new_parameters[splithere] = item;
100                         if (extra >= 0)
101                                 new_parameters[extra] = extrastuff;
102
103                         CommandObj->Handle(new_parameters, user);
104
105                         dupes.insert(item.c_str());
106                 }
107         }
108         return 1;
109 }
110
111 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
112 {
113         Commandtable::iterator n = cmdlist.find(commandname);
114
115         if (n != cmdlist.end())
116         {
117                 if ((pcnt >= n->second->min_params))
118                 {
119                         if (IS_LOCAL(user) && n->second->flags_needed)
120                         {
121                                 if (user->IsModeSet(n->second->flags_needed))
122                                 {
123                                         return (user->HasPermission(commandname));
124                                 }
125                         }
126                         else
127                         {
128                                 return true;
129                         }
130                 }
131         }
132         return false;
133 }
134
135 Command* CommandParser::GetHandler(const std::string &commandname)
136 {
137         Commandtable::iterator n = cmdlist.find(commandname);
138         if (n != cmdlist.end())
139                 return n->second;
140
141         return NULL;
142 }
143
144 // calls a handler function for a command
145
146 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
147 {
148         Commandtable::iterator n = cmdlist.find(commandname);
149
150         if (n != cmdlist.end())
151         {
152                 if (parameters.size() >= n->second->min_params)
153                 {
154                         bool bOkay = false;
155
156                         if (IS_LOCAL(user) && n->second->flags_needed)
157                         {
158                                 /* if user is local, and flags are needed .. */
159
160                                 if (user->IsModeSet(n->second->flags_needed))
161                                 {
162                                         /* if user has the flags, and now has the permissions, go ahead */
163                                         if (user->HasPermission(commandname))
164                                                 bOkay = true;
165                                 }
166                         }
167                         else
168                         {
169                                 /* remote or no flags required anyway */
170                                 bOkay = true;
171                         }
172
173                         if (bOkay)
174                         {
175                                 return n->second->Handle(parameters,user);
176                         }
177                 }
178         }
179         return CMD_INVALID;
180 }
181
182 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
183 {
184         std::vector<std::string> command_p;
185         irc::tokenstream tokens(cmd);
186         std::string command, token;
187         tokens.GetToken(command);
188
189         /* A client sent a nick prefix on their command (ick)
190          * rhapsody and some braindead bouncers do this --
191          * the rfc says they shouldnt but also says the ircd should
192          * discard it if they do.
193          */
194         if (command[0] == ':')
195                 tokens.GetToken(command);
196
197         while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
198                 command_p.push_back(token);
199
200         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
201
202         /* find the command, check it exists */
203         Commandtable::iterator cm = cmdlist.find(command);
204
205         /* Modify the user's penalty regardless of whether or not the command exists */
206         bool do_more = true;
207         if (IS_LOCAL(user) && !user->HasPrivPermission("users/flood/no-throttle"))
208         {
209                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
210                 IS_LOCAL(user)->CommandFloodPenalty += cm != cmdlist.end() ? cm->second->Penalty * 1000 : 2000;
211         }
212
213
214         if (cm == cmdlist.end())
215         {
216                 ModResult MOD_RESULT;
217                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
218                 if (MOD_RESULT == MOD_RES_DENY)
219                         return true;
220
221                 /*
222                  * This double lookup is in case a module (abbreviation) wishes to change a command.
223                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
224                  *
225                  * Thanks dz for making me actually understand why this is necessary!
226                  * -- w00t
227                  */
228                 cm = cmdlist.find(command);
229                 if (cm == cmdlist.end())
230                 {
231                         if (user->registered == REG_ALL)
232                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
233                         ServerInstance->stats->statsUnknown++;
234                         return true;
235                 }
236         }
237
238         if (cm->second->max_params && command_p.size() > cm->second->max_params)
239         {
240                 /*
241                  * command_p input (assuming max_params 1):
242                  *      this
243                  *      is
244                  *      a
245                  *      test
246                  */
247                 std::string lparam = "";
248
249                 /*
250                  * The '-1' here is a clever trick, we'll go backwards throwing everything into a temporary param
251                  * and then just toss that into the array.
252                  * -- w00t
253                  */
254                 while (command_p.size() > (cm->second->max_params - 1))
255                 {
256                         // BE CAREFUL: .end() returns past the end of the vector, hence decrement.
257                         std::vector<std::string>::iterator it = --command_p.end();
258
259                         lparam.insert(0, " " + *(it));
260                         command_p.erase(it); // remove last element
261                 }
262
263                 /* we now have (each iteration):
264                  *      ' test'
265                  *      ' a test'
266                  *      ' is a test' <-- final string
267                  * ...now remove the ' ' at the start...
268                  */
269                 lparam.erase(lparam.begin());
270
271                 /* param is now 'is a test', which is exactly what we wanted! */
272                 command_p.push_back(lparam);
273         }
274
275         /*
276          * We call OnPreCommand here seperately if the command exists, so the magic above can
277          * truncate to max_params if necessary. -- w00t
278          */
279         ModResult MOD_RESULT;
280         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
281         if (MOD_RESULT == MOD_RES_DENY)
282                 return true;
283
284         /* activity resets the ping pending timer */
285         LocalUser* luser = IS_LOCAL(user);
286         if (luser)
287                 luser->nping = ServerInstance->Time() + luser->MyClass->GetPingTime();
288
289         if (cm->second->flags_needed)
290         {
291                 if (!user->IsModeSet(cm->second->flags_needed))
292                 {
293                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
294                         return do_more;
295                 }
296                 if (!user->HasPermission(command))
297                 {
298                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",
299                                 user->nick.c_str(), user->oper->NameStr(), command.c_str());
300                         return do_more;
301                 }
302         }
303         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
304         {
305                 /* command is disabled! */
306                 if (ServerInstance->Config->DisabledDontExist)
307                 {
308                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
309                 }
310                 else
311                 {
312                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
313                                                                                 user->nick.c_str(), command.c_str());
314                 }
315
316                 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
317                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
318                 return do_more;
319         }
320         if (command_p.size() < cm->second->min_params)
321         {
322                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
323                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
324                         user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->name.c_str(), cm->second->syntax.c_str());
325                 return do_more;
326         }
327         if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
328         {
329                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
330                 return do_more;
331         }
332         else
333         {
334                 /* passed all checks.. first, do the (ugly) stats counters. */
335                 cm->second->use_count++;
336                 cm->second->total_bytes += cmd.length();
337
338                 /* module calls too */
339                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
340                 if (MOD_RESULT == MOD_RES_DENY)
341                         return do_more;
342
343                 /*
344                  * WARNING: be careful, the user may be deleted soon
345                  */
346                 CmdResult result = cm->second->Handle(command_p, user);
347
348                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
349                 return do_more;
350         }
351 }
352
353 void CommandParser::RemoveCommand(Command* x)
354 {
355         Commandtable::iterator n = cmdlist.find(x->name);
356         if (n != cmdlist.end() && n->second == x)
357                 cmdlist.erase(n);
358 }
359
360 Command::~Command()
361 {
362         ServerInstance->Parser->RemoveCommand(this);
363 }
364
365 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
366 {
367         if (!user || buffer.empty())
368                 return true;
369
370         ServerInstance->Logs->Log("USERINPUT", DEBUG, "C[%s] I :%s %s",
371                 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
372         return ProcessCommand(user,buffer);
373 }
374
375 bool CommandParser::AddCommand(Command *f)
376 {
377         /* create the command and push it onto the table */
378         if (cmdlist.find(f->name) == cmdlist.end())
379         {
380                 cmdlist[f->name] = f;
381                 return true;
382         }
383         return false;
384 }
385
386 CommandParser::CommandParser()
387 {
388         para.resize(128);
389 }
390
391 int CommandParser::TranslateUIDs(const std::vector<TranslateType> to, const std::vector<std::string> &source, std::string &dest, bool prefix_final, Command* custom_translator)
392 {
393         std::vector<TranslateType>::const_iterator types = to.begin();
394         User* user = NULL;
395         unsigned int i;
396         int translations = 0;
397         dest.clear();
398
399         for(i=0; i < source.size(); i++)
400         {
401                 TranslateType t;
402                 std::string item = source[i];
403
404                 if (types == to.end())
405                         t = TR_TEXT;
406                 else
407                 {
408                         t = *types;
409                         types++;
410                 }
411
412                 if (prefix_final && i == source.size() - 1)
413                         dest.append(":");
414
415                 switch (t)
416                 {
417                         case TR_NICK:
418                                 /* Translate single nickname */
419                                 user = ServerInstance->FindNick(item);
420                                 if (user)
421                                 {
422                                         dest.append(user->uuid);
423                                         translations++;
424                                 }
425                                 else
426                                         dest.append(item);
427                         break;
428                         case TR_CUSTOM:
429                                 if (custom_translator)
430                                         custom_translator->EncodeParameter(item, i);
431                                 dest.append(item);
432                         break;
433                         case TR_END:
434                         case TR_TEXT:
435                         default:
436                                 /* Do nothing */
437                                 dest.append(item);
438                         break;
439                 }
440                 if (i != source.size() - 1)
441                         dest.append(" ");
442         }
443
444         return translations;
445 }
446
447 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
448 {
449         User* user = NULL;
450         std::string item;
451         int translations = 0;
452         dest.clear();
453
454         switch (to)
455         {
456                 case TR_NICK:
457                         /* Translate single nickname */
458                         user = ServerInstance->FindNick(source);
459                         if (user)
460                         {
461                                 dest = user->uuid;
462                                 translations++;
463                         }
464                         else
465                                 dest = source;
466                 break;
467                 case TR_END:
468                 case TR_TEXT:
469                 default:
470                         /* Do nothing */
471                         dest = source;
472                 break;
473         }
474
475         return translations;
476 }