2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
26 bool InspIRCd::PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype)
29 FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
32 if (res == MOD_RES_ALLOW)
35 /* Module explicitly didnt match */
36 if (res == MOD_RES_DENY)
39 /* We dont handle any hash types except for plaintext - Thanks tra26 */
40 if (!hashtype.empty() && hashtype != "plaintext")
43 return TimingSafeCompare(data, input);
46 bool CommandParser::LoopCall(User* user, Command* handler, const CommandBase::Params& parameters, unsigned int splithere, int extra, bool usemax)
48 if (splithere >= parameters.size())
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.
54 if (parameters[splithere].find(',') == std::string::npos)
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.
61 * Only check for duplicates if there is one list (allow them in JOIN).
63 insp::flat_set<std::string, irc::insensitive_swo> dupes;
64 bool check_dupes = (extra < 0);
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"
71 irc::commasepstream items1(parameters[splithere]);
72 irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
75 LocalUser* localuser = IS_LOCAL(user);
77 /* Attempt to iterate these lists and call the command handler
78 * for every parameter or parameter pair until there are no more
81 while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
83 if ((!check_dupes) || (dupes.insert(item).second))
85 CommandBase::Params new_parameters(parameters);
86 new_parameters[splithere] = item;
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;
96 CmdResult result = handler->Handle(user, new_parameters);
99 // Run the OnPostCommand hook with the last parameter (original line) being empty
100 // to indicate that the command had more targets in its original form.
102 FOREACH_MOD(OnPostCommand, (handler, new_parameters, localuser, result));
110 Command* CommandParser::GetHandler(const std::string &commandname)
112 CommandMap::iterator n = cmdlist.find(commandname);
113 if (n != cmdlist.end())
119 // calls a handler function for a command
121 CmdResult CommandParser::CallHandler(const std::string& commandname, const CommandBase::Params& parameters, User* user, Command** cmd)
123 CommandMap::iterator n = cmdlist.find(commandname);
125 if (n != cmdlist.end())
127 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
130 if (parameters.size() >= n->second->min_params)
134 if (IS_LOCAL(user) && n->second->flags_needed)
136 /* if user is local, and flags are needed .. */
138 if (user->IsModeSet(n->second->flags_needed))
140 /* if user has the flags, and now has the permissions, go ahead */
141 if (user->HasPermission(commandname))
147 /* remote or no flags required anyway */
155 return n->second->Handle(user, parameters);
162 void CommandParser::ProcessCommand(LocalUser* user, std::string& command, Command::Params& command_p)
164 /* find the command, check it exists */
165 Command* handler = GetHandler(command);
167 // Penalty to give if the command fails before the handler is executed
168 unsigned int failpenalty = 0;
170 /* Modify the user's penalty regardless of whether or not the command exists */
171 if (!user->HasPrivPermission("users/flood/no-throttle"))
173 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
174 unsigned int penalty = (handler ? handler->Penalty * 1000 : 2000);
175 user->CommandFloodPenalty += penalty;
177 // Increase their penalty later if we fail and the command has 0 penalty by default (i.e. in Command::Penalty) to
178 // throttle sending ERR_* from the command parser. If the command does have a non-zero penalty then this is not
179 // needed because we've increased their penalty above.
186 ModResult MOD_RESULT;
187 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
188 if (MOD_RESULT == MOD_RES_DENY)
192 * This double lookup is in case a module (abbreviation) wishes to change a command.
193 * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
195 * Thanks dz for making me actually understand why this is necessary!
198 handler = GetHandler(command);
201 if (user->registered == REG_ALL)
202 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "Unknown command");
203 ServerInstance->stats.Unknown++;
208 // If we were given more parameters than max_params then append the excess parameter(s)
209 // to command_p[maxparams-1], i.e. to the last param that is still allowed
210 if (handler->max_params && command_p.size() > handler->max_params)
213 * command_p input (assuming max_params 1):
220 // Iterator to the last parameter that will be kept
221 const CommandBase::Params::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
222 // Iterator to the first excess parameter
223 const CommandBase::Params::iterator firstexcess = lastkeep + 1;
225 // Append all excess parameter(s) to the last parameter, seperated by spaces
226 for (CommandBase::Params::const_iterator i = firstexcess; i != command_p.end(); ++i)
228 lastkeep->push_back(' ');
229 lastkeep->append(*i);
232 // Erase the excess parameter(s)
233 command_p.erase(firstexcess, command_p.end());
237 * We call OnPreCommand here seperately if the command exists, so the magic above can
238 * truncate to max_params if necessary. -- w00t
240 ModResult MOD_RESULT;
241 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
242 if (MOD_RESULT == MOD_RES_DENY)
245 /* activity resets the ping pending timer */
246 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
248 if (handler->flags_needed)
250 if (!user->IsModeSet(handler->flags_needed))
252 user->CommandFloodPenalty += failpenalty;
253 user->WriteNumeric(ERR_NOPRIVILEGES, "Permission Denied - You do not have the required operator privileges");
257 if (!user->HasPermission(command))
259 user->CommandFloodPenalty += failpenalty;
260 user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to command %s",
261 user->oper->name.c_str(), command.c_str()));
266 if ((user->registered == REG_ALL) && (!user->IsOper()) && (handler->IsDisabled()))
268 /* command is disabled! */
269 user->CommandFloodPenalty += failpenalty;
270 if (ServerInstance->Config->DisabledDontExist)
272 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "Unknown command");
276 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "This command has been disabled.");
279 ServerInstance->SNO->WriteToSnoMask('a', "%s denied for %s (%s@%s)",
280 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
284 if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
285 command_p.pop_back();
287 if (command_p.size() < handler->min_params)
289 user->CommandFloodPenalty += failpenalty;
290 user->WriteNumeric(ERR_NEEDMOREPARAMS, command, "Not enough parameters.");
291 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (handler->syntax.length()))
292 user->WriteNumeric(RPL_SYNTAX, handler->name, handler->syntax);
296 if ((user->registered != REG_ALL) && (!handler->WorksBeforeReg()))
298 user->CommandFloodPenalty += failpenalty;
299 user->WriteNumeric(ERR_NOTREGISTERED, command, "You have not registered");
303 /* passed all checks.. first, do the (ugly) stats counters. */
304 handler->use_count++;
306 /* module calls too */
307 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true));
308 if (MOD_RESULT == MOD_RES_DENY)
312 * WARNING: be careful, the user may be deleted soon
314 CmdResult result = handler->Handle(user, command_p);
316 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result));
320 void CommandParser::RemoveCommand(Command* x)
322 CommandMap::iterator n = cmdlist.find(x->name);
323 if (n != cmdlist.end() && n->second == x)
327 CommandBase::CommandBase(Module* mod, const std::string& cmd, unsigned int minpara, unsigned int maxpara)
328 : ServiceProvider(mod, cmd, SERVICE_COMMAND)
330 , min_params(minpara)
331 , max_params(maxpara)
334 , works_before_reg(false)
335 , allow_empty_last_param(true)
340 CommandBase::~CommandBase()
344 void CommandBase::EncodeParameter(std::string& parameter, unsigned int index)
348 RouteDescriptor CommandBase::GetRouting(User* user, const Params& parameters)
350 return ROUTE_LOCALONLY;
353 Command::Command(Module* mod, const std::string& cmd, unsigned int minpara, unsigned int maxpara)
354 : CommandBase(mod, cmd, minpara, maxpara)
355 , force_manual_route(false)
361 ServerInstance->Parser.RemoveCommand(this);
364 void Command::RegisterService()
366 if (!ServerInstance->Parser.AddCommand(this))
367 throw ModuleException("Command already exists: " + name);
370 void CommandParser::ProcessBuffer(LocalUser* user, const std::string& buffer)
372 size_t start = buffer.find_first_not_of(" ");
373 if (start == std::string::npos)
375 // Discourage the user from flooding the server.
376 user->CommandFloodPenalty += 2000;
380 ServerInstance->Logs->Log("USERINPUT", LOG_RAWIO, "C[%s] I %s", user->uuid.c_str(), buffer.c_str());
382 irc::tokenstream tokens(buffer, start);
384 CommandBase::Params parameters;
386 // Get the command name. This will always exist because of the check
387 // at the start of the function.
388 tokens.GetMiddle(command);
390 // If this exists then the client sent a prefix as part of their
391 // message. Section 2.3 of RFC 1459 technically says we should only
392 // allow the nick of the client here but in practise everyone just
393 // ignores it so we will copy them.
394 if (command[0] == ':' && !tokens.GetMiddle(command))
396 // Discourage the user from flooding the server.
397 user->CommandFloodPenalty += 2000;
401 // We upper-case the command name to ensure consistency internally.
402 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
404 // Build the parameter map. We intentionally do not respect the RFC 1459
405 // thirteen parameter limit here.
406 std::string parameter;
407 while (tokens.GetTrailing(parameter))
408 parameters.push_back(parameter);
410 ProcessCommand(user, command, parameters);
413 bool CommandParser::AddCommand(Command *f)
415 /* create the command and push it onto the table */
416 if (cmdlist.find(f->name) == cmdlist.end())
418 cmdlist[f->name] = f;
424 CommandParser::CommandParser()
428 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const std::vector<std::string>& source, bool prefix_final, CommandBase* custom_translator)
430 std::vector<TranslateType>::const_iterator types = to.begin();
433 for (unsigned int i = 0; i < source.size(); i++)
435 TranslateType t = TR_TEXT;
436 // They might supply less translation types than parameters,
437 // in that case pretend that all remaining types are TR_TEXT
438 if (types != to.end())
444 bool last = (i == (source.size() - 1));
445 if (prefix_final && last)
448 TranslateSingleParam(t, source[i], dest, custom_translator, i);
457 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, CommandBase* custom_translator, unsigned int paramnumber)
463 /* Translate single nickname */
464 User* user = ServerInstance->FindNick(item);
466 dest.append(user->uuid);
473 if (custom_translator)
475 std::string translated = item;
476 custom_translator->EncodeParameter(translated, paramnumber);
477 dest.append(translated);
480 // If no custom translator was given, fall through