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 bool CommandParser::LoopCall(User* user, Command* handler, const std::vector<std::string>& parameters, unsigned int splithere, int extra, bool usemax)
49 if (splithere >= parameters.size())
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.
55 if (parameters[splithere].find(',') == std::string::npos)
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.
62 * Only check for duplicates if there is one list (allow them in JOIN).
64 std::set<irc::string> dupes;
65 bool check_dupes = (extra < 0);
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"
72 irc::commasepstream items1(parameters[splithere]);
73 irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
76 LocalUser* localuser = IS_LOCAL(user);
78 /* Attempt to iterate these lists and call the command handler
79 * for every parameter or parameter pair until there are no more
82 while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
84 if ((!check_dupes) || (dupes.insert(item.c_str()).second))
86 std::vector<std::string> new_parameters(parameters);
87 new_parameters[splithere] = item;
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;
97 CmdResult result = handler->Handle(new_parameters, user);
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.
103 FOREACH_MOD(OnPostCommand, (handler, new_parameters, localuser, result, item));
111 Command* CommandParser::GetHandler(const std::string &commandname)
113 Commandtable::iterator n = cmdlist.find(commandname);
114 if (n != cmdlist.end())
120 // calls a handler function for a command
122 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
124 Commandtable::iterator n = cmdlist.find(commandname);
126 if (n != cmdlist.end())
128 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
131 if (parameters.size() >= n->second->min_params)
135 if (IS_LOCAL(user) && n->second->flags_needed)
137 /* if user is local, and flags are needed .. */
139 if (user->IsModeSet(n->second->flags_needed))
141 /* if user has the flags, and now has the permissions, go ahead */
142 if (user->HasPermission(commandname))
148 /* remote or no flags required anyway */
154 return n->second->Handle(parameters,user);
161 void CommandParser::ProcessCommand(LocalUser *user, std::string &cmd)
163 std::vector<std::string> command_p;
164 irc::tokenstream tokens(cmd);
165 std::string command, token;
166 tokens.GetToken(command);
168 /* A client sent a nick prefix on their command (ick)
169 * rhapsody and some braindead bouncers do this --
170 * the rfc says they shouldnt but also says the ircd should
171 * discard it if they do.
173 if (command[0] == ':')
174 tokens.GetToken(command);
176 while (tokens.GetToken(token))
177 command_p.push_back(token);
179 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
181 /* find the command, check it exists */
182 Command* handler = GetHandler(command);
184 /* Modify the user's penalty regardless of whether or not the command exists */
185 if (!user->HasPrivPermission("users/flood/no-throttle"))
187 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
188 user->CommandFloodPenalty += handler ? handler->Penalty * 1000 : 2000;
193 ModResult MOD_RESULT;
194 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
195 if (MOD_RESULT == MOD_RES_DENY)
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, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
210 ServerInstance->stats->statsUnknown++;
215 // If we were given more parameters than max_params then append the excess parameter(s)
216 // to command_p[maxparams-1], i.e. to the last param that is still allowed
217 if (handler->max_params && command_p.size() > handler->max_params)
220 * command_p input (assuming max_params 1):
227 // Iterator to the last parameter that will be kept
228 const std::vector<std::string>::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
229 // Iterator to the first excess parameter
230 const std::vector<std::string>::iterator firstexcess = lastkeep + 1;
232 // Append all excess parameter(s) to the last parameter, seperated by spaces
233 for (std::vector<std::string>::const_iterator i = firstexcess; i != command_p.end(); ++i)
235 lastkeep->push_back(' ');
236 lastkeep->append(*i);
239 // Erase the excess parameter(s)
240 command_p.erase(firstexcess, command_p.end());
244 * We call OnPreCommand here seperately if the command exists, so the magic above can
245 * truncate to max_params if necessary. -- w00t
247 ModResult MOD_RESULT;
248 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
249 if (MOD_RESULT == MOD_RES_DENY)
252 /* activity resets the ping pending timer */
253 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
255 if (handler->flags_needed)
257 if (!user->IsModeSet(handler->flags_needed))
259 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
263 if (!user->HasPermission(command))
265 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",
266 user->nick.c_str(), user->oper->name.c_str(), command.c_str());
271 if ((user->registered == REG_ALL) && (!user->IsOper()) && (handler->IsDisabled()))
273 /* command is disabled! */
274 if (ServerInstance->Config->DisabledDontExist)
276 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
280 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
281 user->nick.c_str(), command.c_str());
284 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
285 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
289 if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
290 command_p.pop_back();
292 if (command_p.size() < handler->min_params)
294 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
295 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (handler->syntax.length()))
296 user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), handler->name.c_str(), handler->syntax.c_str());
300 if ((user->registered != REG_ALL) && (!handler->WorksBeforeReg()))
302 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
306 /* passed all checks.. first, do the (ugly) stats counters. */
307 handler->use_count++;
309 /* module calls too */
310 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
311 if (MOD_RESULT == MOD_RES_DENY)
315 * WARNING: be careful, the user may be deleted soon
317 CmdResult result = handler->Handle(command_p, user);
319 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result, cmd));
323 void CommandParser::RemoveCommand(Command* x)
325 Commandtable::iterator n = cmdlist.find(x->name);
326 if (n != cmdlist.end() && n->second == x)
332 ServerInstance->Parser->RemoveCommand(this);
335 void CommandParser::ProcessBuffer(std::string &buffer,LocalUser *user)
337 if (!user || buffer.empty())
340 ServerInstance->Logs->Log("USERINPUT", LOG_RAWIO, "C[%s] I :%s %s",
341 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
342 ProcessCommand(user,buffer);
345 bool CommandParser::AddCommand(Command *f)
347 /* create the command and push it onto the table */
348 if (cmdlist.find(f->name) == cmdlist.end())
350 cmdlist[f->name] = f;
356 CommandParser::CommandParser()
360 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const std::vector<std::string>& source, bool prefix_final, Command* custom_translator)
362 std::vector<TranslateType>::const_iterator types = to.begin();
365 for (unsigned int i = 0; i < source.size(); i++)
367 TranslateType t = TR_TEXT;
368 // They might supply less translation types than parameters,
369 // in that case pretend that all remaining types are TR_TEXT
370 if (types != to.end())
376 bool last = (i == (source.size() - 1));
377 if (prefix_final && last)
380 TranslateSingleParam(t, source[i], dest, custom_translator, i);
389 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, Command* custom_translator, unsigned int paramnumber)
395 /* Translate single nickname */
396 User* user = ServerInstance->FindNick(item);
398 dest.append(user->uuid);
405 if (custom_translator)
407 std::string translated = item;
408 custom_translator->EncodeParameter(translated, paramnumber);
409 dest.append(translated);
412 // If no custom translator was given, fall through