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 bool InspIRCd::ULine(const char* server)
35 return (Config->ulines.find(server) != Config->ulines.end());
38 bool InspIRCd::SilentULine(const char* server)
40 std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
41 if (n != Config->ulines.end())
46 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
49 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
54 return strcmp(data,input);
57 std::string InspIRCd::TimeString(time_t curtime)
59 return std::string(ctime(&curtime),24);
62 /** Refactored by Brain, Jun 2007. Much faster with some clever O(1) array
63 * lookups and pointer maths.
65 long InspIRCd::Duration(const std::string &str)
67 unsigned char multiplier = 0;
72 /* Iterate each item in the string, looking for number or multiplier */
73 for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
75 /* Found a number, queue it onto the current number */
76 if ((*i >= '0') && (*i <= '9'))
78 subtotal = subtotal + ((*i - '0') * times);
83 /* Found something thats not a number, find out how much
84 * it multiplies the built up number by, multiply the total
85 * and reset the built up number.
88 total += subtotal * duration_multi[multiplier];
90 /* Next subtotal please */
98 total += subtotal * duration_multi[multiplier];
101 /* Any trailing values built up are treated as raw seconds */
102 return total + subtotal;
105 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
106 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
107 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
108 * the channel names and their keys as follows:
109 * JOIN #chan1,#chan2,#chan3 key1,,key3
110 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
111 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
112 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
113 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
115 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
117 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
118 * which called us just carries on as it was.
120 if (!strchr(parameters[splithere],','))
123 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
124 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
127 std::map<irc::string, bool> dupes;
129 /* Create two lists, one for channel names, one for keys
131 irc::commasepstream items1(parameters[splithere]);
132 irc::commasepstream items2(parameters[extra]);
133 std::string extrastuff;
135 unsigned int max = 0;
137 /* Attempt to iterate these lists and call the command objech
138 * which called us, for every parameter pair until there are
139 * no more left to parse.
141 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
143 if (dupes.find(item.c_str()) == dupes.end())
145 const char* new_parameters[MAXPARAMETERS];
147 for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
148 new_parameters[t] = parameters[t];
150 if (!items2.GetToken(extrastuff))
153 new_parameters[splithere] = item.c_str();
154 new_parameters[extra] = extrastuff.c_str();
156 CommandObj->Handle(new_parameters,pcnt,user);
158 dupes[item.c_str()] = true;
164 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
166 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
167 * which called us just carries on as it was.
169 if (!strchr(parameters[splithere],','))
172 std::map<irc::string, bool> dupes;
174 /* Only one commasepstream here */
175 irc::commasepstream items1(parameters[splithere]);
177 unsigned int max = 0;
179 /* Parse the commasepstream until there are no tokens remaining.
180 * Each token we parse out, call the command handler that called us
183 while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
185 if (dupes.find(item.c_str()) == dupes.end())
187 const char* new_parameters[MAXPARAMETERS];
189 for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
190 new_parameters[t] = parameters[t];
192 new_parameters[splithere] = item.c_str();
194 parameters[splithere] = item.c_str();
196 /* Execute the command handler over and over. If someone pulls our user
197 * record out from under us (e.g. if we /kill a comma sep list, and we're
198 * in that list ourselves) abort if we're gone.
200 CommandObj->Handle(new_parameters,pcnt,user);
202 dupes[item.c_str()] = true;
205 /* By returning 1 we tell our caller that nothing is to be done,
206 * as all the previous calls handled the data. This makes the parent
207 * return without doing any processing.
212 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
214 command_table::iterator n = cmdlist.find(commandname);
216 if (n != cmdlist.end())
218 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
220 if ((!n->second->flags_needed) || (user->IsModeSet(n->second->flags_needed)))
222 if (n->second->flags_needed)
224 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
233 command_t* CommandParser::GetHandler(const std::string &commandname)
235 command_table::iterator n = cmdlist.find(commandname);
236 if (n != cmdlist.end())
242 // calls a handler function for a command
244 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
246 command_table::iterator n = cmdlist.find(commandname);
248 if (n != cmdlist.end())
250 if (pcnt >= n->second->min_params)
252 if ((!n->second->flags_needed) || (user->IsModeSet(n->second->flags_needed)))
254 if (n->second->flags_needed)
256 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
258 return n->second->Handle(parameters,pcnt,user);
263 return n->second->Handle(parameters,pcnt,user);
271 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
273 const char *command_p[MAXPARAMETERS];
275 irc::tokenstream tokens(cmd);
277 tokens.GetToken(command);
279 /* A client sent a nick prefix on their command (ick)
280 * rhapsody and some braindead bouncers do this --
281 * the rfc says they shouldnt but also says the ircd should
282 * discard it if they do.
284 if (*command.c_str() == ':')
285 tokens.GetToken(command);
287 while (tokens.GetToken(para[items]) && (items < MAXPARAMETERS))
289 command_p[items] = para[items].c_str();
293 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
296 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
297 if (MOD_RESULT == 1) {
301 command_table::iterator cm = cmdlist.find(command);
303 if (cm != cmdlist.end())
307 /* activity resets the ping pending timer */
308 user->nping = ServerInstance->Time() + user->pingmax;
309 if (cm->second->flags_needed)
311 if (!user->IsModeSet(cm->second->flags_needed))
313 user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
316 if (!user->HasPermission(command))
318 user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
322 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
324 /* command is disabled! */
325 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
326 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
327 command.c_str(), user->nick, user->ident, user->host);
330 if (items < cm->second->min_params)
332 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
333 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
334 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
337 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
339 /* ikky /stats counters */
340 cm->second->use_count++;
341 cm->second->total_bytes += cmd.length();
344 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
349 * WARNING: nothing should come after this, as the user may be on a cull list to
350 * be nuked next loop iteration. be sensible.
352 CmdResult result = cm->second->Handle(command_p,items,user);
354 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
359 user->WriteServ("451 %s :You have not registered",command.c_str());
366 ServerInstance->stats->statsUnknown++;
367 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
371 bool CommandParser::RemoveCommands(const char* source)
373 command_table::iterator i,safei;
374 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
378 if (safei != cmdlist.end())
380 RemoveCommand(safei, source);
383 safei = cmdlist.begin();
384 if (safei != cmdlist.end())
386 RemoveCommand(safei, source);
391 void CommandParser::RemoveCommand(command_table::iterator safei, const char* source)
393 command_t* x = safei->second;
394 if (x->source == std::string(source))
396 cmdlist.erase(safei);
401 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
403 std::string::size_type a;
408 while ((a = buffer.rfind("\n")) != std::string::npos)
410 while ((a = buffer.rfind("\r")) != std::string::npos)
417 ServerInstance->Log(DEBUG,"C[%d] -> :%s %s",user->GetFd(), user->nick, buffer.c_str());
418 this->ProcessCommand(user,buffer);
423 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
427 if (RFCCommands.find(f->command) == RFCCommands.end())
428 RFCCommands[f->command] = so_handle;
431 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
436 /* create the command and push it onto the table */
437 if (cmdlist.find(f->command) == cmdlist.end())
439 cmdlist[f->command] = f;
445 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
450 bool CommandParser::FindSym(void** v, void* h)
452 *v = dlsym(h, "init_command");
453 const char* err = dlerror();
456 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
462 bool CommandParser::ReloadCommand(const char* cmd, userrec* user)
464 char filename[MAXBUF];
465 char commandname[MAXBUF];
468 for (const char* x = cmd; *x; x++, y++)
469 commandname[y] = toupper(*x);
473 SharedObjectList::iterator command = RFCCommands.find(commandname);
475 if (command != RFCCommands.end())
477 command_t* cmdptr = cmdlist.find(commandname)->second;
478 cmdlist.erase(cmdlist.find(commandname));
480 for (char* x = commandname; *x; x++)
485 dlclose(command->second);
486 RFCCommands.erase(command);
488 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
489 const char* err = this->LoadCommand(filename);
493 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
503 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
505 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
506 if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
508 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
509 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
514 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
519 const char* CommandParser::LoadCommand(const char* name)
521 char filename[MAXBUF];
523 command_t* (*cmd_factory_func)(InspIRCd*);
525 /* Command already exists? Succeed silently - this is needed for REHASH */
526 if (RFCCommands.find(name) != RFCCommands.end())
528 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
532 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
533 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
537 const char* n = dlerror();
538 ServerInstance->Log(SPARSE, "Error loading core command: %s", n);
542 if (this->FindSym((void **)&cmd_factory_func, h))
544 command_t* newcommand = cmd_factory_func(ServerInstance);
545 this->CreateCommand(newcommand, h);
550 void CommandParser::SetupCommandTable(userrec* user)
556 printf("\nLoading core commands");
560 DIR* library = opendir(LIBRARYDIR);
563 dirent* entry = NULL;
564 while ((entry = readdir(library)))
566 if (match(entry->d_name, "cmd_*.so"))
573 const char* err = this->LoadCommand(entry->d_name);
578 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
582 printf("Error loading %s: %s", entry->d_name, err);
583 exit(EXIT_STATUS_BADHANDLER);
593 if (cmdlist.find("RELOAD") == cmdlist.end())
594 this->CreateCommand(new cmd_reload(ServerInstance));
597 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
599 userrec* user = NULL;
601 int translations = 0;
606 /* Translate single nickname */
607 ServerInstance->Log(DEBUG,"TR_NICK");
608 user = ServerInstance->FindNick(source);
611 ServerInstance->Log(DEBUG,"Managed UUID");
617 ServerInstance->Log(DEBUG,"Had to use source.. (%s)", source.c_str());
623 /* Translate comma seperated list of nicknames */
624 irc::commasepstream items(source);
625 while (items.GetToken(item))
627 user = ServerInstance->FindNick(item);
630 dest.append(user->uuid);
638 dest.erase(dest.end() - 1);
641 case TR_SPACENICKLIST:
643 /* Translate space seperated list of nicknames */
644 irc::spacesepstream items(source);
645 while (items.GetToken(item))
647 user = ServerInstance->FindNick(item);
650 dest.append(user->uuid);
658 dest.erase(dest.end() - 1);