]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
57db5d496c3dc99f3852e7a00be08e622e753fc9
[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 bool 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 true;
34
35         /* Module explicitly didnt match */
36         if (res == MOD_RES_DENY)
37                 return false;
38
39         /* We dont handle any hash types except for plaintext - Thanks tra26 */
40         if (!hashtype.empty() && hashtype != "plaintext")
41                 return false;
42
43         return TimingSafeCompare(data, input);
44 }
45
46 bool CommandParser::LoopCall(User* user, Command* handler, const CommandBase::Params& parameters, unsigned int splithere, int extra, bool usemax)
47 {
48         if (splithere >= parameters.size())
49                 return false;
50
51         /* First check if we have more than one item in the list, if we don't we return false here and the handler
52          * which called us just carries on as it was.
53          */
54         if (parameters[splithere].find(',') == std::string::npos)
55                 return false;
56
57         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
58          * By using std::set (thanks for the idea w00t) we can cut this down a ton.
59          * ...VOOODOOOO!
60          *
61          * Only check for duplicates if there is one list (allow them in JOIN).
62          */
63         insp::flat_set<std::string, irc::insensitive_swo> dupes;
64         bool check_dupes = (extra < 0);
65
66         /* Create two sepstreams, if we have only one list, then initialize the second sepstream with
67          * an empty string. The second parameter of the constructor of the sepstream tells whether
68          * or not to allow empty tokens.
69          * We allow empty keys, so "JOIN #a,#b ,bkey" will be interpreted as "JOIN #a", "JOIN #b bkey"
70          */
71         irc::commasepstream items1(parameters[splithere]);
72         irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
73         std::string item;
74         unsigned int max = 0;
75         LocalUser* localuser = IS_LOCAL(user);
76
77         /* Attempt to iterate these lists and call the command handler
78          * for every parameter or parameter pair until there are no more
79          * left to parse.
80          */
81         while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
82         {
83                 if ((!check_dupes) || (dupes.insert(item).second))
84                 {
85                         CommandBase::Params new_parameters(parameters);
86                         new_parameters[splithere] = item;
87
88                         if (extra >= 0)
89                         {
90                                 // If we have two lists then get the next item from the second list.
91                                 // In case it runs out of elements then 'item' will be an empty string.
92                                 items2.GetToken(item);
93                                 new_parameters[extra] = item;
94                         }
95
96                         CommandBase::Params params(new_parameters, parameters.GetTags());
97                         CmdResult result = handler->Handle(user, params);
98                         if (localuser)
99                         {
100                                 // Run the OnPostCommand hook with the last parameter being true to indicate
101                                 // that the event is being called in a loop.
102                                 item.clear();
103                                 FOREACH_MOD(OnPostCommand, (handler, new_parameters, localuser, result, true));
104                         }
105                 }
106         }
107
108         return true;
109 }
110
111 Command* CommandParser::GetHandler(const std::string &commandname)
112 {
113         CommandMap::iterator n = cmdlist.find(commandname);
114         if (n != cmdlist.end())
115                 return n->second;
116
117         return NULL;
118 }
119
120 // calls a handler function for a command
121
122 CmdResult CommandParser::CallHandler(const std::string& commandname, const CommandBase::Params& parameters, User* user, Command** cmd)
123 {
124         CommandMap::iterator n = cmdlist.find(commandname);
125
126         if (n != cmdlist.end())
127         {
128                 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
129                         return CMD_INVALID;
130
131                 if (parameters.size() >= n->second->min_params)
132                 {
133                         bool bOkay = false;
134
135                         if (IS_LOCAL(user) && n->second->flags_needed)
136                         {
137                                 /* if user is local, and flags are needed .. */
138
139                                 if (user->IsModeSet(n->second->flags_needed))
140                                 {
141                                         /* if user has the flags, and now has the permissions, go ahead */
142                                         if (user->HasCommandPermission(commandname))
143                                                 bOkay = true;
144                                 }
145                         }
146                         else
147                         {
148                                 /* remote or no flags required anyway */
149                                 bOkay = true;
150                         }
151
152                         if (bOkay)
153                         {
154                                 if (cmd)
155                                         *cmd = n->second;
156
157                                 ClientProtocol::TagMap tags;
158                                 return n->second->Handle(user, CommandBase::Params(parameters, tags));
159                         }
160                 }
161         }
162         return CMD_INVALID;
163 }
164
165 void CommandParser::ProcessCommand(LocalUser* user, std::string& command, CommandBase::Params& command_p)
166 {
167         /* find the command, check it exists */
168         Command* handler = GetHandler(command);
169
170         // Penalty to give if the command fails before the handler is executed
171         unsigned int failpenalty = 0;
172
173         /* Modify the user's penalty regardless of whether or not the command exists */
174         if (!user->HasPrivPermission("users/flood/no-throttle"))
175         {
176                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
177                 unsigned int penalty = (handler ? handler->Penalty * 1000 : 2000);
178                 user->CommandFloodPenalty += penalty;
179
180                 // Increase their penalty later if we fail and the command has 0 penalty by default (i.e. in Command::Penalty) to
181                 // throttle sending ERR_* from the command parser. If the command does have a non-zero penalty then this is not
182                 // needed because we've increased their penalty above.
183                 if (penalty == 0)
184                         failpenalty = 1000;
185         }
186
187         if (!handler)
188         {
189                 ModResult MOD_RESULT;
190                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
191                 if (MOD_RESULT == MOD_RES_DENY)
192                         return;
193
194                 /*
195                  * This double lookup is in case a module (abbreviation) wishes to change a command.
196                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
197                  *
198                  * Thanks dz for making me actually understand why this is necessary!
199                  * -- w00t
200                  */
201                 handler = GetHandler(command);
202                 if (!handler)
203                 {
204                         if (user->registered == REG_ALL)
205                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "Unknown command");
206                         ServerInstance->stats.Unknown++;
207                         return;
208                 }
209         }
210
211         // If we were given more parameters than max_params then append the excess parameter(s)
212         // to command_p[maxparams-1], i.e. to the last param that is still allowed
213         if (handler->max_params && command_p.size() > handler->max_params)
214         {
215                 /*
216                  * command_p input (assuming max_params 1):
217                  *      this
218                  *      is
219                  *      a
220                  *      test
221                  */
222
223                 // Iterator to the last parameter that will be kept
224                 const CommandBase::Params::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
225                 // Iterator to the first excess parameter
226                 const CommandBase::Params::iterator firstexcess = lastkeep + 1;
227
228                 // Append all excess parameter(s) to the last parameter, seperated by spaces
229                 for (CommandBase::Params::const_iterator i = firstexcess; i != command_p.end(); ++i)
230                 {
231                         lastkeep->push_back(' ');
232                         lastkeep->append(*i);
233                 }
234
235                 // Erase the excess parameter(s)
236                 command_p.erase(firstexcess, command_p.end());
237         }
238
239         /*
240          * We call OnPreCommand here seperately if the command exists, so the magic above can
241          * truncate to max_params if necessary. -- w00t
242          */
243         ModResult MOD_RESULT;
244         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
245         if (MOD_RESULT == MOD_RES_DENY)
246                 return;
247
248         /* activity resets the ping pending timer */
249         user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
250
251         if (handler->flags_needed)
252         {
253                 if (!user->IsModeSet(handler->flags_needed))
254                 {
255                         user->CommandFloodPenalty += failpenalty;
256                         user->WriteNumeric(ERR_NOPRIVILEGES, "Permission Denied - You do not have the required operator privileges");
257                         return;
258                 }
259
260                 if (!user->HasCommandPermission(command))
261                 {
262                         user->CommandFloodPenalty += failpenalty;
263                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to command %s",
264                                 user->oper->name.c_str(), command.c_str()));
265                         return;
266                 }
267         }
268
269         if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
270                 command_p.pop_back();
271
272         if (command_p.size() < handler->min_params)
273         {
274                 user->CommandFloodPenalty += failpenalty;
275                 user->WriteNumeric(ERR_NEEDMOREPARAMS, command, "Not enough parameters.");
276                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (handler->syntax.length()))
277                         user->WriteNumeric(RPL_SYNTAX, handler->name, handler->syntax);
278                 return;
279         }
280
281         if ((user->registered != REG_ALL) && (!handler->WorksBeforeReg()))
282         {
283                 user->CommandFloodPenalty += failpenalty;
284                 user->WriteNumeric(ERR_NOTREGISTERED, command, "You have not registered");
285         }
286         else
287         {
288                 /* passed all checks.. first, do the (ugly) stats counters. */
289                 handler->use_count++;
290
291                 /* module calls too */
292                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true));
293                 if (MOD_RESULT == MOD_RES_DENY)
294                         return;
295
296                 /*
297                  * WARNING: be careful, the user may be deleted soon
298                  */
299                 CmdResult result = handler->Handle(user, command_p);
300
301                 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result, false));
302         }
303 }
304
305 void CommandParser::RemoveCommand(Command* x)
306 {
307         CommandMap::iterator n = cmdlist.find(x->name);
308         if (n != cmdlist.end() && n->second == x)
309                 cmdlist.erase(n);
310 }
311
312 CommandBase::CommandBase(Module* mod, const std::string& cmd, unsigned int minpara, unsigned int maxpara)
313         : ServiceProvider(mod, cmd, SERVICE_COMMAND)
314         , flags_needed(0)
315         , min_params(minpara)
316         , max_params(maxpara)
317         , use_count(0)
318         , works_before_reg(false)
319         , allow_empty_last_param(true)
320         , Penalty(1)
321 {
322 }
323
324 CommandBase::~CommandBase()
325 {
326 }
327
328 void CommandBase::EncodeParameter(std::string& parameter, unsigned int index)
329 {
330 }
331
332 RouteDescriptor CommandBase::GetRouting(User* user, const Params& parameters)
333 {
334         return ROUTE_LOCALONLY;
335 }
336
337 Command::Command(Module* mod, const std::string& cmd, unsigned int minpara, unsigned int maxpara)
338         : CommandBase(mod, cmd, minpara, maxpara)
339         , force_manual_route(false)
340 {
341 }
342
343 Command::~Command()
344 {
345         ServerInstance->Parser.RemoveCommand(this);
346 }
347
348 void Command::RegisterService()
349 {
350         if (!ServerInstance->Parser.AddCommand(this))
351                 throw ModuleException("Command already exists: " + name);
352 }
353
354 void CommandParser::ProcessBuffer(LocalUser* user, const std::string& buffer)
355 {
356         ClientProtocol::ParseOutput parseoutput;
357         if (!user->serializer->Parse(user, buffer, parseoutput))
358                 return;
359
360         std::string& command = parseoutput.cmd;
361         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
362
363         CommandBase::Params parameters(parseoutput.params, parseoutput.tags);
364         ProcessCommand(user, command, parameters);
365 }
366
367 bool CommandParser::AddCommand(Command *f)
368 {
369         /* create the command and push it onto the table */
370         if (cmdlist.find(f->name) == cmdlist.end())
371         {
372                 cmdlist[f->name] = f;
373                 return true;
374         }
375         return false;
376 }
377
378 CommandParser::CommandParser()
379 {
380 }
381
382 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const CommandBase::Params& source, bool prefix_final, CommandBase* custom_translator)
383 {
384         std::vector<TranslateType>::const_iterator types = to.begin();
385         std::string dest;
386
387         for (unsigned int i = 0; i < source.size(); i++)
388         {
389                 TranslateType t = TR_TEXT;
390                 // They might supply less translation types than parameters,
391                 // in that case pretend that all remaining types are TR_TEXT
392                 if (types != to.end())
393                 {
394                         t = *types;
395                         types++;
396                 }
397
398                 bool last = (i == (source.size() - 1));
399                 if (prefix_final && last)
400                         dest.push_back(':');
401
402                 TranslateSingleParam(t, source[i], dest, custom_translator, i);
403
404                 if (!last)
405                         dest.push_back(' ');
406         }
407
408         return dest;
409 }
410
411 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, CommandBase* custom_translator, unsigned int paramnumber)
412 {
413         switch (to)
414         {
415                 case TR_NICK:
416                 {
417                         /* Translate single nickname */
418                         User* user = ServerInstance->FindNick(item);
419                         if (user)
420                                 dest.append(user->uuid);
421                         else
422                                 dest.append(item);
423                         break;
424                 }
425                 case TR_CUSTOM:
426                 {
427                         if (custom_translator)
428                         {
429                                 std::string translated = item;
430                                 custom_translator->EncodeParameter(translated, paramnumber);
431                                 dest.append(translated);
432                                 break;
433                         }
434                         // If no custom translator was given, fall through
435                 }
436                 /*@fallthrough@*/
437                 default:
438                         /* Do nothing */
439                         dest.append(item);
440                 break;
441         }
442 }