]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
e8d68c8478bf4c82bafa5fe748c9bd344b1174f1
[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 int 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 0;
34
35         /* Module explicitly didnt match */
36         if (res == MOD_RES_DENY)
37                 return 1;
38
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 */
42                 return 1;
43
44         return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
45 }
46
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.
56  */
57 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, int extra, bool usemax)
58 {
59         if (splithere >= parameters.size())
60                 return 0;
61
62         if (extra >= (signed)parameters.size())
63                 extra = -1;
64
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.
67          */
68         if (parameters[splithere].find(',') == std::string::npos)
69                 return 0;
70
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.
73          * ...VOOODOOOO!
74          */
75         std::set<irc::string> dupes;
76
77         /* Create two lists, one for channel names, one for keys
78          */
79         irc::commasepstream items1(parameters[splithere]);
80         irc::commasepstream items2(extra >= 0 ? parameters[extra] : "");
81         std::string extrastuff;
82         std::string item;
83         unsigned int max = 0;
84
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.
88          */
89         while (items1.GetToken(item) && (!usemax || max++ < ServerInstance->Config->MaxTargets))
90         {
91                 if (dupes.find(item.c_str()) == dupes.end())
92                 {
93                         std::vector<std::string> new_parameters(parameters);
94
95                         if (!items2.GetToken(extrastuff))
96                                 extrastuff.clear();
97
98                         new_parameters[splithere] = item;
99                         if (extra >= 0)
100                                 new_parameters[extra] = extrastuff;
101
102                         CommandObj->Handle(new_parameters, user);
103
104                         dupes.insert(item.c_str());
105                 }
106         }
107         return 1;
108 }
109
110 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
111 {
112         Commandtable::iterator n = cmdlist.find(commandname);
113
114         if (n != cmdlist.end())
115         {
116                 if ((pcnt >= n->second->min_params))
117                 {
118                         if (IS_LOCAL(user) && n->second->flags_needed)
119                         {
120                                 if (user->IsModeSet(n->second->flags_needed))
121                                 {
122                                         return (user->HasPermission(commandname));
123                                 }
124                         }
125                         else
126                         {
127                                 return true;
128                         }
129                 }
130         }
131         return false;
132 }
133
134 Command* CommandParser::GetHandler(const std::string &commandname)
135 {
136         Commandtable::iterator n = cmdlist.find(commandname);
137         if (n != cmdlist.end())
138                 return n->second;
139
140         return NULL;
141 }
142
143 // calls a handler function for a command
144
145 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
146 {
147         Commandtable::iterator n = cmdlist.find(commandname);
148
149         if (n != cmdlist.end())
150         {
151                 if ((!parameters.empty()) && (parameters.back().empty()) && (!n->second->allow_empty_last_param))
152                         return CMD_INVALID;
153
154                 if (parameters.size() >= n->second->min_params)
155                 {
156                         bool bOkay = false;
157
158                         if (IS_LOCAL(user) && n->second->flags_needed)
159                         {
160                                 /* if user is local, and flags are needed .. */
161
162                                 if (user->IsModeSet(n->second->flags_needed))
163                                 {
164                                         /* if user has the flags, and now has the permissions, go ahead */
165                                         if (user->HasPermission(commandname))
166                                                 bOkay = true;
167                                 }
168                         }
169                         else
170                         {
171                                 /* remote or no flags required anyway */
172                                 bOkay = true;
173                         }
174
175                         if (bOkay)
176                         {
177                                 return n->second->Handle(parameters,user);
178                         }
179                 }
180         }
181         return CMD_INVALID;
182 }
183
184 void CommandParser::ProcessCommand(LocalUser *user, std::string &cmd)
185 {
186         std::vector<std::string> command_p;
187         irc::tokenstream tokens(cmd);
188         std::string command, token;
189         tokens.GetToken(command);
190
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.
195          */
196         if (command[0] == ':')
197                 tokens.GetToken(command);
198
199         while (tokens.GetToken(token))
200                 command_p.push_back(token);
201
202         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
203
204         /* find the command, check it exists */
205         Command* handler = GetHandler(command);
206
207         /* Modify the user's penalty regardless of whether or not the command exists */
208         if (!user->HasPrivPermission("users/flood/no-throttle"))
209         {
210                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
211                 user->CommandFloodPenalty += handler ? handler->Penalty * 1000 : 2000;
212         }
213
214         if (!handler)
215         {
216                 ModResult MOD_RESULT;
217                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
218                 if (MOD_RESULT == MOD_RES_DENY)
219                         return;
220
221                 /*
222                  * This double lookup is in case a module (abbreviation) wishes to change a command.
223                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
224                  *
225                  * Thanks dz for making me actually understand why this is necessary!
226                  * -- w00t
227                  */
228                 handler = GetHandler(command);
229                 if (!handler)
230                 {
231                         if (user->registered == REG_ALL)
232                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
233                         ServerInstance->stats->statsUnknown++;
234                         return;
235                 }
236         }
237
238         // If we were given more parameters than max_params then append the excess parameter(s)
239         // to command_p[maxparams-1], i.e. to the last param that is still allowed
240         if (handler->max_params && command_p.size() > handler->max_params)
241         {
242                 /*
243                  * command_p input (assuming max_params 1):
244                  *      this
245                  *      is
246                  *      a
247                  *      test
248                  */
249
250                 // Iterator to the last parameter that will be kept
251                 const std::vector<std::string>::iterator lastkeep = command_p.begin() + (handler->max_params - 1);
252                 // Iterator to the first excess parameter
253                 const std::vector<std::string>::iterator firstexcess = lastkeep + 1;
254
255                 // Append all excess parameter(s) to the last parameter, seperated by spaces
256                 for (std::vector<std::string>::const_iterator i = firstexcess; i != command_p.end(); ++i)
257                 {
258                         lastkeep->push_back(' ');
259                         lastkeep->append(*i);
260                 }
261
262                 // Erase the excess parameter(s)
263                 command_p.erase(firstexcess, command_p.end());
264         }
265
266         /*
267          * We call OnPreCommand here seperately if the command exists, so the magic above can
268          * truncate to max_params if necessary. -- w00t
269          */
270         ModResult MOD_RESULT;
271         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
272         if (MOD_RESULT == MOD_RES_DENY)
273                 return;
274
275         /* activity resets the ping pending timer */
276         user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
277
278         if (handler->flags_needed)
279         {
280                 if (!user->IsModeSet(handler->flags_needed))
281                 {
282                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
283                         return;
284                 }
285
286                 if (!user->HasPermission(command))
287                 {
288                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",
289                                 user->nick.c_str(), user->oper->name.c_str(), command.c_str());
290                         return;
291                 }
292         }
293
294         if ((user->registered == REG_ALL) && (!user->IsOper()) && (handler->IsDisabled()))
295         {
296                 /* command is disabled! */
297                 if (ServerInstance->Config->DisabledDontExist)
298                 {
299                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
300                 }
301                 else
302                 {
303                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
304                                                                                 user->nick.c_str(), command.c_str());
305                 }
306
307                 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
308                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
309                 return;
310         }
311
312         if ((!command_p.empty()) && (command_p.back().empty()) && (!handler->allow_empty_last_param))
313                 command_p.pop_back();
314
315         if (command_p.size() < handler->min_params)
316         {
317                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
318                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (handler->syntax.length()))
319                         user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), handler->name.c_str(), handler->syntax.c_str());
320                 return;
321         }
322
323         if ((user->registered != REG_ALL) && (!handler->WorksBeforeReg()))
324         {
325                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
326         }
327         else
328         {
329                 /* passed all checks.. first, do the (ugly) stats counters. */
330                 handler->use_count++;
331
332                 /* module calls too */
333                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
334                 if (MOD_RESULT == MOD_RES_DENY)
335                         return;
336
337                 /*
338                  * WARNING: be careful, the user may be deleted soon
339                  */
340                 CmdResult result = handler->Handle(command_p, user);
341
342                 FOREACH_MOD(I_OnPostCommand, OnPostCommand(handler, command_p, user, result, cmd));
343         }
344 }
345
346 void CommandParser::RemoveCommand(Command* x)
347 {
348         Commandtable::iterator n = cmdlist.find(x->name);
349         if (n != cmdlist.end() && n->second == x)
350                 cmdlist.erase(n);
351 }
352
353 Command::~Command()
354 {
355         ServerInstance->Parser->RemoveCommand(this);
356 }
357
358 void CommandParser::ProcessBuffer(std::string &buffer,LocalUser *user)
359 {
360         if (!user || buffer.empty())
361                 return;
362
363         ServerInstance->Logs->Log("USERINPUT", LOG_RAWIO, "C[%s] I :%s %s",
364                 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
365         ProcessCommand(user,buffer);
366 }
367
368 bool CommandParser::AddCommand(Command *f)
369 {
370         /* create the command and push it onto the table */
371         if (cmdlist.find(f->name) == cmdlist.end())
372         {
373                 cmdlist[f->name] = f;
374                 return true;
375         }
376         return false;
377 }
378
379 CommandParser::CommandParser()
380 {
381 }
382
383 int CommandParser::TranslateUIDs(const std::vector<TranslateType> to, const std::vector<std::string> &source, std::string &dest, bool prefix_final, Command* custom_translator)
384 {
385         std::vector<TranslateType>::const_iterator types = to.begin();
386         User* user = NULL;
387         unsigned int i;
388         int translations = 0;
389         dest.clear();
390
391         for(i=0; i < source.size(); i++)
392         {
393                 TranslateType t;
394                 std::string item = source[i];
395
396                 if (types == to.end())
397                         t = TR_TEXT;
398                 else
399                 {
400                         t = *types;
401                         types++;
402                 }
403
404                 if (prefix_final && i == source.size() - 1)
405                         dest.append(":");
406
407                 switch (t)
408                 {
409                         case TR_NICK:
410                                 /* Translate single nickname */
411                                 user = ServerInstance->FindNick(item);
412                                 if (user)
413                                 {
414                                         dest.append(user->uuid);
415                                         translations++;
416                                 }
417                                 else
418                                         dest.append(item);
419                         break;
420                         case TR_CUSTOM:
421                                 if (custom_translator)
422                                         custom_translator->EncodeParameter(item, i);
423                                 dest.append(item);
424                         break;
425                         case TR_END:
426                         case TR_TEXT:
427                         default:
428                                 /* Do nothing */
429                                 dest.append(item);
430                         break;
431                 }
432                 if (i != source.size() - 1)
433                         dest.append(" ");
434         }
435
436         return translations;
437 }
438
439 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
440 {
441         User* user = NULL;
442         int translations = 0;
443         dest.clear();
444
445         switch (to)
446         {
447                 case TR_NICK:
448                         /* Translate single nickname */
449                         user = ServerInstance->FindNick(source);
450                         if (user)
451                         {
452                                 dest = user->uuid;
453                                 translations++;
454                         }
455                         else
456                                 dest = source;
457                 break;
458                 case TR_END:
459                 case TR_TEXT:
460                 default:
461                         /* Do nothing */
462                         dest = source;
463                 break;
464         }
465
466         return translations;
467 }