]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
cbf6a1005a614402b9fe285efc365353316c0f93
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "inspircd.h"
17 #include "xline.h"
18 #include "socketengine.h"
19 #include "socket.h"
20 #include "command_parse.h"
21 #include "exitcodes.h"
22
23 /* Directory Searching for Unix-Only */
24 #ifndef WIN32
25 #include <dirent.h>
26 #include <dlfcn.h>
27 #endif
28
29 int InspIRCd::PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype)
30 {
31         ModResult res;
32         FIRST_MOD_RESULT(this, OnPassCompare, res, (ex, data, input, hashtype));
33
34         /* Module matched */
35         if (res == MOD_RES_ALLOW)
36                 return 0;
37
38         /* Module explicitly didnt match */
39         if (res == MOD_RES_DENY)
40                 return 1;
41
42         /* We dont handle any hash types except for plaintext - Thanks tra26 */
43         if (hashtype != "" && hashtype != "plaintext")
44                 /* See below. 1 because they dont match */
45                 return 1;
46
47         return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
48 }
49
50 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
51  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
52  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
53  * the channel names and their keys as follows:
54  * JOIN #chan1,#chan2,#chan3 key1,,key3
55  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
56  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
57  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
58  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
59  */
60 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, unsigned int extra)
61 {
62         if (splithere >= parameters.size())
63                 return 0;
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(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) && (max++ < ServerInstance->Config->MaxTargets))
90         {
91                 if (dupes.find(item.c_str()) == dupes.end())
92                 {
93                         std::vector<std::string> new_parameters;
94
95                         for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
96                                 new_parameters.push_back(parameters[t]);
97
98                         if (!items2.GetToken(extrastuff))
99                                 extrastuff = "";
100
101                         new_parameters[splithere] = item.c_str();
102                         new_parameters[extra] = extrastuff.c_str();
103
104                         CommandObj->Handle(new_parameters, user);
105
106                         dupes.insert(item.c_str());
107                 }
108         }
109         return 1;
110 }
111
112 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere)
113 {
114         if (splithere >= parameters.size())
115                 return 0;
116
117         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
118          * which called us just carries on as it was.
119          */
120         if (parameters[splithere].find(',') == std::string::npos)
121                 return 0;
122
123         std::set<irc::string> dupes;
124
125         /* Only one commasepstream here */
126         irc::commasepstream items1(parameters[splithere]);
127         std::string item;
128         unsigned int max = 0;
129
130         /* Parse the commasepstream until there are no tokens remaining.
131          * Each token we parse out, call the command handler that called us
132          * with it
133          */
134         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
135         {
136                 if (dupes.find(item.c_str()) == dupes.end())
137                 {
138                         std::vector<std::string> new_parameters;
139
140                         for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
141                                 new_parameters.push_back(parameters[t]);
142
143                         new_parameters[splithere] = item.c_str();
144
145                         /* Execute the command handler. */
146                         CommandObj->Handle(new_parameters, user);
147
148                         dupes.insert(item.c_str());
149                 }
150         }
151         /* By returning 1 we tell our caller that nothing is to be done,
152          * as all the previous calls handled the data. This makes the parent
153          * return without doing any processing.
154          */
155         return 1;
156 }
157
158 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
159 {
160         Commandtable::iterator n = cmdlist.find(commandname);
161
162         if (n != cmdlist.end())
163         {
164                 if ((pcnt >= n->second->min_params))
165                 {
166                         if (IS_LOCAL(user) && n->second->flags_needed)
167                         {
168                                 if (user->IsModeSet(n->second->flags_needed))
169                                 {
170                                         return (user->HasPermission(commandname));
171                                 }
172                         }
173                         else
174                         {
175                                 return true;
176                         }
177                 }
178         }
179         return false;
180 }
181
182 Command* CommandParser::GetHandler(const std::string &commandname)
183 {
184         Commandtable::iterator n = cmdlist.find(commandname);
185         if (n != cmdlist.end())
186                 return n->second;
187
188         return NULL;
189 }
190
191 // calls a handler function for a command
192
193 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
194 {
195         Commandtable::iterator n = cmdlist.find(commandname);
196
197         if (n != cmdlist.end())
198         {
199                 if (parameters.size() >= n->second->min_params)
200                 {
201                         bool bOkay = false;
202
203                         if (IS_LOCAL(user) && n->second->flags_needed)
204                         {
205                                 /* if user is local, and flags are needed .. */
206
207                                 if (user->IsModeSet(n->second->flags_needed))
208                                 {
209                                         /* if user has the flags, and now has the permissions, go ahead */
210                                         if (user->HasPermission(commandname))
211                                                 bOkay = true;
212                                 }
213                         }
214                         else
215                         {
216                                 /* remote or no flags required anyway */
217                                 bOkay = true;
218                         }
219
220                         if (bOkay)
221                         {
222                                 return n->second->Handle(parameters,user);
223                         }
224                 }
225         }
226         return CMD_INVALID;
227 }
228
229 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
230 {
231         std::vector<std::string> command_p;
232         irc::tokenstream tokens(cmd);
233         std::string command, token;
234         tokens.GetToken(command);
235
236         /* A client sent a nick prefix on their command (ick)
237          * rhapsody and some braindead bouncers do this --
238          * the rfc says they shouldnt but also says the ircd should
239          * discard it if they do.
240          */
241         if (command[0] == ':')
242                 tokens.GetToken(command);
243
244         while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
245                 command_p.push_back(token);
246
247         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
248
249         /* find the command, check it exists */
250         Commandtable::iterator cm = cmdlist.find(command);
251
252         /* Modify the user's penalty regardless of whether or not the command exists */
253         bool do_more = true;
254         if (!user->HasPrivPermission("users/flood/no-throttle"))
255         {
256                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
257                 user->IncreasePenalty(cm != cmdlist.end() ? cm->second->Penalty : 2);
258                 do_more = (user->Penalty < 10);
259         }
260
261
262         if (cm == cmdlist.end())
263         {
264                 ModResult MOD_RESULT;
265                 FIRST_MOD_RESULT(ServerInstance, OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
266                 if (MOD_RESULT == MOD_RES_DENY)
267                         return true;
268
269                 /*
270                  * This double lookup is in case a module (abbreviation) wishes to change a command.
271                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
272                  *
273                  * Thanks dz for making me actually understand why this is necessary!
274                  * -- w00t
275                  */
276                 cm = cmdlist.find(command);
277                 if (cm == cmdlist.end())
278                 {
279                         if (user->registered == REG_ALL)
280                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
281                         ServerInstance->stats->statsUnknown++;
282                         return true;
283                 }
284         }
285
286         if (cm->second->max_params && command_p.size() > cm->second->max_params)
287         {
288                 /*
289                  * command_p input (assuming max_params 1):
290                  *      this
291                  *      is
292                  *      a
293                  *      test
294                  */
295                 std::string lparam = "";
296
297                 /*
298                  * The '-1' here is a clever trick, we'll go backwards throwing everything into a temporary param
299                  * and then just toss that into the array.
300                  * -- w00t
301                  */
302                 while (command_p.size() > (cm->second->max_params - 1))
303                 {
304                         // BE CAREFUL: .end() returns past the end of the vector, hence decrement.
305                         std::vector<std::string>::iterator it = --command_p.end();
306
307                         lparam.insert(0, " " + *(it));
308                         command_p.erase(it); // remove last element
309                 }
310
311                 /* we now have (each iteration):
312                  *      ' test'
313                  *      ' a test'
314                  *      ' is a test' <-- final string
315                  * ...now remove the ' ' at the start...
316                  */
317                 lparam.erase(lparam.begin());
318
319                 /* param is now 'is a test', which is exactly what we wanted! */
320                 command_p.push_back(lparam);
321         }
322
323         /*
324          * We call OnPreCommand here seperately if the command exists, so the magic above can
325          * truncate to max_params if necessary. -- w00t
326          */
327         ModResult MOD_RESULT;
328         FIRST_MOD_RESULT(ServerInstance, OnPreCommand, MOD_RESULT, (command, command_p, user, false, cmd));
329         if (MOD_RESULT == MOD_RES_DENY)
330                 return true;
331
332         /* activity resets the ping pending timer */
333         if (user->MyClass)
334                 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
335
336         if (cm->second->flags_needed)
337         {
338                 if (!user->IsModeSet(cm->second->flags_needed))
339                 {
340                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
341                         return do_more;
342                 }
343                 if (!user->HasPermission(command))
344                 {
345                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",user->nick.c_str(),irc::Spacify(user->oper.c_str()),command.c_str());
346                         return do_more;
347                 }
348         }
349         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
350         {
351                 /* command is disabled! */
352                 if (ServerInstance->Config->DisabledDontExist)
353                 {
354                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
355                 }
356                 else
357                 {
358                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
359                                                                                 user->nick.c_str(), command.c_str());
360                 }
361
362                 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
363                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
364                 return do_more;
365         }
366         if (command_p.size() < cm->second->min_params)
367         {
368                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
369                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
370                         user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->command.c_str(), cm->second->syntax.c_str());
371                 return do_more;
372         }
373         if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
374         {
375                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
376                 return do_more;
377         }
378         else
379         {
380                 /* passed all checks.. first, do the (ugly) stats counters. */
381                 cm->second->use_count++;
382                 cm->second->total_bytes += cmd.length();
383
384                 /* module calls too */
385                 FIRST_MOD_RESULT(ServerInstance, OnPreCommand, MOD_RESULT, (command, command_p, user, true, cmd));
386                 if (MOD_RESULT == MOD_RES_DENY)
387                         return do_more;
388
389                 /*
390                  * WARNING: be careful, the user may be deleted soon
391                  */
392                 CmdResult result = cm->second->Handle(command_p, user);
393
394                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
395                 return do_more;
396         }
397 }
398
399 void CommandParser::RemoveCommands(Module* source)
400 {
401         Commandtable::iterator i,safei;
402         for (i = cmdlist.begin(); i != cmdlist.end();)
403         {
404                 safei = i;
405                 i++;
406                 RemoveCommand(safei, source);
407         }
408 }
409
410 void CommandParser::RemoveCommand(Commandtable::iterator safei, Module* source)
411 {
412         Command* x = safei->second;
413         if (x->creator == source)
414         {
415                 cmdlist.erase(safei);
416         }
417 }
418
419 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
420 {
421         if (!user || buffer.empty())
422                 return true;
423
424         ServerInstance->Logs->Log("USERINPUT", DEBUG, "C[%d] I :%s %s", 
425                 user->GetFd(), user->nick.c_str(), buffer.c_str());
426         return ProcessCommand(user,buffer);
427 }
428
429 bool CommandParser::CreateCommand(Command *f)
430 {
431         /* create the command and push it onto the table */
432         if (cmdlist.find(f->command) == cmdlist.end())
433         {
434                 cmdlist[f->command] = f;
435                 return true;
436         }
437         return false;
438 }
439
440 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
441 {
442         para.resize(128);
443 }
444
445 int CommandParser::TranslateUIDs(const std::vector<TranslateType> to, const std::vector<std::string> &source, std::string &dest, bool prefix_final, Command* custom_translator)
446 {
447         std::vector<TranslateType>::const_iterator types = to.begin();
448         User* user = NULL;
449         unsigned int i;
450         int translations = 0;
451         dest.clear();
452
453         for(i=0; i < source.size(); i++)
454         {
455                 TranslateType t;
456                 std::string item = source[i];
457
458                 if (types == to.end())
459                         t = TR_TEXT;
460                 else
461                 {
462                         t = *types;
463                         types++;
464                 }
465
466                 if (prefix_final && i == source.size() - 1)
467                         dest.append(":");
468
469                 switch (t)
470                 {
471                         case TR_NICK:
472                                 /* Translate single nickname */
473                                 user = ServerInstance->FindNick(item);
474                                 if (user)
475                                 {
476                                         dest.append(user->uuid);
477                                         translations++;
478                                 }
479                                 else
480                                         dest.append(item);
481                         break;
482                         case TR_CUSTOM:
483                                 if (custom_translator)
484                                         custom_translator->EncodeParameter(item, i);
485                                 dest.append(item);
486                         break;
487                         case TR_END:
488                         case TR_TEXT:
489                         default:
490                                 /* Do nothing */
491                                 dest.append(item);
492                         break;
493                 }
494                 if (i != source.size() - 1)
495                         dest.append(" ");
496         }
497
498         return translations;
499 }
500
501 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
502 {
503         User* user = NULL;
504         std::string item;
505         int translations = 0;
506         dest.clear();
507
508         switch (to)
509         {
510                 case TR_NICK:
511                         /* Translate single nickname */
512                         user = ServerInstance->FindNick(source);
513                         if (user)
514                         {
515                                 dest = user->uuid;
516                                 translations++;
517                         }
518                         else
519                                 dest = source;
520                 break;
521                 case TR_END:
522                 case TR_TEXT:
523                 default:
524                         /* Do nothing */
525                         dest = source;
526                 break;
527         }
528
529         return translations;
530 }