]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Remove TR_END, remove TRANSLATEx() from commands that do not need it
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
7  *   Copyright (C) 2005-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2006-2007 Dennis Friis <peavey@inspircd.org>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #include "inspircd.h"
25
26 int InspIRCd::PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype)
27 {
28         ModResult res;
29         FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
30
31         /* Module matched */
32         if (res == MOD_RES_ALLOW)
33                 return 0;
34
35         /* Module explicitly didnt match */
36         if (res == MOD_RES_DENY)
37                 return 1;
38
39         /* We dont handle any hash types except for plaintext - Thanks tra26 */
40         if (!hashtype.empty() && hashtype != "plaintext")
41                 /* See below. 1 because they dont match */
42                 return 1;
43
44         return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
45 }
46
47 bool CommandParser::LoopCall(User* user, Command* handler, const std::vector<std::string>& parameters, unsigned int splithere, int extra, bool usemax)
48 {
49         if (splithere >= parameters.size())
50                 return false;
51
52         /* First check if we have more than one item in the list, if we don't we return false here and the handler
53          * which called us just carries on as it was.
54          */
55         if (parameters[splithere].find(',') == std::string::npos)
56                 return false;
57
58         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
59          * By using std::set (thanks for the idea w00t) we can cut this down a ton.
60          * ...VOOODOOOO!
61          *
62          * Only check for duplicates if there is one list (allow them in JOIN).
63          */
64         std::set<irc::string> dupes;
65         bool check_dupes = (extra < 0);
66
67         /* Create two sepstreams, if we have only one list, then initialize the second sepstream with
68          * an empty string. The second parameter of the constructor of the sepstream tells whether
69          * or not to allow empty tokens.
70          * We allow empty keys, so "JOIN #a,#b ,bkey" will be interpreted as "JOIN #a", "JOIN #b bkey"
71          */
72         irc::commasepstream items1(parameters[splithere]);
73         irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
74         std::string item;
75         unsigned int max = 0;
76         LocalUser* localuser = IS_LOCAL(user);
77
78         /* Attempt to iterate these lists and call the command handler
79          * for every parameter or parameter pair until there are no more
80          * left to parse.
81          */
82         while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
83         {
84                 if ((!check_dupes) || (dupes.insert(item.c_str()).second))
85                 {
86                         std::vector<std::string> new_parameters(parameters);
87                         new_parameters[splithere] = item;
88
89                         if (extra >= 0)
90                         {
91                                 // If we have two lists then get the next item from the second list.
92                                 // In case it runs out of elements then 'item' will be an empty string.
93                                 items2.GetToken(item);
94                                 new_parameters[extra] = item;
95                         }
96
97                         CmdResult result = handler->Handle(new_parameters, user);
98                         if (localuser)
99                         {
100                                 // Run the OnPostCommand hook with the last parameter (original line) being empty
101                                 // to indicate that the command had more targets in its original form.
102                                 item.clear();
103                                 FOREACH_MOD(I_OnPostCommand, OnPostCommand(handler, new_parameters, localuser, result, item));
104                         }
105                 }
106         }
107
108         return true;
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.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
153                         return CMD_INVALID;
154
155                 if (parameters.size() >= n->second->min_params)
156                 {
157                         bool bOkay = false;
158
159                         if (IS_LOCAL(user) && n->second->flags_needed)
160                         {
161                                 /* if user is local, and flags are needed .. */
162
163                                 if (user->IsModeSet(n->second->flags_needed))
164                                 {
165                                         /* if user has the flags, and now has the permissions, go ahead */
166                                         if (user->HasPermission(commandname))
167                                                 bOkay = true;
168                                 }
169                         }
170                         else
171                         {
172                                 /* remote or no flags required anyway */
173                                 bOkay = true;
174                         }
175
176                         if (bOkay)
177                         {
178                                 return n->second->Handle(parameters,user);
179                         }
180                 }
181         }
182         return CMD_INVALID;
183 }
184
185 void CommandParser::ProcessCommand(LocalUser *user, std::string &cmd)
186 {
187         std::vector<std::string> command_p;
188         irc::tokenstream tokens(cmd);
189         std::string command, token;
190         tokens.GetToken(command);
191
192         /* A client sent a nick prefix on their command (ick)
193          * rhapsody and some braindead bouncers do this --
194          * the rfc says they shouldnt but also says the ircd should
195          * discard it if they do.
196          */
197         if (command[0] == ':')
198                 tokens.GetToken(command);
199
200         while (tokens.GetToken(token))
201                 command_p.push_back(token);
202
203         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
204
205         /* find the command, check it exists */
206         Command* handler = GetHandler(command);
207
208         /* Modify the user's penalty regardless of whether or not the command exists */
209         if (!user->HasPrivPermission("users/flood/no-throttle"))
210         {
211                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
212                 user->CommandFloodPenalty += handler ? handler->Penalty * 1000 : 2000;
213         }
214
215         if (!handler)
216         {
217                 ModResult MOD_RESULT;
218                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
219                 if (MOD_RESULT == MOD_RES_DENY)
220                         return;
221
222                 /*
223                  * This double lookup is in case a module (abbreviation) wishes to change a command.
224                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
225                  *
226                  * Thanks dz for making me actually understand why this is necessary!
227                  * -- w00t
228                  */
229                 handler = GetHandler(command);
230                 if (!handler)
231                 {
232                         if (user->registered == REG_ALL)
233                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
234                         ServerInstance->stats->statsUnknown++;
235                         return;
236                 }
237         }
238
239         // If we were given more parameters than max_params then append the excess parameter(s)
240         // to command_p[maxparams-1], i.e. to the last param that is still allowed
241         if (handler->max_params && command_p.size() > handler->max_params)
242         {
243                 /*
244                  * command_p input (assuming max_params 1):
245                  *      this
246                  *      is
247                  *      a
248                  *      test
249                  */
250
251                 // Iterator to the last parameter that will be kept
252                 const std::vector<std::string>::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
253                 // Iterator to the first excess parameter
254                 const std::vector<std::string>::iterator firstexcess = lastkeep + 1;
255
256                 // Append all excess parameter(s) to the last parameter, seperated by spaces
257                 for (std::vector<std::string>::const_iterator i = firstexcess; i != command_p.end(); ++i)
258                 {
259                         lastkeep->push_back(' ');
260                         lastkeep->append(*i);
261                 }
262
263                 // Erase the excess parameter(s)
264                 command_p.erase(firstexcess, command_p.end());
265         }
266
267         /*
268          * We call OnPreCommand here seperately if the command exists, so the magic above can
269          * truncate to max_params if necessary. -- w00t
270          */
271         ModResult MOD_RESULT;
272         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
273         if (MOD_RESULT == MOD_RES_DENY)
274                 return;
275
276         /* activity resets the ping pending timer */
277         user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
278
279         if (handler->flags_needed)
280         {
281                 if (!user->IsModeSet(handler->flags_needed))
282                 {
283                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
284                         return;
285                 }
286
287                 if (!user->HasPermission(command))
288                 {
289                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",
290                                 user->nick.c_str(), user->oper->name.c_str(), command.c_str());
291                         return;
292                 }
293         }
294
295         if ((user->registered == REG_ALL) && (!user->IsOper()) && (handler->IsDisabled()))
296         {
297                 /* command is disabled! */
298                 if (ServerInstance->Config->DisabledDontExist)
299                 {
300                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
301                 }
302                 else
303                 {
304                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
305                                                                                 user->nick.c_str(), command.c_str());
306                 }
307
308                 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
309                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
310                 return;
311         }
312
313         if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
314                 command_p.pop_back();
315
316         if (command_p.size() < handler->min_params)
317         {
318                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
319                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (handler->syntax.length()))
320                         user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), handler->name.c_str(), handler->syntax.c_str());
321                 return;
322         }
323
324         if ((user->registered != REG_ALL) && (!handler->WorksBeforeReg()))
325         {
326                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
327         }
328         else
329         {
330                 /* passed all checks.. first, do the (ugly) stats counters. */
331                 handler->use_count++;
332
333                 /* module calls too */
334                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
335                 if (MOD_RESULT == MOD_RES_DENY)
336                         return;
337
338                 /*
339                  * WARNING: be careful, the user may be deleted soon
340                  */
341                 CmdResult result = handler->Handle(command_p, user);
342
343                 FOREACH_MOD(I_OnPostCommand, OnPostCommand(handler, command_p, user, result, cmd));
344         }
345 }
346
347 void CommandParser::RemoveCommand(Command* x)
348 {
349         Commandtable::iterator n = cmdlist.find(x->name);
350         if (n != cmdlist.end() && n->second == x)
351                 cmdlist.erase(n);
352 }
353
354 Command::~Command()
355 {
356         ServerInstance->Parser->RemoveCommand(this);
357 }
358
359 void CommandParser::ProcessBuffer(std::string &buffer,LocalUser *user)
360 {
361         if (!user || buffer.empty())
362                 return;
363
364         ServerInstance->Logs->Log("USERINPUT", LOG_RAWIO, "C[%s] I :%s %s",
365                 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
366         ProcessCommand(user,buffer);
367 }
368
369 bool CommandParser::AddCommand(Command *f)
370 {
371         /* create the command and push it onto the table */
372         if (cmdlist.find(f->name) == cmdlist.end())
373         {
374                 cmdlist[f->name] = f;
375                 return true;
376         }
377         return false;
378 }
379
380 CommandParser::CommandParser()
381 {
382 }
383
384 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const std::vector<std::string>& source, bool prefix_final, Command* custom_translator)
385 {
386         std::vector<TranslateType>::const_iterator types = to.begin();
387         std::string dest;
388
389         for (unsigned int i = 0; i < source.size(); i++)
390         {
391                 TranslateType t = TR_TEXT;
392                 // They might supply less translation types than parameters,
393                 // in that case pretend that all remaining types are TR_TEXT
394                 if (types != to.end())
395                 {
396                         t = *types;
397                         types++;
398                 }
399
400                 bool last = (i == (source.size() - 1));
401                 if (prefix_final && last)
402                         dest.push_back(':');
403
404                 TranslateSingleParam(t, source[i], dest, custom_translator, i);
405
406                 if (!last)
407                         dest.push_back(' ');
408         }
409
410         return dest;
411 }
412
413 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, Command* custom_translator, unsigned int paramnumber)
414 {
415         switch (to)
416         {
417                 case TR_NICK:
418                 {
419                         /* Translate single nickname */
420                         User* user = ServerInstance->FindNick(item);
421                         if (user)
422                                 dest.append(user->uuid);
423                         else
424                                 dest.append(item);
425                         break;
426                 }
427                 case TR_CUSTOM:
428                 {
429                         if (custom_translator)
430                         {
431                                 std::string translated = item;
432                                 custom_translator->EncodeParameter(translated, paramnumber);
433                                 dest.append(translated);
434                                 break;
435                         }
436                         // If no custom translator was given, fall through
437                 }
438                 case TR_TEXT:
439                 default:
440                         /* Do nothing */
441                         dest.append(item);
442                 break;
443         }
444 }