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 std::string &data, const std::string &input, const std::string &hashtype)
33 FOREACH_RESULT_I(this,I_OnPassCompare,OnPassCompare(ex, data, input, hashtype))
38 return data != input; // this seems back to front, but returns 0 if they *match*, 1 else
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. */
137 CommandObj->Handle(new_parameters, user);
139 dupes[item.c_str()] = true;
142 /* By returning 1 we tell our caller that nothing is to be done,
143 * as all the previous calls handled the data. This makes the parent
144 * return without doing any processing.
149 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
151 Commandable::iterator n = cmdlist.find(commandname);
153 if (n != cmdlist.end())
155 if ((pcnt >= n->second->min_params) && (n->second->source != "<core>"))
157 if (IS_LOCAL(user) && n->second->flags_needed)
159 if (user->IsModeSet(n->second->flags_needed))
161 return (user->HasPermission(commandname));
173 Command* CommandParser::GetHandler(const std::string &commandname)
175 Commandable::iterator n = cmdlist.find(commandname);
176 if (n != cmdlist.end())
182 // calls a handler function for a command
184 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
186 Commandable::iterator n = cmdlist.find(commandname);
188 if (n != cmdlist.end())
190 if (parameters.size() >= n->second->min_params)
194 if (IS_LOCAL(user) && n->second->flags_needed)
196 /* if user is local, and flags are needed .. */
198 if (user->IsModeSet(n->second->flags_needed))
200 /* if user has the flags, and now has the permissions, go ahead */
201 if (user->HasPermission(commandname))
207 /* remote or no flags required anyway */
213 return n->second->Handle(parameters,user);
220 void CommandParser::DoLines(User* current, bool one_only)
222 // while there are complete lines to process...
223 unsigned int floodlines = 0;
225 while (current->BufferIsReady())
227 if (current->MyClass)
229 if (ServerInstance->Time() > current->reset_due)
231 current->reset_due = ServerInstance->Time() + current->MyClass->GetThreshold();
232 current->lines_in = 0;
235 if (++current->lines_in > current->MyClass->GetFlood() && current->MyClass->GetFlood())
237 ServerInstance->FloodQuitUser(current);
241 if ((++floodlines > current->MyClass->GetFlood()) && (current->MyClass->GetFlood() != 0))
243 ServerInstance->FloodQuitUser(current);
248 // use GetBuffer to copy single lines into the sanitized string
249 std::string single_line = current->GetBuffer();
250 current->bytes_in += single_line.length();
252 if (single_line.length() > MAXBUF - 2) // MAXBUF is 514 to allow for neccessary line terminators
253 single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
255 // ProcessBuffer returns false if the user has gone over penalty
256 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
261 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
263 std::vector<std::string> command_p;
264 irc::tokenstream tokens(cmd);
265 std::string command, token;
266 tokens.GetToken(command);
268 /* A client sent a nick prefix on their command (ick)
269 * rhapsody and some braindead bouncers do this --
270 * the rfc says they shouldnt but also says the ircd should
271 * discard it if they do.
273 if (command[0] == ':')
274 tokens.GetToken(command);
276 while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
277 command_p.push_back(token);
279 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
282 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
283 if (MOD_RESULT == 1) {
287 /* find the command, check it exists */
288 Commandable::iterator cm = cmdlist.find(command);
290 if (cm == cmdlist.end())
292 if (user->registered == REG_ALL)
294 user->WriteNumeric(421, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
296 ServerInstance->stats->statsUnknown++;
300 /* Modify the user's penalty */
302 if (!user->ExemptFromPenalty)
304 user->IncreasePenalty(cm->second->Penalty);
305 do_more = (user->Penalty < 10);
307 user->OverPenalty = true;
310 /* activity resets the ping pending timer */
312 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
314 if (cm->second->flags_needed)
316 if (!user->IsModeSet(cm->second->flags_needed))
318 user->WriteNumeric(481, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
321 if (!user->HasPermission(command))
323 user->WriteNumeric(481, "%s :Permission Denied - Oper type %s does not have access to command %s",user->nick.c_str(),user->oper.c_str(),command.c_str());
327 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
329 /* command is disabled! */
330 user->WriteNumeric(421, "%s %s :This command has been disabled.",user->nick.c_str(),command.c_str());
331 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
332 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
335 if (command_p.size() < cm->second->min_params)
337 user->WriteNumeric(461, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
338 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
339 user->WriteNumeric(304, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->command.c_str(), cm->second->syntax.c_str());
342 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
344 user->WriteNumeric(451, "%s :You have not registered",command.c_str());
349 /* passed all checks.. first, do the (ugly) stats counters. */
350 cm->second->use_count++;
351 cm->second->total_bytes += cmd.length();
353 /* module calls too */
355 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, true, cmd));
360 * WARNING: be careful, the user may be deleted soon
362 CmdResult result = cm->second->Handle(command_p, user);
364 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
369 void CommandParser::RemoveCommands(const char* source)
371 Commandable::iterator i,safei;
372 for (i = cmdlist.begin(); i != cmdlist.end();)
376 RemoveCommand(safei, source);
380 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
382 Command* x = safei->second;
383 if (x->source == std::string(source))
385 cmdlist.erase(safei);
390 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
392 std::string::size_type a;
397 while ((a = buffer.rfind("\n")) != std::string::npos)
399 while ((a = buffer.rfind("\r")) != std::string::npos)
404 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick.c_str(), buffer.c_str());
405 return this->ProcessCommand(user,buffer);
411 bool CommandParser::CreateCommand(Command *f, void* so_handle)
415 if (RFCCommands.find(f->command) == RFCCommands.end())
416 RFCCommands[f->command] = so_handle;
419 ServerInstance->Logs->Log("COMMAND",DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
424 /* create the command and push it onto the table */
425 if (cmdlist.find(f->command) == cmdlist.end())
427 cmdlist[f->command] = f;
433 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
438 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
440 *v = dlsym(h, "init_command");
441 const char* err = dlerror();
444 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
450 bool CommandParser::ReloadCommand(std::string cmd, User* user)
452 char filename[MAXBUF];
453 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
455 SharedObjectList::iterator command = RFCCommands.find(cmd);
457 if (command != RFCCommands.end())
459 Command* cmdptr = cmdlist.find(cmd)->second;
460 cmdlist.erase(cmdlist.find(cmd));
462 RFCCommands.erase(cmd);
463 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
465 dlclose(command->second);
467 snprintf(filename, MAXBUF, "cmd_%s.so", cmd.c_str());
468 const char* err = this->LoadCommand(filename);
472 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick.c_str(), cmd.c_str(), err);
482 CmdResult cmd_reload::Handle(const std::vector<std::string>& parameters, User *user)
484 if (parameters.size() < 1)
487 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick.c_str(), parameters[0].c_str());
488 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
490 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick.c_str(), parameters[0].c_str());
491 ServerInstance->SNO->WriteToSnoMask('A', "RELOAD: %s reloaded the '%s' command.", user->nick.c_str(), parameters[0].c_str());
496 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());
501 const char* CommandParser::LoadCommand(const char* name)
503 char filename[MAXBUF];
505 Command* (*cmd_factory_func)(InspIRCd*);
507 /* Command already exists? Succeed silently - this is needed for REHASH */
508 if (RFCCommands.find(name) != RFCCommands.end())
510 ServerInstance->Logs->Log("COMMAND",DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
514 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
515 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
519 const char* n = dlerror();
520 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s", name, n);
524 if (this->FindSym((void **)&cmd_factory_func, h, name))
526 Command* newcommand = cmd_factory_func(ServerInstance);
527 this->CreateCommand(newcommand, h);
532 void CommandParser::SetupCommandTable(User* user)
538 printf("\nLoading core commands");
542 DIR* library = opendir(LIBRARYDIR);
545 dirent* entry = NULL;
546 while (0 != (entry = readdir(library)))
548 if (match(entry->d_name, "cmd_*.so"))
555 const char* err = this->LoadCommand(entry->d_name);
560 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick.c_str(), entry->d_name, err);
564 printf("Error loading %s: %s", entry->d_name, err);
565 exit(EXIT_STATUS_BADHANDLER);
575 if (cmdlist.find("RELOAD") == cmdlist.end())
576 this->CreateCommand(new cmd_reload(ServerInstance));
579 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
583 int translations = 0;
589 /* Translate single nickname */
590 user = ServerInstance->FindNick(source);
601 /* Translate comma seperated list of nicknames */
602 irc::commasepstream items(source);
603 while (items.GetToken(item))
605 user = ServerInstance->FindNick(item);
608 dest.append(user->uuid);
616 dest.erase(dest.end() - 1);
619 case TR_SPACENICKLIST:
621 /* Translate space seperated list of nicknames */
622 irc::spacesepstream items(source);
623 while (items.GetToken(item))
625 user = ServerInstance->FindNick(item);
628 dest.append(user->uuid);
636 dest.erase(dest.end() - 1);