1 /*
2 * InspIRCd -- Internet Relay Chat Daemon
3 *
4 * Copyright (C) 2021 Herman <GermanAizek@yandex.ru>
5 * Copyright (C) 2014, 2018-2020 Sadie Powell <sadie@witchery.services>
6 * Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
8 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
9 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
10 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * Copyright (C) 2005-2008, 2010 Craig Edwards <brain@inspircd.org>
12 *
13 * This file is part of InspIRCd. InspIRCd is free software: you can
14 * redistribute it and/or modify it under the terms of the GNU General Public
15 * License as published by the Free Software Foundation, version 2.
16 *
17 * This program is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27 #include "inspircd.h"
28
PassCompare(Extensible * ex,const std::string & data,const std::string & input,const std::string & hashtype)29 bool InspIRCd::PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype)
30 {
31 ModResult res;
32 FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
33
34 /* Module matched */
35 if (res == MOD_RES_ALLOW)
36 return true;
37
38 /* Module explicitly didnt match */
39 if (res == MOD_RES_DENY)
40 return false;
41
42 /* We dont handle any hash types except for plaintext - Thanks tra26 */
43 if (!hashtype.empty() && !stdalgo::string::equalsci(hashtype, "plaintext"))
44 return false;
45
46 return TimingSafeCompare(data, input);
47 }
48
LoopCall(User * user,Command * handler,const CommandBase::Params & parameters,unsigned int splithere,int extra,bool usemax)49 bool CommandParser::LoopCall(User* user, Command* handler, const CommandBase::Params& parameters, unsigned int splithere, int extra, bool usemax)
50 {
51 if (splithere >= parameters.size())
52 return false;
53
54 /* First check if we have more than one item in the list, if we don't we return false here and the handler
55 * which called us just carries on as it was.
56 */
57 if (parameters[splithere].find(',') == std::string::npos)
58 return false;
59
60 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
61 * By using std::set (thanks for the idea w00t) we can cut this down a ton.
62 * ...VOOODOOOO!
63 *
64 * Only check for duplicates if there is one list (allow them in JOIN).
65 */
66 insp::flat_set<std::string, irc::insensitive_swo> dupes;
67 bool check_dupes = (extra < 0);
68
69 /* Create two sepstreams, if we have only one list, then initialize the second sepstream with
70 * an empty string. The second parameter of the constructor of the sepstream tells whether
71 * or not to allow empty tokens.
72 * We allow empty keys, so "JOIN #a,#b ,bkey" will be interpreted as "JOIN #a", "JOIN #b bkey"
73 */
74 irc::commasepstream items1(parameters[splithere]);
75 irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
76 std::string item;
77 unsigned int max = 0;
78 LocalUser* localuser = IS_LOCAL(user);
79
80 /* Attempt to iterate these lists and call the command handler
81 * for every parameter or parameter pair until there are no more
82 * left to parse.
83 */
84 CommandBase::Params splitparams(parameters);
85 while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
86 {
87 if ((!check_dupes) || (dupes.insert(item).second))
88 {
89 splitparams[splithere] = item;
90
91 if (extra >= 0)
92 {
93 // If we have two lists then get the next item from the second list.
94 // In case it runs out of elements then 'item' will be an empty string.
95 items2.GetToken(item);
96 splitparams[extra] = item;
97 }
98
99 CmdResult result = handler->Handle(user, splitparams);
100 if (localuser)
101 {
102 // Run the OnPostCommand hook with the last parameter being true to indicate
103 // that the event is being called in a loop.
104 item.clear();
105 FOREACH_MOD(OnPostCommand, (handler, splitparams, localuser, result, true));
106 }
107 }
108 }
109
110 return true;
111 }
112
GetHandler(const std::string & commandname)113 Command* CommandParser::GetHandler(const std::string &commandname)
114 {
115 CommandMap::iterator n = cmdlist.find(commandname);
116 if (n != cmdlist.end())
117 return n->second;
118
119 return NULL;
120 }
121
122 // calls a handler function for a command
123
CallHandler(const std::string & commandname,const CommandBase::Params & parameters,User * user,Command ** cmd)124 CmdResult CommandParser::CallHandler(const std::string& commandname, const CommandBase::Params& parameters, User* user, Command** cmd)
125 {
126 /* find the command, check it exists */
127 Command* handler = GetHandler(commandname);
128 if (handler)
129 {
130 if ((!parameters.empty()) && (parameters.back().empty()) && (!handler->allow_empty_last_param))
131 return CMD_INVALID;
132
133 if (parameters.size() >= handler->min_params)
134 {
135 bool bOkay = false;
136
137 if (IS_LOCAL(user) && handler->flags_needed)
138 {
139 /* if user is local, and flags are needed .. */
140
141 if (user->IsModeSet(handler->flags_needed))
142 {
143 /* if user has the flags, and now has the permissions, go ahead */
144 if (user->HasCommandPermission(commandname))
145 bOkay = true;
146 }
147 }
148 else
149 {
150 /* remote or no flags required anyway */
151 bOkay = true;
152 }
153
154 if (bOkay)
155 {
156 if (cmd)
157 *cmd = handler;
158
159 ClientProtocol::TagMap tags;
160 return handler->Handle(user, CommandBase::Params(parameters, tags));
161 }
162 }
163 }
164 return CMD_INVALID;
165 }
166
ProcessCommand(LocalUser * user,std::string & command,CommandBase::Params & command_p)167 void CommandParser::ProcessCommand(LocalUser* user, std::string& command, CommandBase::Params& command_p)
168 {
169 /* find the command, check it exists */
170 Command* handler = GetHandler(command);
171
172 // Penalty to give if the command fails before the handler is executed
173 unsigned int failpenalty = 0;
174
175 /* Modify the user's penalty regardless of whether or not the command exists */
176 if (!user->HasPrivPermission("users/flood/no-throttle"))
177 {
178 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
179 unsigned int penalty = (handler ? handler->Penalty * 1000 : 2000);
180 user->CommandFloodPenalty += penalty;
181
182 // Increase their penalty later if we fail and the command has 0 penalty by default (i.e. in Command::Penalty) to
183 // throttle sending ERR_* from the command parser. If the command does have a non-zero penalty then this is not
184 // needed because we've increased their penalty above.
185 if (penalty == 0)
186 failpenalty = 1000;
187 }
188
189 if (!handler)
190 {
191 ModResult MOD_RESULT;
192 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
193 if (MOD_RESULT == MOD_RES_DENY)
194 {
195 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
196 return;
197 }
198
199 /*
200 * This double lookup is in case a module (abbreviation) wishes to change a command.
201 * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
202 *
203 * Thanks dz for making me actually understand why this is necessary!
204 * -- w00t
205 */
206 handler = GetHandler(command);
207 if (!handler)
208 {
209 if (user->registered == REG_ALL)
210 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "Unknown command");
211
212 ServerInstance->stats.Unknown++;
213 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
214 return;
215 }
216 }
217
218 // If we were given more parameters than max_params then append the excess parameter(s)
219 // to command_p[maxparams-1], i.e. to the last param that is still allowed
220 if (handler->max_params && command_p.size() > handler->max_params)
221 {
222 /*
223 * command_p input (assuming max_params 1):
224 * this
225 * is
226 * a
227 * test
228 */
229
230 // Iterator to the last parameter that will be kept
231 const CommandBase::Params::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
232 // Iterator to the first excess parameter
233 const CommandBase::Params::iterator firstexcess = lastkeep + 1;
234
235 // Append all excess parameter(s) to the last parameter, separated by spaces
236 for (CommandBase::Params::const_iterator i = firstexcess; i != command_p.end(); ++i)
237 {
238 lastkeep->push_back(' ');
239 lastkeep->append(*i);
240 }
241
242 // Erase the excess parameter(s)
243 command_p.erase(firstexcess, command_p.end());
244 }
245
246 /*
247 * We call OnPreCommand here separately if the command exists, so the magic above can
248 * truncate to max_params if necessary. -- w00t
249 */
250 ModResult MOD_RESULT;
251 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
252 if (MOD_RESULT == MOD_RES_DENY)
253 {
254 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
255 return;
256 }
257
258 /* activity resets the ping pending timer */
259 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
260
261 if (handler->flags_needed)
262 {
263 if (!user->IsModeSet(handler->flags_needed))
264 {
265 user->CommandFloodPenalty += failpenalty;
266 user->WriteNumeric(ERR_NOPRIVILEGES, "Permission Denied - You do not have the required operator privileges");
267 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
268 return;
269 }
270
271 if (!user->HasCommandPermission(command))
272 {
273 user->CommandFloodPenalty += failpenalty;
274 user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to command %s",
275 user->oper->name.c_str(), command.c_str()));
276 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
277 return;
278 }
279 }
280
281 if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
282 command_p.pop_back();
283
284 if (command_p.size() < handler->min_params)
285 {
286 user->CommandFloodPenalty += failpenalty;
287 handler->TellNotEnoughParameters(user, command_p);
288 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
289 return;
290 }
291
292 if ((user->registered != REG_ALL) && (!handler->works_before_reg))
293 {
294 user->CommandFloodPenalty += failpenalty;
295 handler->TellNotRegistered(user, command_p);
296 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
297 }
298 else
299 {
300 /* passed all checks.. first, do the (ugly) stats counters. */
301 handler->use_count++;
302
303 /* module calls too */
304 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true));
305 if (MOD_RESULT == MOD_RES_DENY)
306 {
307 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
308 return;
309 }
310
311 /*
312 * WARNING: be careful, the user may be deleted soon
313 */
314 CmdResult result = handler->Handle(user, command_p);
315
316 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result, false));
317 }
318 }
319
RemoveCommand(Command * x)320 void CommandParser::RemoveCommand(Command* x)
321 {
322 CommandMap::iterator n = cmdlist.find(x->name);
323 if (n != cmdlist.end() && n->second == x)
324 cmdlist.erase(n);
325 }
326
ProcessBuffer(LocalUser * user,const std::string & buffer)327 void CommandParser::ProcessBuffer(LocalUser* user, const std::string& buffer)
328 {
329 ClientProtocol::ParseOutput parseoutput;
330 if (!user->serializer->Parse(user, buffer, parseoutput))
331 return;
332
333 std::string& command = parseoutput.cmd;
334 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
335
336 CommandBase::Params parameters(parseoutput.params, parseoutput.tags);
337 ProcessCommand(user, command, parameters);
338 }
339
AddCommand(Command * f)340 bool CommandParser::AddCommand(Command *f)
341 {
342 /* create the command and push it onto the table */
343 if (cmdlist.find(f->name) == cmdlist.end())
344 {
345 cmdlist[f->name] = f;
346 return true;
347 }
348 return false;
349 }
350
CommandParser()351 CommandParser::CommandParser()
352 {
353 }
354
TranslateUIDs(const std::vector<TranslateType> & to,const CommandBase::Params & source,bool prefix_final,CommandBase * custom_translator)355 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const CommandBase::Params& source, bool prefix_final, CommandBase* custom_translator)
356 {
357 std::vector<TranslateType>::const_iterator types = to.begin();
358 std::string dest;
359
360 for (unsigned int i = 0; i < source.size(); i++)
361 {
362 TranslateType t = TR_TEXT;
363 // They might supply less translation types than parameters,
364 // in that case pretend that all remaining types are TR_TEXT
365 if (types != to.end())
366 {
367 t = *types;
368 types++;
369 }
370
371 bool last = (i == (source.size() - 1));
372 if (prefix_final && last)
373 dest.push_back(':');
374
375 TranslateSingleParam(t, source[i], dest, custom_translator, i);
376
377 if (!last)
378 dest.push_back(' ');
379 }
380
381 return dest;
382 }
383
TranslateSingleParam(TranslateType to,const std::string & item,std::string & dest,CommandBase * custom_translator,unsigned int paramnumber)384 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, CommandBase* custom_translator, unsigned int paramnumber)
385 {
386 switch (to)
387 {
388 case TR_NICK:
389 {
390 /* Translate single nickname */
391 User* user = ServerInstance->FindNick(item);
392 if (user)
393 dest.append(user->uuid);
394 else
395 dest.append(item);
396 break;
397 }
398 case TR_CUSTOM:
399 {
400 if (custom_translator)
401 {
402 std::string translated = item;
403 custom_translator->EncodeParameter(translated, paramnumber);
404 dest.append(translated);
405 break;
406 }
407 // If no custom translator was given, fall through
408 }
409 /*@fallthrough@*/
410 default:
411 /* Do nothing */
412 dest.append(item);
413 break;
414 }
415 }
416