1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
18 #include "socketengine.h"
20 #include "command_parse.h"
21 #include "exitcodes.h"
23 /* Directory Searching for Unix-Only */
29 int InspIRCd::PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype)
32 FOREACH_RESULT_I(this,I_OnPassCompare,OnPassCompare(ex, data, input, hashtype))
38 /* Module explicitly didnt match */
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 */
47 return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
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.
60 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, unsigned int extra)
62 if (splithere >= parameters.size())
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.
68 if (parameters[splithere].find(',') == std::string::npos)
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.
75 std::set<irc::string> dupes;
77 /* Create two lists, one for channel names, one for keys
79 irc::commasepstream items1(parameters[splithere]);
80 irc::commasepstream items2(parameters[extra]);
81 std::string extrastuff;
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.
89 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
91 if (dupes.find(item.c_str()) == dupes.end())
93 std::vector<std::string> new_parameters;
95 for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
96 new_parameters.push_back(parameters[t]);
98 if (!items2.GetToken(extrastuff))
101 new_parameters[splithere] = item.c_str();
102 new_parameters[extra] = extrastuff.c_str();
104 CommandObj->Handle(new_parameters, user);
106 dupes.insert(item.c_str());
112 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere)
114 if (splithere >= parameters.size())
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.
120 if (parameters[splithere].find(',') == std::string::npos)
123 std::set<irc::string> dupes;
125 /* Only one commasepstream here */
126 irc::commasepstream items1(parameters[splithere]);
128 unsigned int max = 0;
130 /* Parse the commasepstream until there are no tokens remaining.
131 * Each token we parse out, call the command handler that called us
134 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
136 if (dupes.find(item.c_str()) == dupes.end())
138 std::vector<std::string> new_parameters;
140 for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
141 new_parameters.push_back(parameters[t]);
143 new_parameters[splithere] = item.c_str();
145 /* Execute the command handler. */
146 CommandObj->Handle(new_parameters, user);
148 dupes.insert(item.c_str());
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.
158 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
160 Commandtable::iterator n = cmdlist.find(commandname);
162 if (n != cmdlist.end())
164 if ((pcnt >= n->second->min_params) && (n->second->source != "<core>"))
166 if (IS_LOCAL(user) && n->second->flags_needed)
168 if (user->IsModeSet(n->second->flags_needed))
170 return (user->HasPermission(commandname));
182 Command* CommandParser::GetHandler(const std::string &commandname)
184 Commandtable::iterator n = cmdlist.find(commandname);
185 if (n != cmdlist.end())
191 // calls a handler function for a command
193 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
195 Commandtable::iterator n = cmdlist.find(commandname);
197 if (n != cmdlist.end())
199 if (parameters.size() >= n->second->min_params)
203 if (IS_LOCAL(user) && n->second->flags_needed)
205 /* if user is local, and flags are needed .. */
207 if (user->IsModeSet(n->second->flags_needed))
209 /* if user has the flags, and now has the permissions, go ahead */
210 if (user->HasPermission(commandname))
216 /* remote or no flags required anyway */
222 return n->second->Handle(parameters,user);
229 void CommandParser::DoLines(User* current, bool one_only)
231 while (current->BufferIsReady())
233 // use GetBuffer to copy single lines into the sanitized string
234 std::string single_line = current->GetBuffer();
235 current->bytes_in += single_line.length();
237 if (single_line.length() > MAXBUF - 2) // MAXBUF is 514 to allow for neccessary line terminators
238 single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
240 // ProcessBuffer returns false if the user has gone over penalty
241 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
246 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
248 std::vector<std::string> command_p;
249 irc::tokenstream tokens(cmd);
250 std::string command, token;
251 tokens.GetToken(command);
253 /* A client sent a nick prefix on their command (ick)
254 * rhapsody and some braindead bouncers do this --
255 * the rfc says they shouldnt but also says the ircd should
256 * discard it if they do.
258 if (command[0] == ':')
259 tokens.GetToken(command);
261 while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
262 command_p.push_back(token);
264 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
266 /* find the command, check it exists */
267 Commandtable::iterator cm = cmdlist.find(command);
269 if (cm == cmdlist.end())
272 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
277 * This double lookup is in case a module (abbreviation) wishes to change a command.
278 * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
280 * Thanks dz for making me actually understand why this is necessary!
283 cm = cmdlist.find(command);
284 if (cm == cmdlist.end())
286 if (user->registered == REG_ALL)
287 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
288 ServerInstance->stats->statsUnknown++;
293 if (cm->second->max_params && command_p.size() > cm->second->max_params)
296 * command_p input (assuming max_params 1):
302 std::string lparam = "";
305 * The '-1' here is a clever trick, we'll go backwards throwing everything into a temporary param
306 * and then just toss that into the array.
309 while (command_p.size() > (cm->second->max_params - 1))
311 // BE CAREFUL: .end() returns past the end of the vector, hence decrement.
312 std::vector<std::string>::iterator it = --command_p.end();
314 lparam.insert(0, " " + *(it));
315 command_p.erase(it); // remove last element
318 /* we now have (each iteration):
321 * ' is a test' <-- final string
322 * ...now remove the ' ' at the start...
324 lparam.erase(lparam.begin());
326 /* param is now 'is a test', which is exactly what we wanted! */
327 command_p.push_back(lparam);
331 * We call OnPreCommand here seperately if the command exists, so the magic above can
332 * truncate to max_params if necessary. -- w00t
335 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
339 /* Modify the user's penalty */
341 if (!user->HasPrivPermission("users/flood/no-throttle"))
343 user->IncreasePenalty(cm->second->Penalty);
344 do_more = (user->Penalty < 10);
347 /* activity resets the ping pending timer */
349 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
351 if (cm->second->flags_needed)
353 if (!user->IsModeSet(cm->second->flags_needed))
355 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
358 if (!user->HasPermission(command))
360 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",user->nick.c_str(),user->oper.c_str(),command.c_str());
364 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
366 /* command is disabled! */
367 if (ServerInstance->Config->DisabledDontExist)
369 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
373 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
374 user->nick.c_str(), command.c_str());
377 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
378 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
381 if (command_p.size() < cm->second->min_params)
383 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
384 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
385 user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->command.c_str(), cm->second->syntax.c_str());
388 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
390 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
395 /* passed all checks.. first, do the (ugly) stats counters. */
396 cm->second->use_count++;
397 cm->second->total_bytes += cmd.length();
399 /* module calls too */
401 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, true, cmd));
406 * WARNING: be careful, the user may be deleted soon
408 CmdResult result = cm->second->Handle(command_p, user);
410 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
415 void CommandParser::RemoveCommands(const char* source)
417 Commandtable::iterator i,safei;
418 for (i = cmdlist.begin(); i != cmdlist.end();)
422 RemoveCommand(safei, source);
426 void CommandParser::RemoveCommand(Commandtable::iterator safei, const char* source)
428 Command* x = safei->second;
429 if (x->source == std::string(source))
431 cmdlist.erase(safei);
436 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
438 std::string::size_type a;
443 while ((a = buffer.rfind("\n")) != std::string::npos)
445 while ((a = buffer.rfind("\r")) != std::string::npos)
450 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick.c_str(), buffer.c_str());
451 return this->ProcessCommand(user,buffer);
457 bool CommandParser::CreateCommand(Command *f, void* so_handle)
461 if (RFCCommands.find(f->command) == RFCCommands.end())
462 RFCCommands[f->command] = so_handle;
465 ServerInstance->Logs->Log("COMMAND",DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
470 /* create the command and push it onto the table */
471 if (cmdlist.find(f->command) == cmdlist.end())
473 cmdlist[f->command] = f;
479 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
484 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
486 *v = dlsym(h, "init_command");
487 const char* err = dlerror();
490 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
496 bool CommandParser::ReloadCommand(std::string cmd, User* user)
498 char filename[MAXBUF];
499 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
501 SharedObjectList::iterator command = RFCCommands.find(cmd);
503 if (command != RFCCommands.end())
505 Command* cmdptr = cmdlist.find(cmd)->second;
506 cmdlist.erase(cmdlist.find(cmd));
508 RFCCommands.erase(cmd);
509 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
511 dlclose(command->second);
513 snprintf(filename, MAXBUF, "cmd_%s.so", cmd.c_str());
514 const char* err = this->LoadCommand(filename);
518 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick.c_str(), cmd.c_str(), err);
528 CmdResult CommandReload::Handle(const std::vector<std::string>& parameters, User *user)
530 if (parameters.size() < 1)
533 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick.c_str(), parameters[0].c_str());
534 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
536 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick.c_str(), parameters[0].c_str());
537 ServerInstance->SNO->WriteToSnoMask('A', "RELOAD: %s reloaded the '%s' command.", user->nick.c_str(), parameters[0].c_str());
542 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick.c_str(), parameters[0].c_str());
547 const char* CommandParser::LoadCommand(const char* name)
549 char filename[MAXBUF];
551 Command* (*cmd_factory_func)(InspIRCd*);
553 /* Command already exists? Succeed silently - this is needed for REHASH */
554 if (RFCCommands.find(name) != RFCCommands.end())
556 ServerInstance->Logs->Log("COMMAND",DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
560 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
561 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
565 const char* n = dlerror();
566 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s", name, n);
570 if (this->FindSym((void **)&cmd_factory_func, h, name))
572 Command* newcommand = cmd_factory_func(ServerInstance);
573 this->CreateCommand(newcommand, h);
578 /** This is only invoked on startup
580 void CommandParser::SetupCommandTable()
582 printf("\nLoading core commands");
585 DIR* library = opendir(LIBRARYDIR);
588 dirent* entry = NULL;
589 while (0 != (entry = readdir(library)))
591 if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
596 const char* err = this->LoadCommand(entry->d_name);
599 printf("Error loading %s: %s", entry->d_name, err);
600 exit(EXIT_STATUS_BADHANDLER);
608 if (cmdlist.find("RELOAD") == cmdlist.end())
609 this->CreateCommand(new CommandReload(ServerInstance));
612 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
616 int translations = 0;
622 /* Translate single nickname */
623 user = ServerInstance->FindNick(source);
634 /* Translate comma seperated list of nicknames */
635 irc::commasepstream items(source);
636 while (items.GetToken(item))
638 user = ServerInstance->FindNick(item);
641 dest.append(user->uuid);
649 dest.erase(dest.end() - 1);
652 case TR_SPACENICKLIST:
654 /* Translate space seperated list of nicknames */
655 irc::spacesepstream items(source);
656 while (items.GetToken(item))
658 user = ServerInstance->FindNick(item);
661 dest.append(user->uuid);
669 dest.erase(dest.end() - 1);