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 * ---------------------------------------------------
14 /* $Core: libIRCDcommand_parse */
19 #include "socketengine.h"
21 #include "command_parse.h"
22 #include "exitcodes.h"
24 /* Directory Searching for Unix-Only */
30 int InspIRCd::PassCompare(Extensible* ex, const char* data,const char* input, const char* hashtype)
33 FOREACH_RESULT_I(this,I_OnPassCompare,OnPassCompare(ex, data, input, hashtype))
38 return strcmp(data,input);
41 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
42 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
43 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
44 * the channel names and their keys as follows:
45 * JOIN #chan1,#chan2,#chan3 key1,,key3
46 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
47 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
48 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
49 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
51 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, unsigned int extra)
53 if (splithere >= parameters.size())
56 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
57 * which called us just carries on as it was.
59 if (parameters[splithere].find(',') == std::string::npos)
62 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
63 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
66 std::map<irc::string, bool> dupes;
68 /* Create two lists, one for channel names, one for keys
70 irc::commasepstream items1(parameters[splithere]);
71 irc::commasepstream items2(parameters[extra]);
72 std::string extrastuff;
76 /* Attempt to iterate these lists and call the command objech
77 * which called us, for every parameter pair until there are
78 * no more left to parse.
80 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
82 if (dupes.find(item.c_str()) == dupes.end())
84 std::vector<std::string> new_parameters;
86 for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
87 new_parameters.push_back(parameters[t]);
89 if (!items2.GetToken(extrastuff))
92 new_parameters[splithere] = item.c_str();
93 new_parameters[extra] = extrastuff.c_str();
95 CommandObj->Handle(new_parameters, user);
97 dupes[item.c_str()] = true;
103 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere)
105 if (splithere >= parameters.size())
108 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
109 * which called us just carries on as it was.
111 if (parameters[splithere].find(',') == std::string::npos)
114 std::map<irc::string, bool> dupes;
116 /* Only one commasepstream here */
117 irc::commasepstream items1(parameters[splithere]);
119 unsigned int max = 0;
121 /* Parse the commasepstream until there are no tokens remaining.
122 * Each token we parse out, call the command handler that called us
125 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
127 if (dupes.find(item.c_str()) == dupes.end())
129 std::vector<std::string> new_parameters;
131 for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
132 new_parameters.push_back(parameters[t]);
134 new_parameters[splithere] = item.c_str();
136 /* Execute the command handler over and over. If someone pulls our user
137 * record out from under us (e.g. if we /kill a comma sep list, and we're
138 * in that list ourselves) abort if we're gone.
140 CommandObj->Handle(new_parameters, user);
142 dupes[item.c_str()] = true;
145 /* By returning 1 we tell our caller that nothing is to be done,
146 * as all the previous calls handled the data. This makes the parent
147 * return without doing any processing.
152 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
154 Commandable::iterator n = cmdlist.find(commandname);
156 if (n != cmdlist.end())
158 if ((pcnt >= n->second->min_params) && (n->second->source != "<core>"))
160 if (IS_LOCAL(user) && n->second->flags_needed)
162 if (user->IsModeSet(n->second->flags_needed))
164 return (user->HasPermission(commandname));
176 Command* CommandParser::GetHandler(const std::string &commandname)
178 Commandable::iterator n = cmdlist.find(commandname);
179 if (n != cmdlist.end())
185 // calls a handler function for a command
187 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
189 Commandable::iterator n = cmdlist.find(commandname);
191 if (n != cmdlist.end())
193 if (parameters.size() >= n->second->min_params)
197 if (IS_LOCAL(user) && n->second->flags_needed)
199 /* if user is local, and flags are needed .. */
201 if (user->IsModeSet(n->second->flags_needed))
203 /* if user has the flags, and now has the permissions, go ahead */
204 if (user->HasPermission(commandname))
210 /* remote or no flags required anyway */
216 return n->second->Handle(parameters,user);
223 void CommandParser::DoLines(User* current, bool one_only)
225 // while there are complete lines to process...
226 unsigned int floodlines = 0;
228 while (current->BufferIsReady())
230 if (current->MyClass)
232 if (ServerInstance->Time() > current->reset_due)
234 current->reset_due = ServerInstance->Time() + current->MyClass->GetThreshold();
235 current->lines_in = 0;
238 if (++current->lines_in > current->MyClass->GetFlood() && current->MyClass->GetFlood())
240 ServerInstance->FloodQuitUser(current);
244 if ((++floodlines > current->MyClass->GetFlood()) && (current->MyClass->GetFlood() != 0))
246 ServerInstance->FloodQuitUser(current);
251 // use GetBuffer to copy single lines into the sanitized string
252 std::string single_line = current->GetBuffer();
253 current->bytes_in += single_line.length();
255 if (single_line.length() > MAXBUF - 2) // MAXBUF is 514 to allow for neccessary line terminators
256 single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
258 // ProcessBuffer returns false if the user has gone over penalty
259 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
264 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
266 std::vector<std::string> command_p;
267 irc::tokenstream tokens(cmd);
268 std::string command, token;
269 tokens.GetToken(command);
271 /* A client sent a nick prefix on their command (ick)
272 * rhapsody and some braindead bouncers do this --
273 * the rfc says they shouldnt but also says the ircd should
274 * discard it if they do.
276 if (command[0] == ':')
277 tokens.GetToken(command);
279 while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
280 command_p.push_back(token);
282 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
285 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
286 if (MOD_RESULT == 1) {
290 /* find the command, check it exists */
291 Commandable::iterator cm = cmdlist.find(command);
293 if (cm == cmdlist.end())
295 if (user->registered == REG_ALL)
297 user->WriteNumeric(421, "%s %s :Unknown command",user->nick,command.c_str());
299 ServerInstance->stats->statsUnknown++;
303 /* Modify the user's penalty */
305 if (!user->ExemptFromPenalty)
307 user->IncreasePenalty(cm->second->Penalty);
308 do_more = (user->Penalty < 10);
310 user->OverPenalty = true;
313 /* activity resets the ping pending timer */
315 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
317 if (cm->second->flags_needed)
319 if (!user->IsModeSet(cm->second->flags_needed))
321 user->WriteNumeric(481, "%s :Permission Denied - You do not have the required operator privileges",user->nick);
324 if (!user->HasPermission(command))
326 user->WriteNumeric(481, "%s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
330 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
332 /* command is disabled! */
333 user->WriteNumeric(421, "%s %s :This command has been disabled.",user->nick,command.c_str());
334 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
335 command.c_str(), user->nick, user->ident, user->host);
338 if (command_p.size() < cm->second->min_params)
340 user->WriteNumeric(461, "%s %s :Not enough parameters.", user->nick, command.c_str());
341 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
342 user->WriteNumeric(304, "%s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
345 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
347 user->WriteNumeric(451, "%s :You have not registered",command.c_str());
352 /* passed all checks.. first, do the (ugly) stats counters. */
353 cm->second->use_count++;
354 cm->second->total_bytes += cmd.length();
356 /* module calls too */
358 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, true, cmd));
363 * WARNING: be careful, the user may be deleted soon
365 CmdResult result = cm->second->Handle(command_p, user);
367 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
372 void CommandParser::RemoveCommands(const char* source)
374 Commandable::iterator i,safei;
375 for (i = cmdlist.begin(); i != cmdlist.end();)
379 RemoveCommand(safei, source);
383 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
385 Command* x = safei->second;
386 if (x->source == std::string(source))
388 cmdlist.erase(safei);
393 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
395 std::string::size_type a;
400 while ((a = buffer.rfind("\n")) != std::string::npos)
402 while ((a = buffer.rfind("\r")) != std::string::npos)
407 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
408 return this->ProcessCommand(user,buffer);
414 bool CommandParser::CreateCommand(Command *f, void* so_handle)
418 if (RFCCommands.find(f->command) == RFCCommands.end())
419 RFCCommands[f->command] = so_handle;
422 ServerInstance->Logs->Log("COMMAND",DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
427 /* create the command and push it onto the table */
428 if (cmdlist.find(f->command) == cmdlist.end())
430 cmdlist[f->command] = f;
436 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
441 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
443 *v = dlsym(h, "init_command");
444 const char* err = dlerror();
447 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
453 bool CommandParser::ReloadCommand(std::string cmd, User* user)
455 char filename[MAXBUF];
456 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
458 SharedObjectList::iterator command = RFCCommands.find(cmd);
460 if (command != RFCCommands.end())
462 Command* cmdptr = cmdlist.find(cmd)->second;
463 cmdlist.erase(cmdlist.find(cmd));
465 RFCCommands.erase(cmd);
466 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
468 dlclose(command->second);
470 snprintf(filename, MAXBUF, "cmd_%s.so", cmd.c_str());
471 const char* err = this->LoadCommand(filename);
475 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd.c_str(), err);
485 CmdResult cmd_reload::Handle(const std::vector<std::string>& parameters, User *user)
487 if (parameters.size() < 1)
490 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0].c_str());
491 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
493 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0].c_str());
494 ServerInstance->SNO->WriteToSnoMask('A', "RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0].c_str());
499 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0].c_str());
504 const char* CommandParser::LoadCommand(const char* name)
506 char filename[MAXBUF];
508 Command* (*cmd_factory_func)(InspIRCd*);
510 /* Command already exists? Succeed silently - this is needed for REHASH */
511 if (RFCCommands.find(name) != RFCCommands.end())
513 ServerInstance->Logs->Log("COMMAND",DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
517 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
518 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
522 const char* n = dlerror();
523 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s", name, n);
527 if (this->FindSym((void **)&cmd_factory_func, h, name))
529 Command* newcommand = cmd_factory_func(ServerInstance);
530 this->CreateCommand(newcommand, h);
535 void CommandParser::SetupCommandTable(User* user)
541 printf("\nLoading core commands");
545 DIR* library = opendir(LIBRARYDIR);
548 dirent* entry = NULL;
549 while (0 != (entry = readdir(library)))
551 if (match(entry->d_name, "cmd_*.so"))
558 const char* err = this->LoadCommand(entry->d_name);
563 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
567 printf("Error loading %s: %s", entry->d_name, err);
568 exit(EXIT_STATUS_BADHANDLER);
578 if (cmdlist.find("RELOAD") == cmdlist.end())
579 this->CreateCommand(new cmd_reload(ServerInstance));
582 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
586 int translations = 0;
592 /* Translate single nickname */
593 user = ServerInstance->FindNick(source);
604 /* Translate comma seperated list of nicknames */
605 irc::commasepstream items(source);
606 while (items.GetToken(item))
608 user = ServerInstance->FindNick(item);
611 dest.append(user->uuid);
619 dest.erase(dest.end() - 1);
622 case TR_SPACENICKLIST:
624 /* Translate space seperated list of nicknames */
625 irc::spacesepstream items(source);
626 while (items.GetToken(item))
628 user = ServerInstance->FindNick(item);
631 dest.append(user->uuid);
639 dest.erase(dest.end() - 1);