1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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))
37 return data != input; // this seems back to front, but returns 0 if they *match*, 1 else
40 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
41 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
42 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
43 * the channel names and their keys as follows:
44 * JOIN #chan1,#chan2,#chan3 key1,,key3
45 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
46 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
47 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
48 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
50 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, unsigned int extra)
52 if (splithere >= parameters.size())
55 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
56 * which called us just carries on as it was.
58 if (parameters[splithere].find(',') == std::string::npos)
61 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
62 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
65 std::map<irc::string, bool> dupes;
67 /* Create two lists, one for channel names, one for keys
69 irc::commasepstream items1(parameters[splithere]);
70 irc::commasepstream items2(parameters[extra]);
71 std::string extrastuff;
75 /* Attempt to iterate these lists and call the command objech
76 * which called us, for every parameter pair until there are
77 * no more left to parse.
79 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
81 if (dupes.find(item.c_str()) == dupes.end())
83 std::vector<std::string> new_parameters;
85 for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
86 new_parameters.push_back(parameters[t]);
88 if (!items2.GetToken(extrastuff))
91 new_parameters[splithere] = item.c_str();
92 new_parameters[extra] = extrastuff.c_str();
94 CommandObj->Handle(new_parameters, user);
96 dupes[item.c_str()] = true;
102 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere)
104 if (splithere >= parameters.size())
107 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
108 * which called us just carries on as it was.
110 if (parameters[splithere].find(',') == std::string::npos)
113 std::map<irc::string, bool> dupes;
115 /* Only one commasepstream here */
116 irc::commasepstream items1(parameters[splithere]);
118 unsigned int max = 0;
120 /* Parse the commasepstream until there are no tokens remaining.
121 * Each token we parse out, call the command handler that called us
124 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
126 if (dupes.find(item.c_str()) == dupes.end())
128 std::vector<std::string> new_parameters;
130 for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
131 new_parameters.push_back(parameters[t]);
133 new_parameters[splithere] = item.c_str();
135 /* Execute the command handler. */
136 CommandObj->Handle(new_parameters, user);
138 dupes[item.c_str()] = true;
141 /* By returning 1 we tell our caller that nothing is to be done,
142 * as all the previous calls handled the data. This makes the parent
143 * return without doing any processing.
148 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
150 Commandtable::iterator n = cmdlist.find(commandname);
152 if (n != cmdlist.end())
154 if ((pcnt >= n->second->min_params) && (n->second->source != "<core>"))
156 if (IS_LOCAL(user) && n->second->flags_needed)
158 if (user->IsModeSet(n->second->flags_needed))
160 return (user->HasPermission(commandname));
172 Command* CommandParser::GetHandler(const std::string &commandname)
174 Commandtable::iterator n = cmdlist.find(commandname);
175 if (n != cmdlist.end())
181 // calls a handler function for a command
183 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
185 Commandtable::iterator n = cmdlist.find(commandname);
187 if (n != cmdlist.end())
189 if (parameters.size() >= n->second->min_params)
193 if (IS_LOCAL(user) && n->second->flags_needed)
195 /* if user is local, and flags are needed .. */
197 if (user->IsModeSet(n->second->flags_needed))
199 /* if user has the flags, and now has the permissions, go ahead */
200 if (user->HasPermission(commandname))
206 /* remote or no flags required anyway */
212 return n->second->Handle(parameters,user);
219 void CommandParser::DoLines(User* current, bool one_only)
221 // while there are complete lines to process...
222 unsigned int floodlines = 0;
224 while (current->BufferIsReady())
226 if (current->MyClass)
228 if (ServerInstance->Time() > current->reset_due)
230 current->reset_due = ServerInstance->Time() + current->MyClass->GetThreshold();
231 current->lines_in = 0;
234 if (++current->lines_in > current->MyClass->GetFlood() && current->MyClass->GetFlood())
236 ServerInstance->FloodQuitUser(current);
240 if ((++floodlines > current->MyClass->GetFlood()) && (current->MyClass->GetFlood() != 0))
242 ServerInstance->FloodQuitUser(current);
247 // use GetBuffer to copy single lines into the sanitized string
248 std::string single_line = current->GetBuffer();
249 current->bytes_in += single_line.length();
251 if (single_line.length() > MAXBUF - 2) // MAXBUF is 514 to allow for neccessary line terminators
252 single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
254 // ProcessBuffer returns false if the user has gone over penalty
255 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
260 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
262 std::vector<std::string> command_p;
263 irc::tokenstream tokens(cmd);
264 std::string command, token;
265 tokens.GetToken(command);
267 /* A client sent a nick prefix on their command (ick)
268 * rhapsody and some braindead bouncers do this --
269 * the rfc says they shouldnt but also says the ircd should
270 * discard it if they do.
272 if (command[0] == ':')
273 tokens.GetToken(command);
275 while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
276 command_p.push_back(token);
278 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
281 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
282 if (MOD_RESULT == 1) {
286 /* find the command, check it exists */
287 Commandtable::iterator cm = cmdlist.find(command);
289 if (cm == cmdlist.end())
291 if (user->registered == REG_ALL)
293 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
295 ServerInstance->stats->statsUnknown++;
299 /* Modify the user's penalty */
301 if (!user->ExemptFromPenalty)
303 user->IncreasePenalty(cm->second->Penalty);
304 do_more = (user->Penalty < 10);
306 user->OverPenalty = true;
309 /* activity resets the ping pending timer */
311 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
313 if (cm->second->flags_needed)
315 if (!user->IsModeSet(cm->second->flags_needed))
317 user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
320 if (!user->HasPermission(command))
322 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());
326 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
328 /* command is disabled! */
329 if (ServerInstance->Config->DisabledDontExist)
331 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
335 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
336 user->nick.c_str(), command.c_str());
339 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
340 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
343 if (command_p.size() < cm->second->min_params)
345 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
346 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
347 user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->command.c_str(), cm->second->syntax.c_str());
350 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
352 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
357 /* passed all checks.. first, do the (ugly) stats counters. */
358 cm->second->use_count++;
359 cm->second->total_bytes += cmd.length();
361 /* module calls too */
363 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, true, cmd));
368 * WARNING: be careful, the user may be deleted soon
370 CmdResult result = cm->second->Handle(command_p, user);
372 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
377 void CommandParser::RemoveCommands(const char* source)
379 Commandtable::iterator i,safei;
380 for (i = cmdlist.begin(); i != cmdlist.end();)
384 RemoveCommand(safei, source);
388 void CommandParser::RemoveCommand(Commandtable::iterator safei, const char* source)
390 Command* x = safei->second;
391 if (x->source == std::string(source))
393 cmdlist.erase(safei);
398 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
400 std::string::size_type a;
405 while ((a = buffer.rfind("\n")) != std::string::npos)
407 while ((a = buffer.rfind("\r")) != std::string::npos)
412 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick.c_str(), buffer.c_str());
413 return this->ProcessCommand(user,buffer);
419 bool CommandParser::CreateCommand(Command *f, void* so_handle)
423 if (RFCCommands.find(f->command) == RFCCommands.end())
424 RFCCommands[f->command] = so_handle;
427 ServerInstance->Logs->Log("COMMAND",DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
432 /* create the command and push it onto the table */
433 if (cmdlist.find(f->command) == cmdlist.end())
435 cmdlist[f->command] = f;
441 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
446 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
448 *v = dlsym(h, "init_command");
449 const char* err = dlerror();
452 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
458 bool CommandParser::ReloadCommand(std::string cmd, User* user)
460 char filename[MAXBUF];
461 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
463 SharedObjectList::iterator command = RFCCommands.find(cmd);
465 if (command != RFCCommands.end())
467 Command* cmdptr = cmdlist.find(cmd)->second;
468 cmdlist.erase(cmdlist.find(cmd));
470 RFCCommands.erase(cmd);
471 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
473 dlclose(command->second);
475 snprintf(filename, MAXBUF, "cmd_%s.so", cmd.c_str());
476 const char* err = this->LoadCommand(filename);
480 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick.c_str(), cmd.c_str(), err);
490 CmdResult cmd_reload::Handle(const std::vector<std::string>& parameters, User *user)
492 if (parameters.size() < 1)
495 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick.c_str(), parameters[0].c_str());
496 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
498 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick.c_str(), parameters[0].c_str());
499 ServerInstance->SNO->WriteToSnoMask('A', "RELOAD: %s reloaded the '%s' command.", user->nick.c_str(), parameters[0].c_str());
504 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());
509 const char* CommandParser::LoadCommand(const char* name)
511 char filename[MAXBUF];
513 Command* (*cmd_factory_func)(InspIRCd*);
515 /* Command already exists? Succeed silently - this is needed for REHASH */
516 if (RFCCommands.find(name) != RFCCommands.end())
518 ServerInstance->Logs->Log("COMMAND",DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
522 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
523 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
527 const char* n = dlerror();
528 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s", name, n);
532 if (this->FindSym((void **)&cmd_factory_func, h, name))
534 Command* newcommand = cmd_factory_func(ServerInstance);
535 this->CreateCommand(newcommand, h);
540 void CommandParser::SetupCommandTable(User* user)
546 printf("\nLoading core commands");
550 DIR* library = opendir(LIBRARYDIR);
553 dirent* entry = NULL;
554 while (0 != (entry = readdir(library)))
556 if (InspIRCd::Match(entry->d_name, "cmd_*.so"))
563 const char* err = this->LoadCommand(entry->d_name);
568 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick.c_str(), entry->d_name, err);
572 printf("Error loading %s: %s", entry->d_name, err);
573 exit(EXIT_STATUS_BADHANDLER);
583 if (cmdlist.find("RELOAD") == cmdlist.end())
584 this->CreateCommand(new cmd_reload(ServerInstance));
587 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
591 int translations = 0;
597 /* Translate single nickname */
598 user = ServerInstance->FindNick(source);
609 /* Translate comma seperated list of nicknames */
610 irc::commasepstream items(source);
611 while (items.GetToken(item))
613 user = ServerInstance->FindNick(item);
616 dest.append(user->uuid);
624 dest.erase(dest.end() - 1);
627 case TR_SPACENICKLIST:
629 /* Translate space seperated list of nicknames */
630 irc::spacesepstream items(source);
631 while (items.GetToken(item))
633 user = ServerInstance->FindNick(item);
636 dest.append(user->uuid);
644 dest.erase(dest.end() - 1);