]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Convert the ISO 8859-2 nationalchars files to codepage configs.
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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) 2005-2008, 2010 Craig Edwards <brain@inspircd.org>
11  *
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.
15  *
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
19  * details.
20  *
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/>.
23  */
24
25
26 #include "inspircd.h"
27
28 bool InspIRCd::PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype)
29 {
30         ModResult res;
31         FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
32
33         /* Module matched */
34         if (res == MOD_RES_ALLOW)
35                 return true;
36
37         /* Module explicitly didnt match */
38         if (res == MOD_RES_DENY)
39                 return false;
40
41         /* We dont handle any hash types except for plaintext - Thanks tra26 */
42         if (!hashtype.empty() && !stdalgo::string::equalsci(hashtype, "plaintext"))
43                 return false;
44
45         return TimingSafeCompare(data, input);
46 }
47
48 bool CommandParser::LoopCall(User* user, Command* handler, const CommandBase::Params& parameters, unsigned int splithere, int extra, bool usemax)
49 {
50         if (splithere >= parameters.size())
51                 return false;
52
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.
55          */
56         if (parameters[splithere].find(',') == std::string::npos)
57                 return false;
58
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.
61          * ...VOOODOOOO!
62          *
63          * Only check for duplicates if there is one list (allow them in JOIN).
64          */
65         insp::flat_set<std::string, irc::insensitive_swo> dupes;
66         bool check_dupes = (extra < 0);
67
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"
72          */
73         irc::commasepstream items1(parameters[splithere]);
74         irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
75         std::string item;
76         unsigned int max = 0;
77         LocalUser* localuser = IS_LOCAL(user);
78
79         /* Attempt to iterate these lists and call the command handler
80          * for every parameter or parameter pair until there are no more
81          * left to parse.
82          */
83         CommandBase::Params splitparams(parameters);
84         while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
85         {
86                 if ((!check_dupes) || (dupes.insert(item).second))
87                 {
88                         splitparams[splithere] = item;
89
90                         if (extra >= 0)
91                         {
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;
96                         }
97
98                         CmdResult result = handler->Handle(user, splitparams);
99                         if (localuser)
100                         {
101                                 // Run the OnPostCommand hook with the last parameter being true to indicate
102                                 // that the event is being called in a loop.
103                                 item.clear();
104                                 FOREACH_MOD(OnPostCommand, (handler, splitparams, localuser, result, true));
105                         }
106                 }
107         }
108
109         return true;
110 }
111
112 Command* CommandParser::GetHandler(const std::string &commandname)
113 {
114         CommandMap::iterator n = cmdlist.find(commandname);
115         if (n != cmdlist.end())
116                 return n->second;
117
118         return NULL;
119 }
120
121 // calls a handler function for a command
122
123 CmdResult CommandParser::CallHandler(const std::string& commandname, const CommandBase::Params& parameters, User* user, Command** cmd)
124 {
125         CommandMap::iterator n = cmdlist.find(commandname);
126
127         if (n != cmdlist.end())
128         {
129                 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
130                         return CMD_INVALID;
131
132                 if (parameters.size() >= n->second->min_params)
133                 {
134                         bool bOkay = false;
135
136                         if (IS_LOCAL(user) && n->second->flags_needed)
137                         {
138                                 /* if user is local, and flags are needed .. */
139
140                                 if (user->IsModeSet(n->second->flags_needed))
141                                 {
142                                         /* if user has the flags, and now has the permissions, go ahead */
143                                         if (user->HasCommandPermission(commandname))
144                                                 bOkay = true;
145                                 }
146                         }
147                         else
148                         {
149                                 /* remote or no flags required anyway */
150                                 bOkay = true;
151                         }
152
153                         if (bOkay)
154                         {
155                                 if (cmd)
156                                         *cmd = n->second;
157
158                                 ClientProtocol::TagMap tags;
159                                 return n->second->Handle(user, CommandBase::Params(parameters, tags));
160                         }
161                 }
162         }
163         return CMD_INVALID;
164 }
165
166 void CommandParser::ProcessCommand(LocalUser* user, std::string& command, CommandBase::Params& command_p)
167 {
168         /* find the command, check it exists */
169         Command* handler = GetHandler(command);
170
171         // Penalty to give if the command fails before the handler is executed
172         unsigned int failpenalty = 0;
173
174         /* Modify the user's penalty regardless of whether or not the command exists */
175         if (!user->HasPrivPermission("users/flood/no-throttle"))
176         {
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;
180
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.
184                 if (penalty == 0)
185                         failpenalty = 1000;
186         }
187
188         if (!handler)
189         {
190                 ModResult MOD_RESULT;
191                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
192                 if (MOD_RESULT == MOD_RES_DENY)
193                 {
194                         FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
195                         return;
196                 }
197
198                 /*
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.
201                  *
202                  * Thanks dz for making me actually understand why this is necessary!
203                  * -- w00t
204                  */
205                 handler = GetHandler(command);
206                 if (!handler)
207                 {
208                         if (user->registered == REG_ALL)
209                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, command, "Unknown command");
210
211                         ServerInstance->stats.Unknown++;
212                         FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
213                         return;
214                 }
215         }
216
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)
220         {
221                 /*
222                  * command_p input (assuming max_params 1):
223                  *      this
224                  *      is
225                  *      a
226                  *      test
227                  */
228
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;
233
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)
236                 {
237                         lastkeep->push_back(' ');
238                         lastkeep->append(*i);
239                 }
240
241                 // Erase the excess parameter(s)
242                 command_p.erase(firstexcess, command_p.end());
243         }
244
245         /*
246          * We call OnPreCommand here separately if the command exists, so the magic above can
247          * truncate to max_params if necessary. -- w00t
248          */
249         ModResult MOD_RESULT;
250         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false));
251         if (MOD_RESULT == MOD_RES_DENY)
252         {
253                 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
254                 return;
255         }
256
257         /* activity resets the ping pending timer */
258         user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
259
260         if (handler->flags_needed)
261         {
262                 if (!user->IsModeSet(handler->flags_needed))
263                 {
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));
267                         return;
268                 }
269
270                 if (!user->HasCommandPermission(command))
271                 {
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));
276                         return;
277                 }
278         }
279
280         if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
281                 command_p.pop_back();
282
283         if (command_p.size() < handler->min_params)
284         {
285                 user->CommandFloodPenalty += failpenalty;
286                 handler->TellNotEnoughParameters(user, command_p);
287                 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
288                 return;
289         }
290
291         if ((user->registered != REG_ALL) && (!handler->works_before_reg))
292         {
293                 user->CommandFloodPenalty += failpenalty;
294                 handler->TellNotRegistered(user, command_p);
295                 FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
296         }
297         else
298         {
299                 /* passed all checks.. first, do the (ugly) stats counters. */
300                 handler->use_count++;
301
302                 /* module calls too */
303                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true));
304                 if (MOD_RESULT == MOD_RES_DENY)
305                 {
306                         FOREACH_MOD(OnCommandBlocked, (command, command_p, user));
307                         return;
308                 }
309
310                 /*
311                  * WARNING: be careful, the user may be deleted soon
312                  */
313                 CmdResult result = handler->Handle(user, command_p);
314
315                 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result, false));
316         }
317 }
318
319 void CommandParser::RemoveCommand(Command* x)
320 {
321         CommandMap::iterator n = cmdlist.find(x->name);
322         if (n != cmdlist.end() && n->second == x)
323                 cmdlist.erase(n);
324 }
325
326 void CommandParser::ProcessBuffer(LocalUser* user, const std::string& buffer)
327 {
328         ClientProtocol::ParseOutput parseoutput;
329         if (!user->serializer->Parse(user, buffer, parseoutput))
330                 return;
331
332         std::string& command = parseoutput.cmd;
333         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
334
335         CommandBase::Params parameters(parseoutput.params, parseoutput.tags);
336         ProcessCommand(user, command, parameters);
337 }
338
339 bool CommandParser::AddCommand(Command *f)
340 {
341         /* create the command and push it onto the table */
342         if (cmdlist.find(f->name) == cmdlist.end())
343         {
344                 cmdlist[f->name] = f;
345                 return true;
346         }
347         return false;
348 }
349
350 CommandParser::CommandParser()
351 {
352 }
353
354 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const CommandBase::Params& source, bool prefix_final, CommandBase* custom_translator)
355 {
356         std::vector<TranslateType>::const_iterator types = to.begin();
357         std::string dest;
358
359         for (unsigned int i = 0; i < source.size(); i++)
360         {
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())
365                 {
366                         t = *types;
367                         types++;
368                 }
369
370                 bool last = (i == (source.size() - 1));
371                 if (prefix_final && last)
372                         dest.push_back(':');
373
374                 TranslateSingleParam(t, source[i], dest, custom_translator, i);
375
376                 if (!last)
377                         dest.push_back(' ');
378         }
379
380         return dest;
381 }
382
383 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, CommandBase* custom_translator, unsigned int paramnumber)
384 {
385         switch (to)
386         {
387                 case TR_NICK:
388                 {
389                         /* Translate single nickname */
390                         User* user = ServerInstance->FindNick(item);
391                         if (user)
392                                 dest.append(user->uuid);
393                         else
394                                 dest.append(item);
395                         break;
396                 }
397                 case TR_CUSTOM:
398                 {
399                         if (custom_translator)
400                         {
401                                 std::string translated = item;
402                                 custom_translator->EncodeParameter(translated, paramnumber);
403                                 dest.append(translated);
404                                 break;
405                         }
406                         // If no custom translator was given, fall through
407                 }
408                 /*@fallthrough@*/
409                 default:
410                         /* Do nothing */
411                         dest.append(item);
412                 break;
413         }
414 }