]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
d89d7cbb597097568a781d3f96ec9db7a2f1a4fb
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
9  *
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.
13  *
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
17  * details.
18  *
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/>.
21  */
22
23
24 #include "inspircd.h"
25
26 bool InspIRCd::PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype)
27 {
28         ModResult res;
29         FIRST_MOD_RESULT(OnPassCompare, res, (ex, data, input, hashtype));
30
31         /* Module matched */
32         if (res == MOD_RES_ALLOW)
33                 return true;
34
35         /* Module explicitly didnt match */
36         if (res == MOD_RES_DENY)
37                 return false;
38
39         /* We dont handle any hash types except for plaintext - Thanks tra26 */
40         if (!hashtype.empty() && hashtype != "plaintext")
41                 return false;
42
43         return (data == input);
44 }
45
46 bool CommandParser::LoopCall(User* user, Command* handler, const std::vector<std::string>& parameters, unsigned int splithere, int extra, bool usemax)
47 {
48         if (splithere >= parameters.size())
49                 return false;
50
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.
53          */
54         if (parameters[splithere].find(',') == std::string::npos)
55                 return false;
56
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.
59          * ...VOOODOOOO!
60          *
61          * Only check for duplicates if there is one list (allow them in JOIN).
62          */
63         std::set<irc::string> dupes;
64         bool check_dupes = (extra < 0);
65
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"
70          */
71         irc::commasepstream items1(parameters[splithere]);
72         irc::commasepstream items2(extra >= 0 ? parameters[extra] : "", true);
73         std::string item;
74         unsigned int max = 0;
75         LocalUser* localuser = IS_LOCAL(user);
76
77         /* Attempt to iterate these lists and call the command handler
78          * for every parameter or parameter pair until there are no more
79          * left to parse.
80          */
81         while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
82         {
83                 if ((!check_dupes) || (dupes.insert(item.c_str()).second))
84                 {
85                         std::vector<std::string> new_parameters(parameters);
86                         new_parameters[splithere] = item;
87
88                         if (extra >= 0)
89                         {
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;
94                         }
95
96                         CmdResult result = handler->Handle(new_parameters, user);
97                         if (localuser)
98                         {
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.
101                                 item.clear();
102                                 FOREACH_MOD(OnPostCommand, (handler, new_parameters, localuser, result, item));
103                         }
104                 }
105         }
106
107         return true;
108 }
109
110 Command* CommandParser::GetHandler(const std::string &commandname)
111 {
112         Commandtable::iterator n = cmdlist.find(commandname);
113         if (n != cmdlist.end())
114                 return n->second;
115
116         return NULL;
117 }
118
119 // calls a handler function for a command
120
121 CmdResult CommandParser::CallHandler(const std::string& commandname, const std::vector<std::string>& parameters, User* user, Command** cmd)
122 {
123         Commandtable::iterator n = cmdlist.find(commandname);
124
125         if (n != cmdlist.end())
126         {
127                 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
128                         return CMD_INVALID;
129
130                 if (parameters.size() >= n->second->min_params)
131                 {
132                         bool bOkay = false;
133
134                         if (IS_LOCAL(user) && n->second->flags_needed)
135                         {
136                                 /* if user is local, and flags are needed .. */
137
138                                 if (user->IsModeSet(n->second->flags_needed))
139                                 {
140                                         /* if user has the flags, and now has the permissions, go ahead */
141                                         if (user->HasPermission(commandname))
142                                                 bOkay = true;
143                                 }
144                         }
145                         else
146                         {
147                                 /* remote or no flags required anyway */
148                                 bOkay = true;
149                         }
150
151                         if (bOkay)
152                         {
153                                 if (cmd)
154                                         *cmd = n->second;
155                                 return n->second->Handle(parameters,user);
156                         }
157                 }
158         }
159         return CMD_INVALID;
160 }
161
162 void CommandParser::ProcessCommand(LocalUser *user, std::string &cmd)
163 {
164         std::vector<std::string> command_p;
165         irc::tokenstream tokens(cmd);
166         std::string command, token;
167         tokens.GetToken(command);
168
169         /* A client sent a nick prefix on their command (ick)
170          * rhapsody and some braindead bouncers do this --
171          * the rfc says they shouldnt but also says the ircd should
172          * discard it if they do.
173          */
174         if (command[0] == ':')
175                 tokens.GetToken(command);
176
177         while (tokens.GetToken(token))
178                 command_p.push_back(token);
179
180         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
181
182         /* find the command, check it exists */
183         Command* handler = GetHandler(command);
184
185         /* Modify the user's penalty regardless of whether or not the command exists */
186         if (!user->HasPrivPermission("users/flood/no-throttle"))
187         {
188                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
189                 user->CommandFloodPenalty += handler ? handler->Penalty * 1000 : 2000;
190         }
191
192         if (!handler)
193         {
194                 ModResult MOD_RESULT;
195                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
196                 if (MOD_RESULT == MOD_RES_DENY)
197                         return;
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, "%s :Unknown command",command.c_str());
211                         ServerInstance->stats->statsUnknown++;
212                         return;
213                 }
214         }
215
216         // If we were given more parameters than max_params then append the excess parameter(s)
217         // to command_p[maxparams-1], i.e. to the last param that is still allowed
218         if (handler->max_params && command_p.size() > handler->max_params)
219         {
220                 /*
221                  * command_p input (assuming max_params 1):
222                  *      this
223                  *      is
224                  *      a
225                  *      test
226                  */
227
228                 // Iterator to the last parameter that will be kept
229                 const std::vector<std::string>::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
230                 // Iterator to the first excess parameter
231                 const std::vector<std::string>::iterator firstexcess = lastkeep + 1;
232
233                 // Append all excess parameter(s) to the last parameter, seperated by spaces
234                 for (std::vector<std::string>::const_iterator i = firstexcess; i != command_p.end(); ++i)
235                 {
236                         lastkeep->push_back(' ');
237                         lastkeep->append(*i);
238                 }
239
240                 // Erase the excess parameter(s)
241                 command_p.erase(firstexcess, command_p.end());
242         }
243
244         /*
245          * We call OnPreCommand here seperately if the command exists, so the magic above can
246          * truncate to max_params if necessary. -- w00t
247          */
248         ModResult MOD_RESULT;
249         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
250         if (MOD_RESULT == MOD_RES_DENY)
251                 return;
252
253         /* activity resets the ping pending timer */
254         user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
255
256         if (handler->flags_needed)
257         {
258                 if (!user->IsModeSet(handler->flags_needed))
259                 {
260                         user->WriteNumeric(ERR_NOPRIVILEGES, ":Permission Denied - You do not have the required operator privileges");
261                         return;
262                 }
263
264                 if (!user->HasPermission(command))
265                 {
266                         user->WriteNumeric(ERR_NOPRIVILEGES, ":Permission Denied - Oper type %s does not have access to command %s",
267                                 user->oper->name.c_str(), command.c_str());
268                         return;
269                 }
270         }
271
272         if ((user->registered == REG_ALL) && (!user->IsOper()) && (handler->IsDisabled()))
273         {
274                 /* command is disabled! */
275                 if (ServerInstance->Config->DisabledDontExist)
276                 {
277                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s :Unknown command", command.c_str());
278                 }
279                 else
280                 {
281                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s :This command has been disabled.", command.c_str());
282                 }
283
284                 ServerInstance->SNO->WriteToSnoMask('a', "%s denied for %s (%s@%s)",
285                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
286                 return;
287         }
288
289         if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
290                 command_p.pop_back();
291
292         if (command_p.size() < handler->min_params)
293         {
294                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s :Not enough parameters.", command.c_str());
295                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (handler->syntax.length()))
296                         user->WriteNumeric(RPL_SYNTAX, ":SYNTAX %s %s", handler->name.c_str(), handler->syntax.c_str());
297                 return;
298         }
299
300         if ((user->registered != REG_ALL) && (!handler->WorksBeforeReg()))
301         {
302                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
303         }
304         else
305         {
306                 /* passed all checks.. first, do the (ugly) stats counters. */
307                 handler->use_count++;
308
309                 /* module calls too */
310                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
311                 if (MOD_RESULT == MOD_RES_DENY)
312                         return;
313
314                 /*
315                  * WARNING: be careful, the user may be deleted soon
316                  */
317                 CmdResult result = handler->Handle(command_p, user);
318
319                 FOREACH_MOD(OnPostCommand, (handler, command_p, user, result, cmd));
320         }
321 }
322
323 void CommandParser::RemoveCommand(Command* x)
324 {
325         Commandtable::iterator n = cmdlist.find(x->name);
326         if (n != cmdlist.end() && n->second == x)
327                 cmdlist.erase(n);
328 }
329
330 CommandBase::~CommandBase()
331 {
332 }
333
334 Command::~Command()
335 {
336         ServerInstance->Parser->RemoveCommand(this);
337 }
338
339 void CommandParser::ProcessBuffer(std::string &buffer,LocalUser *user)
340 {
341         if (buffer.empty())
342                 return;
343
344         ServerInstance->Logs->Log("USERINPUT", LOG_RAWIO, "C[%s] I :%s %s",
345                 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
346         ProcessCommand(user,buffer);
347 }
348
349 bool CommandParser::AddCommand(Command *f)
350 {
351         /* create the command and push it onto the table */
352         if (cmdlist.find(f->name) == cmdlist.end())
353         {
354                 cmdlist[f->name] = f;
355                 return true;
356         }
357         return false;
358 }
359
360 CommandParser::CommandParser()
361 {
362 }
363
364 std::string CommandParser::TranslateUIDs(const std::vector<TranslateType>& to, const std::vector<std::string>& source, bool prefix_final, CommandBase* custom_translator)
365 {
366         std::vector<TranslateType>::const_iterator types = to.begin();
367         std::string dest;
368
369         for (unsigned int i = 0; i < source.size(); i++)
370         {
371                 TranslateType t = TR_TEXT;
372                 // They might supply less translation types than parameters,
373                 // in that case pretend that all remaining types are TR_TEXT
374                 if (types != to.end())
375                 {
376                         t = *types;
377                         types++;
378                 }
379
380                 bool last = (i == (source.size() - 1));
381                 if (prefix_final && last)
382                         dest.push_back(':');
383
384                 TranslateSingleParam(t, source[i], dest, custom_translator, i);
385
386                 if (!last)
387                         dest.push_back(' ');
388         }
389
390         return dest;
391 }
392
393 void CommandParser::TranslateSingleParam(TranslateType to, const std::string& item, std::string& dest, CommandBase* custom_translator, unsigned int paramnumber)
394 {
395         switch (to)
396         {
397                 case TR_NICK:
398                 {
399                         /* Translate single nickname */
400                         User* user = ServerInstance->FindNick(item);
401                         if (user)
402                                 dest.append(user->uuid);
403                         else
404                                 dest.append(item);
405                         break;
406                 }
407                 case TR_CUSTOM:
408                 {
409                         if (custom_translator)
410                         {
411                                 std::string translated = item;
412                                 custom_translator->EncodeParameter(translated, paramnumber);
413                                 dest.append(translated);
414                                 break;
415                         }
416                         // If no custom translator was given, fall through
417                 }
418                 case TR_TEXT:
419                 default:
420                         /* Do nothing */
421                         dest.append(item);
422                 break;
423         }
424 }