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 int 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")
41 /* See below. 1 because they dont match */
44 return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
47 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
48 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
49 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
50 * the channel names and their keys as follows:
51 * JOIN #chan1,#chan2,#chan3 key1,,key3
52 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
53 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
54 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
55 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
57 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, int extra, bool usemax)
59 if (splithere >= parameters.size())
62 if (extra >= (signed)parameters.size())
65 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
66 * which called us just carries on as it was.
68 if (parameters[splithere].find(',') == std::string::npos)
71 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
72 * By using std::set (thanks for the idea w00t) we can cut this down a ton.
75 std::set<irc::string> dupes;
77 /* Create two lists, one for channel names, one for keys
79 irc::commasepstream items1(parameters[splithere]);
80 irc::commasepstream items2(extra >= 0 ? parameters[extra] : "");
81 std::string extrastuff;
85 /* Attempt to iterate these lists and call the command objech
86 * which called us, for every parameter pair until there are
87 * no more left to parse.
89 while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
91 if (dupes.find(item.c_str()) == dupes.end())
93 std::vector<std::string> new_parameters(parameters);
95 if (!items2.GetToken(extrastuff))
98 new_parameters[splithere] = item;
100 new_parameters[extra] = extrastuff;
102 CommandObj->Handle(new_parameters, user);
104 dupes.insert(item.c_str());
110 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
112 Commandtable::iterator n = cmdlist.find(commandname);
114 if (n != cmdlist.end())
116 if ((pcnt >= n->second->min_params))
118 if (IS_LOCAL(user) && n->second->flags_needed)
120 if (user->IsModeSet(n->second->flags_needed))
122 return (user->HasPermission(commandname));
134 Command* CommandParser::GetHandler(const std::string &commandname)
136 Commandtable::iterator n = cmdlist.find(commandname);
137 if (n != cmdlist.end())
143 // calls a handler function for a command
145 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
147 Commandtable::iterator n = cmdlist.find(commandname);
149 if (n != cmdlist.end())
151 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
154 if (parameters.size() >= n->second->min_params)
158 if (IS_LOCAL(user) && n->second->flags_needed)
160 /* if user is local, and flags are needed .. */
162 if (user->IsModeSet(n->second->flags_needed))
164 /* if user has the flags, and now has the permissions, go ahead */
165 if (user->HasPermission(commandname))
171 /* remote or no flags required anyway */
177 return n->second->Handle(parameters,user);
184 bool CommandParser::ProcessCommand(LocalUser *user, std::string &cmd)
186 std::vector<std::string> command_p;
187 irc::tokenstream tokens(cmd);
188 std::string command, token;
189 tokens.GetToken(command);
191 /* A client sent a nick prefix on their command (ick)
192 * rhapsody and some braindead bouncers do this --
193 * the rfc says they shouldnt but also says the ircd should
194 * discard it if they do.
196 if ((command.empty() || command[0] == ':') && !tokens.GetToken(command))
198 // Penalise the user to discourage them from spamming the server with trash.
199 user->CommandFloodPenalty += 2000;
203 while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
204 command_p.push_back(token);
206 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
208 /* find the command, check it exists */
209 Commandtable::iterator cm = cmdlist.find(command);
211 // Penalty to give if the command fails before the handler is executed
212 unsigned int failpenalty = 0;
214 /* Modify the user's penalty regardless of whether or not the command exists */
216 if (!user->HasPrivPermission("users/flood/no-throttle"))
218 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
219 unsigned int penalty = (cm != cmdlist.end() ? cm->second->Penalty * 1000 : 2000);
220 user->CommandFloodPenalty += penalty;
222 // Increase their penalty later if we fail and the command has 0 penalty by default (i.e. in Command::Penalty) to
223 // throttle sending ERR_* from the command parser. If the command does have a non-zero penalty then this is not
224 // needed because we've increased their penalty above.
230 if (cm == cmdlist.end())
232 ModResult MOD_RESULT;
233 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
234 if (MOD_RESULT == MOD_RES_DENY)
238 * This double lookup is in case a module (abbreviation) wishes to change a command.
239 * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
241 * Thanks dz for making me actually understand why this is necessary!
244 cm = cmdlist.find(command);
245 if (cm == cmdlist.end())
247 if (user->registered == REG_ALL)
248 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
249 ServerInstance->stats->statsUnknown++;
254 if (cm->second->max_params && command_p.size() > cm->second->max_params)
257 * command_p input (assuming max_params 1):
266 * The '-1' here is a clever trick, we'll go backwards throwing everything into a temporary param
267 * and then just toss that into the array.
270 while (command_p.size() > (cm->second->max_params - 1))
272 // BE CAREFUL: .end() returns past the end of the vector, hence decrement.
273 std::vector<std::string>::iterator it = command_p.end() - 1;
275 lparam.insert(0, " " + *(it));
276 command_p.erase(it); // remove last element
279 /* we now have (each iteration):
282 * ' is a test' <-- final string
283 * ...now remove the ' ' at the start...
285 lparam.erase(lparam.begin());
287 /* param is now 'is a test', which is exactly what we wanted! */
288 command_p.push_back(lparam);
292 * We call OnPreCommand here seperately if the command exists, so the magic above can
293 * truncate to max_params if necessary. -- w00t
295 ModResult MOD_RESULT;
296 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
297 if (MOD_RESULT == MOD_RES_DENY)
300 /* activity resets the ping pending timer */
301 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
303 if (cm->second->flags_needed)
305 if (!user->IsModeSet(cm->second->flags_needed))
307 user->CommandFloodPenalty += failpenalty;
308 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
311 if (!user->HasPermission(command))
313 user->CommandFloodPenalty += failpenalty;
314 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",
315 user->nick.c_str(), user->oper->NameStr(), command.c_str());
319 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
321 /* command is disabled! */
322 user->CommandFloodPenalty += failpenalty;
323 if (ServerInstance->Config->DisabledDontExist)
325 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
329 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
330 user->nick.c_str(), command.c_str());
333 ServerInstance->SNO->WriteToSnoMask('a', "%s denied for %s (%s@%s)",
334 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
338 if ((!command_p.empty()) && (command_p.back().empty()) && (!cm->second->allow_empty_last_param))
339 command_p.pop_back();
341 if (command_p.size() < cm->second->min_params)
343 user->CommandFloodPenalty += failpenalty;
344 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
345 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
346 user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->name.c_str(), cm->second->syntax.c_str());
349 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
351 user->CommandFloodPenalty += failpenalty;
352 user->WriteNumeric(ERR_NOTREGISTERED, "%s %s :You have not registered", user->nick.c_str(), command.c_str());
357 /* passed all checks.. first, do the (ugly) stats counters. */
358 cm->second->use_count++;
359 cm->second->total_bytes += cmd.length();
361 /* module calls too */
362 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
363 if (MOD_RESULT == MOD_RES_DENY)
367 * WARNING: be careful, the user may be deleted soon
369 CmdResult result = cm->second->Handle(command_p, user);
371 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
376 void CommandParser::RemoveCommand(Command* x)
378 Commandtable::iterator n = cmdlist.find(x->name);
379 if (n != cmdlist.end() && n->second == x)
385 ServerInstance->Parser->RemoveCommand(this);
388 bool CommandParser::ProcessBuffer(std::string &buffer,LocalUser *user)
390 if (!user || buffer.empty())
393 ServerInstance->Logs->Log("USERINPUT", RAWIO, "C[%s] I :%s %s",
394 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
395 return ProcessCommand(user,buffer);
398 bool CommandParser::AddCommand(Command *f)
400 /* create the command and push it onto the table */
401 if (cmdlist.find(f->name) == cmdlist.end())
403 cmdlist[f->name] = f;
409 CommandParser::CommandParser()
413 int CommandParser::TranslateUIDs(const std::vector<TranslateType> to, const std::vector<std::string> &source, std::string &dest, bool prefix_final, Command* custom_translator)
415 std::vector<TranslateType>::const_iterator types = to.begin();
418 int translations = 0;
421 for(i=0; i < source.size(); i++)
424 std::string item = source[i];
426 if (types == to.end())
434 if (prefix_final && i == source.size() - 1)
440 /* Translate single nickname */
441 user = ServerInstance->FindNick(item);
444 dest.append(user->uuid);
451 if (custom_translator)
452 custom_translator->EncodeParameter(item, i);
462 if (i != source.size() - 1)
469 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
472 int translations = 0;
478 /* Translate single nickname */
479 user = ServerInstance->FindNick(source);