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 * ---------------------------------------------------
15 #include "configreader.h"
21 #include "socketengine.h"
23 #include "command_parse.h"
25 /* Directory Searching for Unix-Only */
31 bool InspIRCd::ULine(const char* server)
38 return (Config->ulines.find(server) != Config->ulines.end());
41 bool InspIRCd::SilentULine(const char* server)
43 std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
44 if (n != Config->ulines.end())
49 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
52 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
57 return strcmp(data,input);
60 std::string InspIRCd::TimeString(time_t curtime)
62 return std::string(ctime(&curtime),24);
65 /** Refactored by Brain, Jun 2007. Much faster with some clever O(1) array
66 * lookups and pointer maths.
68 long InspIRCd::Duration(const std::string &str)
70 unsigned char multiplier = 0;
75 /* Iterate each item in the string, looking for number or multiplier */
76 for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
78 /* Found a number, queue it onto the current number */
79 if ((*i >= '0') && (*i <= '9'))
81 subtotal = subtotal + ((*i - '0') * times);
86 /* Found something thats not a number, find out how much
87 * it multiplies the built up number by, multiply the total
88 * and reset the built up number.
91 total += subtotal * duration_multi[multiplier];
93 /* Next subtotal please */
101 total += subtotal * duration_multi[multiplier];
104 /* Any trailing values built up are treated as raw seconds */
105 return total + subtotal;
108 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
109 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
110 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
111 * the channel names and their keys as follows:
112 * JOIN #chan1,#chan2,#chan3 key1,,key3
113 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
114 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
115 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
116 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
118 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
120 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
121 * which called us just carries on as it was.
123 if (!strchr(parameters[splithere],','))
126 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
127 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
130 std::map<irc::string, bool> dupes;
132 /* Create two lists, one for channel names, one for keys
134 irc::commasepstream items1(parameters[splithere]);
135 irc::commasepstream items2(parameters[extra]);
136 std::string item = "*";
137 unsigned int max = 0;
139 /* Attempt to iterate these lists and call the command objech
140 * which called us, for every parameter pair until there are
141 * no more left to parse.
143 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
145 if (dupes.find(item.c_str()) == dupes.end())
147 const char* new_parameters[127];
149 for (int t = 0; (t < pcnt) && (t < 127); t++)
150 new_parameters[t] = parameters[t];
152 std::string extrastuff = items2.GetToken();
154 new_parameters[splithere] = item.c_str();
155 new_parameters[extra] = extrastuff.c_str();
157 CommandObj->Handle(new_parameters,pcnt,user);
159 dupes[item.c_str()] = true;
165 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
167 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
168 * which called us just carries on as it was.
170 if (!strchr(parameters[splithere],','))
173 std::map<irc::string, bool> dupes;
175 /* Only one commasepstream here */
176 irc::commasepstream items1(parameters[splithere]);
177 std::string item = "*";
178 unsigned int max = 0;
180 /* Parse the commasepstream until there are no tokens remaining.
181 * Each token we parse out, call the command handler that called us
184 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
186 if (dupes.find(item.c_str()) == dupes.end())
188 const char* new_parameters[127];
190 for (int t = 0; (t < pcnt) && (t < 127); t++)
191 new_parameters[t] = parameters[t];
193 new_parameters[splithere] = item.c_str();
195 parameters[splithere] = item.c_str();
197 /* Execute the command handler over and over. If someone pulls our user
198 * record out from under us (e.g. if we /kill a comma sep list, and we're
199 * in that list ourselves) abort if we're gone.
201 CommandObj->Handle(new_parameters,pcnt,user);
203 dupes[item.c_str()] = true;
206 /* By returning 1 we tell our caller that nothing is to be done,
207 * as all the previous calls handled the data. This makes the parent
208 * return without doing any processing.
213 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
215 command_table::iterator n = cmdlist.find(commandname);
217 if (n != cmdlist.end())
219 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
221 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
223 if (n->second->flags_needed)
225 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
234 command_t* CommandParser::GetHandler(const std::string &commandname)
236 command_table::iterator n = cmdlist.find(commandname);
237 if (n != cmdlist.end())
243 // calls a handler function for a command
245 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
247 command_table::iterator n = cmdlist.find(commandname);
249 if (n != cmdlist.end())
251 if (pcnt >= n->second->min_params)
253 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
255 if (n->second->flags_needed)
257 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
259 return n->second->Handle(parameters,pcnt,user);
264 return n->second->Handle(parameters,pcnt,user);
272 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
274 const char *command_p[127];
276 irc::tokenstream tokens(cmd);
278 tokens.GetToken(command);
280 /* A client sent a nick prefix on their command (ick)
281 * rhapsody and some braindead bouncers do this --
282 * the rfc says they shouldnt but also says the ircd should
283 * discard it if they do.
285 if (*command.c_str() == ':')
286 tokens.GetToken(command);
288 while (tokens.GetToken(para[items]) && (items < 127))
290 command_p[items] = para[items].c_str();
294 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
297 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
298 if (MOD_RESULT == 1) {
302 command_table::iterator cm = cmdlist.find(command);
304 if (cm != cmdlist.end())
308 /* activity resets the ping pending timer */
309 user->nping = ServerInstance->Time() + user->pingmax;
310 if (cm->second->flags_needed)
312 if (!user->IsModeSet(cm->second->flags_needed))
314 user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
317 if (!user->HasPermission(command))
319 user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
323 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
325 /* command is disabled! */
326 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
329 if (items < cm->second->min_params)
331 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
332 /* If syntax is given, display this as the 461 reply */
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 may come after the
350 * command handler call, as the handler
351 * may free the user structure!
353 CmdResult result = cm->second->Handle(command_p,items,user);
355 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
360 user->WriteServ("451 %s :You have not registered",command.c_str());
367 ServerInstance->stats->statsUnknown++;
368 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
372 bool CommandParser::RemoveCommands(const char* source)
374 command_table::iterator i,safei;
375 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
379 if (safei != cmdlist.end())
381 RemoveCommand(safei, source);
384 safei = cmdlist.begin();
385 if (safei != cmdlist.end())
387 RemoveCommand(safei, source);
392 void CommandParser::RemoveCommand(command_table::iterator safei, const char* source)
394 command_t* x = safei->second;
395 if (x->source == std::string(source))
397 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)
448 this->SetupCommandTable();
451 bool CommandParser::FindSym(void** v, void* h)
453 *v = dlsym(h, "init_command");
454 const char* err = dlerror();
457 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
463 bool CommandParser::ReloadCommand(const char* cmd)
465 char filename[MAXBUF];
466 char commandname[MAXBUF];
469 for (const char* x = cmd; *x; x++, y++)
470 commandname[y] = toupper(*x);
474 SharedObjectList::iterator command = RFCCommands.find(commandname);
476 if (command != RFCCommands.end())
478 command_t* cmdptr = cmdlist.find(commandname)->second;
479 cmdlist.erase(cmdlist.find(commandname));
481 for (char* x = commandname; *x; x++)
486 dlclose(command->second);
487 RFCCommands.erase(command);
489 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
490 this->LoadCommand(filename);
498 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
500 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
501 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
503 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
504 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
509 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
514 void CommandParser::LoadCommand(const char* name)
516 char filename[MAXBUF];
518 command_t* (*cmd_factory_func)(InspIRCd*);
520 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
521 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
525 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
529 if (this->FindSym((void **)&cmd_factory_func, h))
531 command_t* newcommand = cmd_factory_func(ServerInstance);
532 this->CreateCommand(newcommand, h);
536 void CommandParser::SetupCommandTable()
540 printf("\nLoading core commands");
543 DIR* library = opendir(LIBRARYDIR);
546 dirent* entry = NULL;
547 while ((entry = readdir(library)))
549 if (match(entry->d_name, "cmd_*.so"))
553 this->LoadCommand(entry->d_name);
560 this->CreateCommand(new cmd_reload(ServerInstance));