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 * ---------------------------------------------------
17 #include "socketengine.h"
19 #include "command_parse.h"
20 #include "exitcodes.h"
22 /* Directory Searching for Unix-Only */
28 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
31 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
36 return strcmp(data,input);
39 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
40 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
41 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
42 * the channel names and their keys as follows:
43 * JOIN #chan1,#chan2,#chan3 key1,,key3
44 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
45 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
46 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
47 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
49 int CommandParser::LoopCall(User* user, Command* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
51 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
52 * which called us just carries on as it was.
54 if (!strchr(parameters[splithere],','))
57 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
58 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
61 std::map<irc::string, bool> dupes;
63 /* Create two lists, one for channel names, one for keys
65 irc::commasepstream items1(parameters[splithere]);
66 irc::commasepstream items2(parameters[extra]);
67 std::string extrastuff;
71 /* Attempt to iterate these lists and call the command objech
72 * which called us, for every parameter pair until there are
73 * no more left to parse.
75 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
77 if (dupes.find(item.c_str()) == dupes.end())
79 const char* new_parameters[MAXPARAMETERS];
81 for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
82 new_parameters[t] = parameters[t];
84 if (!items2.GetToken(extrastuff))
87 new_parameters[splithere] = item.c_str();
88 new_parameters[extra] = extrastuff.c_str();
90 CommandObj->Handle(new_parameters,pcnt,user);
92 dupes[item.c_str()] = true;
98 int CommandParser::LoopCall(User* user, Command* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
100 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
101 * which called us just carries on as it was.
103 if (!strchr(parameters[splithere],','))
106 std::map<irc::string, bool> dupes;
108 /* Only one commasepstream here */
109 irc::commasepstream items1(parameters[splithere]);
111 unsigned int max = 0;
113 /* Parse the commasepstream until there are no tokens remaining.
114 * Each token we parse out, call the command handler that called us
117 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
119 if (dupes.find(item.c_str()) == dupes.end())
121 const char* new_parameters[MAXPARAMETERS];
123 for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
124 new_parameters[t] = parameters[t];
126 new_parameters[splithere] = item.c_str();
128 parameters[splithere] = item.c_str();
130 /* Execute the command handler over and over. If someone pulls our user
131 * record out from under us (e.g. if we /kill a comma sep list, and we're
132 * in that list ourselves) abort if we're gone.
134 CommandObj->Handle(new_parameters,pcnt,user);
136 dupes[item.c_str()] = true;
139 /* By returning 1 we tell our caller that nothing is to be done,
140 * as all the previous calls handled the data. This makes the parent
141 * return without doing any processing.
146 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, User * user)
148 Commandable::iterator n = cmdlist.find(commandname);
150 if (n != cmdlist.end())
152 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
154 if (IS_LOCAL(user) && n->second->flags_needed)
156 if (user->IsModeSet(n->second->flags_needed))
158 return (user->HasPermission(commandname));
170 Command* CommandParser::GetHandler(const std::string &commandname)
172 Commandable::iterator n = cmdlist.find(commandname);
173 if (n != cmdlist.end())
179 // calls a handler function for a command
181 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, User *user)
183 Commandable::iterator n = cmdlist.find(commandname);
185 if (n != cmdlist.end())
187 if (pcnt >= n->second->min_params)
191 if (IS_LOCAL(user) && n->second->flags_needed)
193 /* if user is local, and flags are needed .. */
195 if (user->IsModeSet(n->second->flags_needed))
197 /* if user has the flags, and now has the permissions, go ahead */
198 if (user->HasPermission(commandname))
204 /* remote or no flags required anyway */
210 return n->second->Handle(parameters,pcnt,user);
217 void CommandParser::DoLines(User* current, bool one_only)
219 // while there are complete lines to process...
222 while (current->BufferIsReady())
224 if (ServerInstance->Time() > current->reset_due)
226 current->reset_due = ServerInstance->Time() + current->threshold;
227 current->lines_in = 0;
230 if (++current->lines_in > current->flood && current->flood)
232 ServerInstance->FloodQuitUser(current);
236 if ((++floodlines > current->flood) && (current->flood != 0))
238 ServerInstance->FloodQuitUser(current);
242 // use GetBuffer to copy single lines into the sanitized string
243 std::string single_line = current->GetBuffer();
244 current->bytes_in += single_line.length();
246 if (single_line.length() > MAXBUF - 2) // MAXBUF is 514 to allow for neccessary line terminators
247 single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
249 // ProcessBuffer returns false if the user has gone over penalty
250 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
255 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
257 const char *command_p[MAXPARAMETERS];
259 irc::tokenstream tokens(cmd);
261 tokens.GetToken(command);
263 /* A client sent a nick prefix on their command (ick)
264 * rhapsody and some braindead bouncers do this --
265 * the rfc says they shouldnt but also says the ircd should
266 * discard it if they do.
268 if (*command.c_str() == ':')
269 tokens.GetToken(command);
271 while (tokens.GetToken(para[items]) && (items < MAXPARAMETERS))
273 command_p[items] = para[items].c_str();
277 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
280 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
281 if (MOD_RESULT == 1) {
288 * before, we went and found the command even with no user.. seems nonsensical.
289 * I'm not entirely sure when we would be passed NULL, but let's handle it
290 * anyway, by dropping it like a hot potato. -- w00t
295 /* find the command, check it exists */
296 Commandable::iterator cm = cmdlist.find(command);
298 if (cm == cmdlist.end())
300 ServerInstance->stats->statsUnknown++;
301 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
305 /* Modify the user's penalty */
306 user->Penalty += cm->second->Penalty;
307 bool do_more = (user->Penalty < 10);
309 user->OverPenalty = true;
311 /* activity resets the ping pending timer */
312 user->nping = ServerInstance->Time() + user->pingmax;
313 if (cm->second->flags_needed)
315 if (!user->IsModeSet(cm->second->flags_needed))
317 user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
320 if (!user->HasPermission(command))
322 user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
326 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
328 /* command is disabled! */
329 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
330 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
331 command.c_str(), user->nick, user->ident, user->host);
334 if (items < cm->second->min_params)
336 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
337 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
338 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
341 if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
343 user->WriteServ("451 %s :You have not registered",command.c_str());
348 /* passed all checks.. first, do the (ugly) stats counters. */
349 cm->second->use_count++;
350 cm->second->total_bytes += cmd.length();
352 /* module calls too */
354 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
359 * WARNING: be careful, the user may be deleted soon
361 CmdResult result = cm->second->Handle(command_p,items,user);
363 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
368 bool CommandParser::RemoveCommands(const char* source)
370 Commandable::iterator i,safei;
371 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
375 if (safei != cmdlist.end())
377 RemoveCommand(safei, source);
380 safei = cmdlist.begin();
381 if (safei != cmdlist.end())
383 RemoveCommand(safei, source);
388 void CommandParser::RemoveCommand(Commandable::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)
414 ServerInstance->Log(DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
415 return this->ProcessCommand(user,buffer);
421 bool CommandParser::CreateCommand(Command *f, void* so_handle)
425 if (RFCCommands.find(f->command) == RFCCommands.end())
426 RFCCommands[f->command] = so_handle;
429 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
434 /* create the command and push it onto the table */
435 if (cmdlist.find(f->command) == cmdlist.end())
437 cmdlist[f->command] = f;
443 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
448 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
450 *v = dlsym(h, "init_command");
451 const char* err = dlerror();
454 ServerInstance->Log(SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
460 bool CommandParser::ReloadCommand(const char* cmd, User* user)
462 char filename[MAXBUF];
463 char commandname[MAXBUF];
466 for (const char* x = cmd; *x; x++, y++)
467 commandname[y] = toupper(*x);
471 SharedObjectList::iterator command = RFCCommands.find(commandname);
473 if (command != RFCCommands.end())
475 Command* cmdptr = cmdlist.find(commandname)->second;
476 cmdlist.erase(cmdlist.find(commandname));
478 for (char* x = commandname; *x; x++)
483 dlclose(command->second);
484 RFCCommands.erase(command);
486 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
487 const char* err = this->LoadCommand(filename);
491 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
501 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, User *user)
503 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
504 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
506 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
507 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
512 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
517 const char* CommandParser::LoadCommand(const char* name)
519 char filename[MAXBUF];
521 Command* (*cmd_factory_func)(InspIRCd*);
523 /* Command already exists? Succeed silently - this is needed for REHASH */
524 if (RFCCommands.find(name) != RFCCommands.end())
526 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
530 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
531 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
535 const char* n = dlerror();
536 ServerInstance->Log(SPARSE, "Error loading core command %s: %s", name, n);
540 if (this->FindSym((void **)&cmd_factory_func, h, name))
542 Command* newcommand = cmd_factory_func(ServerInstance);
543 this->CreateCommand(newcommand, h);
548 void CommandParser::SetupCommandTable(User* user)
554 printf("\nLoading core commands");
558 DIR* library = opendir(LIBRARYDIR);
561 dirent* entry = NULL;
562 while ((entry = readdir(library)))
564 if (match(entry->d_name, "cmd_*.so"))
571 const char* err = this->LoadCommand(entry->d_name);
576 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
580 printf("Error loading %s: %s", entry->d_name, err);
581 exit(EXIT_STATUS_BADHANDLER);
591 if (cmdlist.find("RELOAD") == cmdlist.end())
592 this->CreateCommand(new cmd_reload(ServerInstance));
595 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
599 int translations = 0;
605 /* Translate single nickname */
606 user = ServerInstance->FindNick(source);
617 /* Translate comma seperated list of nicknames */
618 irc::commasepstream items(source);
619 while (items.GetToken(item))
621 user = ServerInstance->FindNick(item);
624 dest.append(user->uuid);
632 dest.erase(dest.end() - 1);
635 case TR_SPACENICKLIST:
637 /* Translate space seperated list of nicknames */
638 irc::spacesepstream items(source);
639 while (items.GetToken(item))
641 user = ServerInstance->FindNick(item);
644 dest.append(user->uuid);
652 dest.erase(dest.end() - 1);