1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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::OperPassCompare(const char* data,const char* input, int tagnumber)
33 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
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 char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
53 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
54 * which called us just carries on as it was.
56 if (!strchr(parameters[splithere],','))
59 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
60 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
63 std::map<irc::string, bool> dupes;
65 /* Create two lists, one for channel names, one for keys
67 irc::commasepstream items1(parameters[splithere]);
68 irc::commasepstream items2(parameters[extra]);
69 std::string extrastuff;
73 /* Attempt to iterate these lists and call the command objech
74 * which called us, for every parameter pair until there are
75 * no more left to parse.
77 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
79 if (dupes.find(item.c_str()) == dupes.end())
81 const char* new_parameters[MAXPARAMETERS];
83 for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
84 new_parameters[t] = parameters[t];
86 if (!items2.GetToken(extrastuff))
89 new_parameters[splithere] = item.c_str();
90 new_parameters[extra] = extrastuff.c_str();
92 CommandObj->Handle(new_parameters,pcnt,user);
94 dupes[item.c_str()] = true;
100 int CommandParser::LoopCall(User* user, Command* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
102 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
103 * which called us just carries on as it was.
105 if (!strchr(parameters[splithere],','))
108 std::map<irc::string, bool> dupes;
110 /* Only one commasepstream here */
111 irc::commasepstream items1(parameters[splithere]);
113 unsigned int max = 0;
115 /* Parse the commasepstream until there are no tokens remaining.
116 * Each token we parse out, call the command handler that called us
119 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
121 if (dupes.find(item.c_str()) == dupes.end())
123 const char* new_parameters[MAXPARAMETERS];
125 for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
126 new_parameters[t] = parameters[t];
128 new_parameters[splithere] = item.c_str();
130 parameters[splithere] = item.c_str();
132 /* Execute the command handler over and over. If someone pulls our user
133 * record out from under us (e.g. if we /kill a comma sep list, and we're
134 * in that list ourselves) abort if we're gone.
136 CommandObj->Handle(new_parameters,pcnt,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, int pcnt, User * user)
150 Commandable::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 Commandable::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 char** parameters, int pcnt, User *user)
185 Commandable::iterator n = cmdlist.find(commandname);
187 if (n != cmdlist.end())
189 if (pcnt >= 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,pcnt,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 const char *command_p[MAXPARAMETERS];
264 irc::tokenstream tokens(cmd);
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.c_str() == ':')
274 tokens.GetToken(command);
276 while (tokens.GetToken(para[items]) && (items < MAXPARAMETERS))
278 command_p[items] = para[items].c_str();
282 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
285 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,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() && user->registered == REG_ALL)
295 ServerInstance->stats->statsUnknown++;
296 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
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->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
321 if (!user->HasPermission(command))
323 user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
327 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
329 /* command is disabled! */
330 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
331 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
332 command.c_str(), user->nick, user->ident, user->host);
335 if (items < cm->second->min_params)
337 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
338 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
339 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
342 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
344 user->WriteServ("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,items,user,true,cmd));
360 * WARNING: be careful, the user may be deleted soon
362 CmdResult result = cm->second->Handle(command_p,items,user);
364 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
369 bool CommandParser::RemoveCommands(const char* source)
371 Commandable::iterator i,safei;
372 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
376 if (safei != cmdlist.end())
378 RemoveCommand(safei, source);
381 safei = cmdlist.begin();
382 if (safei != cmdlist.end())
384 RemoveCommand(safei, source);
389 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
391 Command* x = safei->second;
392 if (x->source == std::string(source))
394 cmdlist.erase(safei);
399 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
401 std::string::size_type a;
406 while ((a = buffer.rfind("\n")) != std::string::npos)
408 while ((a = buffer.rfind("\r")) != std::string::npos)
415 ServerInstance->Log(DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
416 return this->ProcessCommand(user,buffer);
422 bool CommandParser::CreateCommand(Command *f, void* so_handle)
426 if (RFCCommands.find(f->command) == RFCCommands.end())
427 RFCCommands[f->command] = so_handle;
430 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
435 /* create the command and push it onto the table */
436 if (cmdlist.find(f->command) == cmdlist.end())
438 cmdlist[f->command] = f;
444 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
449 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
451 *v = dlsym(h, "init_command");
452 const char* err = dlerror();
455 ServerInstance->Log(SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
461 bool CommandParser::ReloadCommand(const char* cmd, User* user)
463 char filename[MAXBUF];
464 char commandname[MAXBUF];
467 for (const char* x = cmd; *x; x++, y++)
468 commandname[y] = toupper(*x);
472 SharedObjectList::iterator command = RFCCommands.find(commandname);
474 if (command != RFCCommands.end())
476 Command* cmdptr = cmdlist.find(commandname)->second;
477 cmdlist.erase(cmdlist.find(commandname));
479 for (char* x = commandname; *x; x++)
484 dlclose(command->second);
485 RFCCommands.erase(command);
487 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
488 const char* err = this->LoadCommand(filename);
492 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
502 CmdResult cmd_reload::Handle(const char** parameters, int /* pcnt */, User *user)
504 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
505 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
507 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
508 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
513 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
518 const char* CommandParser::LoadCommand(const char* name)
520 char filename[MAXBUF];
522 Command* (*cmd_factory_func)(InspIRCd*);
524 /* Command already exists? Succeed silently - this is needed for REHASH */
525 if (RFCCommands.find(name) != RFCCommands.end())
527 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
531 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
532 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
536 const char* n = dlerror();
537 ServerInstance->Log(SPARSE, "Error loading core command %s: %s", name, n);
541 if (this->FindSym((void **)&cmd_factory_func, h, name))
543 Command* newcommand = cmd_factory_func(ServerInstance);
544 this->CreateCommand(newcommand, h);
549 void CommandParser::SetupCommandTable(User* user)
555 printf("\nLoading core commands");
559 DIR* library = opendir(LIBRARYDIR);
562 dirent* entry = NULL;
563 while ((entry = readdir(library)))
565 if (match(entry->d_name, "cmd_*.so"))
572 const char* err = this->LoadCommand(entry->d_name);
577 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
581 printf("Error loading %s: %s", entry->d_name, err);
582 exit(EXIT_STATUS_BADHANDLER);
592 if (cmdlist.find("RELOAD") == cmdlist.end())
593 this->CreateCommand(new cmd_reload(ServerInstance));
596 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
600 int translations = 0;
606 /* Translate single nickname */
607 user = ServerInstance->FindNick(source);
618 /* Translate comma seperated list of nicknames */
619 irc::commasepstream items(source);
620 while (items.GetToken(item))
622 user = ServerInstance->FindNick(item);
625 dest.append(user->uuid);
633 dest.erase(dest.end() - 1);
636 case TR_SPACENICKLIST:
638 /* Translate space seperated list of nicknames */
639 irc::spacesepstream items(source);
640 while (items.GetToken(item))
642 user = ServerInstance->FindNick(item);
645 dest.append(user->uuid);
653 dest.erase(dest.end() - 1);