2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2014, 2018-2020 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
6 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
7 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
8 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10 * Copyright (C) 2006-2008, 2010 Craig Edwards <brain@inspircd.org>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 bool InspIRCd::PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype)
31 FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
34 if (res == MOD_RES_ALLOW)
37 /* Module explicitly didnt match */
38 if (res == MOD_RES_DENY)
41 /* We dont handle any hash types except for plaintext - Thanks tra26 */
42 if (!hashtype.empty() && !stdalgo::string::equalsci(hashtype, "plaintext"))
45 return TimingSafeCompare(data, input);
48 bool CommandParser::LoopCall(User* user, Command* handler, const CommandBase::Params& parameters, unsigned int splithere, int extra, bool usemax)
50 if (splithere >= parameters.size())
53 /* First check if we have more than one item in the list, if we don't we return false here and the handler
54 * which called us just carries on as it was.
56 if (parameters[splithere].find(',') == std::string::npos)
59 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
60 * By using std::set (thanks for the idea w00t) we can cut this down a ton.
63 * Only check for duplicates if there is one list (allow them in JOIN).
65 insp::flat_set<std::string, irc::insensitive_swo> dupes;
66 bool check_dupes = (extra < 0);
68 /* Create two sepstreams, if we have only one list, then initialize the second sepstream with
69 * an empty string. The second parameter of the constructor of the sepstream tells whether
70 * or not to allow empty tokens.
71 * We allow empty keys, so "JOIN #a,#b ,bkey" will be interpreted as "JOIN #a", "JOIN #b bkey"
73 irc::commasepstream items1(parameters[splithere]);
74 irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
77 LocalUser* localuser = IS_LOCAL(user);
79 /* Attempt to iterate these lists and call the command handler
80 * for every parameter or parameter pair until there are no more
83 CommandBase::Params splitparams(parameters);
84 while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
86 if ((!check_dupes) || (dupes.insert(item).second))
88 splitparams[splithere] = item;
92 // If we have two lists then get the next item from the second list.
93 // In case it runs out of elements then 'item' will be an empty string.
94 items2.GetToken(item);
95 splitparams[extra] = item;
98 CmdResult result = handler->Handle(user, splitparams);
101 // Run the OnPostCommand hook with the last parameter being true to indicate
102 // that the event is being called in a loop.
104 FOREACH_MOD(OnPostCommand, (handler, splitparams, localuser, result, true));
112 Command* CommandParser::GetHandler(const std::string &commandname)
114 CommandMap::iterator n = cmdlist.find(commandname);
115 if (n != cmdlist.end())
121 // calls a handler function for a command
123 CmdResult CommandParser::CallHandler(const std::string& commandname, const CommandBase::Params& parameters, User* user, Command** cmd)
125 CommandMap::iterator n = cmdlist.find(commandname);
127 if (n != cmdlist.end())
129 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
132 if (parameters.size() >= n->second->min_params)
136 if (IS_LOCAL(user) && n->second->flags_needed)
138 /* if user is local, and flags are needed .. */
140 if (user->IsModeSet(n->second->flags_needed))
142 /* if user has the flags, and now has the permissions, go ahead */
143 if (user->HasCommandPermission(commandname))
149 /* remote or no flags required anyway */
158 ClientProtocol::TagMap tags;
159 return n->second->Handle(user, CommandBase::Params(parameters, tags));
166 void CommandParser::ProcessCommand(LocalUser* user, std::string& command, CommandBase::Params& command_p)
168 /* find the command, check it exists */
169 Command* handler = GetHandler(command);
171 // Penalty to give if the command fails before the handler is executed
172 unsigned int failpenalty = 0;
174 /* Modify the user's penalty regardless of whether or not the command exists */
175 if (!user->HasPrivPermission("users/flood/no-throttle"))
177 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
178 unsigned int penalty = (handler ? handler->Penalty * 1000 : 2000);
179 user->CommandFloodPenalty += penalty;
181 // Increase their penalty later if we fail and the command has 0 penalty by default (i.e. in Command::Penalty) to
182 // throttle sending ERR_* from the command parser. If the command does have a non-zero penalty then this is not
183 // needed because we've increased their penalty above.
190 ModResult MOD_RESULT;
191 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
192 if (MOD_RESULT == MOD_RES_DENY)
194 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
199 * This double lookup is in case a module (abbreviation) wishes to change a command.
200 * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
202 * Thanks dz for making me actually understand why this is necessary!
205 handler = GetHandler(command);
208 if (user->registered == REG_ALL)
209 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "Unknown command");
211 ServerInstance->stats.Unknown++;
212 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
217 // If we were given more parameters than max_params then append the excess parameter(s)
218 // to command_p[maxparams-1], i.e. to the last param that is still allowed
219 if (handler->max_params && command_p.size() > handler->max_params)
222 * command_p input (assuming max_params 1):
229 // Iterator to the last parameter that will be kept
230 const CommandBase::Params::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
231 // Iterator to the first excess parameter
232 const CommandBase::Params::iterator firstexcess = lastkeep + 1;
234 // Append all excess parameter(s) to the last parameter, separated by spaces
235 for (CommandBase::Params::const_iterator i = firstexcess; i != command_p.end(); ++i)
237 lastkeep->push_back(' ');
238 lastkeep->append(*i);
241 // Erase the excess parameter(s)
242 command_p.erase(firstexcess, command_p.end());
246 * We call OnPreCommand here separately if the command exists, so the magic above can
247 * truncate to max_params if necessary. -- w00t
249 ModResult MOD_RESULT;
250 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
251 if (MOD_RESULT == MOD_RES_DENY)
253 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
257 /* activity resets the ping pending timer */
258 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
260 if (handler->flags_needed)
262 if (!user->IsModeSet(handler->flags_needed))
264 user->CommandFloodPenalty += failpenalty;
265 user->WriteNumeric(ERR_NOPRIVILEGES, "Permission Denied - You do not have the required operator privileges");
266 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
270 if (!user->HasCommandPermission(command))
272 user->CommandFloodPenalty += failpenalty;
273 user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to command %s",
274 user->oper->name.c_str(), command.c_str()));
275 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
280 if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
281 command_p.pop_back();
283 if (command_p.size() < handler->min_params)
285 user->CommandFloodPenalty += failpenalty;
286 handler->TellNotEnoughParameters(user, command_p);
287 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
291 if ((user->registered != REG_ALL) && (!handler->works_before_reg))
293 user->CommandFloodPenalty += failpenalty;
294 handler->TellNotRegistered(user, command_p);
295 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
299 /* passed all checks.. first, do the (ugly) stats counters. */
300 handler->use_count++;
302 /* module calls too */
303 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true));
304 if (MOD_RESULT == MOD_RES_DENY)
306 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
311 * WARNING: be careful, the user may be deleted soon
313 CmdResult result = handler->Handle(user, command_p);
315 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result, false));
319 void CommandParser::RemoveCommand(Command* x)
321 CommandMap::iterator n = cmdlist.find(x->name);
322 if (n != cmdlist.end() && n->second == x)
326 void CommandParser::ProcessBuffer(LocalUser* user, const std::string& buffer)
328 ClientProtocol::ParseOutput parseoutput;
329 if (!user->serializer->Parse(user, buffer, parseoutput))
332 std::string& command = parseoutput.cmd;
333 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
335 CommandBase::Params parameters(parseoutput.params, parseoutput.tags);
336 ProcessCommand(user, command, parameters);
339 bool CommandParser::AddCommand(Command *f)
341 /* create the command and push it onto the table */
342 if (cmdlist.find(f->name) == cmdlist.end())
344 cmdlist[f->name] = f;
350 CommandParser::CommandParser()
354 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const CommandBase::Params& source, bool prefix_final, CommandBase* custom_translator)
356 std::vector<TranslateType>::const_iterator types = to.begin();
359 for (unsigned int i = 0; i < source.size(); i++)
361 TranslateType t = TR_TEXT;
362 // They might supply less translation types than parameters,
363 // in that case pretend that all remaining types are TR_TEXT
364 if (types != to.end())
370 bool last = (i == (source.size() - 1));
371 if (prefix_final && last)
374 TranslateSingleParam(t, source[i], dest, custom_translator, i);
383 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, CommandBase* custom_translator, unsigned int paramnumber)
389 /* Translate single nickname */
390 User* user = ServerInstance->FindNick(item);
392 dest.append(user->uuid);
399 if (custom_translator)
401 std::string translated = item;
402 custom_translator->EncodeParameter(translated, paramnumber);
403 dest.append(translated);
406 // If no custom translator was given, fall through