]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Replace printf(_c) with iostream
[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 != "" && 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 = "";
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.size() >= n->second->min_params)
152                 {
153                         bool bOkay = false;
154
155                         if (IS_LOCAL(user) && n->second->flags_needed)
156                         {
157                                 /* if user is local, and flags are needed .. */
158
159                                 if (user->IsModeSet(n->second->flags_needed))
160                                 {
161                                         /* if user has the flags, and now has the permissions, go ahead */
162                                         if (user->HasPermission(commandname))
163                                                 bOkay = true;
164                                 }
165                         }
166                         else
167                         {
168                                 /* remote or no flags required anyway */
169                                 bOkay = true;
170                         }
171
172                         if (bOkay)
173                         {
174                                 return n->second->Handle(parameters,user);
175                         }
176                 }
177         }
178         return CMD_INVALID;
179 }
180
181 bool CommandParser::ProcessCommand(LocalUser *user, std::string &cmd)
182 {
183         std::vector<std::string> command_p;
184         irc::tokenstream tokens(cmd);
185         std::string command, token;
186         tokens.GetToken(command);
187
188         /* A client sent a nick prefix on their command (ick)
189          * rhapsody and some braindead bouncers do this --
190          * the rfc says they shouldnt but also says the ircd should
191          * discard it if they do.
192          */
193         if (command[0] == ':')
194                 tokens.GetToken(command);
195
196         while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
197                 command_p.push_back(token);
198
199         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
200
201         /* find the command, check it exists */
202         Commandtable::iterator cm = cmdlist.find(command);
203
204         /* Modify the user's penalty regardless of whether or not the command exists */
205         bool do_more = true;
206         if (!user->HasPrivPermission("users/flood/no-throttle"))
207         {
208                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
209                 user->CommandFloodPenalty += cm != cmdlist.end() ? cm->second->Penalty * 1000 : 2000;
210         }
211
212
213         if (cm == cmdlist.end())
214         {
215                 ModResult MOD_RESULT;
216                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
217                 if (MOD_RESULT == MOD_RES_DENY)
218                         return true;
219
220                 /*
221                  * This double lookup is in case a module (abbreviation) wishes to change a command.
222                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
223                  *
224                  * Thanks dz for making me actually understand why this is necessary!
225                  * -- w00t
226                  */
227                 cm = cmdlist.find(command);
228                 if (cm == cmdlist.end())
229                 {
230                         if (user->registered == REG_ALL)
231                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
232                         ServerInstance->stats->statsUnknown++;
233                         return true;
234                 }
235         }
236
237         if (cm->second->max_params && command_p.size() > cm->second->max_params)
238         {
239                 /*
240                  * command_p input (assuming max_params 1):
241                  *      this
242                  *      is
243                  *      a
244                  *      test
245                  */
246                 std::string lparam = "";
247
248                 /*
249                  * The '-1' here is a clever trick, we'll go backwards throwing everything into a temporary param
250                  * and then just toss that into the array.
251                  * -- w00t
252                  */
253                 while (command_p.size() > (cm->second->max_params - 1))
254                 {
255                         // BE CAREFUL: .end() returns past the end of the vector, hence decrement.
256                         std::vector<std::string>::iterator it = --command_p.end();
257
258                         lparam.insert(0, " " + *(it));
259                         command_p.erase(it); // remove last element
260                 }
261
262                 /* we now have (each iteration):
263                  *      ' test'
264                  *      ' a test'
265                  *      ' is a test' <-- final string
266                  * ...now remove the ' ' at the start...
267                  */
268                 lparam.erase(lparam.begin());
269
270                 /* param is now 'is a test', which is exactly what we wanted! */
271                 command_p.push_back(lparam);
272         }
273
274         /*
275          * We call OnPreCommand here seperately if the command exists, so the magic above can
276          * truncate to max_params if necessary. -- w00t
277          */
278         ModResult MOD_RESULT;
279         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
280         if (MOD_RESULT == MOD_RES_DENY)
281                 return true;
282
283         /* activity resets the ping pending timer */
284         user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
285
286         if (cm->second->flags_needed)
287         {
288                 if (!user->IsModeSet(cm->second->flags_needed))
289                 {
290                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
291                         return do_more;
292                 }
293                 if (!user->HasPermission(command))
294                 {
295                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",
296                                 user->nick.c_str(), user->oper->NameStr(), command.c_str());
297                         return do_more;
298                 }
299         }
300         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
301         {
302                 /* command is disabled! */
303                 if (ServerInstance->Config->DisabledDontExist)
304                 {
305                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
306                 }
307                 else
308                 {
309                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
310                                                                                 user->nick.c_str(), command.c_str());
311                 }
312
313                 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
314                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
315                 return do_more;
316         }
317         if (command_p.size() < cm->second->min_params)
318         {
319                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
320                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
321                         user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->name.c_str(), cm->second->syntax.c_str());
322                 return do_more;
323         }
324         if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
325         {
326                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
327                 return do_more;
328         }
329         else
330         {
331                 /* passed all checks.. first, do the (ugly) stats counters. */
332                 cm->second->use_count++;
333                 cm->second->total_bytes += cmd.length();
334
335                 /* module calls too */
336                 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
337                 if (MOD_RESULT == MOD_RES_DENY)
338                         return do_more;
339
340                 /*
341                  * WARNING: be careful, the user may be deleted soon
342                  */
343                 CmdResult result = cm->second->Handle(command_p, user);
344
345                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
346                 return do_more;
347         }
348 }
349
350 void CommandParser::RemoveCommand(Command* x)
351 {
352         Commandtable::iterator n = cmdlist.find(x->name);
353         if (n != cmdlist.end() && n->second == x)
354                 cmdlist.erase(n);
355 }
356
357 Command::~Command()
358 {
359         ServerInstance->Parser->RemoveCommand(this);
360 }
361
362 bool CommandParser::ProcessBuffer(std::string &buffer,LocalUser *user)
363 {
364         if (!user || buffer.empty())
365                 return true;
366
367         ServerInstance->Logs->Log("USERINPUT", RAWIO, "C[%s] I :%s %s",
368                 user->uuid.c_str(), user->nick.c_str(), buffer.c_str());
369         return ProcessCommand(user,buffer);
370 }
371
372 bool CommandParser::AddCommand(Command *f)
373 {
374         /* create the command and push it onto the table */
375         if (cmdlist.find(f->name) == cmdlist.end())
376         {
377                 cmdlist[f->name] = f;
378                 return true;
379         }
380         return false;
381 }
382
383 CommandParser::CommandParser()
384 {
385         para.resize(128);
386 }
387
388 int CommandParser::TranslateUIDs(const std::vector<TranslateType> to, const std::vector<std::string> &source, std::string &dest, bool prefix_final, Command* custom_translator)
389 {
390         std::vector<TranslateType>::const_iterator types = to.begin();
391         User* user = NULL;
392         unsigned int i;
393         int translations = 0;
394         dest.clear();
395
396         for(i=0; i < source.size(); i++)
397         {
398                 TranslateType t;
399                 std::string item = source[i];
400
401                 if (types == to.end())
402                         t = TR_TEXT;
403                 else
404                 {
405                         t = *types;
406                         types++;
407                 }
408
409                 if (prefix_final && i == source.size() - 1)
410                         dest.append(":");
411
412                 switch (t)
413                 {
414                         case TR_NICK:
415                                 /* Translate single nickname */
416                                 user = ServerInstance->FindNick(item);
417                                 if (user)
418                                 {
419                                         dest.append(user->uuid);
420                                         translations++;
421                                 }
422                                 else
423                                         dest.append(item);
424                         break;
425                         case TR_CUSTOM:
426                                 if (custom_translator)
427                                         custom_translator->EncodeParameter(item, i);
428                                 dest.append(item);
429                         break;
430                         case TR_END:
431                         case TR_TEXT:
432                         default:
433                                 /* Do nothing */
434                                 dest.append(item);
435                         break;
436                 }
437                 if (i != source.size() - 1)
438                         dest.append(" ");
439         }
440
441         return translations;
442 }
443
444 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
445 {
446         User* user = NULL;
447         std::string item;
448         int translations = 0;
449         dest.clear();
450
451         switch (to)
452         {
453                 case TR_NICK:
454                         /* Translate single nickname */
455                         user = ServerInstance->FindNick(source);
456                         if (user)
457                         {
458                                 dest = user->uuid;
459                                 translations++;
460                         }
461                         else
462                                 dest = source;
463                 break;
464                 case TR_END:
465                 case TR_TEXT:
466                 default:
467                         /* Do nothing */
468                         dest = source;
469                 break;
470         }
471
472         return translations;
473 }